DEV Community

Jeevachaithanyan Sivanandan
Jeevachaithanyan Sivanandan

Posted on

3

Odoo: Import CSV file and write into sale order lines

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
antonov_mike profile image
Antonov Mike

Dude, thanks a lot for your articles, but use Markdown please

class Markdown
    # It's much easier to
    # read code that way
Enter fullscreen mode Exit fullscreen mode

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay