Skip to main content

Not getting anything in RPC Call from JS in Odoo11

I'm trying to make an RPC call to a method in python, but in the form view nothings happens

odoo.define('alicuam.show_modal_on_load', function (require) {
    "use strict";

    console.log("js loaded");
    var FormController = require('web.FormController');
    var Dialog = require('web.Dialog');

    FormController.include({
        events: _.extend({}, FormController.prototype.events, {
            'click .preview_btn': '_onPreviewBtnClick',
        }),

        _onPreviewBtnClick: function () {
            var self = this; // Guardar el contexto
            this._rpc({
                model: 'crm.files',
                method: 'open_file_preview_dialog',
            }).then(function (result) {
                if (result && result.html_content !== null) { // Revisar resultado
                    var dialog = new Dialog(self, {  // Usar el contexto guardado
                        title: 'Preview',
                        size: 'large',
                        $content: $(result.html_content)
                    });
                    dialog.open();
                    setTimeout(function() {
                        $('.modal-backdrop').addClass('fade_out');
                        $('.o_act_window').parents('.o_technical_modal').first().addClass('slide_up');
                        setTimeout(function() {
                            $('.modal-backdrop').remove();
                            $('.o_act_window').parents('.o_technical_modal').first().remove();
                        }, 350);
                        let $targetModal = dialog.$el.parents('.o_technical_modal').first();
                        $targetModal.addClass("dialog_preview");
                        console.log("Added class to: ", $targetModal.length, " elements");
                        $('.dialog_preview').css('z-index', 9999);
                        console.log("Z-index applied");
                    }, 50);
                } else {
                    console.log("Resultado es null o undefined");
                }
            }).catch(function (error) {  // Manejar errores
                console.error("Error en la solicitud RPC:", error);
            });
        },
    });
});

The Js code above it is supposed to call and get the result of this method but somehow doesn't, what am I doing wrong?

    def open_file_preview_dialog(self):
        _logger.info('El mƩtodo open_file_preview_dialog ha sido llamado.')
        if self.uri:
            uri_split = self.uri.split('.')
            file_format = uri_split[-1]

            # Verificar las dos Ćŗltimas extensiones
            last_two_ext = uri_split[-2:]

            # Si la última extensión es 'jpeg' y la penúltima es una extensión problemÔtica
            if last_two_ext[-1].lower() == 'jpeg' and last_two_ext[-2].lower() in ['gif', 'webp', 'tif', 'tiff']:
                file_format = last_two_ext[-2]

            response = requests.get(self.uri)
        else:
            return

        if response.ok:
            file_content = response.content
            file_data = base64.decodebytes(file_content)

            # PROCESSING IMAGES
            # if file_format in ['png', 'jpg', 'jpeg', 'webp', 'tiff']:
            #     content_type = 'image'
            #     img = Image.open(io.BytesIO(file_data))
            #     img_temp = io.BytesIO()
            #     img.save(img_temp, format=f'{file_format.upper()}')
            #     file = img_temp
            #     tag = 'img'
            #
            #     content = f'<{tag} src="data:{content_type};base64,{base64.b64encode(file.getvalue()).decode("utf-8")}" style="border: 0; width: {img.size[0]}px; height: {img.size[1]}px;" />'
            #     html_content = f'''
            #             <div style="display: flex; justify-content: center; align-items: center; height: 100vh;">
            #                 {content}
            #             </div>'''

            if file_format in ['png', 'jpg', 'jpeg', 'webp', 'tiff', 'tif']:
                mime_types = {
                    'png': 'image/png',
                    'jpg': 'image/jpeg',
                    'jpeg': 'image/jpeg',
                    'webp': 'image/jpeg',
                    'tiff': 'image/tiff',
                    'tif': 'image/tif'
                }

                try:
                    img = Image.open(io.BytesIO(file_data))

                    if file_format == 'webp':
                        img = img.convert("RGB")
                        file_format = 'jpg'

                    img_temp = io.BytesIO()
                    img.save(img_temp, format=f'{file_format.upper()}')
                except Exception:
                    try:
                        # Intentar con imageio
                        if file_format == 'tiff' or file_format == 'tif':
                            img_array = imageio.imread(io.BytesIO(file_data), format='tifffile')
                        elif file_format == 'webp':
                            img_array = imageio.imread(io.BytesIO(file_data))

                        img_temp = io.BytesIO()
                        imageio.imsave(img_temp, img_array, format='JPEG')
                        file_format = 'jpeg'
                    except Exception:
                        # Intentar con OpenCV
                        img_array = cv2.imdecode(np.frombuffer(file_data, np.uint8), -1)

                        # Convertir a RGB si es necesario
                        if len(img_array.shape) == 3 and img_array.shape[2] == 4:
                            img_array = cv2.cvtColor(img_array, cv2.COLOR_BGRA2BGR)

                        _, buffer = cv2.imencode('.jpg', img_array)
                        img_temp = io.BytesIO(buffer)
                        file_format = 'jpeg'

                file = img_temp
                content_type = mime_types.get(file_format, 'image')
                tag = 'img'

                content = f'<{tag} src="data:{content_type};base64,{base64.b64encode(file.getvalue()).decode("utf-8")}" style="border: 0; width: {img.size[0] if "img_array" not in locals() else img_array.shape[1]}px; height: {img.size[1] if "img_array" not in locals() else img_array.shape[0]}px;" />'
                html_content = f'''
                        <div style="display: flex; justify-content: center; align-items: center; height: 100vh;">
                            {content}
                        </div>'''

            # PROCESSING PDFs
            elif file_format == 'pdf':
                content_type = 'application/pdf'
                pdf_temp = io.BytesIO(file_data)
                file = pdf_temp
                tag = 'iframe'

                html_content = f'<{tag} src="data:{content_type};base64,{base64.b64encode(file.getvalue()).decode("utf-8")}" style="border: 0; width: 100%; height: 100vh; allowfullscreen" />'

            # PROCESSING XMLs
            elif file_format == 'xml':
                xml_content = file_data.decode('utf-8')
                formatted_xml = html.escape(xml_content)
                html_content = f'<pre>{formatted_xml}</pre>'

            else:
                raise Warning(f"Lo sentimos el formato {file_format} no esta actualmente soportado para previsualizacion")

        # return {
        #     'name': 'Eventos',
        #     'type': 'ir.actions.act_window',
        #     'res_model': 'crm.lead',
        #     'res_id': self.lead_id.id,
        #     'view_mode': 'form',
        #     'view_type': 'form',
        #     'context': { 'file_preview': html_content },  # si necesitas pasar información adicional
        #     'target': 'new',  # si deseas que se abra en la forma de modal
        # }
        _logger.info(f'Esto voy a retornar: {html_content}')
        return {'html_content': html_content }

Please help me when i call the JS code in my Network application im getting the result ok but nothing happens in the view it is supposed to show it in the Dialog

{jsonrpc: "2.0", id: 905282351, result: {,…}}
id
: 
905282351
jsonrpc
: 
"2.0"
result
: 
{,…}
flags
: 
{}
html_content
: 
"<pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;\r\n&lt;cfdi:Comprobante xmlns:cfdi=&quot;h....;</pre>"
type
: 
"ir.actions.act_window_close"


source https://stackoverflow.com/questions/77025500/not-getting-anything-in-rpc-call-from-js-in-odoo11

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...