Odoo: Import CSV file and write into sale order lines

Jeevachaithanyan Sivanandan - Oct 28 - - Dev Community

Odoo: Import CSV file and write into sale order lines

The method features:

  1. read an imported csv file
  2. check some validations
  3. write the values from the csv file into the sale order line and sale order
    def action_import_csv(self):

        if not self.file_name or not self.file_name.lower().endswith('.csv'):
            raise UserError("Invalid file format! Please upload a CSV file.")

        try:
            csv_data = base64.b64decode(self.csv_file_upload).decode('utf-8')
            csv_reader = csv.DictReader(StringIO(csv_data))
        except Exception:
            raise UserError("Failed to read CSV file. Ensure the file is properly formatted.")

        sale_order = self.get_current_sale_order()

        partner_id = None  
        updated_lines = {}  

        for i, row in enumerate(csv_reader):

            if i == 0:
                row_partner_id = int(row.get("Partner ID", 0) or 0)
                partner_id = row_partner_id

                if sale_order.partner_id.id != partner_id:
                    raise UserError("The Partner ID in the CSV does not match the Sale Order's Partner.")
            elif row.get("Partner ID"):
                raise UserError("Only the first row should contain a Partner ID. Subsequent rows should leave this field empty.")

            sku = row.get("Product ID", "").strip()
            quantity = float(row.get("Product Quantity", 0))

            if not sku:
                raise UserError("Product ID (SKU) is missing in one of the rows.")

            product = self.env['product.product'].search([('default_code', '=', sku)], limit=1)
            if not product:
                raise UserError(f"Product with SKU {sku} not found in the system.")


            sale_order_line = self.env['sale.order.line'].create({
                'order_id': sale_order.id,
                'product_id': product.id,
                'product_uom_qty': quantity,
            })
            updated_lines[sku] = quantity

        sale_order.write({
            'partner_invoice_id': sale_order.partner_id.address_get(['invoice'])['invoice'],
            'partner_shipping_id': sale_order.partner_id.address_get(['delivery'])['delivery'],
        })

        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player