size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
3,725
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools.misc import groupby class AccountMove(models.Model): _inherit = "account.move" @api.constrains("line_ids") def _check_split_lines(self): lines = self.line_ids.filtered("discount_split_by_sale_line_id") if lines: groups = groupby(lines, key=type(lines)._get_split_line_group_key) if groups and any(len(recs) != 2 for key, recs in groups): raise ValidationError( _( "The lines you have created/deleted/modified are" " linked some other ones in the Sale Order.\n" "Please create/delete/modify both lines." ) ) @api.model def _move_autocomplete_invoice_lines_create(self, vals_list): return super()._move_autocomplete_invoice_lines_create( [self._update_vals_with_discount_lines(v) for v in vals_list] ) @api.model def _update_vals_with_discount_lines(self, move_vals: dict) -> dict: invoice_line_vals = move_vals.get("invoice_line_ids") if not invoice_line_vals: return move_vals # We're creating a new invoice: at this point, ``invoice_line_ids`` # should be an iterable of # (fields.Command.CREATE, virtual_ID or False-ish, {line values}) # triplets, because lines too should be created anew. If it's not , # then there must be something wrong at the root of this process. if any(cmd[0] != fields.Command.CREATE for cmd in invoice_line_vals): raise ValueError("Unexpected invoice line values: %s" % invoice_line_vals) inv_line_vals = [] for __, __, line_vals in move_vals["invoice_line_ids"]: discount_line_vals = {} sale_line_id = line_vals.get("discount_split_by_sale_line_id") if sale_line_id: sol = self.env["sale.order.line"].browse(sale_line_id) discount_line_vals = line_vals.copy() line_vals = self._update_line_vals_from_discounted_sale_line( line_vals, sol ) discount_line_vals = ( self._update_discount_line_vals_from_discounted_sale_line( discount_line_vals, sol ) ) inv_line_vals.append((0, 0, line_vals)) if discount_line_vals: inv_line_vals.append((0, 0, discount_line_vals)) move_vals.update({"invoice_line_ids": inv_line_vals}) return move_vals @api.model def _update_line_vals_from_discounted_sale_line( self, line_vals: dict, sale_line: models.Model ) -> dict: return dict( line_vals, price_unit=sale_line.origin_price_unit, is_split_line=True, ) @api.model def _update_discount_line_vals_from_discounted_sale_line( self, discount_line_vals: dict, sale_line: models.Model ) -> dict: product_id = discount_line_vals["product_id"] product = self.env["product.product"].browse(product_id) account = product.product_tmpl_id.get_product_accounts()["discount"] return dict( discount_line_vals, account_id=account.id, price_unit=sale_line.price_unit - sale_line.origin_price_unit, name=_("Discount on %s") % discount_line_vals["name"], is_split_line=True, is_split_discount_line=True, )
40.934066
3,725
530
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductCategory(models.Model): _inherit = "product.category" property_account_discount_categ_id = fields.Many2one( "account.account", company_dependent=True, string="Discount Account", domain="['&', ('deprecated', '=', False), ('company_id', '=', current_company_id)]", help="This account will be used when validating a customer invoice.", )
35.333333
530
792
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" discount_split_by_sale_line_id = fields.Many2one("sale.order.line", copy=False) is_split_line = fields.Boolean() is_split_discount_line = fields.Boolean() @property def _split_lines_group_fields(self) -> tuple: return "move_id", "discount_split_by_sale_line_id", "quantity" def _get_split_line_group_key(self) -> tuple: self.ensure_one() fnames = self._split_lines_group_fields data = self.read(fnames, load=0)[0] # Returned tuple must be ordered like the grouping field names return tuple(data[f] for f in fnames)
34.434783
792
2,662
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" origin_price_unit = fields.Float(digits="Product Price") def _prepare_invoice_line(self, **optional_values): res = super()._prepare_invoice_line(**optional_values) if self._do_split_discount(): res["discount_split_by_sale_line_id"] = self.id return res def _do_split_discount(self): self.ensure_one() return ( self.company_id.account_split_discount_line and self.currency_id.compare_amounts( self.origin_price_unit, self.price_unit ) == 1 ) @api.depends( "invoice_lines.move_id.state", "invoice_lines.quantity", "untaxed_amount_to_invoice", ) def _compute_qty_invoiced(self): # OVERRIDE: take into account the new line for discount in the invoice. # Since the two lines (price and discount) are linked to the same sale # line, we avoid taking into account the discount line (or we would # have doubled the invoiced qty). res = super(SaleOrderLine, self)._compute_qty_invoiced() for line in self: if line.origin_price_unit: qty_invoiced = 0.0 for invoice_line in line._get_invoice_lines(): if ( invoice_line.move_id.state != "cancel" or invoice_line.move_id.payment_state == "invoicing_legacy" ): if ( invoice_line.move_id.move_type == "out_invoice" and not invoice_line.is_split_discount_line ): qty_invoiced += ( invoice_line.product_uom_id._compute_quantity( invoice_line.quantity, line.product_uom ) ) elif ( invoice_line.move_id.move_type == "out_refund" and not invoice_line.is_split_discount_line ): qty_invoiced -= ( invoice_line.product_uom_id._compute_quantity( invoice_line.quantity, line.product_uom ) ) line.qty_invoiced = qty_invoiced return res
40.333333
2,662
786
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" property_account_discount_id = fields.Many2one( "account.account", company_dependent=True, string="Discount Account", domain="['&', ('deprecated', '=', False), ('company_id', '=' current_company_id)]", help="Keep this field empty to use the default value from the product category.", ) def _get_product_accounts(self): res = super()._get_product_accounts() res["discount"] = ( self.property_account_discount_id or self.categ_id.property_account_discount_categ_id ) return res
34.173913
786
356
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" account_split_discount_line = fields.Boolean( "Split Discount Lines", default=False, # Do not set to True, else Odoo/OCB tests will fail )
27.384615
356
507
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" account_split_discount_line = fields.Boolean( "Split Discount Lines", help="If set, a discounted sale line will be split in 2 invoice lines" " when the invoice is generated", related="company_id.account_split_discount_line", readonly=False, )
31.6875
507
596
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Order General Discount", "summary": "General discount per sale order", "version": "15.0.1.0.0", "development_status": "Production/Stable", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale"], "data": ["views/sale_order_view.xml", "views/res_partner_view.xml"], }
37.25
596
4,525
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo.tests import TransactionCase class TestSaleOrderLineInput(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create( {"name": "Test", "sale_discount": 10.0} ) cls.contact = cls.env["res.partner"].create( { "name": "Contact Test", "parent_id": cls.partner.id, "type": "contact", } ) cls.product = cls.env["product.product"].create( {"name": "test_product", "type": "service"} ) cls.order = cls.env["sale.order"].create( { "partner_id": cls.partner.id, "order_line": [ ( 0, 0, { "name": cls.product.name, "product_id": cls.product.id, "product_uom_qty": 1, "product_uom": cls.product.uom_id.id, "price_unit": 1000.00, }, ) ], "pricelist_id": cls.env.ref("product.list0").id, } ) cls.contact_order = cls.env["sale.order"].create( { "partner_id": cls.contact.id, "order_line": [ ( 0, 0, { "name": cls.product.name, "product_id": cls.product.id, "product_uom_qty": 1, "product_uom": cls.product.uom_id.id, "price_unit": 1000.00, }, ) ], "pricelist_id": cls.env.ref("product.list0").id, } ) cls.View = cls.env["ir.ui.view"] def test_default_partner_discount(self): self.assertEqual(self.order.general_discount, self.partner.sale_discount) def test_contact_partner_discount(self): self.assertEqual( self.contact_order.general_discount, self.partner.sale_discount ) def test_sale_order_values(self): self.order.general_discount = 10 self.assertEqual(self.order.order_line.price_reduce, 900.00) def _get_ctx_from_view(self, res): order_xml = etree.XML(res["arch"]) order_line_path = "//field[@name='order_line']" order_line_field = order_xml.xpath(order_line_path)[0] return order_line_field.attrib.get("context", "{}") def test_default_line_discount_value(self): res = self.order.fields_view_get( view_id=self.env.ref( "sale_order_general_discount." "sale_order_general_discount_form_view" ).id, view_type="form", ) ctx = self._get_ctx_from_view(res) self.assertTrue("default_discount" in ctx) view = self.View.create( { "name": "test", "type": "form", "model": "sale.order", "arch": """ <data> <field name='order_line' context="{'default_product_uom_qty': 3.0}"> </field> </data> """, } ) res = self.order.fields_view_get(view_id=view.id, view_type="form") ctx = self._get_ctx_from_view(res) self.assertTrue("default_discount" in ctx) def test_sale_order_line_wo_form_view(self): self.order.general_discount = 10 vals = { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 1, "product_uom": self.product.uom_id.id, "price_unit": 1000.00, "order_id": self.order.id, } order_line = self.env["sale.order.line"].create(vals) self.assertEqual(order_line.price_subtotal, 900.00) self.assertEqual(order_line.discount, 10) vals["discount"] = 20 order_line2 = self.env["sale.order.line"].create(vals) self.assertEqual(order_line2.price_subtotal, 800.00) self.assertEqual(order_line2.discount, 20)
35.629921
4,525
1,789
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" general_discount = fields.Float( string="Discount (%)", compute="_compute_general_discount", store=True, readonly=False, digits="Discount", ) @api.depends("partner_id") def _compute_general_discount(self): for so in self: so.general_discount = so.partner_id.sale_discount @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): """The purpose of this is to write a context on "order_line" field respecting other contexts on this field. There is a PR (https://github.com/odoo/odoo/pull/26607) to odoo for avoiding this. If merged, remove this method and add the attribute in the field. """ res = super(SaleOrder, self).fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu, ) if view_type == "form": order_xml = etree.XML(res["arch"]) order_line_fields = order_xml.xpath("//field[@name='order_line']") if order_line_fields: order_line_field = order_line_fields[0] context = order_line_field.attrib.get("context", "{}").replace( "{", "{'default_discount': general_discount, ", 1, ) order_line_field.attrib["context"] = context res["arch"] = etree.tostring(order_xml) return res
34.403846
1,789
1,056
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" discount = fields.Float( compute="_compute_discount", store=True, readonly=False, ) @api.model def create(self, vals): """Apply general discount for sale order lines which are not created from sale order form view. """ if "discount" not in vals and "order_id" in vals: sale_order = self.env["sale.order"].browse(vals["order_id"]) if sale_order.general_discount: vals["discount"] = sale_order.general_discount return super().create(vals) @api.depends("order_id", "order_id.general_discount") def _compute_discount(self): if hasattr(super(), "_compute_discount"): super()._compute_discount() for line in self: line.discount = line.order_id.general_discount return
33
1,056
450
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" sale_discount = fields.Float( string="Discount", digits="Discount", company_dependent=True, ) @api.model def _commercial_fields(self): return super()._commercial_fields() + ["sale_discount"]
25
450
720
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Sergio Teruel # Copyright 2017-2018 Tecnativa - Carlos Dauden # Copyright 2017 Camptocamp SA # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Sale Order Invoicing Finished Task", "summary": "Control invoice order lines if their related task has been " "set to invoiceable", "version": "15.0.1.0.1", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["sale_timesheet"], "data": ["views/product_view.xml", "views/project_view.xml"], }
37.842105
719
7,322
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests import common class TestInvoicefinishedTask(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.hour_uom = cls.env.ref("uom.product_uom_hour") cls.env.user.company_id.project_time_mode_id = cls.hour_uom.id group_manager = cls.env.ref("sales_team.group_sale_manager") cls.manager = cls.env["res.users"].create( { "name": "Andrew Manager", "login": "manager", "email": "a.m@example.com", "signature": "--\nAndreww", "groups_id": [(6, 0, [group_manager.id])], } ) cls.employee = cls.env["hr.employee"].create( {"name": cls.manager.name, "user_id": cls.manager.id} ) cls.partner = cls.env["res.partner"].create( {"name": "Customer - test", "customer_rank": True} ) cls.project = cls.env["project.project"].create( { "name": "Some test project", "allow_billable": True, } ) cls.stage_new = cls.env["project.task.type"].create(cls._prepare_stage_vals()) cls.stage_invoiceable = cls.env["project.task.type"].create( cls._prepare_stage_vals(invoiceable_stage=True) ) cls.uom_unit = cls.env.ref("uom.product_uom_unit") cls.Product = cls.env["product.product"] cls.product = cls.Product.create(cls._prepare_product_vals()) product_delivery_vals = cls._prepare_product_vals() product_delivery_vals.update( { "name": "Product - Service - Policy delivery - Test", "service_policy": "delivered_timesheet", "invoice_policy": "delivery", "service_type": "timesheet", } ) cls.product_policy_delivery = cls.Product.create(product_delivery_vals) cls.sale_order = cls.env["sale.order"].create(cls._sale_order_vals(cls.product)) cls.sale_order_policy_delivery = cls.env["sale.order"].create( cls._sale_order_vals(cls.product_policy_delivery) ) @classmethod def _prepare_stage_vals(cls, invoiceable_stage=False): return { "name": "Test Invoiceable", "sequence": 5, "project_ids": [(6, 0, cls.project.ids)], "invoiceable": invoiceable_stage, } @classmethod def _sale_order_vals(cls, product): return { "partner_id": cls.partner.id, "pricelist_id": cls.partner.property_product_pricelist.id, "order_line": [ ( 0, 0, { "name": product.name, "product_id": product.id, "product_uom_qty": 5, "product_uom": product.uom_id.id, "price_unit": product.list_price, }, ), ], } @classmethod def _prepare_product_vals(cls): return { "name": "Product - Service - Test", "type": "service", "list_price": 100.00, "standard_price": 50.00, "invoice_policy": "order", "service_policy": "ordered_timesheet", "service_tracking": "task_global_project", "invoicing_finished_task": True, "project_id": cls.project.id, "uom_id": cls.hour_uom.id, "uom_po_id": cls.hour_uom.id, } def _prepare_timesheet_vals(self, task, unit_amount): return { "name": "Test Line", "project_id": self.project.id, "unit_amount": unit_amount, "product_uom_id": task.sale_line_id.product_uom.id, "user_id": self.manager.id, "task_id": task.id, } def test_invoice_status(self): self.sale_order.action_confirm() self.assertEqual(self.sale_order.invoice_status, "no") task = self.sale_order.order_line.task_ids # Add a timesheet line self.env["account.analytic.line"].create( self._prepare_timesheet_vals(task, 5.0) ) self.assertEqual(self.sale_order.invoice_status, "no") # Set task in invoiceable stage task.stage_id = self.stage_invoiceable.id task._onchange_stage_id() self.assertEqual(self.sale_order.invoice_status, "to invoice") # Click on toggle_invoiceable method task.toggle_invoiceable() self.assertEqual(self.sale_order.invoice_status, "no") task.toggle_invoiceable() self.assertEqual(self.sale_order.invoice_status, "to invoice") # Make the invoice self.sale_order._create_invoices() # Click on toggle_invoiceable method after the so is invoiced with self.assertRaises(ValidationError): task.toggle_invoiceable() self.sale_order.action_done() with self.assertRaises(ValidationError): task.write({"sale_line_id": self.sale_order_policy_delivery.order_line.id}) # Try to create a task and link it to so line with self.assertRaises(ValidationError): self.env["project.task"].create( { "name": "Other Task", "user_ids": [(4, self.manager.id)], "project_id": self.project.id, "sale_line_id": self.sale_order.order_line.id, } ) def test_check_qty_to_invoice(self): self.sale_order.action_confirm() task = self.sale_order.order_line.task_ids # Add a timesheet line self.env["account.analytic.line"].create( self._prepare_timesheet_vals(task, 10.5) ) self.assertEqual(self.sale_order.order_line.qty_to_invoice, 0.0) task.toggle_invoiceable() self.assertEqual(self.sale_order.order_line.qty_to_invoice, 5.0) # Set task an invoiceable state self.sale_order_policy_delivery.action_confirm() # Add a timesheet line task_delivery = self.sale_order_policy_delivery.order_line.task_ids self.env["account.analytic.line"].create( self._prepare_timesheet_vals(task_delivery, 10.0) ) task_delivery.write({"stage_id": self.stage_invoiceable.id}) task_delivery._onchange_stage_id() self.assertEqual( self.sale_order_policy_delivery.order_line.qty_to_invoice, 10.0 ) def test_create_task_stage_invoiceable(self): self.sale_order.action_confirm() task = self.env["project.task"].create( { "name": "Other Task", "manager_id": self.manager.id, "user_ids": [(4, self.manager.id)], "project_id": self.project.id, "sale_line_id": self.sale_order.order_line.id, } ) task.stage_id = self.stage_invoiceable task._onchange_stage_id() self.assertTrue(task.invoiceable)
39.365591
7,322
2,263
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Sergio Teruel # Copyright 2017 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" @api.depends( "state", "order_line.invoice_status", "order_line.task_ids.invoiceable" ) def _get_invoiced(self): result = super()._get_invoiced() for order in self.filtered(lambda o: o.invoice_status != "no"): if not all( t.invoiceable for t in order.mapped("order_line.task_ids") if t.invoicing_finished_task ): order.update({"invoice_status": "no"}) return result class SaleOrderLine(models.Model): _inherit = "sale.order.line" task_ids = fields.One2many( comodel_name="project.task", inverse_name="sale_line_id", string="Tasks", ) @api.depends( "qty_invoiced", "qty_delivered", "product_uom_qty", "order_id.state", "task_ids.invoiceable", ) def _get_to_invoice_qty(self): lines = self.filtered( lambda x: ( x.product_id.type == "service" and x.product_id.invoicing_finished_task and x.product_id.service_tracking in ["task_global_project", "task_in_project"] and not all(x.task_ids.mapped("invoiceable")) ) ) if lines: lines.update({"qty_to_invoice": 0.0}) return super(SaleOrderLine, self - lines)._get_to_invoice_qty() def _timesheet_compute_delivered_quantity_domain(self): vals = super()._timesheet_compute_delivered_quantity_domain() vals = ( ["|", ("amount", "<=", 0.0)] + vals + [ # don't update the qty on sale order lines which are not # with a product invoiced on ordered qty + # invoice_finished task = True "|", ("so_line.product_id.invoice_policy", "=", "delivery"), ("so_line.product_id.invoicing_finished_task", "=", False), ] ) return vals
32.328571
2,263
435
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Sergio Teruel # Copyright 2017 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" invoicing_finished_task = fields.Boolean( string="Invoicing control by task", help="Invoice the order lines only when the task is set to invoiceable", )
31.071429
435
2,137
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2017 Tecnativa - Sergio Teruel # Copyright 2017 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ProjectTaskType(models.Model): _inherit = "project.task.type" invoiceable = fields.Boolean() class ProjectTask(models.Model): _inherit = "project.task" invoiceable = fields.Boolean() invoicing_finished_task = fields.Boolean( related="sale_line_id.product_id.invoicing_finished_task", ) @api.onchange("stage_id") def _onchange_stage_id(self): tasks = self.filtered( lambda t: ( t.invoicing_finished_task and t.stage_id.invoiceable and not t.invoiceable ) ) tasks.toggle_invoiceable() def toggle_invoiceable(self): self._check_sale_line_state() for task in self: task.invoiceable = not task.invoiceable def write(self, vals): if "sale_line_id" in vals: self._check_sale_line_state(vals["sale_line_id"]) res = super().write(vals) if "invoiceable" in vals: self.mapped("sale_line_id")._compute_qty_delivered() return res @api.model def create(self, vals): if "sale_line_id" in vals: self._check_sale_line_state(vals["sale_line_id"]) return super().create(vals) def _check_sale_line_state(self, sale_line_id=False): sale_lines = self.mapped("sale_line_id") if sale_line_id: sale_lines |= self.env["sale.order.line"].browse(sale_line_id) for sale_line in sale_lines: if ( sale_line.state in ("done", "cancel") or sale_line.invoice_status == "invoiced" ): raise ValidationError( _( "You cannot create/modify a task related with a " "invoiced, done or cancel sale order line " ) )
31.426471
2,137
931
py
PYTHON
15.0
# Copyright 2014 Carlos Sánchez Cifuentes <csanchez@grupovermon.com> # Copyright 2015-2020 Tecnativa - Pedro M. Baeza # Copyright 2015 Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es> # Copyright 2016 Vicent Cubells <vicent.cubells@tecnativa.com> # Copyright 2017 David Vidal <david.vidal@tecnativa.com> # Copyright 2018 Duc Dao Dong <duc.dd@komit-consulting.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Price recalculation in sales orders", "summary": "Recalculate prices / Reset descriptions on sale order lines", "version": "15.0.1.0.0", "category": "Sales Management", "website": "https://github.com/OCA/sale-workflow", "author": "AvanzOSC," "Grupo Vermon," "Tecnativa," "Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale"], "data": ["views/sale_order_view.xml"], }
40.434783
930
4,464
py
PYTHON
15.0
# Copyright 2015 Pedro M. Baeza <pedro.baeza@serviciosbaeza.com> # Copyright 2016 Vicent Cubells <vicent.cubells@tecnativa.com> # Copyright 2017 David Vidal <david.vidal@tecnativa.com> # Copyright 2018 Duc Dao Dong <duc.dd@komit-consulting.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo.tests import Form, common class TestSaleOrderPriceRecalculation(common.TransactionCase): def setUp(self): super(TestSaleOrderPriceRecalculation, self).setUp() # Enable group_discount_per_so_line for admin user group = self.env.ref("product.group_discount_per_so_line") group.users = [(4, self.env.user.id)] self.partner = self.env["res.partner"].create({"name": "Test partner"}) uom_id = self.env.ref("uom.product_uom_kgm") self.product = self.env["product.product"].create( { "name": "Jacket - Color: Black - Size: XL", "uom_id": uom_id.id, "uom_po_id": uom_id.id, } ) self.pricelist = self.env["product.pricelist"].create( { "name": "Test pricelist", "item_ids": [ ( 0, 0, { "applied_on": "3_global", "compute_price": "formula", "base": "list_price", }, ), ], } ) self.pricelist_dto = self.env["product.pricelist"].create( { "name": "Test pricelist discount policy", "discount_policy": "without_discount", "item_ids": [ ( 0, 0, { "applied_on": "1_product", "compute_price": "percentage", "percent_price": 50.0, "product_tmpl_id": self.product.product_tmpl_id.id, }, ), ], } ) self.sale_order = self.env["sale.order"].create( { "partner_id": self.partner.id, "partner_invoice_id": self.partner.id, "partner_shipping_id": self.partner.id, "pricelist_id": self.pricelist.id, } ) line_vals = { "product_id": self.product.id, "name": self.product.name, "product_uom_qty": 1.0, "product_uom": self.product.uom_id.id, "price_unit": self.product.lst_price, "order_id": self.sale_order.id, } self.sale_order_line = self.env["sale.order.line"].create(line_vals) def test_price_recalculation(self): # Check current price self.sale_order_line.name = "My product description" self.assertEqual(self.sale_order_line.price_unit, self.product.lst_price) # Change price with Form(self.product) as product: product.lst_price = 500 # Launch recalculation self.sale_order.recalculate_prices() # Check if the price has been updated self.assertEqual(self.sale_order_line.price_unit, self.product.lst_price) # Check if quantities have changed self.assertEqual(self.sale_order_line.product_uom_qty, 1.0) # Check the description still unchanged self.assertEqual(self.sale_order_line.name, "My product description") # Apply listprice with a discount self.sale_order.pricelist_id = self.pricelist_dto self.sale_order.recalculate_prices() # Check for ensuring no line addition/removal is performed self.assertEqual(len(self.sale_order.order_line), 1) self.assertEqual(self.sale_order_line.discount, 50.0) def test_name_recalculation(self): self.sale_order_line.price_unit = 150.0 initial_price = self.sale_order_line.price_unit self.assertEqual(self.sale_order_line.name, self.product.name) self.sale_order_line.name = "Custom Jacket" self.sale_order.recalculate_names() self.assertNotEqual("Custom Jacket", self.sale_order_line.name) # Check the price wasn't reset self.assertEqual(initial_price, self.sale_order_line.price_unit)
42.113208
4,464
1,432
py
PYTHON
15.0
# Copyright 2014 Carlos Sánchez Cifuentes <csanchez@grupovermon.com> # Copyright 2015-2020 Tecnativa - Pedro M. Baeza # Copyright 2015 Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es> # Copyright 2016 Vicent Cubells <vicent.cubells@tecnativa.com> # Copyright 2017 David Vidal <david.vidal@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, models class SaleOrder(models.Model): _inherit = "sale.order" @api.model def _recompute_form_line_vals(self, fields): """Helper method for writing in line certain recomputed by onchanges fields.""" for line in self.mapped("order_line"): vals = line._convert_to_write(line.read()[0]) if "product_tmpl_id" in line._fields: vals["product_tmpl_id"] = line.product_tmpl_id # we make this to isolate changed values: line2 = self.env["sale.order.line"].new(vals) line2.env.add_to_compute( line2.product_id._fields["price"], line2.product_id ) line2.product_id_change() line2._onchange_discount() line.write({field: line2[field] for field in fields}) def recalculate_prices(self): self._recompute_form_line_vals(["price_unit", "discount"]) return True def recalculate_names(self): self._recompute_form_line_vals(["name"]) return True
40.885714
1,431
1,572
py
PYTHON
15.0
# Copyright 2018-2016 Tecnativa - Pedro M. Baeza # Copyright 2020 - Iván Todorovich # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import SUPERUSER_ID, api def post_init_hook(cr, registry): """At installation time, propagate the parent sales team to the children contacts that have this field empty, as it's supposed that the intention is to have the same. """ cr.execute( """UPDATE res_partner SET team_id=parent.team_id FROM res_partner AS parent WHERE parent.team_id IS NOT NULL AND res_partner.parent_id = parent.id AND res_partner.team_id IS NULL""" ) def uninstall_hook(cr, registry): # pragma: no cover """At uninstall, revert changes made to record rules""" with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) env.ref("sales_team.group_sale_salesman_all_leads").write( { "implied_ids": [ (6, 0, [env.ref("sales_team.group_sale_salesman").id]), ], } ) # At installation time, we need to sync followers with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) partners = env["res.partner"].search( [ ("parent_id", "=", False), ("is_company", "=", True), "|", ("user_id", "!=", False), ("child_ids.user_id", "!=", False), ] ) partners._add_followers_from_salesmans()
34.152174
1,571
762
py
PYTHON
15.0
# Copyright 2016-2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sales documents permissions by channels (teams)", "summary": "New group for seeing only sales channel's documents", "version": "15.0.1.0.2", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "development_status": "Production/Stable", "maintainers": ["pedrobaeza", "ivantodorovich"], "depends": ["sales_team"], "data": ["security/sales_team_security.xml", "views/res_partner_view.xml"], "post_init_hook": "post_init_hook", "uninstall_hook": "uninstall_hook", }
40.105263
762
3,921
py
PYTHON
15.0
# Copyright 2016-2020 Tecnativa - Pedro M. Baeza # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from lxml import etree from ..hooks import post_init_hook from .common import TestCommon class TestSalesTeamSecurity(TestCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.user_partner = cls.user.partner_id cls.user2_partner = cls.user2.partner_id cls.record = cls.partner def test_onchange_parent_id(self): contact = self.env["res.partner"].create( {"name": "Test contact", "parent_id": self.partner.id} ) contact._onchange_parent_id_sales_team_security() self.assertEqual(contact.team_id, self.team) def test_onchange_user_id(self): contact = self.env["res.partner"].create( { "name": "Test contact", "user_id": self.user.id, } ) contact._onchange_user_id_sales_team_security() self.assertEqual(contact.team_id, self.team) def test_assign_contacts_team(self): contact = self.env["res.partner"].create( {"name": "Test contact", "parent_id": self.partner.id, "team_id": False} ) post_init_hook(self.env.cr, self.env.registry) contact.refresh() self.assertEqual(contact.team_id, self.partner.team_id) def test_change_user_id_partner(self): self.partner.write({"user_id": self.user.id}) self.assertIn(self.user_partner, self.partner.message_partner_ids) self.assertNotIn(self.user_partner, self.partner_child_1.message_partner_ids) self.assertIn(self.user_partner, self.partner_child_2.message_partner_ids) # Change salesman self.partner.write({"user_id": self.user2.id}) self.assertNotIn(self.user_partner, self.partner.message_partner_ids) self.assertIn(self.user2_partner, self.partner.message_partner_ids) self.assertNotIn(self.user_partner, self.partner_child_2.message_partner_ids) self.assertIn(self.user2_partner, self.partner_child_2.message_partner_ids) def test_change_user_id_partner_child_1(self): self.partner_child_1.write({"user_id": self.user.id}) self.assertIn(self.user_partner, self.partner.message_partner_ids) self.assertIn(self.user_partner, self.partner_child_2.message_partner_ids) # Change salesman self.partner_child_1.write({"user_id": self.user2.id}) self.assertNotIn(self.user_partner, self.partner.message_partner_ids) self.assertIn(self.user2_partner, self.partner.message_partner_ids) self.assertNotIn(self.user_partner, self.partner_child_2.message_partner_ids) self.assertIn(self.user2_partner, self.partner_child_2.message_partner_ids) def test_partner_fields_view_get(self): res = self.env["res.partner"].fields_view_get( view_id=self.ref("base.view_partner_form") ) eview = etree.fromstring(res["arch"]) xml_fields = eview.xpath("//field[@name='child_ids']") self.assertTrue(xml_fields) self.assertTrue("default_team_id" in xml_fields[0].get("context", "")) def test_partner_permissions(self): self._check_whole_permission_set() def test_partner_permissions_subscription(self): self.check_permission_subscribe = True self._check_permission(self.user2, False, True) def test_partner_permissions_own_partner(self): self.user.partner_id.write({"user_id": self.user2.id}) domain = [("id", "in", self.user.partner_id.ids)] Partner = self.env["res.partner"].with_user(self.user) # Make sure the acces is not due to the subscription self.partner.message_unsubscribe(partner_ids=self.user.partner_id.ids) self.assertEqual(bool(Partner.search(domain)), True)
44.033708
3,919
5,464
py
PYTHON
15.0
# Copyright 2016-2020 Tecnativa - Pedro M. Baeza # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo.tests import common class TestCommon(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.team = cls.env["crm.team"].create({"name": "Test channel"}) cls.team2 = cls.env["crm.team"].create({"name": "Test channel 2"}) cls.user = cls.env["res.users"].create( { "login": "sales_team_security", "name": "Test sales_team_security user", "groups_id": [(4, cls.env.ref("sales_team.group_sale_salesman").id)], } ) cls.crm_team_member = cls.env["crm.team.member"].create( { "user_id": cls.user.id, "crm_team_id": cls.team.id, } ) cls.partner = cls.env["res.partner"].create( {"name": "Test partner", "team_id": cls.team.id} ) cls.partner_child_1 = cls.env["res.partner"].create( {"name": "Child 1", "parent_id": cls.partner.id} ) cls.partner_child_2 = cls.env["res.partner"].create( {"name": "Child 2", "parent_id": cls.partner.id, "type": "invoice"} ) cls.user2 = cls.env["res.users"].create( { "login": "sales_team_security2", "name": "Test sales_team_security user 2", "groups_id": [(4, cls.env.ref("sales_team.group_sale_salesman").id)], } ) cls.crm_team_member2 = cls.env["crm.team.member"].create( { "user_id": cls.user2.id, "crm_team_id": cls.team.id, } ) cls.check_permission_subscribe = False def _check_permission(self, salesman, team, expected): self.record.write( { "user_id": salesman.id if salesman else salesman, "team_id": team.id if team else team, } ) domain = [("id", "=", self.record.id)] if ( self.check_permission_subscribe ): # Force unsubscription for not interfering with real test self.record.message_subscribe(partner_ids=self.user.partner_id.ids) else: self.record.message_unsubscribe(partner_ids=self.user.partner_id.ids) obj = self.env[self.record._name].with_user(self.user) self.assertEqual(bool(obj.search(domain)), expected) def _check_whole_permission_set(self, extra_checks=True): self._check_permission(False, False, True) self._check_permission(self.user, False, True) self._check_permission(self.user2, False, False) self._check_permission(False, self.team, True) if extra_checks: self._check_permission(False, self.team2, False) self._check_permission(self.user, self.team, True) self._check_permission(self.user, self.team2, True) self._check_permission(self.user2, self.team2, False) self._check_permission(self.user2, self.team, False) # Add to group "Team manager" self.user.groups_id = [ (4, self.env.ref("sales_team_security.group_sale_team_manager").id) ] self._check_permission(False, False, True) self._check_permission(self.user, False, True) self._check_permission(self.user2, False, True) self._check_permission(False, self.team, True) if extra_checks: self._check_permission(False, self.team2, False) self._check_permission(self.user, self.team, True) if self.record._name == "res.partner": self.check_permission_subscribe = True self._check_permission(self.user, self.team2, True) self.check_permission_subscribe = False else: self._check_permission(self.user, self.team2, True) self._check_permission(self.user2, self.team2, False) self._check_permission(self.user2, self.team, True) # Add to group "See all leads" self.user.groups_id = [ (4, self.env.ref("sales_team.group_sale_salesman_all_leads").id) ] self._check_permission(False, False, True) self._check_permission(self.user, False, True) self._check_permission(self.user2, False, True) self._check_permission(False, self.team, True) self._check_permission(False, self.team2, True) self._check_permission(self.user, self.team, True) self._check_permission(self.user, self.team2, True) self._check_permission(self.user2, self.team2, True) self._check_permission(self.user2, self.team, True) # Regular internal user if extra_checks: self.user.groups_id = [(6, 0, [self.env.ref("base.group_user").id])] self._check_permission(False, False, True) self._check_permission(self.user, False, True) self._check_permission(self.user2, False, True) self._check_permission(False, self.team, True) self._check_permission(False, self.team2, True) self._check_permission(self.user, self.team, True) self._check_permission(self.user, self.team2, True) self._check_permission(self.user2, self.team2, True) self._check_permission(self.user2, self.team, True)
44.770492
5,462
2,141
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import api, models, tools from odoo.osv import expression from odoo.tools import config class IrRule(models.Model): _inherit = "ir.rule" @api.model @tools.conditional( "xml" not in config["dev_mode"], tools.ormcache( "self.env.uid", "self.env.su", "model_name", "mode", "tuple(self._compute_domain_context_values())", ), ) def _compute_domain(self, model_name, mode="read"): """Inject extra domain for restricting partners when the user has the group 'Sales / User: Own Documents Only'. """ res = super()._compute_domain(model_name, mode=mode) user = self.env.user group1 = "sales_team.group_sale_salesman" group2 = "sales_team_security.group_sale_team_manager" group3 = "sales_team.group_sale_salesman_all_leads" if model_name == "res.partner" and not self.env.su: if user.has_group(group1) and not user.has_group(group3): extra_domain = [ "|", ("message_partner_ids", "in", user.partner_id.ids), "|", ("id", "=", user.partner_id.id), ] if user.has_group(group2): extra_domain += [ "|", ("team_id", "=", user.sale_team_id.id), ("team_id", "=", False), ] else: extra_domain += [ "|", ("user_id", "=", user.id), "&", ("user_id", "=", False), "|", ("team_id", "=", False), ("team_id", "=", user.sale_team_id.id), ] extra_domain = expression.normalize_domain(extra_domain) res = expression.AND([extra_domain] + [res]) return res
36.913793
2,141
3,914
py
PYTHON
15.0
# Copyright 2016-2018 Tecnativa - Pedro M. Baeza # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from lxml import etree from odoo import api, fields, models class ResPartner(models.Model): _inherit = "res.partner" # add indexes for better performance on record rules user_id = fields.Many2one(index=True) team_id = fields.Many2one(index=True) @api.model def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): """ Patch view to inject the default value for the team_id and user_id. """ # FIXME: Use base_view_inheritance_extension when available res = super().fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu, ) if view_type == "form": eview = etree.fromstring(res["arch"]) xml_fields = eview.xpath("//field[@name='child_ids']") if xml_fields: context_str = ( xml_fields[0] .get("context", "{}") .replace( "{", "{'default_team_id': team_id, 'default_user_id': user_id,", 1, ) ) xml_fields[0].set("context", context_str) res["arch"] = etree.tostring(eview) return res @api.onchange("parent_id") def _onchange_parent_id_sales_team_security(self): """If assigning a parent partner and the contact doesn't have team or salesman, we put the parent's one (if any). """ if self.parent_id and self.parent_id.team_id and not self.team_id: self.team_id = self.parent_id.team_id.id if self.parent_id and self.parent_id.user_id and not self.user_id: self.user_id = self.parent_id.user_id.id @api.onchange("user_id") def _onchange_user_id_sales_team_security(self): if self.user_id.sale_team_id: self.team_id = self.user_id.sale_team_id def _remove_key_followers(self, partner): for record in self.mapped("commercial_partner_id"): # Look for delivery and invoice addresses childrens = record.child_ids.filtered( lambda x: x.type in {"invoice", "delivery"} ) (childrens + record).message_unsubscribe(partner_ids=partner.ids) def _add_followers_from_salesmans(self): """Sync followers in commercial partner + delivery/invoice contacts.""" for record in self.mapped("commercial_partner_id"): followers = (record.child_ids + record).mapped("user_id.partner_id") # Look for delivery and invoice addresses childrens = record.child_ids.filtered( lambda x: x.type in {"invoice", "delivery"} ) (childrens + record).message_subscribe(partner_ids=followers.ids) @api.model_create_multi def create(self, vals_list): """Sync followers on contact creation.""" records = super().create(vals_list) records._add_followers_from_salesmans() return records def write(self, vals): """If the salesman is changed, first remove the old salesman as follower of the key contacts (commercial + delivery/invoice), and then sync for the new ones. It performs as well the followers sync on contact type change. """ if "user_id" in vals: for record in self.filtered("user_id"): record._remove_key_followers(record.user_id.partner_id) result = super().write(vals) if "user_id" in vals or vals.get("type") in {"invoice", "delivery"}: self._add_followers_from_salesmans() return result
38.732673
3,912
855
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale order line price history", "version": "15.0.1.0.0", "category": "Sales Management", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "license": "AGPL-3", "depends": ["sale"], "data": [ "security/ir.model.access.csv", "wizards/sale_order_line_price_history.xml", "views/sale_views.xml", ], "assets": { "web.assets_backend": [ "sale_order_line_price_history/static/src/js/sale_line_price_history_widget.js", ], "web.assets_qweb": [ "sale_order_line_price_history/static/src/xml/sale_line_price_history_widget.xml", ], }, "installable": True, }
34.2
855
7,006
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestSaleOrderLinePriceHistory(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner_1 = cls.env.ref("base.res_partner_1") cls.partner_2 = cls.env.ref("base.res_partner_2") cls.product = cls.env.ref("product.product_order_01") cls.sale_order_1 = cls.env["sale.order"].create( {"partner_id": cls.partner_1.id} ) # Two sale orders confirmed and with different partners cls.sale_order_line_1 = cls.env["sale.order.line"].create( { "order_id": cls.sale_order_1.id, "name": cls.product.name, "product_id": cls.product.id, "product_uom_qty": 2, "product_uom": cls.product.uom_id.id, "price_unit": 10, "discount": 5, } ) cls.sale_order_1.action_confirm() cls.sale_order_2 = cls.env["sale.order"].create( {"partner_id": cls.partner_2.id} ) cls.sale_order_line_2 = cls.env["sale.order.line"].create( { "order_id": cls.sale_order_2.id, "name": cls.product.name, "product_id": cls.product.id, "product_uom_qty": 2, "product_uom": cls.product.uom_id.id, "price_unit": 20, } ) cls.sale_order_2.action_confirm() # Another sale orders with the same partner of cls.sale_order_2 cls.sale_order_3 = cls.env["sale.order"].create( {"partner_id": cls.partner_2.id} ) cls.sale_order_line_3 = cls.env["sale.order.line"].create( { "order_id": cls.sale_order_3.id, "name": cls.product.name, "product_id": cls.product.id, "product_uom_qty": 2, "product_uom": cls.product.uom_id.id, "price_unit": 30, } ) def launch_wizard(self, active_id): wizard_obj = self.env["sale.order.line.price.history"] wizard = wizard_obj.with_context(active_id=active_id).create({}) wizard._onchange_partner_id() return wizard def test_onchange_partner_id(self): # Create a wizard from self.sale_order_line_3. Only one history line # should be shown and should be associated with self.sale_order_line_2 wizard = self.launch_wizard(self.sale_order_line_3.id) self.assertEqual(len(wizard.line_ids), 1) self.assertEqual(wizard.line_ids.sale_order_line_id, self.sale_order_line_2) self.assertEqual(wizard.line_ids.price_unit, 20) # Set partner to False. Two history lines should be shown and # they should be associated with self.sale_order_line_1 # and self.sale_order_line_2 wizard.partner_id = False wizard._onchange_partner_id() self.assertEqual(len(wizard.line_ids), 2) self.assertEqual( set(wizard.line_ids.mapped("sale_order_line_id.price_unit")), set(list([10.0, 20.0])), ) def test_onchange_partner_id_include_quotations(self): # Another sale orders with the same partner of cls.sale_order_2 # and cls.sale_order_3 self.sale_order_4 = self.env["sale.order"].create( {"partner_id": self.partner_2.id} ) self.sale_order_line_4 = self.env["sale.order.line"].create( { "order_id": self.sale_order_4.id, "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 2, "product_uom": self.product.uom_id.id, "price_unit": 40, } ) # Create a wizard from self.sale_order_line_4. Only one history line # should be shown and should be associated with self.sale_order_line_2 wizard = self.launch_wizard(self.sale_order_line_4.id) self.assertEqual(len(wizard.line_ids), 1) self.assertEqual(wizard.line_ids.sale_order_line_id, self.sale_order_line_2) # If include_quotations is checked two history lines should be shown # and they should be associated with self.sale_order_line_2 # and self.sale_order_line_3 wizard.include_quotations = True wizard._onchange_partner_id() self.assertEqual(len(wizard.line_ids), 2) self.assertEqual( wizard.line_ids.mapped("sale_order_line_id"), self.sale_order_line_2 | self.sale_order_line_3, ) def test_onchange_partner_id_include_commercial_partner(self): # Another sale orders with a partner child of cls.sale_order_2 self.sale_order_4 = self.env["sale.order"].create( {"partner_id": self.ref("base.res_partner_address_31")} ) self.sale_order_line_4 = self.env["sale.order.line"].create( { "order_id": self.sale_order_4.id, "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 2, "product_uom": self.product.uom_id.id, "price_unit": 40, } ) # Create a wizard from self.sale_order_line_4. As # include_commercial_partner si checked by default, one history line # should be shown and associated with self.sale_order_line_2 wizard = self.launch_wizard(active_id=self.sale_order_line_4.id) self.assertEqual(len(wizard.line_ids), 1) self.assertEqual(wizard.line_ids.sale_order_line_id, self.sale_order_line_2) # Uncheck include_commercial_partner and Empty sale history # should be shown. wizard.include_commercial_partner = False wizard._onchange_partner_id() self.assertFalse(wizard.line_ids) def test_action_set_price(self): # Create a wizard from self.sale_order_line_3. wizard = self.launch_wizard(active_id=self.sale_order_line_3.id) self.assertEqual(self.sale_order_line_3.price_unit, 30) # Set price of the history line shown. wizard.line_ids.action_set_price() self.assertEqual(self.sale_order_line_3.price_unit, 20) self.assertEqual(self.sale_order_line_3.discount, 0) # Create a wizard from self.sale_order_line_3 again. wizard = self.launch_wizard(active_id=self.sale_order_line_3.id) wizard.partner_id = False wizard._onchange_partner_id() # Find the history line with price_unit == 10 and set this price history_line = wizard.line_ids.filtered(lambda r: r.price_unit == 10) history_line.action_set_price() self.assertEqual(self.sale_order_line_3.price_unit, 10) self.assertEqual(self.sale_order_line_3.discount, 5)
44.341772
7,006
396
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" # In core this a related field. We need to trigger its value on view, so we can # have it even when we're in a NewId order_partner_id = fields.Many2one(depends=["product_id"])
36
396
4,511
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrderLinePriceHistory(models.TransientModel): _name = "sale.order.line.price.history" _description = "Sale order line price history" @api.model def _default_partner_id(self): line_id = self.env.context.get("active_id") return self.env["sale.order.line"].browse(line_id).order_partner_id.id @api.model def _default_product_id(self): line_id = self.env.context.get("active_id") return self.env["sale.order.line"].browse(line_id).product_id.id sale_order_line_id = fields.Many2one( comodel_name="sale.order.line", string="Sale order line", default=lambda self: self.env.context.get("active_id"), ) product_id = fields.Many2one( comodel_name="product.product", string="Product", default=_default_product_id, ) partner_id = fields.Many2one( comodel_name="res.partner", string="Customer", default=_default_partner_id, ) line_ids = fields.One2many( comodel_name="sale.order.line.price.history.line", inverse_name="history_id", string="History lines", readonly=True, ) include_quotations = fields.Boolean( help="Include quotations lines in the sale history", ) include_commercial_partner = fields.Boolean( string="Include commercial entity", default=True, help="Include commercial entity and its contacts in the sale history", ) @api.onchange("partner_id", "include_quotations", "include_commercial_partner") def _onchange_partner_id(self): self.line_ids = False states = ["sale", "done"] if self.include_quotations: states += ["draft", "sent"] domain = [ ("product_id", "=", self.product_id.id), ("state", "in", states), ] if self.partner_id: if self.include_commercial_partner: domain += [ ( "order_partner_id", "child_of", self.partner_id.commercial_partner_id.ids, ) ] else: domain += [("order_partner_id", "child_of", self.partner_id.ids)] vals = [] order_lines = self.env["sale.order.line"].search(domain, limit=20) order_lines -= self.sale_order_line_id for order_line in order_lines: vals.append( ( 0, False, { "sale_order_line_id": order_line.id, "history_sale_order_line_id": self.sale_order_line_id.id, }, ) ) self.line_ids = vals class SaleOrderLinePriceHistoryline(models.TransientModel): _name = "sale.order.line.price.history.line" _description = "Sale order line price history line" history_id = fields.Many2one( comodel_name="sale.order.line.price.history", string="History", ) history_sale_order_line_id = fields.Many2one( comodel_name="sale.order.line", string="history sale order line", ) sale_order_line_id = fields.Many2one( comodel_name="sale.order.line", string="Sale order line", ) order_id = fields.Many2one( related="sale_order_line_id.order_id", ) partner_id = fields.Many2one( related="sale_order_line_id.order_partner_id", ) sale_order_date_order = fields.Datetime( related="sale_order_line_id.order_id.date_order", ) product_uom_qty = fields.Float( related="sale_order_line_id.product_uom_qty", ) price_unit = fields.Float( related="sale_order_line_id.price_unit", ) discount = fields.Float( related="sale_order_line_id.discount", ) def _prepare_set_price_history_vals(self): """Hook method to prepare the values to update the sales order line in context. This method is invoke by action_set_price method in this model. """ self.ensure_one() return {"price_unit": self.price_unit, "discount": self.discount} def action_set_price(self): self.ensure_one() self.history_sale_order_line_id.write(self._prepare_set_price_history_vals())
33.414815
4,511
767
py
PYTHON
15.0
# Copyright 2011 Akretion, Sodexis # Copyright 2018 Akretion # Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Sale Exception", "summary": "Custom exceptions on sale order", "version": "15.0.1.0.0", "category": "Generic Modules/Sale", "author": "Akretion, " "Sodexis, " "Camptocamp, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale", "base_exception"], "license": "AGPL-3", "data": [ "security/ir.model.access.csv", "data/sale_exception_data.xml", "wizard/sale_exception_confirm_view.xml", "views/sale_view.xml", ], "demo": ["demo/sale_exception_demo.xml"], }
31.958333
767
4,705
py
PYTHON
15.0
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html import mock from odoo.tests import TransactionCase class TestSaleExceptionMultiRecord(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) def test_sale_order_exception(self): exception_no_sol = self.env.ref("sale_exception.excep_no_sol") exception_no_free = self.env.ref("sale_exception.excep_no_free") exception_no_dumping = self.env.ref("sale_exception.excep_no_dumping") exceptions = exception_no_sol + exception_no_free + exception_no_dumping exceptions.write({"active": True}) partner = self.env.ref("base.res_partner_1") p = self.env.ref("product.product_product_7") so1 = self.env["sale.order"].create( { "partner_id": partner.id, "partner_invoice_id": partner.id, "partner_shipping_id": partner.id, "order_line": [ ( 0, 0, { "name": p.name, "product_id": p.id, "product_uom_qty": 2, "product_uom": p.uom_id.id, "price_unit": p.list_price, }, ) ], "pricelist_id": self.env.ref("product.list0").id, } ) so2 = self.env["sale.order"].create( { "partner_id": partner.id, "partner_invoice_id": partner.id, "partner_shipping_id": partner.id, "pricelist_id": self.env.ref("product.list0").id, } ) so3 = self.env["sale.order"].create( { "partner_id": partner.id, "partner_invoice_id": partner.id, "partner_shipping_id": partner.id, "order_line": [ ( 0, 0, { "name": p.name, "product_id": p.id, "product_uom_qty": 2, "product_uom": p.uom_id.id, "price_unit": p.list_price / 2, }, ) ], "pricelist_id": self.env.ref("product.list0").id, } ) orders = so1 + so2 + so3 for order in orders: # ensure init state self.assertTrue(order.state == "draft") self.assertTrue(len(order.exception_ids) == 0) self.env["sale.order"].test_all_draft_orders() # basic tests self.assertTrue(so1.state == "draft") self.assertTrue(len(so1.exception_ids) == 0) self.assertTrue(so2.state == "draft") self.assertTrue(exception_no_sol in so2.exception_ids) self.assertTrue(exception_no_free in so2.exception_ids) self.assertTrue(so3.state == "draft") self.assertTrue(exception_no_dumping in so3.exception_ids) self.assertEqual( so3.order_line[0].exceptions_summary, ( "<ul>" "<li>No dumping: <i>A product is sold cheaper than his cost.</i></li>" "</ul>" ), ) # test return value of detect_exception() all_detected = orders.detect_exceptions() self.assertTrue(exception_no_sol.id in all_detected) self.assertTrue(exception_no_dumping.id in all_detected) self.assertTrue(exception_no_free.id in all_detected) one_two_detected = (so1 + so2).detect_exceptions() self.assertTrue(exception_no_sol.id in one_two_detected) self.assertFalse(exception_no_dumping.id in one_two_detected) self.assertTrue(exception_no_free.id in one_two_detected) # test subset of rules domain = [("model", "=", "sale.order"), ("id", "!=", exception_no_sol.id)] with mock.patch.object(type(orders), "_rule_domain", return_value=domain): # even if the rule is excluded from the search # it should still be present on the sale order orders.detect_exceptions() all_detected = orders.mapped("exception_ids").ids self.assertTrue(exception_no_sol.id in all_detected) self.assertTrue(exception_no_dumping.id in all_detected) self.assertTrue(exception_no_free.id in all_detected)
37.64
4,705
6,441
py
PYTHON
15.0
# Copyright 2011 Akretion, Sodexis # Copyright 2018 Akretion # Copyright 2019 Camptocamp SA # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo.exceptions import ValidationError from odoo.tests import Form, TransactionCase class TestSaleException(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) def test_sale_order_exception(self): self.sale_exception_confirm = self.env["sale.exception.confirm"] exception = self.env.ref("sale_exception.excep_no_zip").sudo() exception.active = True partner = self.env.ref("base.res_partner_1") partner.zip = False p = self.env.ref("product.product_product_6") so1 = self.env["sale.order"].create( { "partner_id": partner.id, "partner_invoice_id": partner.id, "partner_shipping_id": partner.id, "order_line": [ ( 0, 0, { "name": p.name, "product_id": p.id, "product_uom_qty": 2, "product_uom": p.uom_id.id, "price_unit": p.list_price, }, ) ], "pricelist_id": self.env.ref("product.list0").id, } ) # confirm quotation exception = self.env.ref("sale_exception.excep_no_zip") exception.active = True so1.action_confirm() self.assertTrue(so1.state == "draft") so1.detect_exceptions() self.assertTrue(so1.exception_ids.filtered(lambda x: x == exception)) # test all draft so so2 = self.env["sale.order"].create( { "partner_id": partner.id, "partner_invoice_id": partner.id, "partner_shipping_id": partner.id, "order_line": [ ( 0, 0, { "name": p.name, "product_id": p.id, "product_uom_qty": 3, "product_uom": p.uom_id.id, "price_unit": p.list_price, }, ) ], "pricelist_id": self.env.ref("product.list0").id, } ) self.env["sale.order"].test_all_draft_orders() self.assertTrue(so2.state == "draft") # Set ignore_exception flag (Done after ignore is selected at wizard) so1.ignore_exception = True so1.action_confirm() self.assertTrue(so1.state == "sale") # Add a order line to test after SO is confirmed p = self.env.ref("product.product_product_7") # set ignore_exception = False (Done by onchange of order_line) self.assertRaises( ValidationError, so1.write, { "ignore_exception": False, "order_line": [ ( 0, 0, { "name": p.name, "product_id": p.id, "product_uom_qty": 2, "product_uom": p.uom_id.id, "price_unit": p.list_price, }, ) ], }, ) p = self.env.ref("product.product_product_7") # Set ignore exception True (Done manually by user) so1.write( { "ignore_exception": True, "order_line": [ ( 0, 0, { "name": p.name, "product_id": p.id, "product_uom_qty": 2, "product_uom": p.uom_id.id, "price_unit": p.list_price, }, ) ], } ) exception.active = False so1.action_cancel() so1.action_draft() self.assertTrue(not so1.ignore_exception) # Simulation the opening of the wizard sale_exception_confirm and # set ignore_exception to True so_except_confirm = self.sale_exception_confirm.with_context( **{"active_id": so1.id, "active_ids": [so1.id], "active_model": so1._name} ).create({"ignore": True}) so_except_confirm.action_confirm() self.assertTrue(so1.ignore_exception) def _create_sale_order(self, partner, product): order_form = Form(self.env["sale.order"]) order_form.partner_id = partner with order_form.order_line.new() as line_form: line_form.product_id = product return order_form.save() def test_exception_partner_sale_warning(self): exception = self.env.ref("sale_exception.exception_partner_sale_warning") exception.active = True partner = self.env.ref("base.res_partner_1") sale_order = self._create_sale_order( partner=partner, product=self.env.ref("product.product_product_6") ) sale_order.action_confirm() partner.sale_warn = "warning" sale_order2 = sale_order.copy() sale_order2.detect_exceptions() self.assertTrue(sale_order2.exception_ids.filtered(lambda x: x == exception)) def test_exception_product_sale_warning(self): exception = self.env.ref("sale_exception.exception_product_sale_warning") exception.active = True product = self.env.ref("product.product_product_6") sale_order = self._create_sale_order( partner=self.env.ref("base.res_partner_1"), product=product ) sale_order.action_confirm() product.sale_line_warn = "warning" sale_order2 = sale_order.copy() sale_order2.detect_exceptions() self.assertTrue(sale_order2.exception_ids.filtered(lambda x: x == exception))
37.005747
6,439
617
py
PYTHON
15.0
# Copyright 2011 Akretion, Sodexis # Copyright 2018 Akretion # Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class SaleExceptionConfirm(models.TransientModel): _name = "sale.exception.confirm" _inherit = ["exception.rule.confirm"] _description = "Sale exception confirm wizard" related_model_id = fields.Many2one("sale.order", "Sale") def action_confirm(self): self.ensure_one() if self.ignore: self.related_model_id.ignore_exception = True return super().action_confirm()
32.473684
617
1,801
py
PYTHON
15.0
# © 2019 Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import html from odoo import api, fields, models class SaleOrderLine(models.Model): _inherit = ["sale.order.line", "base.exception.method"] _name = "sale.order.line" exception_ids = fields.Many2many( "exception.rule", string="Exceptions", copy=False, readonly=True ) exceptions_summary = fields.Html( readonly=True, compute="_compute_exceptions_summary" ) ignore_exception = fields.Boolean( related="order_id.ignore_exception", store=True, string="Ignore Exceptions" ) @api.depends("exception_ids", "ignore_exception") def _compute_exceptions_summary(self): for rec in self: if rec.exception_ids and not rec.ignore_exception: rec.exceptions_summary = rec._get_exception_summary() else: rec.exceptions_summary = False def _get_exception_summary(self): return "<ul>%s</ul>" % "".join( [ "<li>%s: <i>%s</i></li>" % tuple(map(html.escape, (e.name, e.description))) for e in self.exception_ids ] ) def _get_main_records(self): return self.mapped("order_id") @api.model def _reverse_field(self): return "sale_ids" def _detect_exceptions(self, rule): records = super()._detect_exceptions(rule) # Thanks to the new flush of odoo 13.0, queries will be optimized # together at the end even if we update the exception_ids many times. # On previous versions, this could be unoptimized. (self - records).exception_ids = [(3, rule.id)] records.exception_ids = [(4, rule.id)] return records.mapped("order_id")
33.333333
1,800
2,568
py
PYTHON
15.0
# Copyright 2011 Akretion, Sodexis # Copyright 2018 Akretion # Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ExceptionRule(models.Model): _inherit = "exception.rule" model = fields.Selection( selection_add=[ ("sale.order", "Sale order"), ("sale.order.line", "Sale order line"), ], ondelete={ "sale.order": "cascade", "sale.order.line": "cascade", }, ) sale_ids = fields.Many2many("sale.order", string="Sales") class SaleOrder(models.Model): _inherit = ["sale.order", "base.exception"] _name = "sale.order" _order = "main_exception_id asc, date_order desc, name desc" @api.model def _reverse_field(self): return "sale_ids" def detect_exceptions(self): all_exceptions = super().detect_exceptions() lines = self.mapped("order_line") all_exceptions += lines.detect_exceptions() return all_exceptions @api.model def test_all_draft_orders(self): order_set = self.search([("state", "=", "draft")]) order_set.detect_exceptions() return True def _fields_trigger_check_exception(self): return ["ignore_exception", "order_line", "state"] def _check_sale_check_exception(self, vals): check_exceptions = any( field in vals for field in self._fields_trigger_check_exception() ) if check_exceptions: self.sale_check_exception() @api.model def create(self, vals): record = super().create(vals) record._check_sale_check_exception(vals) return record def write(self, vals): result = super().write(vals) self._check_sale_check_exception(vals) return result def sale_check_exception(self): orders = self.filtered(lambda s: s.state == "sale") if orders: orders._check_exception() def action_confirm(self): if self.detect_exceptions(): return self._popup_exceptions() return super().action_confirm() def action_draft(self): res = super().action_draft() orders = self.filtered("ignore_exception") orders.write({"ignore_exception": False}) return res def _sale_get_lines(self): self.ensure_one() return self.order_line @api.model def _get_popup_action(self): return self.env.ref("sale_exception.action_sale_exception_confirm")
28.853933
2,568
547
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Order Line Delivery State", "summary": "Show the delivery state on the sale order line", "version": "15.0.1.0.1", "category": "Product", "website": "https://github.com/OCA/sale-workflow", "author": "ForgeFlow, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["sale"], "data": ["views/sale_order_views.xml"], "demo": [], }
34.1875
547
4,486
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from unittest import mock from odoo.tests import TransactionCase class TestSaleLineDeliveryState(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) # Base data partner = cls.env.ref("base.res_partner_2") product = cls.env.ref("product.product_product_25") pricelist = cls.env.ref("product.list0") cls.uom = cls.env.ref("uom.product_uom_unit") # Create delivery product cls.delivery_cost = cls.env["product.product"].create( {"name": "delivery", "type": "service"} ) # Create sales order cls.order = cls.env["sale.order"].create( { "partner_id": partner.id, "pricelist_id": pricelist.id, "order_line": [ ( 0, 0, { "product_id": product.id, "product_uom": cls.uom.id, "product_uom_qty": 3, "price_unit": 2950.00, "name": product.name, }, ) ], } ) def _mock_delivery(self, delivery_prod=None): delivery_prod = delivery_prod or self.delivery_cost return mock.patch.object( type(self.env["sale.order.line"]), "_is_delivery", lambda self: self.product_id == delivery_prod, ) def _add_delivery_cost_line(self): self.env["sale.order.line"].create( { "order_id": self.order.id, "name": "Delivery cost", "product_id": self.delivery_cost.id, "product_uom_qty": 1, "product_uom": self.uom.id, "price_unit": 10.0, } ) def test_no_delivery(self): self.assertEqual(self.order.order_line[0].delivery_state, "no") def test_unprocessed_delivery(self): self.order.action_confirm() self.assertEqual(self.order.order_line[0].delivery_state, "unprocessed") def test_partially(self): self.order.action_confirm() self.order.order_line[0].qty_delivered = 2 self.assertEqual(self.order.order_line[0].delivery_state, "partially") def test_delivery_done(self): self.order.action_confirm() self.order.order_line[0].qty_delivered = 3 self.assertEqual(self.order.order_line[0].delivery_state, "done") def test_no_delivery_delivery_cost(self): self._add_delivery_cost_line() with self._mock_delivery(): self.assertEqual(self.order.order_line[1].delivery_state, "no") def test_unprocessed_delivery_delivery_cost(self): self._add_delivery_cost_line() with self._mock_delivery(): self.order.action_confirm() self.assertEqual(self.order.order_line[0].delivery_state, "unprocessed") self.assertEqual(self.order.order_line[1].delivery_state, "no") def test_partially_delivery_cost(self): self._add_delivery_cost_line() with self._mock_delivery(): self.order.action_confirm() self.order.order_line[0].qty_delivered = 2 self.assertEqual(self.order.order_line[0].delivery_state, "partially") self.assertEqual(self.order.order_line[1].delivery_state, "no") def test_forced_delivery_cost(self): self._add_delivery_cost_line() with self._mock_delivery(): self.order.action_confirm() self.order.order_line[0].qty_delivered = 2 self.order.order_line[0].force_delivery_state = True self.assertEqual(self.order.order_line[0].delivery_state, "done") self.assertEqual(self.order.order_line[1].delivery_state, "no") def test_delivery_done_delivery_cost(self): self._add_delivery_cost_line() with self._mock_delivery(): self.order.action_confirm() self.order.order_line[0].qty_delivered = 3 self.assertEqual(self.order.order_line[0].delivery_state, "done") self.assertEqual(self.order.order_line[1].delivery_state, "no")
38.672414
4,486
2,703
py
PYTHON
15.0
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.tools import float_compare, float_is_zero class SaleOrderLine(models.Model): _inherit = "sale.order.line" delivery_state = fields.Selection( [ ("no", "No delivery"), ("unprocessed", "Unprocessed"), ("partially", "Partially processed"), ("done", "Done"), ], # Compute method have a different name then the field because # the method _compute_delivery_state already exist to compute # the field delivery_set in odoo delivery module compute="_compute_sale_line_delivery_state", store=True, ) force_delivery_state = fields.Boolean( help=( "Allow to enforce done state of delivery, for instance if some" " quantities were cancelled" ), ) def _all_qty_delivered(self): """ Returns True if line has qty_delivered >= to ordered quantities :returns: boolean """ self.ensure_one() precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) return ( float_compare( self.qty_delivered, self.product_uom_qty, precision_digits=precision ) >= 0 ) def _partially_delivered(self): """ Returns True if line has qty_delivered != to 0 and < ordered quantities. :returns: boolean """ self.ensure_one() precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) return not float_is_zero(self.qty_delivered, precision_digits=precision) @api.depends("qty_delivered", "state", "force_delivery_state") def _compute_sale_line_delivery_state(self): """ If `delivery` module is installed, lines with delivery costs are marked as 'No delivery'. """ for line in self: if line.state in ("draft", "cancel") or line._is_delivery(): line.delivery_state = "no" elif line.force_delivery_state or line._all_qty_delivered(): line.delivery_state = "done" elif line._partially_delivered(): line.delivery_state = "partially" else: line.delivery_state = "unprocessed" def action_force_delivery_state(self): self.write({"force_delivery_state": True}) def action_unforce_delivery_state(self): self.write({"force_delivery_state": False})
32.963415
2,703
706
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2019 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Start End Dates", "version": "15.0.1.0.1", "category": "Sales", "license": "AGPL-3", "summary": "Adds start date and end date on sale order lines", "author": "Akretion, Sodexis, Odoo Community Association (OCA)", "maintainers": ["alexis-via"], "website": "https://github.com/OCA/sale-workflow", "depends": ["account_invoice_start_end_dates", "sale"], "data": ["views/sale_order.xml"], "installable": True, }
39.222222
706
4,378
py
PYTHON
15.0
# Copyright (C) 2018 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import datetime from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestSaleStartEndDates(TransactionCase): def setUp(self): super().setUp() self.partner = self.env.ref("base.res_partner_3") self.product_id = self.env.ref("product.product_product_7") self.product_id.must_have_dates = True self.default_start_date = datetime.datetime.now() self.default_end_date = self.default_start_date + datetime.timedelta(days=9) self.so = self.env["sale.order"].create( { "partner_id": self.partner.id, "partner_invoice_id": self.partner.id, "partner_shipping_id": self.partner.id, "default_start_date": self.default_start_date, "default_end_date": self.default_end_date, "pricelist_id": self.env.ref("product.list0").id, "order_line": [ ( 0, 0, { "name": self.product_id.name, "product_id": self.product_id.id, "product_uom_qty": 2, "product_uom": self.product_id.uom_id.id, "price_unit": self.product_id.list_price, "start_date": self.default_start_date, "end_date": self.default_end_date, }, ) ], } ) self.so.action_confirm() def test_default_start_date_change(self): with self.assertRaises(ValidationError): self.so.write( { "default_start_date": self.default_end_date, "default_end_date": self.default_start_date, } ) self.so.default_start_date_change() def test_default_end_date_change(self): with self.assertRaises(ValidationError): self.so.write( { "default_start_date": self.default_end_date, "default_end_date": self.default_start_date, } ) self.so.default_end_date_change() def test_start_end_dates_product_id_change(self): if self.so.default_end_date and self.so.default_end_date: self.so.order_line.start_end_dates_product_id_change() self.so.order_line.start_date_change() self.so.order_line.end_date_change() def test_start_end_dates_product_id(self): self.product_id.must_have_dates = False self.so.default_start_date = self.so.default_end_date = False self.so.order_line.start_end_dates_product_id_change() def test_end_date_change(self): self.product_id.must_have_dates = False self.so.order_line.write( {"start_date": self.default_end_date, "end_date": self.default_start_date} ) self.so.order_line.end_date_change() def test_start_date_change(self): self.product_id.must_have_dates = False self.so.order_line.write( {"start_date": self.default_end_date, "end_date": self.default_start_date} ) self.so.order_line.start_date_change() def test_constrains_end_dates(self): with self.assertRaises(ValidationError): self.so.order_line.end_date = False def test_constrains_start_date(self): with self.assertRaises(ValidationError): self.so.order_line.start_date = False def test_constrains_greater_st_date(self): with self.assertRaises(ValidationError): self.so.order_line.write( { "start_date": self.default_end_date, "end_date": self.default_start_date, } ) def test_compute_number_of_days(self): self.assertEqual(self.so.order_line[0].number_of_days, 10) def test_inverse_number_of_days(self): self.so.order_line[0].number_of_days = 1 self.assertEqual( self.so.order_line[0].start_date, self.so.order_line[0].end_date )
38.403509
4,378
6,623
py
PYTHON
15.0
# Copyright 2014-2021 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools.misc import format_date class SaleOrder(models.Model): _inherit = "sale.order" default_start_date = fields.Date() default_end_date = fields.Date() @api.constrains("default_start_date", "default_end_date") def _check_default_start_end_dates(self): for order in self: if ( order.default_start_date and order.default_end_date and order.default_start_date > order.default_end_date ): raise ValidationError( _( "Default Start Date ({start_date}) should be before or be the " "same as Default End Date ({end_date}) for sale order '{name}'." ).format( start_date=format_date(self.env, order.default_start_date), end_date=format_date(self.env, order.default_end_date), name=order.display_name, ) ) @api.onchange("default_start_date") def default_start_date_change(self): if ( self.default_start_date and self.default_end_date and self.default_start_date > self.default_end_date ): self.default_end_date = self.default_start_date @api.onchange("default_end_date") def default_end_date_change(self): if ( self.default_start_date and self.default_end_date and self.default_start_date > self.default_end_date ): self.default_start_date = self.default_end_date class SaleOrderLine(models.Model): _inherit = "sale.order.line" start_date = fields.Date( readonly=True, states={"draft": [("readonly", False)], "sent": [("readonly", False)]}, ) end_date = fields.Date( readonly=True, states={"draft": [("readonly", False)], "sent": [("readonly", False)]}, ) number_of_days = fields.Integer( compute="_compute_number_of_days", inverse="_inverse_number_of_days", readonly=False, store=True, ) must_have_dates = fields.Boolean(related="product_id.must_have_dates") @api.depends("start_date", "end_date") def _compute_number_of_days(self): for line in self: days = False if line.start_date and line.end_date: days = (line.end_date - line.start_date).days + 1 line.number_of_days = days @api.onchange("number_of_days") def _inverse_number_of_days(self): res = {"warning": {}} for line in self: if line.number_of_days < 0: res["warning"]["title"] = _("Wrong number of days") res["warning"]["message"] = _( "On sale order line with product '{product_name}', the " "number of days is negative ({number_of_days}) ; this is not " "allowed. The number of days has been forced to 1." ).format( product_name=line.product_id.display_name, number_of_days=line.number_of_days, ) line.number_of_days = 1 if line.start_date: line.end_date = line.start_date + relativedelta( days=line.number_of_days - 1 ) elif line.end_date: line.start_date = line.end_date - relativedelta( days=line.number_of_days - 1 ) return res @api.constrains("product_id", "start_date", "end_date") def _check_start_end_dates(self): for line in self: if line.product_id.must_have_dates: if not line.end_date: raise ValidationError( _("Missing End Date for sale order line with " "Product '%s'.") % (line.product_id.display_name) ) if not line.start_date: raise ValidationError( _( "Missing Start Date for sale order line with " "Product '%s'." ) % (line.product_id.display_name) ) if line.start_date > line.end_date: raise ValidationError( _( "Start Date ({start_date}) should be before or " "be the same as End Date ({end_date}) for sale order line " "with Product '{product_name}'." ).format( start_date=format_date(self.env, line.start_date), end_date=format_date(self.env, line.end_date), product_name=line.product_id.display_name, ) ) def _prepare_invoice_line(self, **optional_values): self.ensure_one() res = super()._prepare_invoice_line(**optional_values) if not self.display_type and self.must_have_dates: res.update({"start_date": self.start_date, "end_date": self.end_date}) return res @api.onchange("end_date") def end_date_change(self): if self.end_date: if self.start_date and self.start_date > self.end_date: self.start_date = self.end_date @api.onchange("start_date") def start_date_change(self): if self.start_date: if self.end_date and self.start_date > self.end_date: self.end_date = self.start_date @api.onchange("product_id") def start_end_dates_product_id_change(self): if self.product_id.must_have_dates: if self.order_id.default_start_date: self.start_date = self.order_id.default_start_date else: self.start_date = False if self.order_id.default_end_date: self.end_date = self.order_id.default_end_date else: self.end_date = False else: self.start_date = False self.end_date = False
38.730994
6,623
582
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale product set layout", "category": "Sale", "author": "ACSONE SA/NV, Anybox, Odoo Community Association (OCA)", "version": "15.0.1.0.1", "license": "AGPL-3", "website": "https://github.com/OCA/sale-workflow", "summary": "This module allows to add sections with product sets", "depends": [ "sale_product_set", ], "data": [ "views/product_set.xml", "wizards/product_set_add.xml", ], "demo": [ "demo/product_set.xml", ], }
29.1
582
1,468
py
PYTHON
15.0
from odoo.tests import common class TestProductSetLayout(common.TransactionCase): """Test Product set""" def setUp(self): super(TestProductSetLayout, self).setUp() self.product_set_add = self.env["product.set.add"] def test_add_set(self): so = self.env.ref("sale.sale_order_6") base_line_ids = so.order_line count_lines = len(so.order_line) product_set_with_section = self.env.ref("sale_product_set.product_set_services") so_set = self.product_set_add.create( { "product_set_id": product_set_with_section.id, "quantity": 2, "order_id": so.id, } ) so_set.add_set() self.assertEqual(len(so.order_line), count_lines + 3) products_in_set = product_set_with_section.set_line_ids.filtered( lambda a: a.product_id ).mapped("product_id") # Check lines with products for line in so.order_line.filtered( lambda a: a.id not in base_line_ids.ids and a.product_id ): self.assertFalse(line.display_type) self.assertTrue(line.product_id.id in products_in_set.ids) # Test sections for line in so.order_line.filtered( lambda a: a.id not in base_line_ids.ids and not a.product_id ): self.assertEqual( line.display_type, "line_section", )
35.804878
1,468
318
py
PYTHON
15.0
from odoo import fields, models class ProductSetLine(models.Model): _inherit = "product.set.line" product_id = fields.Many2one(required=False) display_type = fields.Selection( [ ("line_section", "Section"), ("line_note", "Note"), ] ) name = fields.Char()
22.714286
318
504
py
PYTHON
15.0
from odoo import models class ProductSetAdd(models.TransientModel): _inherit = "product.set.add" def prepare_sale_order_line_data(self, set_line, max_sequence=0): """ Adds specific sections data to lines """ sol_data = super().prepare_sale_order_line_data(set_line, max_sequence) if set_line.display_type: sol_data.update( {"name": set_line.name, "display_type": set_line.display_type} ) return sol_data
29.647059
504
454
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # Copyright 2017 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID from odoo.api import Environment def post_init_hook(cr, pool): """ Fetches all the sale order and resets the sequence of the order lines """ env = Environment(cr, SUPERUSER_ID, {}) sale = env["sale.order"].search([]) sale._reset_sequence()
30.266667
454
643
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # Copyright 2017 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Sale Order Line Sequence", "summary": "Propagates SO line sequence to invoices and stock picking.", "version": "15.0.1.0.0", "author": "ForgeFlow, Serpent CS, Odoo Community Association (OCA)", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "license": "AGPL-3", "data": ["views/sale_view.xml", "views/report_saleorder.xml"], "depends": ["sale"], "post_init_hook": "post_init_hook", "installable": True, }
37.823529
643
1,238
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo.tests.common import TransactionCase class TestSaleOrderLineSequence(TransactionCase): def setUp(self): super(TestSaleOrderLineSequence, self).setUp() self.sale_order = self.env["sale.order"] self.sale_order_line = self.env["sale.order.line"] self.partner = self.env.ref("base.res_partner_1") self.product = self.env.ref("product.product_product_4") def test_sale_order_line_sequence(self): vals = { "partner_id": self.partner.id, "order_line": [ ( 0, 0, { "product_id": self.product.id, "name": self.product.name, "product_uom_qty": 1.0, "price_unit": self.product.lst_price, }, ) ], } so1 = self.sale_order.create(vals) so1.action_confirm() self.assertEqual(so1.order_line.sequence, 1) so2 = so1.copy() self.assertEqual(so2.order_line.sequence, 1)
35.371429
1,238
2,328
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # Copyright 2017 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" @api.depends("order_line") def _compute_max_line_sequence(self): """Allow to know the highest sequence entered in sale order lines. Then we add 1 to this value for the next sequence. This value is given to the context of the o2m field in the view. So when we create new sale order lines, the sequence is automatically added as : max_sequence + 1 """ for sale in self: sale.max_line_sequence = max(sale.mapped("order_line.sequence") or [0]) + 1 max_line_sequence = fields.Integer( string="Max sequence in lines", compute="_compute_max_line_sequence", store=True ) def _reset_sequence(self): for rec in self: current_sequence = 1 for line in sorted(rec.order_line, key=lambda x: (x.sequence, x.id)): if line.sequence != current_sequence: line.sequence = current_sequence current_sequence += 1 def write(self, line_values): res = super(SaleOrder, self).write(line_values) self._reset_sequence() return res def copy(self, default=None): return super(SaleOrder, self.with_context(keep_line_sequence=True)).copy( default ) class SaleOrderLine(models.Model): _inherit = "sale.order.line" # re-defines the field to change the default sequence = fields.Integer( help="Gives the sequence of this line when displaying the sale order.", default=9999, ) # displays sequence on the order line sequence2 = fields.Integer( help="Shows the sequence of this line in the sale order.", related="sequence", string="Line Number", readonly=True, store=True, ) @api.model def create(self, values): line = super(SaleOrderLine, self).create(values) # We do not reset the sequence if we are copying a complete sale order if self.env.context.get("keep_line_sequence"): line.order_id._reset_sequence() return line
33.73913
2,328
563
py
PYTHON
15.0
# Copyright 2017-To Day Akretion # @author Sébastien BEAU <sebastien.beau@akretion.com> # @author: Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> { "name": "Sale shipping info helper", "version": "15.0.1.0.0", "category": "Sales", "license": "AGPL-3", "development_status": "Production/Stable", "summary": "Add shipping amounts on sale order", "depends": ["sale", "delivery"], "author": "Akretion, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "installable": True, }
33.058824
562
4,506
py
PYTHON
15.0
# Copyright 2017 Akretion (Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import Form, common from odoo.tools import float_compare class TestDeliveryCost(common.TransactionCase): def setUp(self): super(TestDeliveryCost, self).setUp() self.tax_model = self.env["account.tax"] self.SaleOrder = self.env["sale.order"] self.SaleOrderLine = self.env["sale.order.line"] self.partner_18 = self.env.ref("base.res_partner_18") self.pricelist = self.env.ref("product.list0") self.product_4 = self.env.ref("product.product_product_4") self.product_uom_unit = self.env.ref("uom.product_uom_unit") self.normal_delivery = self.env.ref("delivery.normal_delivery_carrier") def test_00_shipping_info(self): # Create sale order with Normal Delivery Charges self.percent_tax = self.tax_model.create( { "name": "Percent tax", "amount_type": "percent", "amount": 10, "sequence": 3, } ) self.normal_delivery.product_id.taxes_id = self.percent_tax self.sale = self.SaleOrder.create( { "partner_id": self.partner_18.id, "partner_invoice_id": self.partner_18.id, "partner_shipping_id": self.partner_18.id, "pricelist_id": self.pricelist.id, "order_line": [ ( 0, 0, { "name": "PC Assamble + 2GB RAM", "product_id": self.product_4.id, "product_uom_qty": 1, "product_uom": self.product_uom_unit.id, "price_unit": 750.00, "tax_id": [(4, self.percent_tax.id, 0)], }, ) ], "carrier_id": self.normal_delivery.id, } ) # set delivery cost in Sales order delivery_wizard = Form( self.env["choose.delivery.carrier"].with_context( default_order_id=self.sale.id, default_carrier_id=self.normal_delivery.id, ) ) choose_delivery_carrier = delivery_wizard.save() choose_delivery_carrier.button_confirm() # check sale order computed field after added delivery cost line = self.SaleOrderLine.search( [ ("order_id", "=", self.sale.id), ("product_id", "=", self.sale.carrier_id.product_id.id), ] ) self.assertEqual(len(line), 1, "Delivery cost is not Added") self.assertEqual( float_compare(line.price_subtotal, 10, precision_digits=2), 0, "Sale line delivery price subtotal is not correct", ) self.assertEqual( float_compare(line.price_total, 11, precision_digits=2), 0, "Sale line delivery price total is not correct", ) self.assertEqual( float_compare(line.price_tax, 1, precision_digits=2), 0, "Sale line delivery price tax is not correct", ) self.assertEqual( float_compare(self.sale.shipping_amount_tax, 1, precision_digits=2), 0, "Shipping amount tax is not correct", ) self.assertEqual( float_compare(self.sale.shipping_amount_untaxed, 10, precision_digits=2), 0, "Shipping amount untaxed is not correct", ) self.assertEqual( float_compare(self.sale.shipping_amount_total, 11, precision_digits=2), 0, "Shipping amount total is not correct", ) self.assertEqual( float_compare(self.sale.item_amount_tax, 75, precision_digits=2), 0, "Item amount tax is not correct", ) self.assertEqual( float_compare(self.sale.item_amount_untaxed, 750, precision_digits=2), 0, "Item amount untaxed is not correct", ) self.assertEqual( float_compare(self.sale.item_amount_total, 825.0, precision_digits=2), 0, "Item amount total is not correct", )
37.865546
4,506
1,922
py
PYTHON
15.0
# Copyright 2017-To Day Akretion # @author Sébastien BEAU <sebastien.beau@akretion.com> # @author: Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" shipping_amount_total = fields.Float( compute="_compute_shipping", digits="Account", store=True ) shipping_amount_untaxed = fields.Float( compute="_compute_shipping", digits="Account", store=True ) shipping_amount_tax = fields.Float( compute="_compute_shipping", digits="Account", store=True ) item_amount_total = fields.Float( compute="_compute_shipping", digits="Account", store=True ) item_amount_untaxed = fields.Float( compute="_compute_shipping", digits="Account", store=True ) item_amount_tax = fields.Float( compute="_compute_shipping", digits="Account", store=True ) @api.depends("amount_total", "amount_untaxed") def _compute_shipping(self): for record in self: shipping_amount_untaxed = shipping_amount_total = shipping_amount_tax = 0 for line in record.order_line: if not line.is_delivery: continue shipping_amount_untaxed += line.price_subtotal shipping_amount_total += line.price_total shipping_amount_tax += line.price_tax record.update( { "shipping_amount_untaxed": shipping_amount_untaxed, "shipping_amount_total": shipping_amount_total, "shipping_amount_tax": shipping_amount_tax, } ) for key in ["amount_total", "amount_untaxed", "amount_tax"]: record["item_%s" % key] = record[key] - record["shipping_%s" % key]
38.42
1,921
481
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "GraphQL Demo", "version": "14.0.1.0.0", "license": "LGPL-3", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": ["graphql_base"], "external_dependencies": {"python": ["graphene"]}, "development_status": "Beta", "maintainers": ["sbidoul"], "installable": False, }
32.066667
481
2,836
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). # disable undefined variable error, which erroneously triggers # on forward declarations of classes in lambdas # pylint: disable=E0602 import graphene from odoo import _ from odoo.exceptions import UserError from odoo.addons.graphql_base import OdooObjectType class Country(OdooObjectType): code = graphene.String(required=True) name = graphene.String(required=True) class Partner(OdooObjectType): name = graphene.String(required=True) street = graphene.String() street2 = graphene.String() city = graphene.String() zip = graphene.String() country = graphene.Field(Country) email = graphene.String() phone = graphene.String() is_company = graphene.Boolean(required=True) contacts = graphene.List(graphene.NonNull(lambda: Partner), required=True) @staticmethod def resolve_country(root, info): return root.country_id or None @staticmethod def resolve_contacts(root, info): return root.child_ids class Query(graphene.ObjectType): all_partners = graphene.List( graphene.NonNull(Partner), required=True, companies_only=graphene.Boolean(), limit=graphene.Int(), offset=graphene.Int(), ) reverse = graphene.String( required=True, description="Reverse a string", word=graphene.String(required=True), ) error_example = graphene.String() @staticmethod def resolve_all_partners(root, info, companies_only=False, limit=None, offset=None): domain = [] if companies_only: domain.append(("is_company", "=", True)) return info.context["env"]["res.partner"].search( domain, limit=limit, offset=offset ) @staticmethod def resolve_reverse(root, info, word): return word[::-1] @staticmethod def resolve_error_example(root, info): raise UserError(_("UserError example")) class CreatePartner(graphene.Mutation): class Arguments: name = graphene.String(required=True) email = graphene.String(required=True) is_company = graphene.Boolean() raise_after_create = graphene.Boolean() Output = Partner @staticmethod def mutate(self, info, name, email, is_company=False, raise_after_create=False): env = info.context["env"] partner = env["res.partner"].create( {"name": name, "email": email, "is_company": is_company} ) if raise_after_create: raise UserError(_("as requested")) return partner class Mutation(graphene.ObjectType): create_partner = CreatePartner.Field(description="Documentation of CreatePartner") schema = graphene.Schema(query=Query, mutation=Mutation)
28.079208
2,836
2,333
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import logging from graphene.test import Client from odoo.tests import TransactionCase from ..schema import schema class TestGraphene(TransactionCase): @classmethod def setUpClass(cls): super(TestGraphene, cls).setUpClass() cls.client = Client(schema) # disable logging for the graphql executor because we are testing # errors and OCA's test runner considers the two errors being logged # as fatal logging.getLogger("graphql.execution").setLevel(logging.CRITICAL) def execute(self, query): res = self.client.execute(query, context={"env": self.env}) if not res: raise RuntimeError("GraphQL query returned no data") if res.get("errors"): raise RuntimeError( "GraphQL query returned error: {}".format(repr(res["errors"])) ) return res.get("data") def test_query_all_partners(self): expected_names = set(self.env["res.partner"].search([]).mapped("name")) actual_names = { r["name"] for r in self.execute(" {allPartners{ name } }")["allPartners"] } self.assertEqual(actual_names, expected_names) def test_query_all_partners_companies_only(self): expected_names = set( self.env["res.partner"].search([("is_company", "=", True)]).mapped("name") ) actual_names = { r["name"] for r in self.execute(" {allPartners(companiesOnly: true){ name } }")[ "allPartners" ] } self.assertEqual(actual_names, expected_names) def test_error(self): r = self.client.execute("{errorExample}", context={"env": self.env}) self.assertIn("UserError example", r["errors"][0]["message"]) def test_mutation(self): mutation = """\ mutation{ createPartner( name: "toto", email: "toto@acsone.eu", ) { name } } """ self.client.execute(mutation, context={"env": self.env}) self.assertEqual( len(self.env["res.partner"].search([("name", "=", "toto")])), 1 )
33.328571
2,333
5,974
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import json from werkzeug.urls import url_encode from odoo.tests import HttpCase from odoo.tests.common import HOST from odoo.tools import config, mute_logger class TestController(HttpCase): def url_open_json(self, url, json): return self.opener.post( "http://{}:{}{}".format(HOST, config["http_port"], url), json=json ) def _check_all_partners(self, all_partners, companies_only=False): domain = [] if companies_only: domain.append(("is_company", "=", True)) expected_names = set(self.env["res.partner"].search(domain).mapped("name")) actual_names = {r["name"] for r in all_partners} self.assertEqual(actual_names, expected_names) def test_get(self): self.authenticate("admin", "admin") query = "{allPartners{name}}" data = {"query": query} r = self.url_open("/graphql/demo?" + url_encode(data)) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self._check_all_partners(r.json()["data"]["allPartners"]) def test_get_with_variables(self): self.authenticate("admin", "admin") query = """ query myQuery($companiesOnly: Boolean) { allPartners(companiesOnly: $companiesOnly) { name } } """ variables = {"companiesOnly": True} data = {"query": query, "variables": json.dumps(variables)} r = self.url_open("/graphql/demo?" + url_encode(data)) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self._check_all_partners(r.json()["data"]["allPartners"], companies_only=True) def test_post_form(self): self.authenticate("admin", "admin") query = "{allPartners{name}}" data = {"query": query} r = self.url_open("/graphql/demo", data=data) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self._check_all_partners(r.json()["data"]["allPartners"]) def test_post_form_with_variables(self): self.authenticate("admin", "admin") query = """ query myQuery($companiesOnly: Boolean) { allPartners(companiesOnly: $companiesOnly) { name } } """ variables = {"companiesOnly": True} data = {"query": query, "variables": json.dumps(variables)} r = self.url_open("/graphql/demo", data=data) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self._check_all_partners(r.json()["data"]["allPartners"], companies_only=True) def test_post_json_with_variables(self): self.authenticate("admin", "admin") query = """ query myQuery($companiesOnly: Boolean) { allPartners(companiesOnly: $companiesOnly) { name } } """ variables = {"companiesOnly": True} data = {"query": query, "variables": variables} r = self.url_open_json("/graphql/demo", data) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self._check_all_partners(r.json()["data"]["allPartners"], companies_only=True) def test_post_form_mutation(self): self.authenticate("admin", "admin") query = """ mutation { createPartner( name: "Le Héro, Toto", email: "toto@example.com" ) { name } } """ data = {"query": query} r = self.url_open("/graphql/demo", data=data) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self.assertEqual("Le Héro, Toto", r.json()["data"]["createPartner"]["name"]) self.assertEqual( len(self.env["res.partner"].search([("email", "=", "toto@example.com")])), 1 ) def test_get_mutation_not_allowed(self): """ Cannot perform a mutation with a GET, must use POST. """ self.authenticate("admin", "admin") query = """ mutation { createPartner( name: "Le Héro, Toto", email: "toto@example.com" ) { name } } """ data = {"query": query} r = self.url_open("/graphql/demo?" + url_encode(data)) self.assertEqual(r.status_code, 405) self.assertEqual(r.headers["Content-Type"], "application/json") self.assertIn( "Can only perform a mutation operation from a POST request.", r.json()["errors"][0]["message"], ) @mute_logger("graphql.execution.executor", "graphql.execution.utils") def test_post_form_mutation_rollback(self): self.authenticate("admin", "admin") query = """ mutation { createPartner( name: "Le Héro, Toto", email: "toto@example.com", raiseAfterCreate: true ) { name } } """ data = {"query": query} r = self.url_open("/graphql/demo", data=data) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers["Content-Type"], "application/json") self.assertIn("as requested", r.json()["errors"][0]["message"]) # a rollback must have occured self.assertEqual( len(self.env["res.partner"].search([("email", "=", "toto@example.com")])), 0 )
37.78481
5,970
1,078
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import http from odoo.addons.graphql_base import GraphQLControllerMixin from ..schema import schema class GraphQLController(http.Controller, GraphQLControllerMixin): # The GraphiQL route, providing an IDE for developers @http.route("/graphiql/demo", auth="user") def graphiql(self, **kwargs): return self._handle_graphiql_request(schema.graphql_schema) # Optional monkey patch, needed to accept application/json GraphQL # requests. If you only need to accept GET requests or POST # with application/x-www-form-urlencoded content, # this is not necessary. GraphQLControllerMixin.patch_for_json("^/graphql/demo/?$") # The graphql route, for applications. # Note csrf=False: you may want to apply extra security # (such as origin restrictions) to this route. @http.route("/graphql/demo", auth="user", csrf=False) def graphql(self, **kwargs): return self._handle_graphql_request(schema.graphql_schema)
37.172414
1,078
275
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) class ExtendableRegistriesDatabase(dict): """Holds an extendable classses registry for each database""" _extendable_registries_database = ExtendableRegistriesDatabase()
30.555556
275
520
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Extendable", "summary": """ Extendable classes registry loader for Odoo""", "version": "15.0.1.0.1", "development_status": "Beta", "maintainers": ["lmignon"], "license": "LGPL-3", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": [], "external_dependencies": {"python": ["extendable"]}, }
32.5
520
2,226
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from contextlib import contextmanager import odoo from odoo import api from odoo.tests import common from extendable.context import extendable_registry def _get_addon_name(full_name: str) -> str: # The (Odoo) module name can be in the ``odoo.addons`` namespace # or not. For instance, module ``sale`` can be imported as # ``odoo.addons.sale`` (the right way) or ``sale`` (for backward # compatibility). module_parts = full_name.split(".") if len(module_parts) > 2 and module_parts[:2] == ["odoo", "addons"]: addon_name = full_name.split(".")[2] else: addon_name = full_name.split(".")[0] return addon_name @contextmanager def new_rollbacked_env(): registry = odoo.registry(common.get_db_name()) uid = odoo.SUPERUSER_ID cr = registry.cursor() try: yield api.Environment(cr, uid, {}) finally: cr.rollback() # we shouldn't have to commit anything cr.close() class ExtendableMixin(object): @classmethod def setUpExtendable(cls): with new_rollbacked_env() as env: builder = env["extendable.registry.loader"] # build the extendable classes of every installed addons extendable_registry = builder._init_global_registry() cls._extendable_registry = extendable_registry # ensure that we load only the extendable classes of the 'installed' # modules, not 'to install', which means we load only the # dependencies of the tested addons, not the siblings or # children addons builder.build_registry(extendable_registry, states=("installed",)) # build the extendable classes of the current tested addon current_addon = _get_addon_name(cls.__module__) extendable_registry.init_registry([f"odoo.addons.{current_addon}.*"]) # pylint: disable=W8106 def setUp(self): # initialize the registry context token = extendable_registry.set(self._extendable_registry) @self.addCleanup def reset_context(): extendable_registry.reset(token)
35.903226
2,226
795
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) from contextlib import contextmanager from odoo import models from odoo.http import request from extendable import context from ..registry import _extendable_registries_database class IrHttp(models.AbstractModel): _inherit = "ir.http" @classmethod def _dispatch(cls): with cls._extendable_context_registry(): return super()._dispatch() @classmethod @contextmanager def _extendable_context_registry(cls): registry = _extendable_registries_database.get(request.env.cr.dbname, {}) token = context.extendable_registry.set(registry) try: yield finally: context.extendable_registry.reset(token)
26.5
795
2,293
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) """ Extendale classes Loader ======================== Load the extendable classes at the build of a registry. """ from typing import List, Optional import odoo from odoo import api, models from extendable.registry import ExtendableClassesRegistry from ..registry import _extendable_registries_database class ExtendableRegistryLoader(models.AbstractModel): _name = "extendable.registry.loader" _description = "Extendable Registry Loader" def _register_hook(self): # This method is called by Odoo when the registry is built, # so in case the registry is rebuilt (cache invalidation, ...), # we have to to rebuild the extendable classes. We use a new # registry so we have an empty cache and we'll add extendable classes # in it. registry = self._init_global_registry() self.build_registry(registry) @api.model def _init_global_registry(self): registry = ExtendableClassesRegistry() _extendable_registries_database[self.env.cr.dbname] = registry return registry @api.model def build_registry( self, registry: ExtendableClassesRegistry, states: Optional[List[str]] = None, exclude_addons: Optional[List[str]] = None, ): if not states: states = ("installed", "to upgrade") # lookup all the installed (or about to be) addons and generate # the graph, so we can load the components following the order # of the addons' dependencies graph = odoo.modules.graph.Graph() graph.add_module(self.env.cr, "base") query = "SELECT name " "FROM ir_module_module " "WHERE state IN %s " params = [tuple(states)] if exclude_addons: query += " AND name NOT IN %s " params.append(tuple(exclude_addons)) self.env.cr.execute(query, params) module_list = [name for (name,) in self.env.cr.fetchall() if name not in graph] graph.add_modules(self.env.cr, module_list) module_matchings = [] for m in graph: module_matchings.append(f"odoo.addons.{m.name}.*") registry.init_registry(module_matchings)
33.720588
2,293
758
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Base Rest Demo", "summary": """ Demo addon for Base REST""", "version": "15.0.1.0.2", "development_status": "Beta", "license": "LGPL-3", "author": "ACSONE SA/NV, " "Odoo Community Association (OCA)", "maintainers": ["lmignon"], "website": "https://github.com/OCA/rest-framework", "depends": [ "base_rest", "base_rest_datamodel", "base_rest_pydantic", "component", "extendable", "pydantic", ], "data": [], "demo": [], "external_dependencies": { "python": ["jsondiff", "extendable-pydantic", "pydantic"] }, "installable": True, }
27.071429
758
771
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from marshmallow import fields from odoo.addons.datamodel.core import Datamodel from odoo.addons.datamodel.fields import NestedModel class PartnerInfo(Datamodel): _name = "partner.info" _inherit = "partner.short.info" street = fields.String(required=True, allow_none=False) street2 = fields.String(required=False, allow_none=True) zip_code = fields.String(required=True, allow_none=False) city = fields.String(required=True, allow_none=False) phone = fields.String(required=False, allow_none=True) state = NestedModel("state.info") country = NestedModel("country.info") is_company = fields.Boolean(required=False, allow_none=False)
36.714286
771
347
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from marshmallow import fields from odoo.addons.datamodel.core import Datamodel class StateInfo(Datamodel): _name = "state.info" id = fields.Integer(required=True, allow_none=False) name = fields.String(required=True, allow_none=False)
26.692308
347
351
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from marshmallow import fields from odoo.addons.datamodel.core import Datamodel class CountryInfo(Datamodel): _name = "country.info" id = fields.Integer(required=True, allow_none=False) name = fields.String(required=True, allow_none=False)
27
351
368
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from marshmallow import fields from odoo.addons.datamodel.core import Datamodel class PartnerSearchParam(Datamodel): _name = "partner.search.param" id = fields.Integer(required=False, allow_none=False) name = fields.String(required=False, allow_none=False)
28.307692
368
362
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from marshmallow import fields from odoo.addons.datamodel.core import Datamodel class PartnerShortInfo(Datamodel): _name = "partner.short.info" id = fields.Integer(required=True, allow_none=False) name = fields.String(required=True, allow_none=False)
27.846154
362
2,007
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import jsondiff from .common import CommonCase, get_canonical_json class TestOpenAPI(CommonCase): def _fix_server_url(self, openapi_def): # The server url depends of base_url. base_url depends of the odoo # config url = openapi_def["servers"][0]["url"] url.replace("http://localhost:8069", self.base_url) openapi_def["servers"][0]["url"] = url def _fix_openapi_components(self, openapi_def): """ Remove additional components that could be added by others addons than base_rest """ security_components = openapi_def.get("components", {}).get( "securitySchemes", {} ) unknow_keys = set(security_components.keys()) - {"user"} for key in unknow_keys: del security_components[key] def assertOpenApiDef(self, service, canocincal_json_file, default_auth): openapi_def = service.to_openapi(default_auth=default_auth) self._fix_openapi_components(openapi_def) canonical_def = get_canonical_json(canocincal_json_file) self._fix_server_url(canonical_def) self.assertFalse(jsondiff.diff(openapi_def, canonical_def)) def test_partner_api(self): service = self.private_services_env.component(usage="partner") self.assertOpenApiDef(service, "partner_api.json", "user") def test_ping_api(self): service = self.public_services_env.component(usage="ping") self.assertOpenApiDef(service, "ping_api.json", "public") def test_partner_image_api(self): service = self.private_services_env.component(usage="partner_image") self.assertOpenApiDef(service, "partner_image_api.json", "user") def test_partner_pydantic_api(self): service = self.new_api_services_env.component(usage="partner_pydantic") self.assertOpenApiDef(service, "partner_pydantic_api.json", "public")
40.14
2,007
1,605
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import json import os from odoo.addons.base_rest.controllers.main import _PseudoCollection from odoo.addons.base_rest.tests.common import BaseRestCase from odoo.addons.component.core import WorkContext from odoo.addons.extendable.tests.common import ExtendableMixin DATA_DIR = os.path.join(os.path.realpath(os.path.dirname(__file__)), "data") class CommonCase(BaseRestCase, ExtendableMixin): @classmethod def setUpClass(cls): super(CommonCase, cls).setUpClass() collection = _PseudoCollection("base.rest.demo.private.services", cls.env) cls.private_services_env = WorkContext( model_name="rest.service.registration", collection=collection ) collection = _PseudoCollection("base.rest.demo.public.services", cls.env) cls.public_services_env = WorkContext( model_name="rest.service.registration", collection=collection ) collection = _PseudoCollection("base.rest.demo.new_api.services", cls.env) cls.new_api_services_env = WorkContext( model_name="rest.service.registration", collection=collection ) cls.setUpExtendable() # pylint: disable=W8106 def setUp(self): # resolve an inheritance issue (common.TransactionCase does not call # super) BaseRestCase.setUp(self) ExtendableMixin.setUp(self) def get_canonical_json(file_name): path = os.path.join(DATA_DIR, file_name) with open(path, "r") as f: return json.load(f)
35.666667
1,605
4,405
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import json import odoo.tools from odoo.tests import HttpCase from odoo.tests.common import tagged from odoo.addons.base_rest.tests.common import RegistryMixin @tagged("-at_install", "post_install") class TestException(HttpCase, RegistryMixin): @classmethod def setUpClass(cls): super(TestException, cls).setUpClass() cls.setUpRegistry() host = "127.0.0.1" port = odoo.tools.config["http_port"] cls.url = "http://%s:%d/base_rest_demo_api/public/exception" % (host, port) def setUp(self): super(TestException, self).setUp() self.opener.headers["Content-Type"] = "application/json" @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_user_error(self): response = self.url_open("%s/user_error" % self.url, "{}") self.assertEqual(response.status_code, 400) self.assertEqual(response.headers["content-type"], "application/json") body = json.loads(response.content.decode("utf-8")) self.assertDictEqual( body, { "code": 400, "name": "Bad Request", "description": "<p>UserError message</p>", }, ) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_validation_error(self): response = self.url_open("%s/validation_error" % self.url, "{}") self.assertEqual(response.status_code, 400) self.assertEqual(response.headers["content-type"], "application/json") body = json.loads(response.content.decode("utf-8")) self.assertDictEqual( body, { "code": 400, "name": "Bad Request", "description": "<p>ValidationError message</p>", }, ) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_session_expired(self): response = self.url_open("%s/session_expired" % self.url, "{}") self.assertEqual(response.status_code, 401) self.assertEqual(response.headers["content-type"], "application/json") body = json.loads(response.content.decode("utf-8")) self.assertDictEqual(body, {"code": 401, "name": "Unauthorized"}) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_missing_error(self): response = self.url_open("%s/missing_error" % self.url, "{}") self.assertEqual(response.status_code, 404) self.assertEqual(response.headers["content-type"], "application/json") body = json.loads(response.content.decode("utf-8")) self.assertDictEqual(body, {"code": 404, "name": "Not Found"}) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_access_error(self): response = self.url_open("%s/access_error" % self.url, "{}") self.assertEqual(response.status_code, 403) self.assertEqual(response.headers["content-type"], "application/json") body = json.loads(response.content.decode("utf-8")) self.assertDictEqual(body, {"code": 403, "name": "Forbidden"}) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_access_denied(self): response = self.url_open("%s/access_denied" % self.url, "{}") self.assertEqual(response.status_code, 403) self.assertEqual(response.headers["content-type"], "application/json") body = json.loads(response.content.decode("utf-8")) self.assertDictEqual(body, {"code": 403, "name": "Forbidden"}) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_http_exception(self): response = self.url_open("%s/http_exception" % self.url, "{}") self.assertEqual(response.status_code, 405) self.assertEqual(response.headers["content-type"], "text/html") body = response.content self.assertIn(b"Method Not Allowed", body) @odoo.tools.mute_logger("odoo.addons.base_rest.http") def test_bare_exception(self): response = self.url_open("%s/bare_exception" % self.url, "{}") self.assertEqual(response.status_code, 500) self.assertEqual(response.headers["content-type"], "application/json") body = json.loads(response.content.decode("utf-8")) self.assertDictEqual(body, {"code": 500, "name": "Internal Server Error"})
43.186275
4,405
1,635
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.http import controllers_per_module from ..controllers.main import ( BaseRestDemoJwtApiController, BaseRestDemoNewApiController, BaseRestDemoPrivateApiController, BaseRestDemoPublicApiController, ) from .common import CommonCase class TestController(CommonCase): def test_controller_registry(self): # at the end of the start process, our tow controllers must into the # controller registered controllers = controllers_per_module["base_rest_demo"] self.assertEqual(len(controllers), 4) self.assertIn( ( "odoo.addons.base_rest_demo.controllers.main." "BaseRestDemoPrivateApiController", BaseRestDemoPrivateApiController, ), controllers, ) self.assertIn( ( "odoo.addons.base_rest_demo.controllers.main." "BaseRestDemoPublicApiController", BaseRestDemoPublicApiController, ), controllers, ) self.assertIn( ( "odoo.addons.base_rest_demo.controllers.main." "BaseRestDemoNewApiController", BaseRestDemoNewApiController, ), controllers, ) self.assertIn( ( "odoo.addons.base_rest_demo.controllers.main." "BaseRestDemoJwtApiController", BaseRestDemoJwtApiController, ), controllers, )
30.849057
1,635
558
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import pydantic from .country_info import CountryInfo from .partner_short_info import PartnerShortInfo from .state_info import StateInfo class PartnerInfo(PartnerShortInfo): street: str street2: str = None zip_code: str = pydantic.Field(..., alias="zip") city: str phone: str = None state: StateInfo = pydantic.Field(..., alias="state_id") country: CountryInfo = pydantic.Field(..., alias="country_id") is_company: bool = None
27.9
558
199
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from .naive_orm_model import NaiveOrmModel class StateInfo(NaiveOrmModel): id: int name: str
19.9
199
201
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from .naive_orm_model import NaiveOrmModel class CountryInfo(NaiveOrmModel): id: int name: str
20.1
201
372
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from extendable_pydantic import ExtendableModelMeta from odoo.addons.pydantic import utils from pydantic import BaseModel class NaiveOrmModel(BaseModel, metaclass=ExtendableModelMeta): class Config: orm_mode = True getter_dict = utils.GenericOdooGetter
26.571429
372
290
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from extendable_pydantic import ExtendableModelMeta from pydantic import BaseModel class PartnerSearchParam(BaseModel, metaclass=ExtendableModelMeta): id: int = None name: str = None
24.166667
290
206
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from .naive_orm_model import NaiveOrmModel class PartnerShortInfo(NaiveOrmModel): id: int name: str
20.6
206
1,142
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.base_rest.controllers import main class BaseRestDemoPublicApiController(main.RestController): _root_path = "/base_rest_demo_api/public/" _collection_name = "base.rest.demo.public.services" _default_auth = "public" class BaseRestDemoPrivateApiController(main.RestController): _root_path = "/base_rest_demo_api/private/" _collection_name = "base.rest.demo.private.services" _default_auth = "user" class BaseRestDemoNewApiController(main.RestController): _root_path = "/base_rest_demo_api/new_api/" _collection_name = "base.rest.demo.new_api.services" _default_auth = "public" class BaseRestDemoJwtApiController(main.RestController): # JWT Demo Controller, to be used with auth_jwt_demo # https://github.com/OCA/server-auth/tree/15.0/auth_jwt_demo _root_path = "/base_rest_demo_api/jwt/" _collection_name = "base.rest.demo.jwt.services" _default_auth = "jwt_demo_keycloak" _component_context_provider = "auth_jwt_component_context_provider" _default_cors = "*"
35.6875
1,142
288
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import Component class PingJwtService(Component): _inherit = "ping.service" _name = "ping.jwt.service" _collection = "base.rest.demo.jwt.services"
28.8
288
1,798
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import base64 from odoo import _ from odoo.exceptions import MissingError from odoo.http import request from odoo.addons.base_rest.components.service import skip_secure_response from odoo.addons.component.core import Component class PartnerImageService(Component): _inherit = "base.rest.service" _name = "partner_image.service" _usage = "partner_image" _collection = "base.rest.demo.private.services" _description = """ Partner Image Services Service used to retrieve the partner's image Access to the partner image service is only allowed to authenticated users. If you are not authenticated go to <a href='/web/login'>Login</a> """ @skip_secure_response def get(self, _id, size): """ Get partner's image """ field = "image" if size == "small": field = "image_small" elif size == "medium": field = "image_medium" status, headers, content = self.env["ir.http"].binary_content( model="res.partner", id=_id, field=field ) if not content: raise MissingError(_("No image found for partner %s") % _id) image_base64 = base64.b64decode(content) headers.append(("Content-Length", len(image_base64))) response = request.make_response(image_base64, headers) response.status_code = status return response # Validator def _validator_get(self): return { "size": { "type": "string", "required": False, "default": "small", "allowed": ["small", "medium", "large"], } }
31.54386
1,798
3,635
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from werkzeug.exceptions import MethodNotAllowed from odoo import _ from odoo.exceptions import ( AccessDenied, AccessError, MissingError, UserError, ValidationError, ) from odoo.http import SessionExpiredException from odoo.addons.component.core import Component class ExceptionService(Component): _inherit = "base.rest.service" _name = "exception.service" _usage = "exception" _collection = "base.rest.demo.public.services" _description = """ Exception Services Services to test hiw exception are handled by base_erst """ def user_error(self): """ Simulate an odoo.exceptions.UserError Should be translated into BadRequest with a description into the json body """ raise UserError(_("UserError message")) def validation_error(self): """ Simulate an odoo.exceptions.ValidationError Should be translated into BadRequest with a description into the json body """ raise ValidationError(_("ValidationError message")) def session_expired(self): """ Simulate an odoo.http.SessionExpiredException Should be translated into Unauthorized without description into the json body """ raise SessionExpiredException("Expired message") def missing_error(self): """ Simulate an odoo.exceptions.MissingError Should be translated into NotFound without description into the json body """ raise MissingError(_("Missing message")) def access_error(self): """ Simulate an odoo.exceptions.AccessError Should be translated into Forbidden without description into the json body """ raise AccessError(_("Access error message")) def access_denied(self): """ Simulate an odoo.exceptions.AccessDenied Should be translated into Forbidden without description into the json body """ raise AccessDenied() def http_exception(self): """ Simulate an werkzeug.exceptions.MethodNotAllowed This exception is not by the framework """ raise MethodNotAllowed(description="Method not allowed message") def bare_exception(self): """ Simulate a python exception. Should be translated into InternalServerError without description into the json body """ raise IOError("My IO error") # Validator def _validator_user_error(self): return {} def _validator_return_user_error(self): return {} def _validator_validation_error(self): return {} def _validator_return_validation_error(self): return {} def _validator_session_expired(self): return {} def _validator_return_session_expired(self): return {} def _validator_missing_error(self): return {} def _validator_return_missing_error(self): return {} def _validator_access_error(self): return {} def _validator_return_access_error(self): return {} def _validator_access_denied(self): return {} def _validator_return_access_denied(self): return {} def _validator_http_exception(self): return {} def _validator_return_http_exception(self): return {} def _validator_bare_exception(self): return {} def _validator_return_bare_exception(self): return {}
25.964286
3,635
2,773
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.base_rest.components.service import to_int from odoo.addons.component.core import Component class PingService(Component): _inherit = "base.rest.service" _name = "ping.service" _usage = "ping" _collection = "base.rest.demo.public.services" _description = """ Ping Services Access to the ping services is allowed to everyone """ # The following method are 'public' and can be called from the controller. def get(self, _id, message): """ This method is used to get the information of the object specified by Id. """ return {"message": message, "id": _id} def search(self, **params): """ A search method to illustrate how you can define a complex request. In the case of the methods 'get' and 'search' the parameters are passed to the server as the query part of the service URL. """ return {"response": "Search called search with params %s" % params} def update(self, _id, message): """ Update method description ... """ return {"response": "PUT called with message " + message} # pylint:disable=method-required-super def create(self, **params): """ Create method description ... """ return {"response": "POST called with message " + params["message"]} def delete(self, _id): """ Delete method description ... """ return {"response": "DELETE called with id %s " % _id} # Validator def _validator_search(self): return { "param_string": {"type": "string"}, "param_required": {"type": "string", "required": True}, "limit": {"type": "integer", "default": 50, "coerce": to_int}, "offset": {"type": "integer", "default": 0, "coerce": to_int}, "params": {"type": "list", "schema": {"type": "string"}}, } def _validator_return_search(self): return {"response": {"type": "string"}} # Validator def _validator_get(self): return {"message": {"type": "string"}} def _validator_return_get(self): return {"message": {"type": "string"}, "id": {"type": "integer"}} def _validator_update(self): return {"message": {"type": "string"}} def _validator_return_update(self): return {"response": {"type": "string"}} def _validator_create(self): return {"message": {"type": "string"}} def _validator_return_create(self): return {"response": {"type": "string"}} def _validator_return_delete(self): return {"response": {"type": "string"}}
32.623529
2,773
2,660
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.base_rest import restapi from odoo.addons.base_rest_datamodel.restapi import Datamodel from odoo.addons.component.core import Component class PartnerNewApiService(Component): _inherit = "base.rest.service" _name = "partner.new_api.service" _usage = "partner" _collection = "base.rest.demo.new_api.services" _description = """ Partner New API Services Services developed with the new api provided by base_rest """ @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=Datamodel("partner.info"), auth="public", ) def get(self, _id): """ Get partner's information """ partner = self._get(_id) PartnerInfo = self.env.datamodels["partner.info"] partner_info = PartnerInfo(partial=True) partner_info.id = partner.id partner_info.name = partner.name partner_info.street = partner.street partner_info.street2 = partner.street2 partner_info.zip_code = partner.zip partner_info.city = partner.city partner_info.phone = partner.phone partner_info.country = self.env.datamodels["country.info"]( id=partner.country_id.id, name=partner.country_id.name ) partner_info.state = self.env.datamodels["state.info"]( id=partner.state_id.id, name=partner.state_id.name ) partner_info.is_company = partner.is_company return partner_info @restapi.method( [(["/", "/search"], "GET")], input_param=Datamodel("partner.search.param"), output_param=Datamodel("partner.short.info", is_list=True), auth="public", ) def search(self, partner_search_param): """ Search for partners :param partner_search_param: An instance of partner.search.param :return: List of partner.short.info """ domain = [] if partner_search_param.name: domain.append(("name", "like", partner_search_param.name)) if partner_search_param.id: domain.append(("id", "=", partner_search_param.id)) res = [] PartnerShortInfo = self.env.datamodels["partner.short.info"] for p in self.env["res.partner"].search(domain): res.append(PartnerShortInfo(id=p.id, name=p.name)) return res # The following method are 'private' and should be never never NEVER call # from the controller. def _get(self, _id): return self.env["res.partner"].browse(_id)
36.438356
2,660
2,100
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.base_rest import restapi from odoo.addons.base_rest_pydantic.restapi import PydanticModel, PydanticModelList from odoo.addons.component.core import Component from ..pydantic_models.partner_info import PartnerInfo from ..pydantic_models.partner_search_param import PartnerSearchParam from ..pydantic_models.partner_short_info import PartnerShortInfo class PartnerNewApiService(Component): _inherit = "base.rest.service" _name = "partner.pydantic.service" _usage = "partner_pydantic" _collection = "base.rest.demo.new_api.services" _description = """ Partner New API Services Services developed with the new api provided by base_rest and pydantic """ @restapi.method( [(["/<int:id>/get", "/<int:id>"], "GET")], output_param=PydanticModel(PartnerInfo), auth="public", ) def get(self, _id): """ Get partner's information """ partner = self._get(_id) return PartnerInfo.from_orm(partner) @restapi.method( [(["/", "/search"], "GET")], input_param=PydanticModel(PartnerSearchParam), output_param=PydanticModelList(PartnerShortInfo), auth="public", ) def search(self, partner_search_param): """ Search for partners :param partner_search_param: An instance of partner.search.param :return: List of partner.short.info """ domain = [] if partner_search_param.name: domain.append(("name", "like", partner_search_param.name)) if partner_search_param.id: domain.append(("id", "=", partner_search_param.id)) res = [] for p in self.env["res.partner"].sudo().search(domain): res.append(PartnerShortInfo.from_orm(p)) return res # The following method are 'private' and should be never never NEVER call # from the controller. def _get(self, _id): return self.env["res.partner"].sudo().browse(_id)
35
2,100
5,477
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.base_rest.components.service import to_bool, to_int from odoo.addons.component.core import Component class PartnerService(Component): _inherit = "base.rest.service" _name = "partner.service" _usage = "partner" _collection = "base.rest.demo.private.services" _description = """ Partner Services Access to the partner services is only allowed to authenticated users. If you are not authenticated go to <a href='/web/login'>Login</a> """ def get(self, _id): """ Get partner's informations """ return self._to_json(self._get(_id)) def search(self, name): """ Searh partner by name """ partners = self.env["res.partner"].name_search(name) partners = self.env["res.partner"].browse([i[0] for i in partners]) rows = [] res = {"count": len(partners), "rows": rows} for partner in partners: rows.append(self._to_json(partner)) return res # pylint:disable=method-required-super def create(self, **params): """ Create a new partner """ partner = self.env["res.partner"].create(self._prepare_params(params)) return self._to_json(partner) def update(self, _id, **params): """ Update partner informations """ partner = self._get(_id) partner.write(self._prepare_params(params)) return self._to_json(partner) def archive(self, _id, **params): """ Archive the given partner. This method is an empty method, IOW it don't update the partner. This method is part of the demo data to illustrate that historically it's not mandatory to defined a schema describing the content of the response returned by a method. This kind of definition is DEPRECATED and will no more supported in the future. :param _id: :param params: :return: """ return {"response": "Method archive called with id %s" % _id} # The following method are 'private' and should be never never NEVER call # from the controller. def _get(self, _id): return self.env["res.partner"].browse(_id) def _prepare_params(self, params): for key in ["country", "state"]: if key in params: val = params.pop(key) if val.get("id"): params["%s_id" % key] = val["id"] return params # Validator def _validator_return_get(self): res = self._validator_create() res.update({"id": {"type": "integer", "required": True, "empty": False}}) return res def _validator_search(self): return {"name": {"type": "string", "nullable": False, "required": True}} def _validator_return_search(self): return { "count": {"type": "integer", "required": True}, "rows": { "type": "list", "required": True, "schema": {"type": "dict", "schema": self._validator_return_get()}, }, } def _validator_create(self): res = { "name": {"type": "string", "required": True, "empty": False}, "street": {"type": "string", "required": True, "empty": False}, "street2": {"type": "string", "nullable": True}, "zip": {"type": "string", "required": True, "empty": False}, "city": {"type": "string", "required": True, "empty": False}, "phone": {"type": "string", "nullable": True, "empty": False}, "state": { "type": "dict", "schema": { "id": {"type": "integer", "coerce": to_int, "nullable": True}, "name": {"type": "string"}, }, }, "country": { "type": "dict", "schema": { "id": { "type": "integer", "coerce": to_int, "required": True, "nullable": False, }, "name": {"type": "string"}, }, }, "is_company": {"coerce": to_bool, "type": "boolean"}, } return res def _validator_return_create(self): return self._validator_return_get() def _validator_update(self): res = self._validator_create() for key in res: if "required" in res[key]: del res[key]["required"] return res def _validator_return_update(self): return self._validator_return_get() def _validator_archive(self): return {} def _to_json(self, partner): res = { "id": partner.id, "name": partner.name, "street": partner.street, "street2": partner.street2 or "", "zip": partner.zip, "city": partner.city, "phone": partner.city, } if partner.country_id: res["country"] = { "id": partner.country_id.id, "name": partner.country_id.name, } if partner.state_id: res["state"] = {"id": partner.state_id.id, "name": partner.state_id.name} return res
33.601227
5,477
550
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html) { "name": "Base Rest Datamodel", "summary": """ Datamodel binding for base_rest""", "version": "15.0.1.1.0", "license": "LGPL-3", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": ["base_rest", "datamodel"], "data": [], "demo": [], "external_dependencies": {"python": ["apispec>=4.0.0", "marshmallow"]}, "installable": True, }
32.352941
550
3,506
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import marshmallow from apispec.ext.marshmallow.openapi import OpenAPIConverter from marshmallow.exceptions import ValidationError from odoo import _ from odoo.exceptions import UserError from odoo.addons.base_rest import restapi class Datamodel(restapi.RestMethodParam): def __init__(self, name, is_list=False, partial=None): """ :param name: The datamodel name :param is_list: Should be set to True if params is a collection so that the object will be de/serialized from/to a list :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to ``Nested`` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. """ self._name = name self._is_list = is_list self._partial = partial def from_params(self, service, params): ModelClass = service.env.datamodels[self._name] try: return ModelClass.load( params, many=self._is_list, unknown=marshmallow.EXCLUDE, partial=self._partial, ) except ValidationError as ve: raise UserError(_("BadRequest %s") % ve.messages) from ve def to_response(self, service, result): ModelClass = service.env.datamodels[self._name] if self._is_list: json = [i.dump() for i in result] else: json = result.dump() errors = ModelClass.validate( json, many=self._is_list, unknown=marshmallow.EXCLUDE ) if errors: raise SystemError(_("Invalid Response %s") % errors) return json def to_openapi_query_parameters(self, service, spec): converter = self._get_converter() schema = self._get_schema(service) return converter.schema2parameters(schema, location="query") # TODO, we should probably get the spec as parameters. That should # allows to add the definition of a schema only once into the specs # and use a reference to the schema into the parameters def to_openapi_requestbody(self, service, spec): return { "content": { "application/json": { "schema": self.to_json_schema(service, spec, "input") } } } def to_openapi_responses(self, service, spec): return { "200": { "content": { "application/json": { "schema": self.to_json_schema(service, spec, "output") } } } } def to_json_schema(self, service, spec, direction): converter = self._get_converter() schema = self._get_schema(service) return converter.resolve_nested_schema(schema) def _get_schema(self, service): return service.env.datamodels[self._name].get_schema(many=self._is_list) def _get_converter(self): return OpenAPIConverter("3.0", self._schema_name_resolver, None) def _schema_name_resolver(self, schema): # name resolver used by the OpenapiConverter. always return None # to force nested schema definition return None restapi.Datamodel = Datamodel
35.06
3,506
2,089
py
PYTHON
15.0
# Copyright 2021 Wakari SRL # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import mock from odoo.exceptions import UserError from odoo.addons.datamodel import fields from odoo.addons.datamodel.core import Datamodel from odoo.addons.datamodel.tests import common from .. import restapi class TestDataModel(common.DatamodelRegistryCase): def setUp(self): super(TestDataModel, self).setUp() class Datamodel1(Datamodel): _name = "datamodel1" name = fields.String(required=True, allow_none=False) description = fields.String(required=False) Datamodel1._build_datamodel(self.datamodel_registry) def _from_params(self, datamodel_name, params, **kwargs): restapi_datamodel = restapi.Datamodel(datamodel_name, **kwargs) mock_service = mock.Mock() mock_service.env = self.env return restapi_datamodel.from_params(mock_service, params) def test_from_params(self): params = {"name": "Instance Name", "description": "Instance Description"} instance = self._from_params("datamodel1", params) self.assertEqual(instance.name, params["name"]) self.assertEqual(instance.description, params["description"]) def test_from_params_missing_optional_field(self): params = {"name": "Instance Name"} instance = self._from_params("datamodel1", params) self.assertEqual(instance.name, params["name"]) self.assertIsNone(instance.description) def test_from_params_missing_required_field(self): msg = r"BadRequest {'name': \['Missing data for required field.'\]}" with self.assertRaisesRegex(UserError, msg): self._from_params("datamodel1", {"description": "Instance Description"}) def test_from_partial_params_missing_required_field(self): params = {"description": "Instance Description"} instance = self._from_params("datamodel1", params, partial=True) self.assertEqual(instance.description, params["description"]) self.assertIsNone(instance.name)
39.415094
2,089
3,325
py
PYTHON
15.0
# Copyright 2021 Wakari SRL # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import marshmallow import mock from odoo.addons.base_rest_datamodel import restapi from odoo.addons.datamodel import fields from odoo.addons.datamodel.core import Datamodel from odoo.addons.datamodel.tests import common class TestDataModel(common.DatamodelRegistryCase): def _to_response(self, instance): restapi_datamodel = restapi.Datamodel(instance._name) mock_service = mock.Mock() mock_service.env = self.env return restapi_datamodel.to_response(mock_service, instance) def test_to_response(self): class Datamodel1(Datamodel): _name = "datamodel1" name = fields.String(required=True, allow_none=False) Datamodel1._build_datamodel(self.datamodel_registry) instance = self.env.datamodels["datamodel1"](name="Instance 1") res = self._to_response(instance) self.assertEqual(res["name"], instance.name) def test_to_response_dump_only(self): class Datamodel2(Datamodel): _name = "datamodel2" name = fields.String(required=True, allow_none=False, dump_only=True) Datamodel2._build_datamodel(self.datamodel_registry) schema = self.env.datamodels["datamodel2"].get_schema() self.assertEqual(schema.unknown, "raise") msg = r"{'name': \['Unknown field.'\]}" with self.assertRaisesRegex(marshmallow.exceptions.ValidationError, msg): # confirmation that "name" cannot be loaded self.env.datamodels["datamodel2"].load({"name": "Failure"}) instance = self.env.datamodels["datamodel2"](name="Instance 2") res = self._to_response(instance) self.assertEqual(res["name"], instance.name) # schema 'unknown' is back to "raise" self.assertEqual(schema.unknown, "raise") def test_to_response_dump_only_nested(self): class Datamodel3(Datamodel): _name = "datamodel3" child = fields.NestedModel("nested_datamodel") class NestedDatamodel(Datamodel): _name = "nested_datamodel" name = fields.String(required=True, allow_none=False, dump_only=True) NestedDatamodel._build_datamodel(self.datamodel_registry) Datamodel3._build_datamodel(self.datamodel_registry) for datamodel_name in ("datamodel3", "nested_datamodel"): schema = self.env.datamodels[datamodel_name].get_schema() self.assertEqual(schema.unknown, "raise") msg = r"{'name': \['Unknown field.'\]}" with self.assertRaisesRegex(marshmallow.exceptions.ValidationError, msg): # confirmation that child "name" cannot be loaded self.env.datamodels["datamodel3"].load({"child": {"name": "Failure"}}) child_instance = NestedDatamodel(name="Child Instance") instance = self.env.datamodels["datamodel3"](child=child_instance) res = self._to_response(instance) self.assertEqual(res["child"]["name"], child_instance.name) for datamodel_name in ("datamodel3", "nested_datamodel"): schema = self.env.datamodels[datamodel_name].get_schema() # schema 'unknown' is back to "raise" self.assertEqual(schema.unknown, "raise")
43.75
3,325
667
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Base Rest Auth Api Key", "summary": """ Base Rest: Add support for the auth_api_key security policy into the openapi documentation""", "version": "15.0.1.0.0", "license": "LGPL-3", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/rest-framework", "depends": ["base_rest", "auth_api_key"], "maintainers": ["lmignon"], "installable": True, "auto_install": True, "external_dependencies": { "python": [ "apispec>=4.0.0", ] }, }
30.318182
667
550
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo.addons.component.core import AbstractComponent from ..apispec.rest_method_security_plugin import RestMethodSecurityPlugin class BaseRestService(AbstractComponent): _inherit = "base.rest.service" def _get_api_spec(self, **params): spec = super(BaseRestService, self)._get_api_spec(**params) plugin = RestMethodSecurityPlugin(self) plugin.init_spec(spec) spec.plugins.append(plugin) return spec
32.352941
550
1,340
py
PYTHON
15.0
# Copyright 2021 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from apispec import BasePlugin class RestMethodSecurityPlugin(BasePlugin): def __init__(self, service): super(RestMethodSecurityPlugin, self).__init__() self._service = service # pylint: disable=W8110 def init_spec(self, spec): super(RestMethodSecurityPlugin, self).init_spec(spec) self.spec = spec self.openapi_version = spec.openapi_version api_key_scheme = {"type": "apiKey", "in": "header", "name": "API-KEY"} spec.components.security_scheme("api_key", api_key_scheme) def operation_helper(self, path=None, operations=None, **kwargs): routing = kwargs.get("routing") if not routing: super(RestMethodSecurityPlugin, self).operation_helper( path, operations, **kwargs ) if not operations: return default_auth = self.spec._params.get("default_auth") auth = routing.get("auth", default_auth) if auth == "api_key" or ( auth == "public_or_default" and default_auth == "api_key" ): for _method, params in operations.items(): security = params.setdefault("security", []) security.append({"api_key": []})
38.285714
1,340
1,064
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-rest-framework", description="Meta package for oca-rest-framework Odoo addons", version=version, install_requires=[ 'odoo-addon-base_rest>=15.0dev,<15.1dev', 'odoo-addon-base_rest_auth_api_key>=15.0dev,<15.1dev', 'odoo-addon-base_rest_auth_user_service>=15.0dev,<15.1dev', 'odoo-addon-base_rest_datamodel>=15.0dev,<15.1dev', 'odoo-addon-base_rest_demo>=15.0dev,<15.1dev', 'odoo-addon-base_rest_pydantic>=15.0dev,<15.1dev', 'odoo-addon-datamodel>=15.0dev,<15.1dev', 'odoo-addon-extendable>=15.0dev,<15.1dev', 'odoo-addon-graphql_base>=15.0dev,<15.1dev', 'odoo-addon-model_serializer>=15.0dev,<15.1dev', 'odoo-addon-pydantic>=15.0dev,<15.1dev', 'odoo-addon-rest_log>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
36.689655
1,064
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100