From 237842ad549d559241755e7c83b9e2e9a4a3dcce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ram=C3=B3n=20V=C3=A1squez?= <ramon.vasquez@eynes.com.ar>
Date: Thu, 11 Apr 2024 12:39:29 -0300
Subject: [PATCH] [FIX][T3730] Importer

---
 i18n/es_AR.po                              |   4 +-
 models/customer_purchase_order_importer.py | 104 ++++++++-------------
 2 files changed, 41 insertions(+), 67 deletions(-)

diff --git a/i18n/es_AR.po b/i18n/es_AR.po
index b402c4f..d2dd280 100644
--- a/i18n/es_AR.po
+++ b/i18n/es_AR.po
@@ -2871,8 +2871,8 @@ msgstr ""
 #. module: customer_purchase_order
 #: code:addons/customer_purchase_order/models/customer_purchase_order_importer.py:700
 #, python-format
-msgid "~ Product {} with EAN code {} not found.\n"
-msgstr "~ Producto {} con código EAN {} no encontrado.\n"
+msgid "~ Product {} with code {} not found.\n"
+msgstr "~ Producto {} con código {} no encontrado.\n"
 
 #. module: customer_purchase_order
 #: code:addons/customer_purchase_order/models/customer_purchase_order_importer.py:104
diff --git a/models/customer_purchase_order_importer.py b/models/customer_purchase_order_importer.py
index 322cc53..71ef261 100644
--- a/models/customer_purchase_order_importer.py
+++ b/models/customer_purchase_order_importer.py
@@ -66,9 +66,7 @@ class CustomerPurchaseOrderImporter(models.Model):
                 if len(partner) > 1:
                     partner = None
                     msg_list.append(
-                        _(
-                            '~ More than one partner found with EAN code {}.\n'
-                        ).format(partner_ean_code)
+                        _('~ More than one partner found with EAN code {}.\n').format(partner_ean_code)
                     )
                 else:
                     # Product type
@@ -101,17 +99,17 @@ class CustomerPurchaseOrderImporter(models.Model):
                     po_exists = self.purchase_order_exists_for_branch(po_number, branch)
                     if po_exists:
                         msg_list.append(
-                            _(
-                                '~ Purchase order ORD{} already exists for branch {}.\n'
-                            ).format(po_number, branch.name)
+                            _('~ Purchase order ORD{} already exists for branch {}.\n').format(
+                                po_number, branch.name
+                            )
                         )
 
         if partner and branch:
             if not self.vat_matches(partner, branch):
                 msg_list.append(
-                    _(
-                        '~ Partner VAT code ({}) does not match branch VAT code ({}).\n'
-                    ).format(partner.vat, branch.vat)
+                    _('~ Partner VAT code ({}) does not match branch VAT code ({}).\n').format(
+                        partner.vat, branch.vat
+                    )
                 )
 
         # Dates
@@ -255,9 +253,7 @@ class CustomerPurchaseOrderImporter(models.Model):
         purchase_order_number = purchase_order_number.pop() if purchase_order_number else None
 
         purchase_order_down_index = lines[0][496:496].split()
-        purchase_order_down_index = (
-            purchase_order_down_index.pop() if purchase_order_down_index else None
-        )
+        purchase_order_down_index = purchase_order_down_index.pop() if purchase_order_down_index else None
 
         pier = lines[0][497:507].split()
         pier = pier.pop() if pier else None
@@ -377,9 +373,7 @@ class CustomerPurchaseOrderImporter(models.Model):
         line_total_amount = float(line_total_amount.pop()) if line_total_amount else 0.0
 
         additional_line_expense = line[324:339].split()
-        additional_line_expense = (
-            float(additional_line_expense.pop()) if additional_line_expense else 0.0
-        )
+        additional_line_expense = float(additional_line_expense.pop()) if additional_line_expense else 0.0
 
         vat_tax = line[339:347].split()
         vat_tax = float(vat_tax.pop()) if vat_tax else 0.0
