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

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...

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

Where and how is this Laravel kernel constructor called? [closed]

Where and how is this Laravel kernel constructor called? public fucntion __construct(Application $app, $Router $roouter) { } I have read the documentation and some online tutorial but I can find any clear explanation. I am learning Laravel and I am wondering where does this kernel constructor receives its arguments from. "POSTMOTERM" CLARIFICATION: Here is more clarity.I have checked the boostrap/app.php and it is only used for boostrapping the interfaces into the container class. What is not clear to me is where and how the Kernel class is instatiated and the arguments passed to the object calling the constructor.Something similar to; obj = new kernel(arg1,arg2) or, is the framework using some magic functions somewhere? Special gratitude to those who burn their eyeballs and brain cells on this trivia before it goes into a full blown menopause alias "MARKED AS DUPLICATE". To some of the itchy-finger keyboard warriors, a.k.a The mods,because I believe in th...