diff --git a/sale_order_import_edifact/README.rst b/sale_order_import_edifact/README.rst new file mode 100644 index 0000000000..e5eb5e217c --- /dev/null +++ b/sale_order_import_edifact/README.rst @@ -0,0 +1,137 @@ +=========================================== +Import Business Document EDIFACT/D96A Order +=========================================== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:46860173810e6f096acdc9b7aef8ddd3a5f7cbda5bde91f48aa52f65491a536d + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Alpha-red.png + :target: https://odoo-community.org/page/development-status + :alt: Alpha +.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fedi-lightgray.png?logo=github + :target: https://github.com/OCA/edi/tree/16.0/sale_order_import_edifact + :alt: OCA/edi +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/edi-16-0/edi-16-0-sale_order_import_edifact + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/edi&target_branch=16.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +UN/EDIFACT + United Nations rules for Elec­tronic Data Interchange for Administration, Commerce and Transport + +This module plugs EDIFACT/D96A ORDER in sale_order_import process. + +https://www.stedi.com/edi/edifact/D96A/messages/ORDERS + +.. IMPORTANT:: + This is an alpha version, the data model and design can change at any time without warning. + Only for development or testing purpose, do not use in production. + `More details on development status `_ + +**Table of contents** + +.. contents:: + :local: + +Configuration +============= + + +This module struggles with EDIFACT format, if you need X12 format you will need something like sale_order_import_x12 module. + +Regardless format, a concret document should need a concret specification nammed release. For example Amazon uses "D96A" specification. + +See + +Known issues / Roadmap +====================== + +* Move the previews button feature to the base module + +Changelog +========= + +.. The change log. The goal of this file is to help readers + understand changes between versions. The primary audience is + end users and integrators. Purely technical changes such as + code refactoring must not be mentioned here. + + This file may contain ONE level of section titles, underlined + with the ~ (tilde) character. Other section markers are + forbidden and will likely break the structure of the README.rst + or other documents where this fragment is included. + +14.0.1.0.0 (2023-06-07) +~~~~~~~~~~~~~~~~~~~~~~~ + +* [14.0][ADD] sale_order_import_edifact & base_edifact. + (`#779 `_) + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +~~~~~~~ + +* ALBA Software +* Camptocamp + +Contributors +~~~~~~~~~~~~ + +* Rafa Morant (https://www.albasoft.com) +* Marc Poch +* Duong (Tran Quoc) +* Simone Orsi + +Other credits +~~~~~~~~~~~~~ + +The migration of this module from 14.0 to 16.0 was financially supported by Camptocamp + +Maintainers +~~~~~~~~~~~ + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +.. |maintainer-rmorant| image:: https://github.com/rmorant.png?size=40px + :target: https://github.com/rmorant + :alt: rmorant + +Current `maintainer `__: + +|maintainer-rmorant| + +This module is part of the `OCA/edi `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/sale_order_import_edifact/__init__.py b/sale_order_import_edifact/__init__.py new file mode 100644 index 0000000000..9b4296142f --- /dev/null +++ b/sale_order_import_edifact/__init__.py @@ -0,0 +1,2 @@ +from . import models +from . import wizard diff --git a/sale_order_import_edifact/__manifest__.py b/sale_order_import_edifact/__manifest__.py new file mode 100644 index 0000000000..47ef2a812d --- /dev/null +++ b/sale_order_import_edifact/__manifest__.py @@ -0,0 +1,24 @@ +# Copyright 2023 ALBA Software S.L. +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0) + +{ + "name": "Import Business Document EDIFACT/D96A Order", + "summary": "EDIFACT/D96A Order", + "version": "16.0.1.0.0", + "development_status": "Alpha", + "category": "Sales Management", + "website": "https://github.com/OCA/edi", + "author": "ALBA Software, Camptocamp, Odoo Community Association (OCA)", + "maintainers": ["rmorant"], + "license": "AGPL-3", + "depends": [ + "sale_management", + "partner_identification_gln", + "base_edifact", + "sale_order_import", + ], + "data": [ + "wizard/sale_order_import_view.xml", + ], + "demo": ["demo/demo_data.xml"], +} diff --git a/sale_order_import_edifact/demo/demo_data.xml b/sale_order_import_edifact/demo/demo_data.xml new file mode 100644 index 0000000000..54888b6a79 --- /dev/null +++ b/sale_order_import_edifact/demo/demo_data.xml @@ -0,0 +1,116 @@ + + + + + AMATEST EU SARL + + + 38 Avenue J.F. Kennedy + 1234 + Luxembourg + + + + AMATEST EU (TST) + + 80 Bojsdoeisn + 4321 + Gliwice + + + delivery + + + AMATEST Invoice + + Accountant + + invoice + + + + + + + 5450534000017 + + + + + 5450534008617 + + + + + 5450534008143 + + + + EDIFACT Demo 1 + + consu + edifact1 + + 9783898307529 + + + EDIFACT Demo 2 + + consu + edifac2 + + 9783898307538 + + + EDIFACT Demo 3 + + consu + edifact + + 9783898307645 + + + Product1 + + consu + 1276 + + + + Product2 + + consu + 46630 + + + + Product3 + + consu + 98891 75 + + + + Product4 + + consu + 37230 + + + + Product5 + + consu + 1076 + + + diff --git a/sale_order_import_edifact/models/__init__.py b/sale_order_import_edifact/models/__init__.py new file mode 100644 index 0000000000..d695bc5f59 --- /dev/null +++ b/sale_order_import_edifact/models/__init__.py @@ -0,0 +1 @@ +from . import business_document_import diff --git a/sale_order_import_edifact/models/business_document_import.py b/sale_order_import_edifact/models/business_document_import.py new file mode 100644 index 0000000000..d79ad3c4f6 --- /dev/null +++ b/sale_order_import_edifact/models/business_document_import.py @@ -0,0 +1,57 @@ +# Copyright 2019 PlanetaTIC - Marc Poch +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from odoo import _, api, exceptions, models + + +class BusinessDocumentImport(models.AbstractModel): + _inherit = "business.document.import" + + # TODO: refactor code in partner_identification_import and drop this one + @api.model + def _hook_match_partner(self, partner_dict, chatter_msg, domain, order): + """ + 2 types + partner_dict = {'gln':""} + partner_dict = {'partner': {'gln':""}, 'address':{'country_code':"ES",...}} + """ + partner = partner_dict.get("partner", partner_dict) + partner_dict.get("address", False) + if not partner.get("gln"): + return super()._hook_match_partner(partner_dict, chatter_msg, domain, order) + party_id = partner["gln"] + + partner_id_category = self.env.ref( + "partner_identification_gln.partner_identification_gln_number_category" + ) + if not partner_id_category: + raise exceptions.UserError( + _( + "partner_identification_gln module should be installed with a xmlid: " + "partner_identification_gln_number_category" + ) + ) + id_number = self.env["res.partner.id_number"].search( + [("category_id", "=", int(partner_id_category)), ("name", "=", party_id)], + limit=1, + ) + if not id_number: + ctx = partner.get( + "edi_ctx", {"order_filename": _("Unknown"), "rff_va": _("Unknown")} + ) + raise exceptions.UserError( + _( + "Partner GLN Code: %(party)s not found in order file: '%(file)s' " + "from VAT registration number '%(vat)s'.", + party=party_id, + file=ctx.get("order_filename"), + vat=ctx.get("rff_va"), + ) + ) + + return id_number.partner_id + + # @api.model + # def post_create_or_update(self, parsed_dict, record, doc_filename=None): + # if 'origin_exchange_record_id' in record.fields_get(): + # record.origin_exchange_record_id = diff --git a/sale_order_import_edifact/readme/CONFIGURE.rst b/sale_order_import_edifact/readme/CONFIGURE.rst new file mode 100644 index 0000000000..89cd9f6bde --- /dev/null +++ b/sale_order_import_edifact/readme/CONFIGURE.rst @@ -0,0 +1,6 @@ + +This module struggles with EDIFACT format, if you need X12 format you will need something like sale_order_import_x12 module. + +Regardless format, a concret document should need a concret specification nammed release. For example Amazon uses "D96A" specification. + +See diff --git a/sale_order_import_edifact/readme/CONTRIBUTORS.rst b/sale_order_import_edifact/readme/CONTRIBUTORS.rst new file mode 100644 index 0000000000..ebb246915b --- /dev/null +++ b/sale_order_import_edifact/readme/CONTRIBUTORS.rst @@ -0,0 +1,4 @@ +* Rafa Morant (https://www.albasoft.com) +* Marc Poch +* Duong (Tran Quoc) +* Simone Orsi diff --git a/sale_order_import_edifact/readme/CREDITS.rst b/sale_order_import_edifact/readme/CREDITS.rst new file mode 100644 index 0000000000..a5c8f66b93 --- /dev/null +++ b/sale_order_import_edifact/readme/CREDITS.rst @@ -0,0 +1 @@ +The migration of this module from 14.0 to 16.0 was financially supported by Camptocamp diff --git a/sale_order_import_edifact/readme/DESCRIPTION.rst b/sale_order_import_edifact/readme/DESCRIPTION.rst new file mode 100644 index 0000000000..0874269f06 --- /dev/null +++ b/sale_order_import_edifact/readme/DESCRIPTION.rst @@ -0,0 +1,6 @@ +UN/EDIFACT + United Nations rules for Elec­tronic Data Interchange for Administration, Commerce and Transport + +This module plugs EDIFACT/D96A ORDER in sale_order_import process. + +https://www.stedi.com/edi/edifact/D96A/messages/ORDERS diff --git a/sale_order_import_edifact/readme/HISTORY.rst b/sale_order_import_edifact/readme/HISTORY.rst new file mode 100644 index 0000000000..6d08184cf0 --- /dev/null +++ b/sale_order_import_edifact/readme/HISTORY.rst @@ -0,0 +1,15 @@ +.. The change log. The goal of this file is to help readers + understand changes between versions. The primary audience is + end users and integrators. Purely technical changes such as + code refactoring must not be mentioned here. + + This file may contain ONE level of section titles, underlined + with the ~ (tilde) character. Other section markers are + forbidden and will likely break the structure of the README.rst + or other documents where this fragment is included. + +14.0.1.0.0 (2023-06-07) +~~~~~~~~~~~~~~~~~~~~~~~ + +* [14.0][ADD] sale_order_import_edifact & base_edifact. + (`#779 `_) diff --git a/sale_order_import_edifact/readme/ROADMAP.rst b/sale_order_import_edifact/readme/ROADMAP.rst new file mode 100644 index 0000000000..41d2ef1401 --- /dev/null +++ b/sale_order_import_edifact/readme/ROADMAP.rst @@ -0,0 +1 @@ +* Move the previews button feature to the base module diff --git a/sale_order_import_edifact/static/description/icon.png b/sale_order_import_edifact/static/description/icon.png new file mode 100644 index 0000000000..3a0328b516 Binary files /dev/null and b/sale_order_import_edifact/static/description/icon.png differ diff --git a/sale_order_import_edifact/static/description/icon.svg b/sale_order_import_edifact/static/description/icon.svg new file mode 100644 index 0000000000..a7a26d0932 --- /dev/null +++ b/sale_order_import_edifact/static/description/icon.svg @@ -0,0 +1,79 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + diff --git a/sale_order_import_edifact/static/description/index.html b/sale_order_import_edifact/static/description/index.html new file mode 100644 index 0000000000..070da90458 --- /dev/null +++ b/sale_order_import_edifact/static/description/index.html @@ -0,0 +1,480 @@ + + + + + + +Import Business Document EDIFACT/D96A Order + + + +
+

