scieee AI-readable full text Open interactive document viewer

Odoo and SPS commerce integration

Coll Bernabé, Ferran

Abstract

In the last decades, more and more companies need to adapt to the new complex and demanding market in order to keep up the pace with their competitors. The alternative most of them is opting for, is the implementation of an ERP software to manage all the information flow generated in each area or department of the organization. At the same time, no one can discuss that a globalization process has progressively been taking place, which has led to companies searching for paperless techniques that ease the communication between buyer and seller companies. This is when EDI plays an important role as it enables to carry on certain operations and transactions that would otherwise have been impossible. This project aims to provide an integration of these two time-saving concepts, which can help a company to automize all their business workflow, sparing them of labor. Not only will these reduce the amount of time spent in the management of a single document, but it will also increase security and minimize all kind of errors in document management.

Full text

ODOO & SPS COMMERCE INTEGRATION A Degree Thesis submitted to the Barcelona School of Telecommunications Engeneering Universitat Politècnica de Catalunya by Ferran Coll Bernabé In partial fulfilment of the requirements for the degree in Enginyeria de Tecnologies i Serveis de Telecomunicació Advisors: Marcel Fernández Muñóz Jordi Ballester Alomar Barcelona, 11th of September 2021 1 Abstract In the last decades, more and more companies need to adapt to the new complex and demanding market in order to keep up the pace with their competitors. The alternative most of them is opting for, is the implementation of an ERP software to manage all the information flow generated in each area or department of the organization. At the same time, no one can discuss that a globalization process has progressively been taking place, which has led to companies searching for paperless techniques that ease the communication between buyer and seller companies. This is when EDI plays an important role as it enables to carry on certain operations and transactions that would otherwise have been impossible. This project aims to provide an integration of these two time-saving concepts, which can help a company to automize all their business workflow, sparing them of labor. Not only will these reduce the amount of time spent in the management of a single document, but it will also increase security and minimize all kind of errors in document management. 2 Acknowledgements I would like to thank my supervisor Jordi Ballester Alomar for all his help and advices during the initial training weeks as well as for the opportunity to undertake this project at ForgeFlow. I would also like to thank Lois Rilo Antelo for his patience and for providing me technical support which was crucial in the development of the project. I also appreciate the support I received from my workmate Raúl Ortiz Sanz, who also partially took part on this project and was really helpful. Finally, but not least, I would like to express gratitude to my university advisor, Marcel Fernández Muñoz. 3 Revision history and approval record Revision Date Purpose 0 19/04/2021 Document creation 1 04/10/2021 Document revision 2 11/10/2021 Document approval DOCUMENT DISTRIBUTION LIST Name e-mail Ferran Coll Bernabé Marcel Fernández Muñoz Jordi Ballester Alomar Written by: Reviewed and approved by: Date 19/04/2021 Date 11/10/2021 Name Ferran Coll Bernabé Name Marcel Fernandez Muñoz Position Project Author Position Project Supervisor 4 Table of contents Abstract .......................................................................................................................................................................... 1 Acknowledgements ................................................................................................................................................... 2 Revision history and approval record ............................................................................................................... 3 Table of contents ........................................................................................................................................................ 4 List of figures ................................................................................................................................................................ 6 List of Tables ................................................................................................................................................................ 7 1. Introduction ........................................................................................................................................................ 8 1.1. Motivation .................................................................................................................................................. 8 1.2. Statement of purpose ............................................................................................................................ 8 1.3. Methods and procedures ..................................................................................................................... 8 1.4. Company and customer ........................................................................................................................ 9 1.5. Initial plan deviations and incidences ............................................................................................ 9 2. State of the art of the technology used or applied in this thesis: ............................................... 10 2.1. ERP ............................................................................................................................................................. 10 2.2. e-Commerce and EDI .......................................................................................................................... 11 3. System introduction ..................................................................................................................................... 12 3.1. Odoo .......................................................................................................................................................... 12 3.1.1. Odoo definition ............................................................................................................................ 12 3.1.2. Odoo ecosystem .......................................................................................................................... 12 3.1.3. Odoo architecture ...................................................................................................................... 14 3.1.4. Modular structure ...................................................................................................................... 15 3.1.4.1. Module components................................................................................................................. 16 4. Module development ................................................................................................................................... 22 4.1. Contextualization ................................................................................................................................. 22 4.1.1. Business flow ............................................................................................................................... 22 4.1.2. Context ............................................................................................................................................ 23 4.2. EDI Module ............................................................................................................................................. 24 4.3. Elements involved ............................................................................................................................... 25 4.3.1. Backend .......................................................................................................................................... 25 4.3.2. Backend type ................................................................................................................................ 25 4.3.3. Exchange record ......................................................................................................................... 25 4.3.3.1. Output exchange records ....................................................................................................... 25 5 4.3.3.2. Input exchange records .......................................................................................................... 26 4.3.4. Exchange Type ............................................................................................................................. 26 4.4. Components ........................................................................................................................................... 27 4.4.1.1. Basic Components ..................................................................................................................... 27 4.4.1.2. Listeners ....................................................................................................................................... 31 4.5. EDI Storage Module............................................................................................................................. 32 4.6. Scheduled actions or cron jobs ....................................................................................................... 33 4.7. Application to the module ................................................................................................................ 33 4.7.1. Workflow ....................................................................................................................................... 33 4.7.2. EDI messages ............................................................................................................................... 33 4.7.3. UBL format .................................................................................................................................... 34 4.7.3.1. Base UBL module ...................................................................................................................... 36 4.7.4. Module scheduled actions ...................................................................................................... 36 4.7.5. Different EDI flows .................................................................................................................... 37 4.7.5.1. Product catalogue ..................................................................................................................... 37 4.7.5.2. Sale Order ..................................................................................................................................... 38 4.7.5.3. Invoice ........................................................................................................................................... 39 4.7.5.4. Delivery ......................................................................................................................................... 39 4.7.6. Data introduction ....................................................................................................................... 40 5. Results ................................................................................................................................................................ 41 6. Budget ................................................................................................................................................................ 42 7. Conclusions and future development ................................................................................................... 43 Bibliography .............................................................................................................................................................. 45 Appendices ................................................................................................................................................................. 47 A Customer requirements table .................................................................................................................. 47 a. Order ................................................................................................................................................................... 47 b. Invoice ................................................................................................................................................................ 49 c. Advanced Shipping Notifications ............................................................................................................ 50 B UBL resulting files ......................................................................................................................................... 51 C UBL resulting files ......................................................................................................................................... 51 Glossary: ...................................................................................................................................................................... 52 6 List of figures Figure 1: ERP basic modules overview [19] ................................................................................................ 10 Figure 2: EDI vs Traditional Data Interchange [21] .................................................................................. 11 Figure 3: Odoo Ecosystem [3] ............................................................................................................................ 12 Figure 4: Odoo Architecture [6] ........................................................................................................................ 14 Figure 5: Application menu ................................................................................................................................. 15 Figure 6: Basic Odoo Model skeleton of a module called product [7] ............................................... 16 Figure 7: __init__.py file of the product module [7] .................................................................................... 16 Figure 8: __manifest__.py file of the product module [7] ......................................................................... 18 Figure 9: product.category.py module file [7] ............................................................................................. 19 Figure 10: part of a list view definition of the product.template model .......................................... 20 Figure 11: part of the product_data.xml file where product categories are created ................... 20 Figure 12:part of the ir.model.access.csv of the product module ....................................................... 21 Figure 13: Basic business flow (vendor) ....................................................................................................... 22 Figure 14: SPS Commerce transaction dashboard including invoices, orders... ........................... 23 Figure 15: More detailed business flow with external intermediary platforms ........................... 24 Figure 16: EDI module icon [10] ....................................................................................................................... 24 Figure 17: Definition of the base receiving and processing components ........................................ 29 Figure 18: Input component example for processing sale orders ...................................................... 30 Figure 19:Output component example for generating invoices .......................................................... 30 Figure 20: Model definition with a method that triggers and event notification ......................... 32 Figure 21: Listener component associated with the edi.product.catalogue model ..................... 32 Figure 22: Part of an EDI purchase order message example [18] ....................................................... 34 Figure 23: Piece of a UBL xml where the seller is specified................................................................... 35 Figure 24: EDI Scheduled Actions view in Odoo ........................................................................................ 37 Figure 25: edi.product.catalogue model and attribute definition ....................................................... 37 Figure 26: Call to the sale.order.import wizard function in SO processing component ............ 39 Figure 27: Automatized workflow ................................................................................................................... 40 7 List of Tables Table 1: Relation between EDI and UBL messages ................................................................................... 35 Table 2: Budget table ............................................................................................................................................. 42 Table 3: Sale Order UBL requirements for the customer ....................................................................... 48 Table 4: Invoice UBL requirements for the customer .............................................................................. 50 Table 5: Advanced Shipping Notifications UBL requirements for the customer .......................... 51 8 1. Introduction 1.1. Motivation The globalization process that is progressively taking place over the last two decades, has broaden the market possibilities for businesses. Consequently, companies are starting to look for any kind of tool that turn their business into competitive ones. For many of them, this is achieved through the use of Enterprise Resource Planning software (ERP), which is extremely helpful to manage their business data within a centralized and integrated system; improving their performance and efficiency. The same way as ERP, EDI which stands for Electronic Data Interchange and considered the core of electronic commerce, has also made great strides in the last years, helping to reduce time and cost during standard and traditional document exchanges. In an immediate-based society as the nowadays one, businesses need to be as swift as possible if they do not want to lose the race against their competitors. The use of either ERP or EDI can help them to achieve this goal; however, what about using these two technologies at once? 1.2. Statement of purpose This degree thesis consists on designing and building a system that allows to integrate the Odoo ERP with the supply chain management software SPS Commerce using EDI. This integration has to allow companies using Odoo to exchange data with certain logistic suppliers through the SPS Commerce platform. In order to fulfill the aim of this project, it is important to first master the Odoo software both, technically and functionally, so as to be able to understand the EDI but more precisely focused on using it inside an ERP software. 1.3. Methods and procedures This work is not the continuation of another project, but it actually uses an in-development software as basis. The software is an Odoo module called EDI, which as it names says, tries to implement the EDI technique within the Odoo environment. It was deployed in its 13.0 version in December 2020 by Simone Orsi and Enric Tobella, and currently maintained by the OCA (Odoo Community Association). 15 Figure 5: Application menu 3.1.4. Modular structure In the past sections it has been stated that new modules or applications can be added to the basic ones of the Odoo Core. So, in order to understand the module this thesis is based on, it is preferable to deepen on the concept of module as well as its structure. Modules are those different functionalities that can be installed and uninstalled from the current database and that can apply both, visual and functional modifications, to the existing applications or even to other modules depending on the goal. The general structure of a module is clearly defined by a set of Odoo rules, and is based on a directory structure that should contain very specific files for its correct working (Figure 6). Basically, an Odoo module is a directory that contains code files and other assets and whose technical name comes from the actual name of the directory. The basic skeleton of a module can be seen in the following figure, containing the most frequently used directories: 16 Figure 6: Basic Odoo Model skeleton of a module called product [7] As it can be seen, firstly, there is a main directory called product (which is going to be the technical name of the module), followed by a set of sub-directories in charge of different actions that will be further explained in the following section 3.1.4.1. 3.1.4.1. Module components • __init__.py: In order for the directory to be a module instead of a simple folder it needs to be a Python executable, thus, this file contains imports to all the wanted .py files and code subdirectories. These subdirectories also containing Python code, in turn, need their own __init__.py file. In the example from above, the __init__.py file would look the following way: # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from . import models from . import report from . import wizard Figure 7: __init__.py file of the product module [7] 17 • __manifest__.py: The manifest is an important piece for Odoo modules, since it contains important metadata about the add-on module and declares the data files that should be loaded. The content in the manifest file is a regular Python dictionary, with keys and values. The example manifest in Figure 8 contains the most relevant keys: o name: module’s title o version: this is the module’s version number, which starts with the Odoo’s version (Odoo 13 in our case), followed by the version of the module. o category: represents the area of interest the module belongs to, such as Invoicing, Sales, Human Resources, Marketing… o depends: list of all the technical names of the modules it directly depends on (also known as dependencies). Notice that if your module does not exactly depend on another, it is necessary to add at least the base one. This list ensures that all the dependencies are installed when trying to install this module; if not, the dependencies will be automatically installed together with the module. o data: list of all the relative paths (to the module root directory) for the data files to load during the module installation or update. These files normally tend to be XML or CSV formatted containing the user interface, fixture data and module access rules. These files will be further explained when talking about the data and view folders later on in this section. o demo: list of relative paths for the files containing demonstration data to load. 18 • Models: before commenting the structure of the models’ sub-directory, it is first going to be explained what a model exactly is. Models are those who define an object and all their attributes and methods. In this case the attributes are named fields in the Odoo slang. These definitions handle directly or through the ORM with the database. Since Odoo is Python-based, models are represented as Python classes (Figure 9). In order to define a new model, it is first crucial to import from the Odoo library those needed objects to generate a basic model: models and fields. The first one will be inherited when creating the Python class, and the second one will be used to create as many fields as wanted in the model. Once the header of the class has been defined, there are some private attributes that can be defined and that will determine the model structure; three of the most relevant ones are: • _name: name of the model. If the name contains more than one word, each of them needs to be separated by dots. For instance, in the example below, the module is named “product.category”. This attribute is mandatory except in the cases where the _inherit attribute takes a value, since the name of the model will automatically be set to the same as the inherited module. # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Products & Pricelists', 'version': '1.2', 'category': 'Sales/Sales', 'depends': ['base', 'mail', 'uom'], 'description': 'Base module for managing Odoo products and pricelists' 'data': [ 'data/product_data.xml', 'security/product_security.xml', 'security/ir.model.access.csv', 'wizard/product_price_list_views.xml', 'views/product_views.xml', 'views/product_pricelist_views.xml', 'views/res_partner_views.xml', 'report/product_reports.xml', ], 'demo': [ 'data/product_demo.xml', ], 'installable': True, 'auto_install': False, 'license': 'LGPL-3', } Figure 8: __manifest__.py file of the product module [7] 19 • _description: a more detailed description the user will read when trying to install the module. • _inherit: indicates from which existing module/s does it inherit from On the other hand, after these protected attributes, any other field can be defined which, depending on the kind of information it defines, can be classified the following way: • Basic fields: store simple data types such as integer, float, boolean, char or string. • Advanced fields: store more complex data types ranging from date/datetime, binary, html to relational fields. The latter allow the model to establish 3 different types of relations with other models, whose name are actually quite self-explanatory. o Many2one: instances (also known as records) of a first model can be related with a single record of a second model. In the field definition the relational model needs to be specified as the first argument. o One2many: is the complementary relation of the Many2one, since one record of the first model can be related to several records of the second model. o Many2many: records of a first model can be related to multiple records of the second model. The database follows a relational model, which means that data is represented in a table that has relations between the data of the same table or even with other tables as well. No sooner a new model is defined with its corresponding fields, than a new table is created in the database, whose columns will correspond to each of the attributes and each row to each of the different records of the model. Back to the module directory itself, it contains the backend code files, thus creating the models and their business logic. One file per model is recommended with the same name as the model, for example, product_template.py for the product.template model. from odoo import fields, models class ProductCategory(models.Model): _name = "product.category" _description = "Product Category" _parent_name = "parent_id" name = fields.Char('Name', index=True, required=True) parent_id = fields.Many2one('product.category', 'Parent Category) parent_path = fields.Char(index=True) child_id = fields.One2many('product.category', 'parent_id') product_count = fields.Integer(compute='_compute_product_count') Figure 9: product.category.py module file [7] 20 • Views: they define how records should be displayed to end-users. Basically, we can find the XML files for the user interface, with the actions, forms, lists, and so on. Like models, it is advised to have one file per model. • Data: contains other XML files which are used to provide the module's initial data in its installation as a sample to the user (Figure 11). • Demo: contains data files with demonstration data, which is useful for tests, training, or module evaluation. The main difference with the data directory is that these files will not be used in a real production scenario, while the ones in data could perfectly be used for those cases. <?xml version="1.0" encoding="utf-8"?> <odoo> <record id="product_template_tree_view" model="ir.ui.view"> <field name="name">product.template.product.tree</field> <field name="model">product.template</field> <field name="arch" type="xml"> <tree string="Product" multi_edit="1" sample="1"> <field name="product_variant_count" invisible="1"/> <field name="sale_ok" invisible="1"/> <field name="currency_id" invisible="1"/> <field name="cost_currency_id" invisible="1"/> . . . <field name="active" invisible="1"/> <field name="activity_exception_decoration"/> </tree> </field> </record> </odoo> Figure 10: part of a list view definition of the product.template model <?xml version="1.0" encoding="utf-8"?> <odoo> <data noupdate="1"> <record id="product_category_all" model="product.category"> <field name="name">All</field> </record> <record id="product_category_1" model="product.category"> <field name="parent_id" ref="product_category_all"/> <field name="name">Saleable</field> </record> </data> </odoo> Figure 11: part of the product_data.xml file where product categories are created 21 Notice that in the data file, there is an optional no-update flag, which, if set to true, allows the module to only load the data the first time the module is installed, instead of each time it is upgraded. • Security: contains the data files that define access control lists, and possibly an XML file to define access groups and record rules for row-level security. Each user is assigned to one group, which may or not have access to some modules. This restriction is set by the ir.model.access.csv file, which defines the reading, writing and creating permissions for each group in that module. If the flag is set to one that group is allowed to perform that action, while if it is set to 0, it is not. Figure 12:part of the ir.model.access.csv of the product module • I18n: is the directory where Odoo will look for the translation .pot and .po files, which contain all the translatable strings as well as their translation to different languages. • Wizard: a wizard is the same as a model, but for the fact that it is created inheriting the models.TransientModel object instead of the models.Model one, so its records are periodically cleaned up in the database, hence the name transient. These are used to create dialog boxes, which are filled in the user interface and are generally used to perform actions on the persistent records of the database, so it can be said that wizards are used to hold intermediate data. • Tests: this sub-package contains files used for testing the models’ added functionalities. There are three kinds of test in Odoo: Python unit tests, JS unit tests and Tours. However, in this thesis since there is no developed JavaScript code, the only testing alternative used is the first one, which allows testing the model business logic. 22 4. Module development Once the Odoo system architecture and the structure of modules has been detailed and is clear enough, it is time to go into detail with the custom module this thesis is based on. 4.1. Contextualization First of all, it is important to define the customer’s business flow, as well as to contextualize which was the reason that led to the development of this module. 4.1.1. Business flow In every company, the business flow is the process in which tasks in a business take place. It represents the steps from the beginning to the end that ensure that the company objectives and goals are met. The customer takes the role of a vendor in this context, and its business flow follows the structure of Figure 13. For instance, when one of the clients buys a product, from one side it is seen as a purchase order (PO), but from the customer’s side it is seen as a sale order (SO). This sale order is registered in the Sales application of Odoo. Therefore, from this order, both, the customer invoice and the delivery order can be created, which will respectively be recorded in the Accounting and Inventory applications. The invoice is first sent to the customer and, once it has been paid, the product delivery finally takes place. Now the question is: how does the purchase order arrive to the Odoo system? The answer is simple: it does not arrive. Customers use external supply chain management platforms as intermediary, such as SPS Commerce and NemEDI (Figure 14). This means that the customer Figure 13: Basic business flow (vendor) 23 makes the purchase order to another platform which is not actually Odoo. Therefore, this order information needs to be manually introduced in Odoo from scratch. Figure 14: SPS Commerce transaction dashboard including invoices, orders... 4.1.2. Context The main idea was to develop a module to speed up some of the customer basic sales, invoicing and delivery procedures. Two of their biggest regular customers were using SPS Commerce to manage all the flow; so, each time a sale order came into SPS, workers had to introduce it back manually in Odoo. For instance, if a big sale order came into SPS Commerce, not only had they to introduce individually each product line in Odoo, but also check whether the prices, discounts, delivery dates… were matching between the two platforms; which took over to 15- 20min to the responsible to manage just a single sale order. Furthermore, they also had to manually control the remaining stages of the business: invoice, delivery… which was extremely time-consuming. This module basically provides automatization for all the business flow. Therefore, it implies some modifications to the basic workflow explained before (Figure 15). 24 4.2. EDI Module There is already a semi-developed module in Odoo which can partly solve this issue, called EDI (Figure 16). Its aim is to provide an infrastructure to simplify interchangeability of documents between systems providing a configuration platform. It will be inherited by other modules in order to define the proper and customized implementations of components, so we can take advantage of the basic functionalities this module provides, and implement them properly in our own module implementation. This module was in an alpha version when this project started in February, so it has been evolving using this thesis as a test, thus, several changes to the original version have been proposed, as well as some errors have been solved. Since this module conforms the foundation this thesis is based on, it is first important to give a detailed explanation of its different features and how do they work. Figure 16: EDI module icon [10] Figure 15: More detailed business flow with external intermediary platforms 31 4.4.1.2. Listeners There is also a specific type of component called listener, which is waiting for a certain event to happen. Several points can be established in the code where a notification is sent to any listener paying attention to them. These notifications are sent using events, which are the constructs that enable a class to notify other classes when something of interest takes place. Events are normally used while working with user interfaces where different elements need to be signaled of some occurrence. The notifications are sent by using the following command: A listener containing a method called “on_action_done” will be detected, thus, his code will be executed. However, there may be more than one listener with the same function name; this is when the _apply_on_ before mentioned protected attribute plays an important role, since it contains a list of all the models that the listener will be paying attention to. Therefore, if a model that is not in the _apply_on list triggers a notification, the listener will ignore it, no matter if the listener actually contains a method with the same name as the notification event. Moreover, this component is differentiated from the order by the inheritance of the base.event.listener, which provides the component with all the listener features. Definitely, listeners will manage all the EDI flow and there are normally two of them: output and input listeners, which will manage the output and input steps in section 4.3.3 respectively. Figures 20 and 21 exemplify how the relation between a model and a listener component should be done. The first figure shows the model definition of a product catalogue, but it is only highlighted the send_product_button() method, which triggers an event with “on_send_product” as key word. Complementarily, Figure 21 shows the listener code, where the inheritance of the base listener component is done, as well as the insertion of the edi.product.catalogue model to the _apply__on list. It also appears the on_send_product() method whose code will be executed since it is matching with the key word of the event. self._event("on_action_done").notify(self) 32 4.5. EDI Storage Module A second module from the EDI repository is used, called EDI Storage, which allows exchanging files using storage backends. This module adds a storage backend relation on the EDI Backend, where the server absolute paths where to read or put files can be configured. In this module the SFTP storage backend will be used since it is a better protocol for managing files than HTTP, which was another protocol alternative. When exchanging files by SFTP, output and input folders are used to send and receive files respectively. On the basis of this, the EDI Storage module requires the following directory subdivision: - Input/output folder - Pending: contains files that have just been sent - Done: contains files that have been successfully processed - Error: contains files with errors and cannot be processed The storage handler takes care of reading and posting files in the right place and updating the exchange records data accordingly. class EdiProductCatalogue(models.Model): _name = "edi.product.catalogue" . . . def send_product_button(self): self._event("on_send_product").notify(self) Figure 20: Model definition with a method that triggers and event notification class EdiProductListenerOutput(Component): _name = "edi.product.listener.output" _inherit = "base.event.listener" _apply_on = "edi.product.catalogue" def on_send_product(self, record): . . . Figure 21: Listener component associated with the edi.product.catalogue model 33 4.6. Scheduled actions or cron jobs It has before been stated how the exchange records flow is managed by components. However, notice that this still requires labor at least to trigger the first step. This is the reason why schedulers or cron jobs are used, automated actions that run automatically within specified time ranges and without requiring manual interaction, which turns them into really advantageous features. These scheduled actions are managed with the Job Queue module, which delays model methods in asynchronous jobs, executed in the background as soon as possible or on a schedule according to the queue capacity. This also allows capturing arguments for later processing. These scheduled actions can also be manually run for testing purposes so as not to wait for the next iteration to trigger them. 4.7. Application to the module 4.7.1. Workflow The developed module takes advantages and makes use of all the features and possibilities of the already presented modules, following the expected workflow from the customer which can be divided in 4 clear steps: 1. The customer sends Product Catalogues to SPS Commerce/NemEDI 2. The customer receives Purchase Orders from SPS Commerce/NemEDI 3. The customer sends Advance Shipping Notifications to SPS Commerce/NemEDI 4. The customer sends Invoices to SPS Commerce/NemEDI This whole process will be partly automatized by the use of crons, which will be constantly looking at the SFTP server in order to retrieve a document each time a file gets uploaded from the other side, as well as will be paying attention if there is any possible file to send to the SFTP from our side. 4.7.2. EDI messages In information exchange processes between two parts, it is really important to establish a convention in certain aspects, one of which has been crucial for this project development: the file format. 34 The Electronic Data Interchange presents many different business documents represented by a transaction code. These messages can be exchanged with trading partners and other partners using EDI. However, it is not that easy to manage EDI files since they present a quite abstract and not trivial inner structure as it can be seen in Figure 22. Nevertheless, SPS is a platform that works and manages this kind of messages since it includes pre-built EDI maps that are fully automated. This allows us to work with the file format that we want, and perform a mapping between our format and the EDI one, turning EDI messages into something much more understandable. 4.7.3. UBL format Among all the possible formats that could have been selected, the chosen one has been UBL, standing for Universal Business Language from OASIS, which is an open and royalty-free library of standard XML business document types. The standardization of these documents allows the user to customize the xml at its convenience but always following the structure that the document index summary indicates, as the final content is always checked against the document constraints with a set of validation tools. All the fields appearing in the xml are preceded either by cbc or cac, acronyms for Common Basic Component and Common Aggregate Component, which are the two elements that conform the whole UBL. The first one corresponds to simple fields such as a name or a street, while the second one references more complex elements that can be broken down into further structures: cbc or even more cac. See Figure 23 to clearly see this differentiation and a piece of UBL code. ISA*01*0000000000*01*0000000000*ZZ*ABCDEFGHIJKLMNO*ZZ*123456789012345*> GS*PO*4405197800*999999999*20101127*1719*1421*X*004010VICS ST*850*000000010 BEG*00*SA*08292233294**20101127*610385385 REF*DP*038 REF*PS*R ITD*14*3*2**45**46 DTM*002*20101214 PKG*F*68***PALLETIZE SHIPMENT PKG*F*66***REGULAR TD5*A*92*P3**SEE XYZ RETAIL ROUTING GUIDE Figure 22: Part of an EDI purchase order message example [18] 35 The reason why UBL has been chosen is because it provides business related elements as cac:SellerSupplierParty, cac:BuyerCustomerParty, cac:Delivery or cbc:TaxID for instance, which are really helpful and indicative when creating an xml file from scratch, not leading to confusions of where to locate certain data. The UBL documents needed for accomplishing the workflow of section 4.7.1, appear in the following chart as well as its mapping to EDI format: Action to perform EDI Message UBL Document Send product catalogue EDI 832 UBL-Catalog-2.1 Receive purchase order EDI 850 UBL-Order-2.1 Send shipping notification EDI 856 UBL-DespatchAdvice-2.1 Send invoice EDI 810 UBL-Invoice-2.1 Table 1: Relation between EDI and UBL messages In the output files (all except the order), SPS Commerce indicated us the required fields they needed in order to validly create the records in their system, and we specified them the UBL paths where we were going to locate those required fields. On the other hand, in the input documents, they designated us the fields that they were going to send and we showed them the paths where we would like to receive those fields. A requirements table of all the EDI messages can be found in section A of the appendices. <cac:SellerSupplierParty> <cac:Party> <cac:PartyIdentification> <cbc:ID>SellerPartyID123</cbc:ID> </cac:PartyIdentification> <cac:PartyName> <cbc:Name>Moderna Produkter AB</cbc:Name> </cac:PartyName> <cac:PostalAddress> <cbc:StreetName>Kungsgatan</cbc:StreetName> <cbc:BuildingNumber>22</cbc:BuildingNumber> <cbc:CityName>Stockholm</cbc:CityName> <cbc:PostalZone>11000</cbc:PostalZone> <cac:Country> <cbc:IdentificationCode>SE</cbc:IdentificationCode> </cac:Country> </cac:PostalAddress> </cac:Party> <cac:SellerSupplierParty> Figure 23: Piece of a UBL xml where the seller is specified 36 4.7.3.1. Base UBL module There is an OCA module which works with UBL language and that provides a set of basic methods for both, generating and parsing UBL documents. It is done by defining a new model called base.ubl, which is thought to be inherited as it is an AbstractModel. Notice that the methods this model implements are only the ones that are shared between all the UBL documents, such as adding an item, an address location… 4.7.4. Module scheduled actions The concept of scheduled actions has already been discussed, so let’s focus on the actual scheduled actions of the project and what is their task. For this module to properly work, only three configured actions are needed (Figure 24): • EDI backend storage check pending input: it basically makes a call to the edi_storage method named _storage_cron_check_pending_input(), which is in charge of looking at the SFTP server, and create an exchange record in Odoo for all the files located in the pending folder, with its name in the Exchange Filename field but without downloading it. • EDI exchange input status: this second action is the one that follows the latter and triggers the _cron_check_input_exchange_sync() action of the edi model. It is basically in charge of receiving and processing the file that is still in the server. For all the exchange records that have “Waiting to be received” as state, it takes its Exchange Filename field, downloads a file from the server with that exact name, and associates it with the exchange record(Exchange File field). At this point, the state of the exchange record turns into “Waiting to be processed” as we only have an exchange with a file linked to it, but not an Odoo record. Therefore, for all the exchanges that are waiting to be processed, it parses the associated file and creates an Odoo record with its data. • EDI Exchange check status: while the other two crons are used in the receiving process, this last one makes a call to the _cron_check_output_exchange_sync() action of the edi module in order to carry on the sending stage. It looks for all the “Waiting to be send” exchange records and puts in the SFTP server the file associated with them. We have seen two scheduled actions in the receiving process: one for creating the exchange record and a second for receiving and processing the file. On the other hand, we have seen one action in the sending process in charge of sending the file to the server. Now someone could ask: how are the output exchange records created if there is no scheduled action for it? The 37 answer is that each time an invoice is posted and a delivery is confirmed (which means click on the post and validate buttons), apart from performing the normal Odoo tasks, it also creates an exchange record containing a file with the record data. Figure 24: EDI Scheduled Actions view in Odoo 4.7.5. Different EDI flows In this section it will be described with detail each of the steps of the workflow by analyzing the models, views and components that are used, whose code can be found in section C of the appendices. 4.7.5.1. Product catalogue The first and initial step is sending the product catalogue to SPS Commerce so the customers know all the available customer products. There are some already existing models in Odoo such as pricelists (product.pricelist) whose concept and idea takes after a catalogue, but they are not the exact thing we need . So the only remaining alternative is to create a completely new model to manage pricelists: edi.product.catalogue. The goal of this new model (Figure 25) is to create a catalogue for each customer (many2one partner_id field) containing a list of the specific products that concrete customer can buy (many2many item_ids). Notice that the catalogue model inherits the base.ubl model, in order to be able to use its basic methods when creating the UBL-ProductCatalogue document. class EdiProductCatalogue(models.Model): _name = "edi.product.catalogue" _inherit = ["base.ubl", "edi.exchange.consumer.mixin"] _description = "EDI Product Catalogue" name = fields.Char("Catalogue Name", required=True, translate=True) item_ids = fields.Many2many("product.product") partner_id = fields.Many2one("res.partner", string="Partner") company_id = fields.Many2one("res.company", "Company",) backend_id = fields.Many2one( string="EDI backend", comodel_name="edi.backend", ) Figure 25: edi.product.catalogue model and attribute definition 38 When clicking at the “Send Catalogue” button defined in the views, a new event will be notified with the key word “on_send_product” and the on_send_product() method of the product catalogue listener (edi.product.listener.output) will be executed. This method will perform 3 things: 1. Search for an adequate backend, first by backend_type and if more than one possible backend is detected, it performs a second search by exchange_type. 2. Create an empty exchange record and associates the Odoo catalogue record with it. 3. Generates the xml file from the record data and associates it with the exchange. This third step basically makes a call to the exchange_generate() function from the edi module which searches for components with output.generate as _usage, and executes its overwritten generate() function. This function uses the different UBL generating methods specifically implemented in the edi.product.catalogue model, as well as the basic ones from the base.ubl inherited model. Finally, once the scheduled action is run, the file will be sent to the SFTP server. 4.7.5.2. Sale Order The first and second scheduled actions of section 4.7.4 will create a new exchange record, receive the file from the server and process it. The processing of the file will be done by a sale order component (edi.input.process.order.ubl) and its process() method. Yet, there is no associated record, so the parsing functions of the model cannot be used in this case. However, we can take advantage of the fact that wizards are transient models and that its data is removed after a period of time. It can be created a wizard (sale.order.import) that contains all the parsing functions, and that ends up returning a sale order record with those parsed values. Despite it may not seem the best option as two records need to be created in order to generate a sale order, it should be reminded that the sale.order.import one will be deleted after some time. In output scenarios, at the second step of the above section, an exchange record is being created, and the model and unique identifier of the Odoo record are indicated so as to be linked up. However, in input scenarios this cannot be done at the beginning since there is no Odoo record created, so it is performed at the end of the process() method. 39 As mentioned, SPS designated the fields that they were going to send some of which didn’t actually had a field created in Odoo since they were really specific, thus, a sale order model (sale.order) and a partner model (res.partner) inheriting the original ones have been created, where those new fields can be defined and added to the already existing ones. For instance, internal SPS customer and transaction references needed to be stored in the partners model, so the sps_customer_vendor_code and sps_transaction_code fields have been defined in the models and added in the partner views. 4.7.5.3. Invoice Once the order has been entered in Odoo, the invoice is automatically created from that sale order. When the invoice content is checked and verified, it can be confirmed by clicking at the “Post” button, which will trigger the same flow as the product catalogue: the listener (edi.invoice.listener.output) will search for a backend, create an empty exchange record and associate it with the invoice, while the output component (edi.invoice.output.generate) will generate the xml file using the model (account.move) UBL generating functions. 4.7.5.4. Delivery Idem to the invoice and product catalogue, except for the minor change that the flow is triggered when the “Validate” button is clicked. In this case the model corresponding to deliveries is named stock.picking. class EdiOrderProcess(Component): _name = "edi.input.process.order.ubl" _inherit = "edi.component.input.mixin" _description = "Processes UBL Order (ISO 850)" _usage = "input.process" _backend_type = "gubi_ubl" _exchange_type = "order_in" def process(self): file_content = self.exchange_record._get_file_content() xml_root = etree.fromstring(file_content) so = self._parse_xml_file(xml_root) self.exchange_record.write({"model": "sale.order", "res_id": so.id}) def _parse_xml_file(self, xml_root): return self.env["sale.order.import"].parse_ubl_sale_order(xml_root) Figure 26: Call to the sale.order.import wizard function in SO processing component 40 4.7.6. Data introduction In order to make the module more user-friendly, some data has been set to be registered during the module installation. There are basically three different xml defined files: edi_backend_type_data.xml, edi_backend_data.xml and edi_exchange_type.xml; whose names are quite self-explanatory, as they are used to define an initial EDI configuration set including the backend, the backend type and the exchange type definitions. The order in which their relative paths appear in the manifest is important since some records reference others, so the backend type needs to be firstly defined since it is independent to the others, secondly the backend and finally the exchange type. The initial configuration set defined is an SPS Commerce Backend Type, an SPS Commerce Backend with the corresponding SPS Backend Type associated, and finally all the exchange types needed in the workflow for invoices, output product catalogues, deliveries and input sale orders. After all, the workflow has gone from the manual basic one explained in section 4.1.1, to an automatized one as it can be seen in Figure 27. Figure 27: Automatized workflow 47 Appendices A Customer requirements table The following tables are the customer requirements regarding the information it is expected to be sent (b and c) or received (a) in the files. It is indicated the UBL path where to locate the information, as well as a brief description of the field. In this case only the minimum and mandatory ones appear in the table, as they are required to perform certain operations and searches in the database. This means that extra ones can be added if more information wants to be provided. a. Order Order 2.1 UBL field path Description Header fields (Order data fields) M cbc:ID Order number assigned by the sender M cbc:IssueDate Order date M cbc:DocumentCurrencyCode Currency of the document Order Parties Buyer M cac:BuyerCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID VAT Number M cac:BuyerCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID Name of the tax VAT Seller M cac:SellerSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID VAT Number M cac:SellerSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxScheme/cbc:ID Name of the tax Delivery M cac:Delivery/cac:DeliveryAddress/cbc:StreetName Delivery street name M cac:Delivery/cac:DeliveryAddress/cbc:CityName Delivery City Name M cac:Delivery/cac:DeliveryAddress/cbc:PostalZone Delivery ZIP code M cac:Delivery/cac:DeliveryAddress/cbc:CountrySubentity Delivery province or state 48 M cac:Delivery/cac:DeliveryAddress/cac:Country/cbc:IdentificationCode Delivery country code M cac:Delivery/cac:RequestedDeliveryPeriod/cbc:EndDate Date on which the requested delivery period ends Transaction Conditions M cac:TransactionConditions/cbc:Description Purchasing or sales conditions applying to the whole order Total M cac:TaxTotal/cbc:TaxAmount + attribute currencyID Total tax amount M cac:AnticipatedMonetaryTotal/cbc:TaxExclusiveAmount + attribute currencyID Total order tax exclusive M cac:AnticipatedMonetaryTotal/cbc:PayableAmount + attribute currencyID Total order amount Order Lines M cac:OrderLine/cac:LineItem/cbc:ID Line number M cac:OrderLine/cac:LineItem/cbc:Quantity + attribute unitCode Ordered quantity M cac:OrderLine/cac:LineItem/cbc:LineExtensionAmount + attribute currencyID Total amount for this line item, including allowances but net of taxes M cac:OrderLine/cac:LineItem/cbc:TotalTaxAmount + attribute currencyID The total tax amount for this line item M cac:OrderLine/cac:LineItem/cac:Price/cbc:PriceAmount + attribute currencyID Unit price M cac:OrderLine/cac:LineItem/cac:Price/cbc:BaseQuantity + attribute unitCode Base quantity for unit price M cac:OrderLine/cac:LineItem/cac:Item/cac:SellersItemIdentification/cbc:ID SKU or Item identification number Table 3: Sale Order UBL requirements for the customer 49 b. Invoice Invoice 2.1 UBL field Description Header fields (Invoice data fields) M cbc:ID Invoice number M cbc:IssueDate The date, assigned by the sender, on which this document was issued M cbc:DocumentCurrencyCode A code signifying the default currency for this document Invoice Parties Seller (Vendor) M cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc: CompanyID VAT Number M cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cac: Tax Scheme/cbc:Name Name of the tax Payer (Customer) M cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cbc :CompanyID VAT Number M cac:AccountingCustomerParty/cac:Party/cac:PartyTaxScheme/cac: Tax Scheme/cbc:Name Name of the tax Payment Means M cac:PaymentMeans/cbc:PaymentMeansCode + listID attribute A code signifying the type of means of payment M cac:PaymentMeans/cbc:PaymentDueDate The date on which payment is due for this means of payment TOTAL M cac:TaxTotal/cbc:TaxAmount + attribute currencyID Total tax amount M cac:LegalMonetaryTotal/cbc:TaxExclusiveAmount + attribute currencyID Total amount invoiced tax exclusive M cac:LegalMonetaryTotal/cbc:PayableAmount + attribute currencyID Total amount invoiced tax inclusive Invoice Lines M cac:InvoiceLine/cbc:ID Line number M cac:InvoiceLine/cbc:InvoicedQuantity + attribute unitCode The quantity (of items) in this invoice line 50 M cac:InvoiceLine/cbc:LineExtensionAmount + attribute currencyID The total amount for this invoice line, including allowance charges but net of taxes M cac:InvoiceLine/cac:OrderLineReference/cbc:LineID An identifier for the referenced order line, assigned by the buyer M cac:InvoiceLine/cac:OrderLineReference/cac:OrderReference/cbc: SalesOrderID An identifier for this order reference, assigned by the seller M cac:InvoiceLine/cac:TaxTotal/cbc:TaxAmount + attribute currencyID A total amount of taxes of a particular kind applicable to this invoice line M cac:InvoiceLine/cac:Item/cac:SellersItemIdentification/cbc:ID Identifying information for this item, assigned by the seller M cac:InvoiceLine/cac:Price/cbc:PriceAmount + attribute currencyID Item unit price M cac:InvoiceLine/cac:Price/cbc:BaseQuantity + attribute unitCode The quantity at which this price applies Table 4: Invoice UBL requirements for the customer c. Advanced Shipping Notifications Despatch Advice 2.1 UBL field path Description Header fields (ASN data fields) M cbc:ID Despatch advice assigned by the sender M cbc:IssueDate Despatch advice date Order reference M cac:OrderReference/cbc:ID Order that originated the despatch advice Order Parties Buyer M cac:DeliveryCustomerParty/cac:Party/cac:PartyTaxScheme/cbc:Compan yID VAT Number M cac:DeliveryCustomerParty/cac:Party/cac:PartyTaxScheme/cac:TaxSche me/cbc:ID Name of the tax VAT Seller M cac:DespatchSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:Compan yID VAT Number M cac:DespatchSupplierParty/cac:Party/cac:PartyTaxScheme/cac:TaxSche me/cbc:ID Name of the tax 51 Shipment M cac:Shipment/cbc:ID Tracking reference Delivery Address M cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:StreetName Delivery street name M cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:CityName Delivery City Name M cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:PostalZone Delivery ZIP code M cac:Shipment/cac:Delivery/cac:DeliveryAddress/cbc:CountrySubentity Delivery province or state M cac:Shipment/cac:Delivery/cac:DeliveryAddress/cac:Country/cbc:Identi ficationCode Delivery country code M cac:Shipment/cac:Delivery/cac:RequestedDeliveryPeriod/cbc:EndDate Date on which the requested delivery period ends Delivery Terms M cac:Shipment/cac:Delivery/cac:DeliveryTerms/cbc:ID Terms and conditions applied to the delivery Despatch Lines M cac:DespatchLine/cbc:ID Line number M cac:DespatchLine/cbc:DeliveredQuantity + attribute unitCode Delivered quantity M cac:DespatchLine/cac:Item/cac:SellersItemIdentification/cbc:ID Identifying information for this item, assigned by the seller Table 5: Advanced Shipping Notifications UBL requirements for the customer B UBL resulting files The resulting and definitive files for each process of the workflow can be found in on this GitHub account [1]. C UBL resulting files As well as the sample UBL files, the project code can be found in this GitHub account [1]. 52 Glossary: ERP – Enterprise Resource Planning, is a software that allow companies to integrate the management of the different areas of the business and to control all their information flow. EDI – Electronic Data Interchange, an interactive electronic system that enables supplier and customer to electronically communicate information that was traditionally communicated on paper. e-commerce – Electronic Commerce, refers to buying or selling items or services and transferring the money and data using Internet. B2B – Business to Business, refers to all the transactions done between two different companies B2C – Business to Customer, refers to all the transaction done between a company and an individual consumer. SFTP – Secure File Transfer Protocol, is a network protocol that provides file acces, file transfer and file management over any data stream. HTTP – Hypertext Transfer Protocol, is a protocol that articulates the exchange of information between Web clients and HTTP Servers such as Apache. GNU GPL – GNU General Public License, is intended to guarantee the freedom to share and change all versions of a software; to make sure it remains free for all its users. ORM – Object-relational mapping, is a programming technique that allows to map the structures from a relational model database into a logical structure of entities using objectoriented programming languages. OCA – Odoo Community Association, is an organization whose aim is to support the community development of Odoo features and promote its use. OCR – Optical Character Recognition, is a software that transform into strings the text contained in an image.