@@ -588,9 +582,7 @@ class CustomerPurchaseOrderImporter(models.Model):
             due_date,
         )
         if not start_date_is_earlier:
-            errors.append(
-                _('~ {} cannot be earlier than {}.\n').format(_('Due date'), _('order date'))
-            )
+            errors.append(_('~ {} cannot be earlier than {}.\n').format(_('Due date'), _('order date')))
 
         # Delivery shift date
         _delivery_shift_date = header_data['delivery_shift_date']
@@ -640,7 +632,7 @@ class CustomerPurchaseOrderImporter(models.Model):
             for code in product_codes:
                 config = self.get_config_internal_code(partner.id if partner else None)
 
-                _product = self.get_product(code, config, partner)
+                _product = self.get_product(config, code, partner=partner)
                 product = _product.get('product')
                 if not product:
                     continue
@@ -664,7 +656,7 @@ class CustomerPurchaseOrderImporter(models.Model):
                 _(
                     '~ Product type not found. This is because no product has been found in the '
                     'database with its corresponding code. Without a defined product type, the '
-                    'branch will not be found, even when the branch\'s EAN code was correct.\n'
+                    "branch will not be found, even when the branch's EAN code was correct.\n"
                 )
             )
 
@@ -673,19 +665,19 @@ class CustomerPurchaseOrderImporter(models.Model):
             'errors': errors,
         }
 
-    def get_product(self, product_code, config, partner=None, branch=None, description=''):
+    def get_product(self, config, code, is_ean_code=False, partner=None, description=''):
         CustomerPurchaseOrderConfigLine = self.env['customer.purchase.order.config.line']
         ProductProduct = self.env['product.product']
 
         errors = []
 
-        product = ProductProduct.search([('default_code', '=', product_code)])
+        product = ProductProduct.search(['|', ('barcode', '=', code), ('default_code', '=', code)])
 
-        if product_code and (partner or branch):
+        if code and partner:
             if config:
                 config_line = CustomerPurchaseOrderConfigLine.search(
                     [
-                        ('product_internal_code', '=', product_code),
+                        ('product_internal_code', '=', code),
                         ('customer_purchase_order_config_id', '=', config.id),
                     ]
                 )
@@ -694,9 +686,9 @@ class CustomerPurchaseOrderImporter(models.Model):
                     product = config_line.product
 
         if not product:
-            errors.append(_('~ Product %s with EAN code %s not found.\n') % (description, product_code))
+            errors.append(_('~ Product %s with code %s not found.\n') % (description, code))
         elif len(product) > 1:
-            errors.append(_('~ More than one product found with EAN code %s.\n') % product_code)
+            errors.append(_('~ More than one product found with EAN code %s.\n') % code)
             product = None
 
         return {'product': product, 'errors': errors}
@@ -725,7 +717,7 @@ class CustomerPurchaseOrderImporter(models.Model):
                 config = self.get_config_internal_code(partner.id if partner else None)
 
                 _product = self.get_product(
-                    ean13_code, config, partner, description=product_description
+                    config, ean13_code, is_ean_code=True, partner=partner, description=product_description
                 )
                 if _product.get('errors'):
                     errors.extend(_product.get('errors'))
@@ -903,9 +895,7 @@ class CustomerPurchaseOrderImporter(models.Model):
                 product_id = line[2]['product_id']
                 product = ProductProduct.browse(product_id)
 
-                line[2]['errors'].append(
-                    _('~ Content not set for product {}.\n').format(product.name)
-                )
+                line[2]['errors'].append(_('~ Content not set for product {}.\n').format(product.name))
 
         return vals
 
@@ -921,9 +911,7 @@ class CustomerPurchaseOrderImporter(models.Model):
                 product_id = line[2]['product_id']
                 product = ProductProduct.browse(product_id)
 
-                line[2]['errors'].append(
-                    _('~ Box Quantity not set for product {}.\n').format(product.name)
-                )
+                line[2]['errors'].append(_('~ Box Quantity not set for product {}.\n').format(product.name))
 
         return vals
 
@@ -942,9 +930,7 @@ class CustomerPurchaseOrderImporter(models.Model):
                 product_id = line[2]['product_id']
                 product = ProductProduct.browse(product_id)
 
-                line[2]['errors'].append(
-                    _('~ Box Kilograms not set for product {}.\n').format(product.name)
-                )
+                line[2]['errors'].append(_('~ Box Kilograms not set for product {}.\n').format(product.name))
 
         return vals
 
@@ -1001,11 +987,7 @@ class CustomerPurchaseOrderImporter(models.Model):
             product_uom = line[2]['product_uom']
             units_per_box = line[2]['units_per_box']['original']
 
-            if (
-                product_uom
-                and product_uom == self.env.ref('uom.product_uom_kgm').id
-                and units_per_box
-            ):
+            if product_uom and product_uom == self.env.ref('uom.product_uom_kgm').id and units_per_box:
                 line[2]['box_qty']['modified'] = units_per_box
 
         return vals
@@ -1104,14 +1086,10 @@ class CustomerPurchaseOrderImporter(models.Model):
 
                                 try:
                                     po_vals.update(
-                                        getattr(self, 'get_config_{}_vals'.format(config_type))(
-                                            file_vals
-                                        )
+                                        getattr(self, 'get_config_{}_vals'.format(config_type))(file_vals)
                                     )
                                 except AttributeError:
-                                    _type = CustomerPurchaseOrderConfig._fields[
-                                        'config_type'
-                                    ].selection
+                                    _type = CustomerPurchaseOrderConfig._fields['config_type'].selection
                                     config_type_name = dict(_type).get(config_type)
 
                                     msg_list.insert(0, _('FILE: {}\n').format(_file))
@@ -1119,9 +1097,7 @@ class CustomerPurchaseOrderImporter(models.Model):
                                         _(
                                             '~ No method has been defined for {}. Please contact '
                                             'the developer to fix this issue.\n'
-                                        ).format(
-                                            _('configuration type {}').format(config_type_name)
-                                        )
+                                        ).format(_('configuration type {}').format(config_type_name))
                                         + '\n'
                                     )
                                     not_imported.append(''.join(msg_list))
@@ -1137,19 +1113,15 @@ class CustomerPurchaseOrderImporter(models.Model):
 
         if len(not_imported) > 0:
             msg += (
-                _(
-                    'The following files have errors that need to be corrected before importing '
-                    'them:\n\n'
-                )
-                if manual_import else ''
+                _('The following files have errors that need to be corrected before importing ' 'them:\n\n')
+                if manual_import
+                else ''
             ) + ''.join(sorted(not_imported))
 
             self._create_error_file(rejected_path, msg)
 
         if len(imported) > 0:
-            msg += _(
-                'The following files have been imported successfully:\n'
-            ) + ', '.join(sorted(imported))
+            msg += _('The following files have been imported successfully:\n') + ', '.join(sorted(imported))
 
         self.env.cr.commit()
 
@@ -1168,18 +1140,20 @@ class CustomerPurchaseOrderImporter(models.Model):
         file.write(msg)
         file.seek(0)
 
-        datas = base64.b64encode((file.read()).encode("utf-8"))
+        datas = base64.b64encode((file.read()).encode('utf-8'))
 
         name = _('[{}] Rejected Purchase Order Files').format(today)
         attachment_id = IrAttachment.search([('name', '=', name)])
 
         if not attachment_id:
-            IrAttachment.create({
-                'datas_fname': file_name,
-                'datas': datas,
-                'name': name,
-                'type': 'binary',
-            })
+            IrAttachment.create(
+                {
+                    'datas_fname': file_name,
+                    'datas': datas,
+                    'name': name,
+                    'type': 'binary',
+                }
+            )
         else:
             attachment_id.write({'datas': datas, 'name': name})
 
-- 
GitLab