Import Business Document EDIFACT/D96A Order

+ + +

Alpha License: AGPL-3 OCA/edi Translate me on Weblate Try me on Runboat

+
+
UN/EDIFACT
+
United Nations rules for Elec­tronic Data Interchange for Administration, Commerce and Transport
+
+

This module plugs EDIFACT/D96A ORDER in sale_order_import process.

+

https://www.stedi.com/edi/edifact/D96A/messages/ORDERS

+
+

Important

+

This is an alpha version, the data model and design can change at any time without warning. +Only for development or testing purpose, do not use in production. +More details on development status

+
+

Table of contents

+ +
+

Configuration

+

This module struggles with EDIFACT format, if you need X12 format you will need something like sale_order_import_x12 module.

+

Regardless format, a concret document should need a concret specification nammed release. For example Amazon uses “D96A” specification.

+

See <https://www.stedi.com/edi/edifact>

+
+
+

Known issues / Roadmap

+
    +
  • Move the previews button feature to the base module
  • +
+
+
+

Changelog

+ +
+

14.0.1.0.0 (2023-06-07)

+
    +
  • [14.0][ADD] sale_order_import_edifact & base_edifact. +(#779)
  • +
+
+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • ALBA Software
  • +
  • Camptocamp
  • +
+
+ +
+

Other credits

+

The migration of this module from 14.0 to 16.0 was financially supported by Camptocamp

+
+
+

Maintainers

+

This module is maintained by the OCA.

+Odoo Community Association +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

Current maintainer:

+

rmorant

+

This module is part of the OCA/edi project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+ + diff --git a/sale_order_import_edifact/tests/__init__.py b/sale_order_import_edifact/tests/__init__.py new file mode 100644 index 0000000000..90d50ce03d --- /dev/null +++ b/sale_order_import_edifact/tests/__init__.py @@ -0,0 +1 @@ +from . import test_edifact_order_import diff --git a/sale_order_import_edifact/tests/common.py b/sale_order_import_edifact/tests/common.py new file mode 100644 index 0000000000..3ac0916a85 --- /dev/null +++ b/sale_order_import_edifact/tests/common.py @@ -0,0 +1,90 @@ +# Copyright 2016 Akretion +# @author: Alexis de Lattre ) +# Copyright 2022 Camptocamp +# @author: Simone Orsi +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from functools import partial + +from odoo.tools import DotDict, file_open + + +def _get_file_content(filename): + path = "base_edifact/tests/files/" + filename + with file_open(path, "rb") as fd: + return fd.read() + + +def get_test_data(env): + ref = env.ref + return { + "Retail_EDIFACT_ORDERS_sample1.txt": DotDict( + { + "_get_content": partial( + _get_file_content, "Retail_EDIFACT_ORDERS_sample1.txt" + ), + "client_order_ref": "1AA1TEST", + "date_order": "2023-06-06", + "partner": ref("sale_order_import_edifact.partner_edi_invoiceto_dm"), + "shipping_partner": ref( + "sale_order_import_edifact.partner_edi_shipto_dm" + ), + # "invoicing_partner": ref( + # "sale_order_import_edifact.partner_edi_invoiceto_dm" + # ), + # "currency": ref("base.SEK"), + # "commitment_date": "", + "products": ref("sale_order_import_edifact.product_product_edifact1_dm") + + ref("sale_order_import_edifact.product_product_edifact2_dm") + + ref("sale_order_import_edifact.product_product_edifact3_dm"), + } + ) + } + + +def get_test_data_no_ean_in_lin(env): + ref = env.ref + return { + "test_orders_-_no_ean_in_LIN_segments.txt": DotDict( + { + "_get_content": partial( + _get_file_content, "test_orders_-_no_ean_in_LIN_segments.txt" + ), + "client_order_ref": "467819", + "date_order": "2023-03-20", + "partner": ref("sale_order_import_edifact.partner_edi_shipto_dm"), + "shipping_partner": ref( + "sale_order_import_edifact.partner_edi_shipto_dm" + ), + "products": ref("sale_order_import_edifact.product_product_edifact4_dm") + + ref("sale_order_import_edifact.product_product_edifact5_dm") + + ref("sale_order_import_edifact.product_product_edifact6_dm") + + ref("sale_order_import_edifact.product_product_edifact7_dm") + + ref("sale_order_import_edifact.product_product_edifact8_dm"), + "qty": [12.0, 24.0, 12.0, 24.0, 90.0], + } + ) + } + + +def get_test_data_no_price(env): + ref = env.ref + return { + "test_orders_-_no_PRI_segments.txt": DotDict( + { + "_get_content": partial( + _get_file_content, "test_orders_-_no_PRI_segments.txt" + ), + "client_order_ref": "COM-004017", + "date_order": "2023-03-20", + "partner": ref("sale_order_import_edifact.partner_edi_invoiceto_dm"), + "shipping_partner": ref( + "sale_order_import_edifact.partner_edi_shipto_dm" + ), + "products": ref("sale_order_import_edifact.product_product_edifact1_dm") + + ref("sale_order_import_edifact.product_product_edifact2_dm") + + ref("sale_order_import_edifact.product_product_edifact3_dm"), + "price": [1.0, 1.0, 1.0], + } + ) + } diff --git a/sale_order_import_edifact/tests/test_edifact_order_import.py b/sale_order_import_edifact/tests/test_edifact_order_import.py new file mode 100644 index 0000000000..c9138b2252 --- /dev/null +++ b/sale_order_import_edifact/tests/test_edifact_order_import.py @@ -0,0 +1,109 @@ +# Copyright 2023 ALBA Software S.L. +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0) + +import base64 + +from odoo.tests.common import TransactionCase +from odoo.tools import mute_logger + +from .common import get_test_data, get_test_data_no_ean_in_lin, get_test_data_no_price + + +class TestEdifactOrderImport(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) + + @mute_logger("odoo.addons.sale_order_import.wizard.sale_order_import") + def test_edifact_order_import(self): + tests = get_test_data(self.env) + for filename, expected in tests.items(): + edifact_file = expected._get_content() + wiz = self.env["sale.order.import"].create( + { + "import_type": "edifact", + "order_file": base64.b64encode(edifact_file), + "order_filename": filename, + } + ) + action = wiz.import_order_button() + so = self.env["sale.order"].browse(action["res_id"]) + self.assertEqual(so.partner_id, expected["partner"]) + + if expected.get("client_order_ref"): + self.assertEqual(so.client_order_ref, expected["client_order_ref"]) + + if expected.get("shipping_partner"): + self.assertEqual(so.partner_shipping_id, expected["shipping_partner"]) + if expected.get("invoicing_partner"): + self.assertEqual(so.partner_invoice_id, expected["invoicing_partner"]) + + if expected.get("products"): + expected_ids = sorted(expected["products"].ids) + self.assertEqual( + sorted(so.order_line.mapped("product_id").ids), expected_ids + ) + + @mute_logger("odoo.addons.sale_order_import.wizard.sale_order_import") + def test_edifact_order_import_no_ean_in_lin(self): + tests = get_test_data_no_ean_in_lin(self.env) + for filename, expected in tests.items(): + edifact_file = expected._get_content() + wiz = self.env["sale.order.import"].create( + { + "import_type": "edifact", + "order_file": base64.b64encode(edifact_file), + "order_filename": filename, + } + ) + action = wiz.import_order_button() + so = self.env["sale.order"].browse(action["res_id"]) + self.assertEqual(so.partner_id, expected["partner"]) + + if expected.get("client_order_ref"): + self.assertEqual(so.client_order_ref, expected["client_order_ref"]) + + if expected.get("shipping_partner"): + self.assertEqual(so.partner_shipping_id, expected["shipping_partner"]) + + if expected.get("products"): + expected_ids = sorted(expected["products"].ids) + self.assertEqual( + sorted(so.order_line.mapped("product_id").ids), expected_ids + ) + self.assertEqual( + so.order_line.mapped("product_uom_qty"), expected["qty"] + ) + self.assertEqual( + so.order_line.mapped("name")[0], "Product1 description" + ) + + @mute_logger("odoo.addons.sale_order_import.wizard.sale_order_import") + def test_edifact_order_import_no_price(self): + tests = get_test_data_no_price(self.env) + for filename, expected in tests.items(): + edifact_file = expected._get_content() + wiz = self.env["sale.order.import"].create( + { + "import_type": "edifact", + "order_file": base64.b64encode(edifact_file), + "order_filename": filename, + } + ) + action = wiz.import_order_button() + so = self.env["sale.order"].browse(action["res_id"]) + self.assertEqual(so.partner_id, expected["partner"]) + + if expected.get("client_order_ref"): + self.assertEqual(so.client_order_ref, expected["client_order_ref"]) + + if expected.get("shipping_partner"): + self.assertEqual(so.partner_shipping_id, expected["shipping_partner"]) + + if expected.get("products"): + expected_ids = sorted(expected["products"].ids) + self.assertEqual( + sorted(so.order_line.mapped("product_id").ids), expected_ids + ) + self.assertEqual(so.order_line.mapped("price_unit"), expected["price"]) diff --git a/sale_order_import_edifact/wizard/__init__.py b/sale_order_import_edifact/wizard/__init__.py new file mode 100644 index 0000000000..e0ddf6156f --- /dev/null +++ b/sale_order_import_edifact/wizard/__init__.py @@ -0,0 +1 @@ +from . import sale_order_import diff --git a/sale_order_import_edifact/wizard/sale_order_import.py b/sale_order_import_edifact/wizard/sale_order_import.py new file mode 100644 index 0000000000..d67a5c6574 --- /dev/null +++ b/sale_order_import_edifact/wizard/sale_order_import.py @@ -0,0 +1,276 @@ +import json +import logging +import os +from base64 import b64decode +from collections import defaultdict + +from odoo import _, api, fields, models +from odoo.exceptions import UserError + +logger = logging.getLogger(__name__) + + +class SaleOrderImport(models.TransientModel): + _inherit = "sale.order.import" + + import_type = fields.Selection( + selection_add=[("edifact", "EDIFACT")], ondelete={"edifact": "cascade"} + ) + # Make doc_type field support for EDIFACT type + doc_type = fields.Selection(readonly=False) + # TODO: Move this feature to the base module or to an additional module. + json_data_preview = fields.Text( + help="Used by the btn `button_parse_order_preview` to preview data before importing" + ) + edifact_ok = fields.Boolean(compute="_compute_edifact_ok") + # Techincal fields used to get the extension part of files + file_ext = fields.Char(default="txt,d96a") + # EDIFACT format release + release = fields.Char(default="d96a") + + @api.depends("order_file", "order_filename") + def _compute_edifact_ok(self): + for rec in self: + if not (rec.order_file and rec.order_filename): + rec.edifact_ok = False + continue + extensions = rec.file_ext.split(",") + path, ext = os.path.splitext(self.order_filename) + ok = ext and ext[1:] in extensions + if not ok: + ok = b64decode(self.order_file[:4]) in (b"UNA", b"UNB") + rec.edifact_ok = ok + + # TODO: Move this feature to the base module or to an additional module. + def button_parse_order_preview(self): + """ + Generate a preview of the data before importing. + + This method is called by the button to take a quick look at the pydifact + structure ('edifact' type) and the parsed object ('order') from + the original document before importing the document. + """ + + self.ensure_one() + edifact_model = self.env["base.edifact"] + order_file_decoded = b64decode(self.order_file) + parsed_obj = dict(edifact=None, order=None) + if self.edifact_ok: + parsed_obj["edifact"] = edifact_model.pydifact_obj(order_file_decoded) + + parsed_order = self.parse_order( + order_file_decoded, self.order_filename, self.partner_id + ) + del parsed_order["attachments"] + parsed_obj["order"] = parsed_order + self.write( + { + "json_data_preview": json.dumps(parsed_obj, indent=4, default=str), + } + ) + action = self.env["ir.actions.act_window"]._for_xml_id( + "sale_order_import.sale_order_import_action" + ) + action["res_id"] = self.id + return action + + def _get_supported_types(self): + # Add more types for EDIFACT + res = super()._get_supported_types() + res.update({"edifact": ("text/plain", None)}) + return res + + @api.model + def parse_edifact_order(self, filecontent, detect_doc_type=False): + # https://github.com/nerdocs/pydifact/blob/master/pydifact/segmentcollection.py + if detect_doc_type: + if not self.edifact_ok: + return None + return self.env.context.get("default_doc_type", "rfq") + + edifact_model = self.env["base.edifact"] + interchange = edifact_model._loads_edifact(filecontent) + header = interchange.get_header_segment() + # > UNB segment: [['UNOA', '2'], ['5450534000000', '14'], + # ['8435337000003', '14'], ['230306', '0435'], '5506'] + + msg_type, msg_type_release = edifact_model._get_msg_type(interchange) + supported = ["ORDERS"] + if msg_type not in supported: + raise UserError(_("%s document is not a Sale Order document")) + + bgm = interchange.get_segment("BGM") + # Customer PO number + # BGM segment: ['220', '1LP6WZGF', '9'] + order_ref = bgm[1] + + rd = { + "doc_type": self.doc_type, + # Customer PO number + "order_ref": order_ref, + "edi_ctx": {"sender": header[1], "recipient": header[2]}, # header[1][0] + } + parties = self._prepare_edifact_parties(interchange) + order_dict = { + **rd, + **self._prepare_edifact_dates(interchange), + **self._prepare_edifact_currencies(interchange), + **parties, + } + lines = self._prepare_edifact_lines(interchange) + if lines: + order_dict["lines"] = lines + return order_dict + + @api.model + def _prepare_edifact_parties(self, interchange): + references = self._prepare_edifact_references(interchange) + parties = self._prepare_edifact_name_and_address(interchange) + if references.get("vat") and parties.get("invoice_to"): + # just for check vat + if parties["invoice_to"].get("partner"): + parties["invoice_to"]["partner"]["rff_va"] = references["vat"] + if parties.get("invoice_to") and parties["invoice_to"].get("partner"): + newpartner = parties["invoice_to"]["partner"].copy() + if parties.get("partner") and parties["partner"].get("gln"): + # To see if NAD_BY is different NAD_IV + newpartner["gln_by"] = parties["partner"]["gln"] + parties["partner"] = newpartner + # add context information + for pval in parties.values(): + partner_dict = pval.get("partner", pval) + partner_dict["edi_ctx"] = { + "order_filename": self.order_filename, + } + if references.get("vat"): + partner_dict["edi_ctx"]["rff_va"] = references["vat"] + if parties.get("company"): + parties["company"]["edi_ctx"]["vendor_code"] = references.get("vendor_code") + return parties + + @api.model + def _prepare_edifact_dates(self, interchange): + dates = defaultdict(dict) + edifact_model = self.env["base.edifact"] + for seg in interchange.get_segments("DTM"): + date_meaning_code = seg[0][0] + if date_meaning_code == "137": + dates["date"] = edifact_model.map2odoo_date(seg[0]) + elif date_meaning_code == "63": + # latest delivery date + # dates.setdefault("delivery_detail",{}) + dates["delivery_detail"]["validity_date"] = edifact_model.map2odoo_date( + seg[0] + ) + elif date_meaning_code == "64": + # earliest delivery date + dates["delivery_detail"][ + "commitment_date" + ] = edifact_model.map2odoo_date(seg[0]) + + return dates + + @api.model + def _prepare_edifact_references(self, interchange): + """ + RFF segment: [['CR', 'IK142']] + """ + refs = {} + for seg in interchange.get_segments("RFF"): + reference = seg[0] + reference_code = reference[0] + if reference_code == "ADE": + # ['firstorder','backorder','advantage','nyp'] + refs["account_reference"] = reference[1] + elif reference_code == "CR": + # Customer reference Number + refs["vendor_code"] = reference[1] + elif reference_code == "PD": + # Promotion Deal Number + # Number assigned by a vendor to a special promotion activity + refs["promotion_number"] = reference[1] + elif reference_code == "VA": + # Unique number assigned by the relevant tax authority to identify a + # party for use in relation to Value Added Tax (VAT). + refs["vat"] = reference[1] + + return refs + + @api.model + def _prepare_edifact_name_and_address(self, interchange): + nads = {} + edifact_model = self.env["base.edifact"] + for seg in interchange.get_segments("NAD"): + reference_code = seg[0] + if reference_code == "BY": + # NAD segment: ['BY', ['5450534001649', '', '9']] + # Customer (Buyer's GLN) + nads["partner"] = edifact_model.map2odoo_partner(seg) + elif reference_code == "SU": + # Our number of Supplier's GLN + # Can be used to check that we are not importing the order + # in the wrong company by mistake + nads["company"] = edifact_model.map2odoo_partner(seg) + elif reference_code == "DP": + # Delivery Party + nads["ship_to"] = edifact_model.map2odoo_address(seg) + elif reference_code == "IV": + # Invoice Party + nads["invoice_to"] = edifact_model.map2odoo_address(seg) + return nads + + @api.model + def _prepare_edifact_currencies(self, interchange): + currencies = {} + edifact_model = self.env["base.edifact"] + for seg in interchange.get_segments("CUX"): + usage_code = seg[0] + if usage_code == "2": + currencies["currency"] = edifact_model.map2odoo_currency(seg) + return currencies + + @api.model + def _prepare_edifact_lines(self, interchange): + edifact_model = self.env["base.edifact"] + lines = [] + pia_list = [] + qty_list = [] + pri_list = [] + imd_list = [] + + for i in interchange.get_segments("PIA"): + if i[1][1] == "SA": + pia_list.append(i) + for i in interchange.get_segments("QTY"): + if i[0][0] == "21": + qty_list.append(i) + for i in interchange.get_segments("PRI"): + pri_list.append(i) + for i in interchange.get_segments("IMD"): + if i[1] == "79": + imd_list.append(i) + + for linseg in interchange.get_segments("LIN"): + + piaseg = pia_list.pop(0) if pia_list else None + qtyseg = qty_list.pop(0) if qty_list else None + priseg = pri_list.pop(0) if pri_list else None + imdseg = imd_list.pop(0) if imd_list else None + + line = { + "sequence": int(linseg[0]), + "product": edifact_model.map2odoo_product(linseg, piaseg), + "qty": edifact_model.map2odoo_qty(qtyseg), + } + + price_unit = edifact_model.map2odoo_unit_price(priseg) + # If the product price is not provided, the price will be taken from the system + if price_unit != 0.0: + line["price_unit"] = price_unit + description = edifact_model.map2odoo_description(imdseg) + if description: + line["name"] = description + + lines.append(line) + + return lines diff --git a/sale_order_import_edifact/wizard/sale_order_import_view.xml b/sale_order_import_edifact/wizard/sale_order_import_view.xml new file mode 100644 index 0000000000..a1d1bda221 --- /dev/null +++ b/sale_order_import_edifact/wizard/sale_order_import_view.xml @@ -0,0 +1,34 @@ + + + + sale.order.import.form.dev + sale.order.import + + + + + {'readonly': [('import_type','!=','edifact')]} + +
+ + + +
+ + +
+
+
diff --git a/setup/sale_order_import_edifact/odoo/addons/sale_order_import_edifact b/setup/sale_order_import_edifact/odoo/addons/sale_order_import_edifact new file mode 120000 index 0000000000..59ca90b132 --- /dev/null +++ b/setup/sale_order_import_edifact/odoo/addons/sale_order_import_edifact @@ -0,0 +1 @@ +../../../../sale_order_import_edifact \ No newline at end of file diff --git a/setup/sale_order_import_edifact/setup.py b/setup/sale_order_import_edifact/setup.py new file mode 100644 index 0000000000..28c57bb640 --- /dev/null +++ b/setup/sale_order_import_edifact/setup.py @@ -0,0 +1,6 @@ +import setuptools + +setuptools.setup( + setup_requires=['setuptools-odoo'], + odoo_addon=True, +)