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

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...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...