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
|
---|---|---|---|---|---|---|
5,827 |
py
|
PYTHON
|
15.0
|
from odoo import Command
from odoo.models import BaseModel
from odoo.tests import Form, TransactionCase
class TestMrpBomAttributeMatchBase(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.warehouse = cls.env.ref("stock.warehouse0")
cls.route_manufacture = cls.warehouse.manufacture_pull_id.route_id
# Create products
cls.product_sword = cls.env["product.template"].create(
{
"name": "Plastic Sword",
"type": "product",
}
)
cls.product_surf = cls.env["product.template"].create(
{
"name": "Surf",
"type": "product",
}
)
cls.product_fin = cls.env["product.template"].create(
{
"name": "Surf Fin",
"type": "product",
}
)
cls.product_plastic = cls.env["product.template"].create(
{
"name": "Plastic Component",
"type": "product",
}
)
cls.p1 = cls.env["product.template"].create(
{
"name": "P1",
"type": "product",
"route_ids": [Command.link(cls.route_manufacture.id)],
}
)
cls.p2 = cls.env["product.template"].create(
{
"name": "P2",
"type": "product",
"route_ids": [Command.link(cls.route_manufacture.id)],
}
)
cls.p3 = cls.env["product.template"].create(
{
"name": "P3",
"type": "product",
"route_ids": [Command.link(cls.route_manufacture.id)],
}
)
cls.product_9 = cls.env["product.product"].create(
{
"name": "Paper",
}
)
cls.product_10 = cls.env["product.product"].create(
{
"name": "Stone",
}
)
cls.product_attribute = cls.env["product.attribute"].create(
{"name": "Colour", "display_type": "radio", "create_variant": "always"}
)
cls.attribute_value_ids = cls.env["product.attribute.value"].create(
[
{"name": "Cyan", "attribute_id": cls.product_attribute.id},
{"name": "Magenta", "attribute_id": cls.product_attribute.id},
]
)
cls.plastic_attrs = cls.env["product.template.attribute.line"].create(
{
"attribute_id": cls.product_attribute.id,
"product_tmpl_id": cls.product_plastic.id,
"value_ids": [Command.set(cls.product_attribute.value_ids.ids)],
}
)
cls.sword_attrs = cls.env["product.template.attribute.line"].create(
{
"attribute_id": cls.product_attribute.id,
"product_tmpl_id": cls.product_sword.id,
"value_ids": [Command.set(cls.product_attribute.value_ids.ids)],
}
)
# Create boms
cls.bom_id = cls._create_bom(
cls.product_sword,
[
dict(
component_template_id=cls.product_plastic.id,
product_qty=1,
),
dict(
product_id=cls.product_9,
product_qty=1,
),
],
)
cls.fin_bom_id = cls._create_bom(
cls.product_fin,
[
dict(
product_id=cls.product_plastic.product_variant_ids[0],
product_qty=1,
),
],
)
cls.surf_bom_id = cls._create_bom(
cls.product_surf,
[
dict(
product_id=cls.product_fin.product_variant_ids[0],
product_qty=1,
),
],
)
cls.p1_bom_id = cls._create_bom(
cls.p1,
[
dict(
product_id=cls.p2.product_variant_ids[0],
product_qty=1,
),
],
)
cls.p2_bom_id = cls._create_bom(
cls.p2,
[
dict(
product_id=cls.p3.product_variant_ids[0],
product_qty=1,
),
],
)
cls.p3_bom_id = cls._create_bom(
cls.p3,
[
dict(
product_id=cls.p1.product_variant_ids[0],
product_qty=1,
),
],
)
@classmethod
def _create_bom(cls, product, line_form_vals):
if product._name == "product.template":
template = product
product = cls.env["product.product"]
else:
template = product.product_tmpl_id
with Form(cls.env["mrp.bom"]) as form:
form.product_tmpl_id = template
form.product_id = product
for vals in line_form_vals:
with form.bom_line_ids.new() as line_form:
for key, value in vals.items():
field = line_form._model._fields.get(key)
if field and field.relational: # pragma: no cover
if value and not isinstance(value, BaseModel):
value = cls.env[field.comodel_name].browse(value)
elif not value:
value = cls.env[field.comodel_name]
setattr(line_form, key, value)
return form.save()
| 33.877907 | 5,827 |
3,053 |
py
|
PYTHON
|
15.0
|
from odoo import _, api, models
from odoo.exceptions import UserError
class ProductTemplate(models.Model):
_inherit = "product.template"
@api.constrains("attribute_line_ids")
def _check_product_with_component_change_allowed(self):
for rec in self:
if not rec.attribute_line_ids:
continue
for bom in rec.bom_ids:
for line in bom.bom_line_ids.filtered("match_on_attribute_ids"):
prod_attr_ids = rec.attribute_line_ids.attribute_id.filtered(
lambda x: x.create_variant != "no_variant"
).ids
comp_attr_ids = line.match_on_attribute_ids.ids
diff_ids = list(set(comp_attr_ids) - set(prod_attr_ids))
diff = rec.env["product.attribute"].browse(diff_ids)
if diff:
raise UserError(
_(
"The attributes you're trying to remove are used in "
"the BoM as a match with Component (Product Template). "
"To remove these attributes, first remove the BOM line "
"with the matching component.\n"
"Attributes: %(attributes)s\nBoM: %(bom)s",
attributes=", ".join(diff.mapped("name")),
bom=bom.display_name,
)
)
@api.constrains("attribute_line_ids")
def _check_component_change_allowed(self):
for rec in self:
if not rec.attribute_line_ids:
continue
boms = self._get_component_boms()
if not boms:
continue
for bom in boms:
vpa = bom.product_tmpl_id.valid_product_template_attribute_line_ids
prod_attr_ids = vpa.attribute_id.ids
comp_attr_ids = self.attribute_line_ids.attribute_id.ids
diff = list(set(comp_attr_ids) - set(prod_attr_ids))
if len(diff) > 0:
attr_recs = self.env["product.attribute"].browse(diff)
raise UserError(
_(
"This product template is used as a component in the "
"BOMs for %(bom)s and attribute(s) %(attributes)s is "
"not present in all such product(s), and this would "
"break the BOM behavior.",
attributes=", ".join(attr_recs.mapped("name")),
bom=bom.display_name,
)
)
def _get_component_boms(self):
self.ensure_one()
bom_lines = self.env["mrp.bom.line"].search(
[("component_template_id", "=", self._origin.id)]
)
if bom_lines:
return bom_lines.mapped("bom_id")
return False
| 45.567164 | 3,053 |
545 |
py
|
PYTHON
|
15.0
|
from odoo import api, models
class MrpProduction(models.Model):
_inherit = "mrp.production"
def action_confirm(self):
res = super().action_confirm()
for bom_line in self.bom_id.bom_line_ids:
if bom_line.component_template_id:
# product_id was set in mrp.bom.explode for correct flow. Need to remove it.
bom_line.product_id = False
return res
@api.constrains("bom_id")
def _check_component_attributes(self):
self.bom_id._check_component_attributes()
| 32.058824 | 545 |
14,420 |
py
|
PYTHON
|
15.0
|
import logging
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_round
_log = logging.getLogger(__name__)
class MrpBomLine(models.Model):
_inherit = "mrp.bom.line"
product_id = fields.Many2one("product.product", "Component", required=False)
product_backup_id = fields.Many2one(
"product.product", help="Technical field to store previous value of product_id"
)
component_template_id = fields.Many2one(
"product.template", "Component (product template)"
)
match_on_attribute_ids = fields.Many2many(
"product.attribute",
string="Match on Attributes",
compute="_compute_match_on_attribute_ids",
store=True,
)
product_uom_category_id = fields.Many2one(
"uom.category",
related=None,
compute="_compute_product_uom_category_id",
)
@api.depends("product_id", "component_template_id")
def _compute_product_uom_category_id(self):
"""Compute the product_uom_category_id field.
This is the product category that will be allowed to use on the product_uom_id
field, already covered by core module:
https://github.com/odoo/odoo/blob/331b9435c/addons/mrp/models/mrp_bom.py#L372
In core, though, this field is related to "product_id.uom_id.category_id".
Here we make it computed to choose between component_template_id and
product_id, depending on which one is set
"""
# pylint: disable=missing-return
# NOTE: To play nice with other modules trying to do the same:
# 1) Set the field value as if it were a related field (core behaviour)
# 2) Call super (if it's there)
# 3) Update only the records we want
for rec in self:
rec.product_uom_category_id = rec.product_id.uom_id.category_id
if hasattr(super(), "_compute_product_uom_category_id"):
super()._compute_product_uom_category_id()
for rec in self:
if rec.component_template_id:
rec.product_uom_category_id = (
rec.component_template_id.uom_id.category_id
)
@api.onchange("component_template_id")
def _onchange_component_template_id(self):
if self.component_template_id:
if self.product_id:
self.product_backup_id = self.product_id
self.product_id = False
if (
self.product_uom_id.category_id
!= self.component_template_id.uom_id.category_id
):
self.product_uom_id = self.component_template_id.uom_id
else:
if self.product_backup_id:
self.product_id = self.product_backup_id
self.product_backup_id = False
if self.product_uom_id.category_id != self.product_id.uom_id.category_id:
self.product_uom_id = self.product_id.uom_id
@api.depends("component_template_id")
def _compute_match_on_attribute_ids(self):
for rec in self:
if rec.component_template_id:
rec.match_on_attribute_ids = (
rec.component_template_id.attribute_line_ids.attribute_id.filtered(
lambda x: x.create_variant != "no_variant"
)
)
else:
rec.match_on_attribute_ids = False
@api.constrains("component_template_id")
def _check_component_attributes(self):
for rec in self:
if not rec.component_template_id:
continue
comp_attrs = (
rec.component_template_id.valid_product_template_attribute_line_ids.attribute_id
)
prod_attrs = (
rec.bom_id.product_tmpl_id.valid_product_template_attribute_line_ids.attribute_id
)
if not comp_attrs:
raise ValidationError(
_(
"No match on attribute has been detected for Component "
"(Product Template) %s",
rec.component_template_id.display_name,
)
)
if not all(attr in prod_attrs for attr in comp_attrs):
raise ValidationError(
_(
"Some attributes of the dynamic component are not included into "
"production product attributes."
)
)
@api.constrains("component_template_id", "bom_product_template_attribute_value_ids")
def _check_variants_validity(self):
for rec in self:
if (
not rec.bom_product_template_attribute_value_ids
or not rec.component_template_id
):
continue
variant_attrs = rec.bom_product_template_attribute_value_ids.attribute_id
same_attr_ids = set(rec.match_on_attribute_ids.ids) & set(variant_attrs.ids)
same_attrs = self.env["product.attribute"].browse(same_attr_ids)
if same_attrs:
raise ValidationError(
_(
"You cannot use an attribute value for attribute(s) %(attributes)s "
"in the field “Apply on Variants” as it's the same attribute used "
"in the field “Match on Attribute” related to the component "
"%(component)s.",
attributes=", ".join(same_attrs.mapped("name")),
component=rec.component_template_id.name,
)
)
@api.onchange("match_on_attribute_ids")
def _onchange_match_on_attribute_ids_check_component_attributes(self):
if self.match_on_attribute_ids:
self._check_component_attributes()
@api.onchange("bom_product_template_attribute_value_ids")
def _onchange_bom_product_template_attribute_value_ids_check_variants(self):
if self.bom_product_template_attribute_value_ids:
self._check_variants_validity()
class MrpBom(models.Model):
_inherit = "mrp.bom"
# flake8: noqa: C901
def explode(self, product, quantity, picking_type=False):
# Had to replace this method
"""
Explodes the BoM and creates two lists with all the information you need:
bom_done and line_done
Quantity describes the number of times you need the BoM: so the quantity
divided by the number created by the BoM
and converted into its UoM
"""
from collections import defaultdict
graph = defaultdict(list)
V = set()
def check_cycle(v, visited, recStack, graph):
visited[v] = True
recStack[v] = True
for neighbour in graph[v]:
if visited[neighbour] is False:
if check_cycle(neighbour, visited, recStack, graph) is True:
return True
elif recStack[neighbour] is True:
return True
recStack[v] = False
return False
product_ids = set()
product_boms = {}
def update_product_boms():
products = self.env["product.product"].browse(product_ids)
product_boms.update(
self._bom_find(
products,
bom_type="phantom",
picking_type=picking_type or self.picking_type_id,
company_id=self.company_id.id,
)
)
# Set missing keys to default value
for product in products:
product_boms.setdefault(product, self.env["mrp.bom"])
boms_done = [
(
self,
{
"qty": quantity,
"product": product,
"original_qty": quantity,
"parent_line": False,
},
)
]
lines_done = []
V |= {product.product_tmpl_id.id}
bom_lines = []
for bom_line in self.bom_line_ids:
product_id = bom_line.product_id
V |= {product_id.product_tmpl_id.id}
graph[product.product_tmpl_id.id].append(product_id.product_tmpl_id.id)
bom_lines.append((bom_line, product, quantity, False))
product_ids.add(product_id.id)
update_product_boms()
product_ids.clear()
while bom_lines:
current_line, current_product, current_qty, parent_line = bom_lines[0]
bom_lines = bom_lines[1:]
if current_line._skip_bom_line(current_product):
continue
line_quantity = current_qty * current_line.product_qty
if current_line.product_id not in product_boms:
update_product_boms()
product_ids.clear()
# upd start
component_template_product = self._get_component_template_product(
current_line, product, current_line.product_id
)
if component_template_product:
# need to set product_id temporary
current_line.product_id = component_template_product
else:
# component_template_id is set, but no attribute value match.
continue
# upd end
bom = product_boms.get(current_line.product_id)
if bom:
converted_line_quantity = current_line.product_uom_id._compute_quantity(
line_quantity / bom.product_qty, bom.product_uom_id
)
bom_lines += [
(
line,
current_line.product_id,
converted_line_quantity,
current_line,
)
for line in bom.bom_line_ids
]
for bom_line in bom.bom_line_ids:
graph[current_line.product_id.product_tmpl_id.id].append(
bom_line.product_id.product_tmpl_id.id
)
if bom_line.product_id.product_tmpl_id.id in V and check_cycle(
bom_line.product_id.product_tmpl_id.id,
{key: False for key in V},
{key: False for key in V},
graph,
):
raise UserError(
_(
"Recursion error! A product with a Bill of Material "
"should not have itself in its BoM or child BoMs!"
)
)
V |= {bom_line.product_id.product_tmpl_id.id}
if bom_line.product_id not in product_boms:
product_ids.add(bom_line.product_id.id)
boms_done.append(
(
bom,
{
"qty": converted_line_quantity,
"product": current_product,
"original_qty": quantity,
"parent_line": current_line,
},
)
)
else:
# We round up here because the user expects
# that if he has to consume a little more, the whole UOM unit
# should be consumed.
rounding = current_line.product_uom_id.rounding
line_quantity = float_round(
line_quantity, precision_rounding=rounding, rounding_method="UP"
)
lines_done.append(
(
current_line,
{
"qty": line_quantity,
"product": current_product,
"original_qty": quantity,
"parent_line": parent_line,
},
)
)
return boms_done, lines_done
def _get_component_template_product(
self, bom_line, bom_product_id, line_product_id
):
if bom_line.component_template_id:
comp = bom_line.component_template_id
comp_attr_ids = (
comp.valid_product_template_attribute_line_ids.attribute_id.ids
)
prod_attr_ids = (
bom_product_id.valid_product_template_attribute_line_ids.attribute_id.ids
)
# check attributes
if not all(item in prod_attr_ids for item in comp_attr_ids):
_log.info(
"Component skipped. Component attributes must be included into "
"product attributes to use component_template_id."
)
return False
# find matching combination
combination = self.env["product.template.attribute.value"]
for ptav in bom_product_id.product_template_attribute_value_ids:
combination |= self.env["product.template.attribute.value"].search(
[
("product_tmpl_id", "=", comp.id),
("attribute_id", "=", ptav.attribute_id.id),
(
"product_attribute_value_id",
"=",
ptav.product_attribute_value_id.id,
),
]
)
if len(combination) == 0:
return False
product_id = comp._get_variant_for_combination(combination)
if product_id and product_id.active:
return product_id
return False
else:
return line_product_id
@api.constrains("product_tmpl_id", "product_id")
def _check_component_attributes(self):
return self.bom_line_ids._check_component_attributes()
@api.constrains("product_tmpl_id", "product_id")
def _check_variants_validity(self):
return self.bom_line_ids._check_variants_validity()
| 40.711864 | 14,412 |
1,972 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import Command, models
class ReportBomStructure(models.AbstractModel):
_inherit = "report.mrp.report_bom_structure"
def _get_bom_lines(self, bom, bom_quantity, product, line_id, level):
# OVERRIDE to fill in the `line.product_id` if a component template is used.
# To avoid a complete override, we HACK the bom by replacing it with a virtual
# record, and modifying it's lines on-the-fly.
has_template_lines = any(
line.component_template_id for line in bom.bom_line_ids
)
if has_template_lines:
bom = bom.new(origin=bom)
to_ignore_line_ids = []
for line in bom.bom_line_ids:
if line._skip_bom_line(product) or not line.component_template_id:
continue
line_product = bom._get_component_template_product(
line, product, line.product_id
)
if not line_product:
to_ignore_line_ids.append(line.id)
continue
else:
line.product_id = line_product
if to_ignore_line_ids:
bom.bom_line_ids = [Command.unlink(id) for id in to_ignore_line_ids]
components, total = super()._get_bom_lines(
bom, bom_quantity, product, line_id, level
)
# Replace any NewId value by the real record id
# Otherwise it's evaluated as False in some situations, and it may cause issues
if has_template_lines:
for component in components:
for key, value in component.items():
if isinstance(value, models.NewId):
component[key] = value.origin
return components, total
| 44.795455 | 1,971 |
640 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "MRP Tags",
"summary": "Allows to add multiple tags to Manufacturing Orders",
"version": "15.0.1.0.0",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/manufacture",
"category": "Purchases",
"depends": ["mrp"],
"data": [
"security/ir.model.access.csv",
"views/mrp_production_view.xml",
"views/mrp_tag_view.xml",
],
"license": "AGPL-3",
"installable": True,
"application": False,
}
| 30.47619 | 640 |
580 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from random import randint
from odoo import fields, models
class MrpTag(models.Model):
_name = "mrp.tag"
_description = "MRP Tag"
def _get_default_color(self):
return randint(1, 11)
name = fields.Char("Tag Name", required=True, translate=True)
color = fields.Integer("Tag Color", default=_get_default_color)
_sql_constraints = [
("tag_name_uniq", "unique (name)", "Tag name already exists !"),
]
| 26.363636 | 580 |
435 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class MrpProduction(models.Model):
_inherit = "mrp.production"
tag_ids = fields.Many2many(
comodel_name="mrp.tag",
relation="mrp_production_tag_rel",
column1="mrp_production_id",
column2="tag_id",
string="Tags",
)
| 25.588235 | 435 |
598 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2017 Akretion (http://www.akretion.com). All Rights Reserved
# @author Florian DA COSTA <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Mrp Progress Button",
"summary": "Add a button on MO to make the MO state 'In Progress'",
"author": "Akretion, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/manufacture",
"category": "Manufacturing",
"version": "15.0.2.0.0",
"license": "AGPL-3",
"depends": ["mrp"],
"data": ["views/production.xml"],
"installable": True,
}
| 37.375 | 598 |
2,789 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2017 Akretion (http://www.akretion.com). All Rights Reserved
# @author Florian DA COSTA <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime
from odoo.tests.common import TransactionCase
class TestProgressButton(TransactionCase):
def setUp(self, *args, **kwargs):
super(TestProgressButton, self).setUp(*args, **kwargs)
self.production_model = self.env["mrp.production"]
self.bom_model = self.env["mrp.bom"]
self.stock_location_stock = self.env.ref("stock.stock_location_stock")
self.manufacture_route = self.env.ref("mrp.route_warehouse0_manufacture")
self.uom_unit = self.env.ref("uom.product_uom_unit")
self.product_manuf = self.env["product.product"].create(
{
"name": "Manuf",
"type": "product",
"uom_id": self.uom_unit.id,
"route_ids": [(4, self.manufacture_route.id)],
}
)
self.product_raw_material = self.env["product.product"].create(
{
"name": "Raw Material",
"type": "product",
"uom_id": self.uom_unit.id,
}
)
self.bom = self.env["mrp.bom"].create(
{
"product_id": self.product_manuf.id,
"product_tmpl_id": self.product_manuf.product_tmpl_id.id,
"bom_line_ids": (
[
(
0,
0,
{
"product_id": self.product_raw_material.id,
"product_qty": 1,
"product_uom_id": self.uom_unit.id,
},
),
]
),
}
)
def test_01_manufacture_with_forecast_stock(self):
"""
Test Manufacture mto with stock based on forecast quantity
and no link between sub assemblies MO's and Main MO raw material
"""
production = self.production_model.create(
{
"product_id": self.product_manuf.id,
"product_qty": 1,
"product_uom_id": self.uom_unit.id,
"bom_id": self.bom.id,
}
)
production.action_confirm()
production.action_progress()
self.assertEqual(production.state, "progress")
self.assertEqual(
production.date_start.replace(microsecond=0),
datetime.now().replace(microsecond=0),
)
production.action_unstart()
self.assertEqual(production.state, "confirmed")
| 36.697368 | 2,789 |
1,089 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2017 Akretion (http://www.akretion.com). All Rights Reserved
# @author Florian DA COSTA <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime
from odoo import api, models
class MrpProduction(models.Model):
_inherit = "mrp.production"
@api.depends(
"move_raw_ids.state",
"move_raw_ids.quantity_done",
"move_finished_ids.state",
"workorder_ids.state",
"product_qty",
"qty_producing",
"date_start",
)
def _compute_state(self):
res = super()._compute_state()
for production in self:
if production.state == "confirmed" and production.date_start:
production.state = "progress"
return res
def action_progress(self):
self.write(
{
"date_start": datetime.now(),
}
)
return True
def action_unstart(self):
self.write({"state": "confirmed", "date_start": False, "qty_producing": 0})
return True
| 27.923077 | 1,089 |
1,184 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014-2021 Tecnativa Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017-2020 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Quality Control OCA",
"version": "15.0.1.0.0",
"category": "Quality Control",
"license": "AGPL-3",
"summary": "Generic infrastructure for quality tests.",
"author": "AvanzOSC, Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/manufacture",
"depends": ["product"],
"data": [
"data/quality_control_data.xml",
"security/quality_control_security.xml",
"security/ir.model.access.csv",
"wizard/qc_test_wizard_view.xml",
"views/qc_menus.xml",
"views/qc_inspection_view.xml",
"views/qc_test_category_view.xml",
"views/qc_test_view.xml",
"views/qc_trigger_view.xml",
"views/product_template_view.xml",
"views/product_category_view.xml",
],
"demo": ["demo/quality_control_demo.xml"],
"installable": True,
}
| 37 | 1,184 |
9,192 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import exceptions
from odoo.tests.common import TransactionCase
from ..models.qc_trigger_line import _filter_trigger_lines
class TestQualityControl(TransactionCase):
def setUp(self):
super().setUp()
self.inspection_model = self.env["qc.inspection"]
self.category_model = self.env["qc.test.category"]
self.question_model = self.env["qc.test.question"]
self.wizard_model = self.env["qc.inspection.set.test"]
self.qc_trigger = self.env["qc.trigger"].create(
{"name": "Test Trigger", "active": True}
)
self.test = self.env.ref("quality_control_oca.qc_test_1")
self.val_ok = self.env.ref("quality_control_oca.qc_test_question_value_1")
self.val_ko = self.env.ref("quality_control_oca.qc_test_question_value_2")
self.qn_question = self.env.ref("quality_control_oca.qc_test_question_2")
self.cat_generic = self.env.ref(
"quality_control_oca.qc_test_template_category_generic"
)
self.product = self.env.ref("product.product_product_11")
inspection_lines = self.inspection_model._prepare_inspection_lines(self.test)
self.inspection1 = self.inspection_model.create(
{"name": "Test Inspection", "inspection_lines": inspection_lines}
)
self.wizard = self.wizard_model.with_context(
active_id=self.inspection1.id
).create({"test": self.test.id})
self.wizard.action_create_test()
self.inspection1.action_todo()
def test_inspection_correct(self):
for line in self.inspection1.inspection_lines:
if line.question_type == "qualitative":
line.qualitative_value = self.val_ok
if line.question_type == "quantitative":
line.quantitative_value = 5.0
self.inspection1.action_confirm()
for line in self.inspection1.inspection_lines:
self.assertTrue(
line.success, "Incorrect state in inspection line %s" % line.name
)
self.assertTrue(
self.inspection1.success,
"Incorrect state in inspection %s" % self.inspection1.name,
)
self.assertEqual(self.inspection1.state, "success")
self.inspection1.action_approve()
self.assertEqual(self.inspection1.state, "success")
def test_inspection_incorrect(self):
for line in self.inspection1.inspection_lines:
if line.question_type == "qualitative":
line.qualitative_value = self.val_ko
if line.question_type == "quantitative":
line.quantitative_value = 15.0
self.inspection1.action_confirm()
for line in self.inspection1.inspection_lines:
self.assertFalse(
line.success, "Incorrect state in inspection line %s" % line.name
)
self.assertFalse(
self.inspection1.success,
"Incorrect state in inspection %s" % self.inspection1.name,
)
self.assertEqual(self.inspection1.state, "waiting")
self.inspection1.action_approve()
self.assertEqual(self.inspection1.state, "failed")
def test_actions_errors(self):
inspection2 = self.inspection1.copy()
inspection2.action_draft()
inspection2.write({"test": False})
with self.assertRaises(exceptions.UserError):
inspection2.action_todo()
inspection3 = self.inspection1.copy()
inspection3.write(
{
"inspection_lines": self.inspection_model._prepare_inspection_lines(
inspection3.test
)
}
)
for line in inspection3.inspection_lines:
if line.question_type == "quantitative":
line.quantitative_value = 15.0
with self.assertRaises(exceptions.UserError):
inspection3.action_confirm()
inspection4 = self.inspection1.copy()
inspection4.write(
{
"inspection_lines": self.inspection_model._prepare_inspection_lines(
inspection4.test
)
}
)
for line in inspection4.inspection_lines:
if line.question_type == "quantitative":
line.write({"uom_id": False, "quantitative_value": 15.0})
elif line.question_type == "qualitative":
line.qualitative_value = self.val_ok
with self.assertRaises(exceptions.UserError):
inspection4.action_confirm()
def test_categories(self):
category1 = self.category_model.create({"name": "Category ONE"})
category2 = self.category_model.create(
{"name": "Category TWO", "parent_id": category1.id}
)
self.assertEqual(
category2.complete_name,
"{} / {}".format(category1.name, category2.name),
"Something went wrong when computing complete name",
)
with self.assertRaises(exceptions.UserError):
category1.parent_id = category2.id
def test_get_qc_trigger_product(self):
self.test.write({"fill_correct_values": True})
trigger_lines = set()
self.product.write(
{
"qc_triggers": [
(0, 0, {"trigger": self.qc_trigger.id, "test": self.test.id})
],
}
)
self.product.product_tmpl_id.write(
{
"qc_triggers": [
(0, 0, {"trigger": self.qc_trigger.id, "test": self.test.id})
],
}
)
self.product.categ_id.write(
{
"qc_triggers": [
(0, 0, {"trigger": self.qc_trigger.id, "test": self.test.id})
],
}
)
for model in [
"qc.trigger.product_category_line",
"qc.trigger.product_template_line",
"qc.trigger.product_line",
]:
trigger_lines = trigger_lines.union(
self.env[model].get_trigger_line_for_product(
self.qc_trigger, self.product
)
)
self.assertEqual(len(trigger_lines), 3)
filtered_trigger_lines = _filter_trigger_lines(trigger_lines)
self.assertEqual(len(filtered_trigger_lines), 1)
for trigger_line in filtered_trigger_lines:
inspection = self.inspection_model._make_inspection(
self.product, trigger_line
)
self.assertEqual(inspection.state, "ready")
self.assertTrue(inspection.auto_generated)
self.assertEqual(inspection.test, self.test)
for line in inspection.inspection_lines:
if line.question_type == "qualitative":
self.assertEqual(line.qualitative_value, self.val_ok)
elif line.question_type == "quantitative":
self.assertAlmostEqual(
round(line.quantitative_value, 2),
round(
(self.qn_question.min_value + self.qn_question.max_value)
* 0.5,
2,
),
)
def test_qc_inspection_not_draft_unlink(self):
with self.assertRaises(exceptions.UserError):
self.inspection1.unlink()
inspection2 = self.inspection1.copy()
inspection2.action_cancel()
self.assertEqual(inspection2.state, "canceled")
inspection2.action_draft()
self.assertEqual(inspection2.state, "draft")
inspection2.unlink()
def test_qc_inspection_auto_generate_unlink(self):
inspection2 = self.inspection1.copy()
inspection2.write({"auto_generated": True})
with self.assertRaises(exceptions.UserError):
inspection2.unlink()
def test_qc_inspection_product(self):
self.inspection1.write(
{"object_id": "%s,%d" % (self.product._name, self.product.id)}
)
self.assertEqual(self.inspection1.product_id, self.product)
def test_qc_test_question_constraints(self):
with self.assertRaises(exceptions.ValidationError):
self.question_model.create(
{
"name": "Quantitative Question",
"type": "quantitative",
"min_value": 1.0,
"max_value": 0.0,
}
)
with self.assertRaises(exceptions.ValidationError):
self.question_model.create(
{
"name": "Qualitative Question",
"type": "qualitative",
"ql_values": [(0, 0, {"name": "Qualitative answer", "ok": False})],
}
)
| 41.035714 | 9,192 |
1,069 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class QcInspectionSetTest(models.TransientModel):
"""This wizard is used to preset the test for a given
inspection. This will not only fill in the 'test' field, but will
also fill in all lines of the inspection with the corresponding lines of
the template.
"""
_name = "qc.inspection.set.test"
_description = "Set test for inspection"
test = fields.Many2one(comodel_name="qc.test")
def action_create_test(self):
inspection = self.env["qc.inspection"].browse(self.env.context["active_id"])
inspection.test = self.test
inspection.inspection_lines.unlink()
inspection.inspection_lines = inspection._prepare_inspection_lines(self.test)
return True
| 38.178571 | 1,069 |
1,615 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class QcTestTemplateCategory(models.Model):
_name = "qc.test.category"
_description = "Test category"
@api.depends("name", "parent_id")
def _compute_get_complete_name(self):
for record in self:
names = [record.name or ""]
parent = record.parent_id
while parent:
names.append(parent.name)
parent = parent.parent_id
record.complete_name = " / ".join(reversed(names))
@api.constrains("parent_id")
def _check_parent_id(self):
if not self._check_recursion():
raise exceptions.UserError(
_("Error! You can not create recursive categories.")
)
name = fields.Char(required=True, translate=True)
parent_id = fields.Many2one(
comodel_name="qc.test.category", string="Parent category"
)
complete_name = fields.Char(
compute="_compute_get_complete_name", string="Full name"
)
child_ids = fields.One2many(
comodel_name="qc.test.category",
inverse_name="parent_id",
string="Child categories",
)
active = fields.Boolean(
default=True,
help="This field allows you to hide the category without removing it.",
)
| 34.361702 | 1,615 |
1,923 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
def _filter_trigger_lines(trigger_lines):
filtered_trigger_lines = []
unique_tests = []
for trigger_line in trigger_lines:
if trigger_line.test not in unique_tests:
filtered_trigger_lines.append(trigger_line)
unique_tests.append(trigger_line.test)
return filtered_trigger_lines
class QcTriggerLine(models.AbstractModel):
_name = "qc.trigger.line"
_inherit = "mail.thread"
_description = "Abstract line for defining triggers"
trigger = fields.Many2one(comodel_name="qc.trigger", required=True)
test = fields.Many2one(comodel_name="qc.test", required=True)
user = fields.Many2one(
comodel_name="res.users",
string="Responsible",
tracking=True,
default=lambda self: self.env.user,
)
partners = fields.Many2many(
comodel_name="res.partner",
help="If filled, the test will only be created when the action is done"
" for one of the specified partners. If empty, the test will always be"
" created.",
domain="[('parent_id', '=', False)]",
)
def get_trigger_line_for_product(self, trigger, product, partner=False):
"""Overridable method for getting trigger_line associated to a product.
Each inherited model will complete this module to make the search by
product, template or category.
:param trigger: Trigger instance.
:param product: Product instance.
:return: Set of trigger_lines that matches to the given product and
trigger.
"""
return set()
| 37.705882 | 1,923 |
1,200 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class QcTriggerProductTemplateLine(models.Model):
_inherit = "qc.trigger.line"
_name = "qc.trigger.product_template_line"
_description = "Quality Control Trigger Product Template Line"
product_template = fields.Many2one(comodel_name="product.template")
def get_trigger_line_for_product(self, trigger, product, partner=False):
trigger_lines = super().get_trigger_line_for_product(
trigger, product, partner=partner
)
for trigger_line in product.product_tmpl_id.qc_triggers.filtered(
lambda r: r.trigger == trigger
and (
not r.partners
or not partner
or partner.commercial_partner_id in r.partners
)
and r.test.active
):
trigger_lines.add(trigger_line)
return trigger_lines
| 37.5 | 1,200 |
600 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductCategory(models.Model):
_inherit = "product.category"
qc_triggers = fields.One2many(
comodel_name="qc.trigger.product_category_line",
inverse_name="product_category",
string="Quality control triggers",
)
| 33.333333 | 600 |
3,894 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
class QcTest(models.Model):
"""
A test is a group of questions along with the values that make them valid.
"""
_name = "qc.test"
_description = "Quality control test"
_inherit = "mail.thread"
def object_selection_values(self):
return set()
@api.onchange("type")
def onchange_type(self):
if self.type == "generic":
self.object_id = False
active = fields.Boolean(default=True)
name = fields.Char(required=True, translate=True)
test_lines = fields.One2many(
comodel_name="qc.test.question",
inverse_name="test",
string="Questions",
copy=True,
)
object_id = fields.Reference(
string="Reference object",
selection="object_selection_values",
)
fill_correct_values = fields.Boolean(string="Pre-fill with correct values")
type = fields.Selection(
[("generic", "Generic"), ("related", "Related")],
required=True,
default="generic",
)
category = fields.Many2one(comodel_name="qc.test.category")
company_id = fields.Many2one(
comodel_name="res.company",
default=lambda self: self.env.company,
)
class QcTestQuestion(models.Model):
"""Each test line is a question with its valid value(s)."""
_name = "qc.test.question"
_description = "Quality control question"
_order = "sequence, id"
@api.constrains("ql_values")
def _check_valid_answers(self):
for tc in self:
if (
tc.type == "qualitative"
and tc.ql_values
and not tc.ql_values.filtered("ok")
):
raise exceptions.ValidationError(
_(
"Question '%s' is not valid: "
"you have to mark at least one value as OK."
)
% tc.name_get()[0][1]
)
@api.constrains("min_value", "max_value")
def _check_valid_range(self):
for tc in self:
if tc.type == "quantitative" and tc.min_value > tc.max_value:
raise exceptions.ValidationError(
_(
"Question '%s' is not valid: "
"minimum value can't be higher than maximum value."
)
% tc.name_get()[0][1]
)
sequence = fields.Integer(required=True, default="10")
test = fields.Many2one(comodel_name="qc.test")
name = fields.Char(required=True, translate=True)
type = fields.Selection(
[("qualitative", "Qualitative"), ("quantitative", "Quantitative")],
required=True,
)
ql_values = fields.One2many(
comodel_name="qc.test.question.value",
inverse_name="test_line",
string="Qualitative values",
copy=True,
)
notes = fields.Text()
min_value = fields.Float(string="Min", digits="Quality Control")
max_value = fields.Float(string="Max", digits="Quality Control")
uom_id = fields.Many2one(comodel_name="uom.uom", string="Uom")
class QcTestQuestionValue(models.Model):
_name = "qc.test.question.value"
_description = "Possible values for qualitative questions."
test_line = fields.Many2one(comodel_name="qc.test.question", string="Test question")
name = fields.Char(required=True, translate=True)
ok = fields.Boolean(
string="Correct answer?",
help="When this field is marked, the answer is considered correct.",
)
| 33.568966 | 3,894 |
600 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
qc_triggers = fields.One2many(
comodel_name="qc.trigger.product_template_line",
inverse_name="product_template",
string="Quality control triggers",
)
| 33.333333 | 600 |
580 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductProduct(models.Model):
_inherit = "product.product"
qc_triggers = fields.One2many(
comodel_name="qc.trigger.product_line",
inverse_name="product",
string="Quality control triggers",
)
| 32.222222 | 580 |
12,831 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, exceptions, fields, models
from odoo.tools import formatLang
class QcInspection(models.Model):
_name = "qc.inspection"
_description = "Quality control inspection"
_inherit = ["mail.thread", "mail.activity.mixin"]
@api.depends("inspection_lines", "inspection_lines.success")
def _compute_success(self):
for i in self:
i.success = all([x.success for x in i.inspection_lines])
def object_selection_values(self):
"""
Overridable method for adding more object models to an inspection.
:return: A list with the selection's possible values.
"""
return [("product.product", "Product")]
@api.depends("object_id")
def _compute_product_id(self):
for i in self:
if i.object_id and i.object_id._name == "product.product":
i.product_id = i.object_id
else:
i.product_id = False
name = fields.Char(
string="Inspection number",
required=True,
default="/",
readonly=True,
states={"draft": [("readonly", False)]},
copy=False,
)
date = fields.Datetime(
required=True,
readonly=True,
copy=False,
default=fields.Datetime.now,
states={"draft": [("readonly", False)]},
)
object_id = fields.Reference(
string="Reference",
selection="object_selection_values",
readonly=True,
states={"draft": [("readonly", False)]},
ondelete="set null",
)
product_id = fields.Many2one(
comodel_name="product.product",
compute="_compute_product_id",
store=True,
help="Product associated with the inspection",
)
qty = fields.Float(string="Quantity", default=1.0)
test = fields.Many2one(comodel_name="qc.test", readonly=True)
inspection_lines = fields.One2many(
comodel_name="qc.inspection.line",
inverse_name="inspection_id",
readonly=True,
states={"ready": [("readonly", False)]},
)
internal_notes = fields.Text(string="Internal notes")
external_notes = fields.Text(
states={"success": [("readonly", True)], "failed": [("readonly", True)]},
)
state = fields.Selection(
[
("draft", "Draft"),
("ready", "Ready"),
("waiting", "Waiting supervisor approval"),
("success", "Quality success"),
("failed", "Quality failed"),
("canceled", "Canceled"),
],
readonly=True,
default="draft",
tracking=True,
)
success = fields.Boolean(
compute="_compute_success",
help="This field will be marked if all tests have succeeded.",
store=True,
)
auto_generated = fields.Boolean(
string="Auto-generated",
readonly=True,
copy=False,
help="If an inspection is auto-generated, it can be canceled but not removed.",
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
readonly=True,
states={"draft": [("readonly", False)]},
default=lambda self: self.env.company,
)
user = fields.Many2one(
comodel_name="res.users",
string="Responsible",
tracking=True,
default=lambda self: self.env.user,
)
@api.model_create_multi
def create(self, val_list):
for vals in val_list:
if vals.get("name", "/") == "/":
vals["name"] = self.env["ir.sequence"].next_by_code("qc.inspection")
return super().create(vals)
def unlink(self):
for inspection in self:
if inspection.auto_generated:
raise exceptions.UserError(
_("You cannot remove an auto-generated inspection.")
)
if inspection.state != "draft":
raise exceptions.UserError(
_("You cannot remove an inspection that is not in draft state.")
)
return super().unlink()
def action_draft(self):
self.write({"state": "draft"})
def action_todo(self):
for inspection in self:
if not inspection.test:
raise exceptions.UserError(_("You must first set the test to perform."))
self.write({"state": "ready"})
def action_confirm(self):
for inspection in self:
for line in inspection.inspection_lines:
if line.question_type == "qualitative" and not line.qualitative_value:
raise exceptions.UserError(
_(
"You should provide an answer for all "
"qualitative questions."
)
)
elif line.question_type != "qualitative" and not line.uom_id:
raise exceptions.UserError(
_(
"You should provide a unit of measure for "
"quantitative questions."
)
)
if inspection.success:
inspection.state = "success"
else:
inspection.state = "waiting"
def action_approve(self):
for inspection in self:
if inspection.success:
inspection.state = "success"
else:
inspection.state = "failed"
def action_cancel(self):
self.write({"state": "canceled"})
def set_test(self, trigger_line, force_fill=False):
for inspection in self:
header = self._prepare_inspection_header(inspection.object_id, trigger_line)
del header["state"] # don't change current status
del header["auto_generated"] # don't change auto_generated flag
del header["user"] # don't change current user
inspection.write(header)
inspection.inspection_lines.unlink()
inspection.inspection_lines = inspection._prepare_inspection_lines(
trigger_line.test, force_fill=force_fill
)
def _make_inspection(self, object_ref, trigger_line):
"""Overridable hook method for creating inspection from test.
:param object_ref: Object instance
:param trigger_line: Trigger line instance
:return: Inspection object
"""
inspection = self.create(
self._prepare_inspection_header(object_ref, trigger_line)
)
inspection.set_test(trigger_line)
return inspection
def _prepare_inspection_header(self, object_ref, trigger_line):
"""Overridable hook method for preparing inspection header.
:param object_ref: Object instance
:param trigger_line: Trigger line instance
:return: List of values for creating the inspection
"""
return {
"object_id": object_ref
and "{},{}".format(object_ref._name, object_ref.id)
or False,
"state": "ready",
"test": trigger_line.test.id,
"user": trigger_line.user.id,
"auto_generated": True,
}
def _prepare_inspection_lines(self, test, force_fill=False):
new_data = []
for line in test.test_lines:
data = self._prepare_inspection_line(
test, line, fill=test.fill_correct_values or force_fill
)
new_data.append((0, 0, data))
return new_data
def _prepare_inspection_line(self, test, line, fill=None):
data = {
"name": line.name,
"test_line": line.id,
"notes": line.notes,
"min_value": line.min_value,
"max_value": line.max_value,
"test_uom_id": line.uom_id.id,
"uom_id": line.uom_id.id,
"question_type": line.type,
"possible_ql_values": [x.id for x in line.ql_values],
}
if fill:
if line.type == "qualitative":
# Fill with the first correct value found
for value in line.ql_values:
if value.ok:
data["qualitative_value"] = value.id
break
else:
# Fill with a value inside the interval
data["quantitative_value"] = (line.min_value + line.max_value) * 0.5
return data
class QcInspectionLine(models.Model):
_name = "qc.inspection.line"
_description = "Quality control inspection line"
@api.depends(
"question_type",
"uom_id",
"test_uom_id",
"max_value",
"min_value",
"quantitative_value",
"qualitative_value",
"possible_ql_values",
)
def _compute_quality_test_check(self):
for insp_line in self:
if insp_line.question_type == "qualitative":
insp_line.success = insp_line.qualitative_value.ok
else:
if insp_line.uom_id.id == insp_line.test_uom_id.id:
amount = insp_line.quantitative_value
else:
amount = self.env["uom.uom"]._compute_quantity(
insp_line.quantitative_value, insp_line.test_uom_id.id
)
insp_line.success = insp_line.max_value >= amount >= insp_line.min_value
@api.depends(
"possible_ql_values", "min_value", "max_value", "test_uom_id", "question_type"
)
def _compute_valid_values(self):
for insp_line in self:
if insp_line.question_type == "qualitative":
insp_line.valid_values = ", ".join(
[x.name for x in insp_line.possible_ql_values if x.ok]
)
else:
insp_line.valid_values = "{} ~ {}".format(
formatLang(self.env, insp_line.min_value),
formatLang(self.env, insp_line.max_value),
)
if self.env.ref("uom.group_uom") in self.env.user.groups_id:
insp_line.valid_values += " %s" % insp_line.test_uom_id.name
inspection_id = fields.Many2one(
comodel_name="qc.inspection", string="Inspection", ondelete="cascade"
)
name = fields.Char(string="Question", readonly=True)
product_id = fields.Many2one(
comodel_name="product.product",
related="inspection_id.product_id",
store=True,
)
test_line = fields.Many2one(
comodel_name="qc.test.question", string="Test question", readonly=True
)
possible_ql_values = fields.Many2many(
comodel_name="qc.test.question.value", string="Answers"
)
quantitative_value = fields.Float(
string="Quantitative value",
digits="Quality Control",
help="Value of the result for a quantitative question.",
)
qualitative_value = fields.Many2one(
comodel_name="qc.test.question.value",
string="Qualitative value",
help="Value of the result for a qualitative question.",
domain="[('id', 'in', possible_ql_values)]",
)
notes = fields.Text()
min_value = fields.Float(
string="Min",
digits="Quality Control",
readonly=True,
help="Minimum valid value for a quantitative question.",
)
max_value = fields.Float(
string="Max",
digits="Quality Control",
readonly=True,
help="Maximum valid value for a quantitative question.",
)
test_uom_id = fields.Many2one(
comodel_name="uom.uom",
string="Test UoM",
readonly=True,
help="UoM for minimum and maximum values for a quantitative " "question.",
)
test_uom_category = fields.Many2one(
comodel_name="uom.category", related="test_uom_id.category_id", store=True
)
uom_id = fields.Many2one(
comodel_name="uom.uom",
string="UoM",
domain="[('category_id', '=', test_uom_category)]",
help="UoM of the inspection value for a quantitative question.",
)
question_type = fields.Selection(
[("qualitative", "Qualitative"), ("quantitative", "Quantitative")],
readonly=True,
)
valid_values = fields.Char(
string="Valid values", store=True, compute="_compute_valid_values"
)
success = fields.Boolean(
compute="_compute_quality_test_check", string="Success?", store=True
)
| 36.042135 | 12,831 |
1,293 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class QcTriggerProductCategoryLine(models.Model):
_inherit = "qc.trigger.line"
_name = "qc.trigger.product_category_line"
_description = "Quality Control Trigger Product Category Line"
product_category = fields.Many2one(comodel_name="product.category")
def get_trigger_line_for_product(self, trigger, product, partner=False):
trigger_lines = super().get_trigger_line_for_product(
trigger, product, partner=partner
)
category = product.categ_id
while category:
for trigger_line in category.qc_triggers.filtered(
lambda r: r.trigger == trigger
and (
not r.partners
or not partner
or partner.commercial_partner_id in r.partners
)
):
trigger_lines.add(trigger_line)
category = category.parent_id
return trigger_lines
| 38.029412 | 1,293 |
908 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class QcTrigger(models.Model):
_name = "qc.trigger"
_description = "Quality control trigger"
name = fields.Char(required=True, translate=True)
active = fields.Boolean(default=True)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
default=lambda self: self.env.company,
)
partner_selectable = fields.Boolean(
string="Selectable by partner",
default=False,
readonly=True,
help="This technical field is to allow to filter by partner in triggers",
)
| 33.62963 | 908 |
1,148 |
py
|
PYTHON
|
15.0
|
# Copyright 2010 NaN Projectes de Programari Lliure, S.L.
# Copyright 2014 Serv. Tec. Avanzados - Pedro M. Baeza
# Copyright 2014 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 ForgeFlow S.L.
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class QcTriggerProductLine(models.Model):
_inherit = "qc.trigger.line"
_name = "qc.trigger.product_line"
_description = "Quality Control Trigger Product Line"
product = fields.Many2one(comodel_name="product.product")
def get_trigger_line_for_product(self, trigger, product, partner=False):
trigger_lines = super().get_trigger_line_for_product(
trigger, product, partner=partner
)
for trigger_line in product.qc_triggers.filtered(
lambda r: r.trigger == trigger
and (
not r.partners
or not partner
or partner.commercial_partner_id in r.partners
)
and r.test.active
):
trigger_lines.add(trigger_line)
return trigger_lines
| 35.875 | 1,148 |
630 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "MRP Component Availability Search",
"summary": "Filter manufacturing orders by their components availability state",
"version": "15.0.1.0.0",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"website": "https://github.com/OCA/manufacture",
"license": "AGPL-3",
"category": "Manufacture",
"depends": ["mrp"],
"data": ["views/mrp_production.xml"],
}
| 39.3125 | 629 |
3,707 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import Command
from odoo.tests import Form, TransactionCase
class TestSearch(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.partner = cls.env.ref("base.res_partner_1")
cls.component = cls.env["product.product"].create(
{"name": "Component", "type": "product"}
)
cls.product = cls.env["product.product"].create(
{"name": "Product", "type": "product"}
)
cls.product_bom = cls.env["mrp.bom"].create(
{
"product_tmpl_id": cls.product.product_tmpl_id.id,
"product_qty": 1.0,
"product_uom_id": cls.product.uom_id.id,
"bom_line_ids": [
Command.create(
{
"product_id": cls.component.id,
"product_qty": 1.0,
"product_uom_id": cls.component.uom_id.id,
}
)
],
}
)
# Create some initial stocks
cls.location_stock = cls.env.ref("stock.stock_location_stock")
cls.env["stock.quant"].create(
{
"product_id": cls.component.id,
"product_uom_id": cls.component.uom_id.id,
"location_id": cls.location_stock.id,
"quantity": 10.00,
}
)
# Create some manufacturing orders
cls.mo_draft = cls._create_mo(confirm=False)
cls.mo_confirm = cls._create_mo(confirm=True)
cls.mo_unavailable = cls._create_mo(quantity=1000.0, confirm=True)
@classmethod
def _create_mo(cls, product=None, bom=None, quantity=1.0, confirm=False):
if product is None:
product = cls.product
if bom is None:
bom = cls.product_bom
mo_form = Form(cls.env["mrp.production"])
mo_form.product_id = product
mo_form.bom_id = bom
mo_form.product_qty = quantity
mo_form.product_uom_id = product.uom_id
mo = mo_form.save()
if confirm:
mo.action_confirm()
return mo
def test_search_is_set(self):
records = self.env["mrp.production"].search(
[
("product_id", "=", self.product.id),
("components_availability_state", "!=", False),
]
)
self.assertEqual(records, self.mo_confirm + self.mo_unavailable)
def test_search_is_not_set(self):
records = self.env["mrp.production"].search(
[
("product_id", "=", self.product.id),
("components_availability_state", "=", False),
]
)
self.assertEqual(records, self.mo_draft)
def test_search_is_available(self):
records = self.env["mrp.production"].search(
[
("product_id", "=", self.product.id),
("components_availability_state", "=", "available"),
]
)
self.assertEqual(records, self.mo_confirm)
def test_search_is_not_available(self):
records = self.env["mrp.production"].search(
[
("product_id", "=", self.product.id),
("components_availability_state", "!=", "available"),
]
)
self.assertEqual(records, self.mo_draft + self.mo_unavailable)
| 36.333333 | 3,706 |
1,893 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.osv.expression import OR, distribute_not, normalize_domain
class MrpProduction(models.Model):
_inherit = "mrp.production"
components_availability_state = fields.Selection(
search="_search_components_availability_state"
)
@api.model
def _search_components_availability_state(self, operator, value):
if operator not in ("=", "!="):
raise UserError(_("Invalid domain operator %s", operator))
if not isinstance(value, str) and value is not False:
raise UserError(_("Invalid domain right operand %s", value))
# Search all orders for which we need to compute the products availability.
# The value would be ``False`` if the mo doesn't fall under this list.
domain = [("state", "in", ["confirmed", "progress"])]
# Special case for "is set" / "is not set" domains
if operator == "=" and value is False:
return distribute_not(["!"] + normalize_domain(domain))
if operator == "!=" and value is False:
return domain
# Perform a search and compute values to filter on-the-fly
res_ids = []
orders = self.with_context(prefetch_fields=False).search(domain)
for order in orders:
if order.components_availability_state == value:
res_ids.append(order.id)
if operator == "=":
return [("id", "in", res_ids)]
else:
return OR(
[
distribute_not(["!"] + normalize_domain(domain)),
[("id", "not in", res_ids)],
]
)
| 42.044444 | 1,892 |
495 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Stock whole kit constraint",
"summary": "Avoid to deliver a kit partially",
"version": "15.0.1.0.0",
"category": "Stock",
"website": "https://github.com/OCA/manufacture",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["mrp"],
"data": ["views/product_template_views.xml"],
}
| 35.357143 | 495 |
6,673 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.exceptions import ValidationError
from odoo.tests import Form, common
class TestStockWholeKitConstraint(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.customer = cls.env["res.partner"].create({"name": "Mr. Odoo"})
# Kit 1 that can be partially delivered
cls.product_kit_1 = cls.env["product.product"].create(
{"name": "Product Kit 1", "type": "consu"}
)
cls.component_1_kit_1 = cls.env["product.product"].create(
{"name": "Component 1 Kit 1", "type": "product"}
)
cls.component_2_kit_1 = cls.env["product.product"].create(
{"name": "Component 2 Kit 1", "type": "product"}
)
bom_form = Form(cls.env["mrp.bom"])
bom_form.product_tmpl_id = cls.product_kit_1.product_tmpl_id
bom_form.product_id = cls.product_kit_1
bom_form.type = "phantom"
with bom_form.bom_line_ids.new() as line:
line.product_id = cls.component_1_kit_1
with bom_form.bom_line_ids.new() as line:
line.product_id = cls.component_2_kit_1
cls.bom_kit_1 = bom_form.save()
# Kit 2 - disallow partial deliveries
cls.product_kit_2 = cls.env["product.product"].create(
{
"name": "Product Kit 2",
"type": "consu",
"allow_partial_kit_delivery": False,
}
)
cls.component_1_kit_2 = cls.env["product.product"].create(
{"name": "Component 1 Kit 2", "type": "product"}
)
cls.component_2_kit_2 = cls.env["product.product"].create(
{"name": "Component 2 Kit 2", "type": "product"}
)
bom_form = Form(cls.env["mrp.bom"])
bom_form.product_tmpl_id = cls.product_kit_2.product_tmpl_id
bom_form.product_id = cls.product_kit_2
bom_form.type = "phantom"
with bom_form.bom_line_ids.new() as line:
line.product_id = cls.component_1_kit_2
with bom_form.bom_line_ids.new() as line:
line.product_id = cls.component_2_kit_2
cls.bom_kit_2 = bom_form.save()
# Manufactured product as control
cls.product_mrp = cls.env["product.product"].create(
{
"name": "Product Kit 2",
"type": "consu",
# Force the setting in a manufactured product.
# It should not affect it
"allow_partial_kit_delivery": False,
}
)
bom_form = Form(cls.env["mrp.bom"])
bom_form.product_tmpl_id = cls.product_mrp.product_tmpl_id
bom_form.product_id = cls.product_mrp
bom_form.type = "normal"
with bom_form.bom_line_ids.new() as line:
line.product_id = cls.component_1_kit_2
cls.bom_mrp = bom_form.save()
# Not a kit product as control
cls.regular_product = cls.env["product.product"].create(
{
"name": "Regular test product",
"type": "product",
# Force the setting in a regular product. It should not affect it
"allow_partial_kit_delivery": False,
}
)
# Delivery picking
picking_form = Form(cls.env["stock.picking"])
picking_form.picking_type_id = cls.env.ref("stock.picking_type_out")
picking_form.partner_id = cls.customer
with picking_form.move_ids_without_package.new() as move:
move.product_id = cls.product_kit_1
move.product_uom_qty = 3.0
with picking_form.move_ids_without_package.new() as move:
move.product_id = cls.product_kit_2
move.product_uom_qty = 3.0
with picking_form.move_ids_without_package.new() as move:
move.product_id = cls.product_mrp
move.product_uom_qty = 3.0
with picking_form.move_ids_without_package.new() as move:
move.product_id = cls.regular_product
move.product_uom_qty = 3.0
cls.customer_picking = picking_form.save()
cls.customer_picking.action_confirm()
def test_01_all_partially_done_but_the_disallow_partial_kit(self):
"""No quantity is done for the kit disallowed and only partially for the
others so the backorder wizard raises."""
moves_allowed = self.customer_picking.move_lines.filtered(
lambda x: x.bom_line_id.bom_id != self.bom_kit_2
)
moves_allowed.write({"quantity_done": 1})
response = self.customer_picking.button_validate()
self.assertEqual("stock.backorder.confirmation", response.get("res_model"))
def test_02_all_done_but_partial_disallow_partial_kit(self):
"""We try to deliver partially the disallowed kit"""
moves_disallowed = self.customer_picking.move_lines.filtered(
lambda x: x.bom_line_id.bom_id == self.bom_kit_2
)
moves_disallowed.write({"quantity_done": 1})
with self.assertRaises(ValidationError):
self.customer_picking.button_validate()
# We can split the picking if the whole kit components are delivered
moves_disallowed.write({"quantity_done": 3})
# We've got a backorder on the rest of the lines
response = self.customer_picking.button_validate()
self.assertEqual("stock.backorder.confirmation", response.get("res_model"))
def test_03_all_done(self):
"""Deliver the whole picking normally"""
self.customer_picking.move_lines.write({"quantity_done": 3})
self.customer_picking.button_validate()
self.assertEqual("done", self.customer_picking.state)
def test_04_manual_move_lines(self):
"""If a user adds manual operations, we should consider it as well"""
# We need to enable detaild operations to test this case
self.customer_picking.picking_type_id.show_operations = True
picking_form = Form(self.customer_picking)
for product in (self.bom_kit_1 + self.bom_kit_2).mapped(
"bom_line_ids.product_id"
):
with picking_form.move_line_ids_without_package.new() as line:
line.product_id = product
line.qty_done = 3
picking_form.save()
self.customer_picking.move_lines.filtered(
lambda x: x.product_id in (self.product_mrp, self.regular_product)
).write({"quantity_done": 3})
self.customer_picking.button_validate()
self.assertEqual("done", self.customer_picking.state)
| 46.02069 | 6,673 |
437 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
allow_partial_kit_delivery = fields.Boolean(
default=True,
help="If not set, and this product is delivered with a BoM of type "
"kit, partial deliveries of the components won't be allowed.",
)
| 33.615385 | 437 |
2,349 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class StockMove(models.Model):
_inherit = "stock.move"
allow_partial_kit_delivery = fields.Boolean(
compute="_compute_allow_partial_kit_delivery",
compute_sudo=True,
)
@api.depends("product_id.product_tmpl_id.allow_partial_kit_delivery", "state")
def _compute_allow_partial_kit_delivery(self):
"""Take it from the product only if it's a kit"""
self.write({"allow_partial_kit_delivery": True})
for move in self.filtered(
lambda x: x.product_id and x.state not in ["done", "cancel"]
):
# If it isn't a kit it will always be True
if not move.bom_line_id or move.bom_line_id.bom_id.type != "phantom":
move.allow_partial_kit_delivery = True
continue
move.allow_partial_kit_delivery = (
move.bom_line_id.bom_id.product_tmpl_id.allow_partial_kit_delivery
)
def _check_backorder_moves(self):
"""Check if there are partial deliveries on any set of moves. The
computing is done in the same way the main picking method does it"""
quantity_todo = {}
quantity_done = {}
for move in self:
quantity_todo.setdefault(move.product_id.id, 0)
quantity_done.setdefault(move.product_id.id, 0)
quantity_todo[move.product_id.id] += move.product_uom_qty
quantity_done[move.product_id.id] += move.quantity_done
for ops in self.mapped("move_line_ids").filtered(
lambda x: x.package_id and not x.product_id and not x.move_id
):
for quant in ops.package_id.quant_ids:
quantity_done.setdefault(quant.product_id.id, 0)
quantity_done[quant.product_id.id] += quant.qty
for pack in self.mapped("move_line_ids").filtered(
lambda x: x.product_id and not x.move_id
):
quantity_done.setdefault(pack.product_id.id, 0)
quantity_done[pack.product_id.id] += pack.product_uom_id._compute_quantity(
pack.qty_done, pack.product_id.uom_id
)
return any(quantity_done[x] < quantity_todo.get(x, 0) for x in quantity_done)
| 45.173077 | 2,349 |
1,219 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, models
from odoo.exceptions import ValidationError
class StockPicking(models.Model):
_inherit = "stock.picking"
def _check_backorder(self):
"""On the moment of the picking validation, we'll check wether there
are kits that can't be partially delivered or not"""
moves = self.mapped("move_lines").filtered(
lambda x: not x.allow_partial_kit_delivery and x.bom_line_id
)
boms = moves.mapped("bom_line_id.bom_id")
for bom in boms:
bom_moves = moves.filtered(lambda x: x.bom_line_id.bom_id == bom)
# We can put it in backorder if the whole kit goes
if not sum(bom_moves.mapped("quantity_done")):
continue
if bom_moves._check_backorder_moves():
raise ValidationError(
_(
"You can't make a partial delivery of components of the "
"%s kit",
bom.product_tmpl_id.display_name,
)
)
return super()._check_backorder()
| 40.633333 | 1,219 |
724 |
py
|
PYTHON
|
15.0
|
# Copyright 2019-22 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "MRP Planned Order Matrix",
"summary": "Allows to create fixed planned orders on a grid view.",
"version": "15.0.1.1.0",
"development_status": "Production/Stable",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/manufacture",
"category": "Warehouse Management",
"depends": ["mrp_multi_level", "web_widget_x2many_2d_matrix", "date_range"],
"data": [
"security/ir.model.access.csv",
"wizards/mrp_planned_order_wizard_view.xml",
],
"license": "AGPL-3",
"installable": True,
}
| 40.222222 | 724 |
4,034 |
py
|
PYTHON
|
15.0
|
# Copyright 2020-21 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from dateutil.rrule import MONTHLY
from odoo import fields
from odoo.addons.mrp_multi_level.tests.common import TestMrpMultiLevelCommon
class TestMrpPlannedOrderMatrix(TestMrpMultiLevelCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.mrp_planned_order_matrix_wiz = cls.env["mrp.planned.order.wizard"]
cls.drt_monthly = cls.env["date.range.type"].create(
{"name": "Month", "allow_overlap": False}
)
generator = cls.env["date.range.generator"]
generator = generator.create(
{
"date_start": "1943-01-01",
"name_prefix": "1943-",
"type_id": cls.drt_monthly.id,
"duration_count": 1,
"unit_of_time": str(MONTHLY),
"count": 12,
}
)
generator.action_apply()
# Create a product:
cls.product_1 = cls.product_obj.create(
{"name": "Test Product 1", "type": "product", "default_code": "PROD1"}
)
# Create a product mrp area:
cls.product_mrp_area_1 = cls.product_mrp_area_obj.create(
{"product_id": cls.product_1.id, "mrp_area_id": cls.mrp_area.id}
)
def test_01_mrp_planned_order_matrix(self):
"""Tests creation of planned orders using matrix wizard."""
wiz = self.mrp_planned_order_matrix_wiz
wiz = wiz.create(
{
"date_start": "1943-01-01",
"date_end": "1943-12-31",
"date_range_type_id": self.drt_monthly.id,
"product_mrp_area_ids": [(6, 0, [self.product_mrp_area_1.id])],
}
)
wiz.create_sheet()
sheets = self.env["mrp.planned.order.sheet"].search([])
for sheet in sheets:
self.assertEqual(
len(sheet.line_ids),
12,
"There should be 12 lines.",
)
self.assertEqual(
fields.Date.to_string(sheet.date_start),
"1943-01-01",
"The date start should be 1943-01-01",
)
self.assertEqual(
fields.Date.to_string(sheet.date_end),
"1943-12-31",
"The date end should be 1943-12-31",
)
for line in sheet.line_ids:
line.product_qty = 1
self.assertEqual(
line.product_mrp_area_id.product_id.id,
self.product_1.id,
"The product does not match in the line",
)
sheet.button_validate()
ranges = self.env["date.range"].search(
[("type_id", "=", self.drt_monthly.id)],
)
mrp_planned_order_sheet_lines = self.env[
"mrp.planned.order.sheet.line"
].search([("date_range_id", "in", ranges.ids)])
self.assertEqual(
len(mrp_planned_order_sheet_lines),
12,
"There should be 12 estimate records.",
)
for planned_order in mrp_planned_order_sheet_lines:
self.assertEqual(
planned_order.product_mrp_area_id.product_id.id,
self.product_1.id,
"The product does not match in the estimate",
)
self.assertEqual(
planned_order.product_qty,
1,
"The product qty does not match",
)
mrp_planned_orders = self.env["mrp.planned.order"].search(
[("product_mrp_area_id", "=", self.product_mrp_area_1.id)]
)
self.assertEqual(
len(mrp_planned_orders),
12,
"There should be 12 planned order records.",
)
| 37.351852 | 4,034 |
8,374 |
py
|
PYTHON
|
15.0
|
# Copyright 2020-21 ForgeFlow S.L. (https://www.forgeflow.com)
# - Jordi Ballester Alomar <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import timedelta
from itertools import zip_longest
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
from odoo.tools.float_utils import float_compare
class MrpPlannedOrderWizard(models.TransientModel):
_name = "mrp.planned.order.wizard"
_description = "MPS Wizard"
date_start = fields.Date(string="Date From", required=True)
date_end = fields.Date(string="Date To", required=True)
date_range_type_id = fields.Many2one(
string="Date Range Type",
comodel_name="date.range.type",
required=True,
)
product_mrp_area_ids = fields.Many2many(
string="Product Parameters", comodel_name="product.mrp.area", required=True
)
@api.constrains("date_start", "date_end")
def _check_start_end_dates(self):
self.ensure_one()
if self.date_start > self.date_end:
raise ValidationError(
_("The start date cannot be later than the end date.")
)
def create_sheet(self):
self.ensure_one()
if not self.product_mrp_area_ids:
raise ValidationError(
_("You must select at least one Product MRP parameter.")
)
# 2d matrix widget need real records to work
sheet = self.env["mrp.planned.order.sheet"].create(
{
"date_start": self.date_start,
"date_end": self.date_end,
"date_range_type_id": self.date_range_type_id.id,
"product_mrp_area_ids": [(6, 0, self.product_mrp_area_ids.ids)],
}
)
sheet._onchange_dates()
res = {
"name": _("MPS Sheet"),
"src_model": "mrp.planned.order.wizard",
"view_mode": "form",
"target": "new",
"res_model": "mrp.planned.order.sheet",
"res_id": sheet.id,
"type": "ir.actions.act_window",
}
return res
class MprPlannedOrderSheet(models.TransientModel):
_name = "mrp.planned.order.sheet"
_description = "MPS Sheet"
date_start = fields.Date(string="Date From", readonly=True)
date_end = fields.Date(string="Date to", readonly=True)
date_range_type_id = fields.Many2one(
string="Date Range Type",
comodel_name="date.range.type",
readonly=True,
)
product_mrp_area_ids = fields.Many2many(
string="Product Parameters", comodel_name="product.mrp.area"
)
line_ids = fields.Many2many(
string="Items", comodel_name="mrp.planned.order.sheet.line"
)
@api.onchange("date_start", "date_end", "date_range_type_id")
def _onchange_dates(self):
if not all([self.date_start, self.date_end, self.date_range_type_id]):
return
ranges = self._get_ranges()
if not ranges:
raise UserError(_("There are no date ranges created."))
lines = []
for rec in self.product_mrp_area_ids:
for d_range in ranges:
items = self.env["mrp.planned.order"].search(
[
("product_mrp_area_id", "=", rec.id),
("due_date", ">=", d_range.date_start),
("due_date", "<", d_range.date_end),
("fixed", "=", True),
]
)
if items:
uom_qty = sum(items.mapped("mrp_qty"))
item_ids = items.ids
else:
uom_qty = 0.0
item_ids = []
lines.append(
[
0,
0,
self._get_default_sheet_line(d_range, rec, uom_qty, item_ids),
]
)
self.line_ids = lines
def _get_ranges(self):
domain_1 = [
"&",
("type_id", "=", self.date_range_type_id.id),
"|",
"&",
("date_start", ">=", self.date_start),
("date_start", "<=", self.date_end),
"&",
("date_end", ">=", self.date_start),
("date_end", "<=", self.date_end),
]
domain_2 = [
"&",
("type_id", "=", self.date_range_type_id.id),
"&",
("date_start", "<=", self.date_start),
("date_end", ">=", self.date_start),
]
domain = expression.OR([domain_1, domain_2])
ranges = self.env["date.range"].search(domain)
return ranges
def _get_default_sheet_line(self, d_range, product_mrp, uom_qty, item_ids):
name_y = "{} - {}".format(
product_mrp.display_name, product_mrp.product_id.uom_id.name
)
values = {
"value_x": d_range.name,
"value_y": name_y,
"date_range_id": d_range.id,
"product_mrp_area_id": product_mrp.id,
"product_qty": uom_qty,
"mrp_planned_order_ids": [(6, 0, item_ids)],
}
return values
@api.model
def _prepare_planned_order_data(self, line, qty):
calendar = line.product_mrp_area_id.mrp_area_id.calendar_id
due_date = line.date_range_id.date_start
lt = line.product_mrp_area_id.mrp_lead_time
due_date_dt = fields.Datetime.from_string(due_date)
if calendar:
res = calendar.plan_days(-1 * lt - 1, due_date_dt)
release_date = res.date()
else:
release_date = due_date_dt - timedelta(days=lt)
return {
"name": "Planned Order for %s"
% line.product_mrp_area_id.product_id.display_name,
"order_release_date": release_date,
"due_date": due_date,
"product_mrp_area_id": line.product_mrp_area_id.id,
"mrp_qty": qty,
"qty_released": 0.0,
"mrp_action": line.product_mrp_area_id.supply_method,
"fixed": True,
}
def button_validate(self):
res_ids = []
for line in self.line_ids:
quantities = []
qty_to_order = line.product_qty
while qty_to_order > 0.0:
qty = line.product_mrp_area_id._adjust_qty_to_order(qty_to_order)
quantities.append(qty)
qty_to_order -= qty
rounding = line.product_mrp_area_id.product_id.uom_id.rounding
for proposed, current in zip_longest(
quantities, line.mrp_planned_order_ids
):
if not proposed:
current.unlink()
elif not current:
data = self._prepare_planned_order_data(line, proposed)
item = self.env["mrp.planned.order"].create(data)
res_ids.append(item.id)
elif (
float_compare(
proposed, current.mrp_qty, precision_rounding=rounding
)
== 0
):
res_ids.append(current.id)
else:
current.mrp_qty = proposed
res_ids.append(current.id)
res = {
"domain": [("id", "in", res_ids)],
"name": _("Planned Orders"),
"src_model": "mrp.planned.order.wizard",
"view_mode": "tree,form,pivot",
"res_model": "mrp.planned.order",
"type": "ir.actions.act_window",
}
return res
class MprPlannedOrderSheetLine(models.TransientModel):
_name = "mrp.planned.order.sheet.line"
_description = "MPS Sheet Line"
mrp_planned_order_ids = fields.Many2many(comodel_name="mrp.planned.order")
product_mrp_area_id = fields.Many2one(
string="Product Parameters", comodel_name="product.mrp.area"
)
date_range_id = fields.Many2one(
comodel_name="date.range",
string="Date Range",
)
value_x = fields.Char(string="Period")
value_y = fields.Char(string="Product")
product_qty = fields.Float(string="Quantity", digits="Product UoM")
| 36.251082 | 8,374 |
504 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "MRP Production Putaway Strategy",
"summary": "Applies putaway strategies to manufacturing orders for "
"finished products.",
"version": "15.0.1.0.0",
"author": "ForgeFlow, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/manufacture",
"category": "Manufacture",
"depends": ["mrp"],
"license": "AGPL-3",
"installable": True,
}
| 33.6 | 504 |
2,499 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-18 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class MrpProductionCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(MrpProductionCase, self).setUp(*args, **kwargs)
self.warehouse = self.env["stock.warehouse"].create(
{
"name": "X Warehouse",
"code": "X WH",
"reception_steps": "one_step",
"delivery_steps": "ship_only",
}
)
self.category = self.env["product.category"].create({"name": "Test"})
self.loc_stock = self.warehouse.lot_stock_id
self.bin_loc_stock = self.env["stock.location"].create(
{"name": "Bin 1", "location_id": self.loc_stock.id, "usage": "internal"}
)
self.product1 = self.env.ref("mrp.product_product_computer_desk")
self.product1.categ_id = self.category
self.bom1 = self.env.ref("mrp.mrp_bom_desk")
self.putaway_strategy = self.env["stock.putaway.rule"].create(
{
"product_id": self.product1.id,
"location_in_id": self.loc_stock.id,
"location_out_id": self.bin_loc_stock.id,
}
)
self.loc_stock.putaway_rule_ids = self.putaway_strategy
def _create_mo(
self,
product=False,
bom=False,
src_loc=False,
dest_loc=False,
qty=10.0,
uom=False,
):
if not product:
product = self.product1
uom = product.uom_id or uom
if not bom:
bom = self.bom1
if not src_loc:
src_loc = self.loc_stock
if not dest_loc:
dest_loc = self.loc_stock
res = {
"product_id": product.id,
"bom_id": bom.id,
"location_src_id": src_loc.id,
"location_dest_id": dest_loc.id,
"product_qty": qty,
"product_uom_id": uom.id,
}
return self.env["mrp.production"].create(res)
def test_putaway_strategy_01(self):
"""Tests if the putaway strategy applies to a Manufacturing Order."""
# Create MO
mo = self._create_mo()
for finished in mo.move_finished_ids:
self.assertEqual(
finished.location_dest_id,
self.bin_loc_stock,
"Putaway strategy hasn't been applied.",
)
| 32.454545 | 2,499 |
977 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-18 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, models
class MrpProduction(models.Model):
_inherit = "mrp.production"
@api.model
def create(self, vals):
location_dest = self.env["stock.location"].browse(vals.get("location_dest_id"))
product = self.env["product.product"].browse(vals.get("product_id"))
location_id = location_dest._get_putaway_strategy(product)
if location_id:
vals["location_dest_id"] = location_id.id
mo = super(MrpProduction, self).create(vals)
if location_id:
message = (
_(
"Applied Putaway strategy to finished products.\n Finished "
"Products Location: %s. "
)
% mo.location_dest_id.complete_name
)
mo.message_post(body=message, message_type="comment")
return mo
| 34.892857 | 977 |
648 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Manufacturing Analytic Items",
"summary": "Consuming raw materials and operations generated Analytic Items",
"version": "15.0.1.0.1",
"category": "Manufacturing",
"author": "Open Source Integrators, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/manufacture",
"license": "AGPL-3",
"depends": ["mrp_analytic"],
"data": [
"views/account_analytic_line_view.xml",
],
"installable": True,
"maintainers": ["dreispt"],
"development_status": "Beta",
}
| 34.105263 | 648 |
4,322 |
py
|
PYTHON
|
15.0
|
from odoo.tests import Form, common
class TestMRP(common.TransactionCase):
"""
Create a Manufacturing Order, with Raw Materials and Operations.
Consuming raw materials generates or updates Analytic Items.
Working on Operations generates or updates Analytic Items.
"""
def setUp(self):
super().setUp()
# Analytic Account
self.analytic_1 = self.env["account.analytic.account"].create({"name": "Job 1"})
# Work Center
self.mrp_workcenter_1 = self.env["mrp.workcenter"].create(
{
"name": "Assembly Line",
"costs_hour": 40,
}
)
# Products
self.product_lemonade = self.env["product.product"].create(
{
"name": "Lemonade",
"type": "product",
"standard_price": 20,
}
)
self.product_lemon = self.env["product.product"].create(
{
"name": "Lemon",
"type": "product",
"standard_price": 1,
}
)
# BOM
self.mrp_bom_lemonade = self.env["mrp.bom"].create(
{
"product_tmpl_id": self.product_lemonade.product_tmpl_id.id,
"operation_ids": [
(
0,
0,
{
"workcenter_id": self.mrp_workcenter_1.id,
"name": "Squeeze Lemons",
"time_cycle": 15,
},
),
],
}
)
self.mrp_bom_lemonade.write(
{
"bom_line_ids": [
(
0,
0,
{
"product_id": self.product_lemon.id,
"product_qty": 4,
},
)
]
}
)
# MO
mo_create_form = Form(self.env["mrp.production"])
mo_create_form.product_id = self.product_lemonade
mo_create_form.bom_id = self.mrp_bom_lemonade
mo_create_form.product_qty = 1
self.mo_lemonade = mo_create_form.save()
self.mo_lemonade.analytic_account_id = self.analytic_1
self.mo_lemonade.action_confirm()
def test_100_one_step_produce(self):
# Form edit the MO and Save
mo_form = Form(self.mo_lemonade)
mo_form.qty_producing = 1
mo_lemonade = mo_form.save()
# Set 15 minutes to work time and "Mark As Done"
mo_lemonade.workorder_ids.duration = 15
mo_lemonade.button_mark_done()
analytic_items = self.env["account.analytic.line"].search(
[("manufacturing_order_id", "=", mo_lemonade.id)]
)
# Expected (4 * 1.00) + (0.25 * 40.00) => 14.00
analytic_qty = sum(analytic_items.mapped("unit_amount"))
self.assertEqual(analytic_qty, 4.25, "Expected Analytic Items total quantity")
analytic_amount = sum(analytic_items.mapped("amount"))
self.assertEqual(
analytic_amount, -14.00, "Expected Analytic Items total amount"
)
def test_110_two_step_produce(self):
# Consume some raw material
self.mo_lemonade.move_raw_ids.write({"quantity_done": 1})
self.mo_lemonade.move_raw_ids.write({"quantity_done": 2})
self.mo_lemonade.move_raw_ids.write({"quantity_done": 4})
# Work on operations up to 15 minutes
self.mo_lemonade.workorder_ids.write({"duration": 5})
self.mo_lemonade.workorder_ids.write({"duration": 10})
self.mo_lemonade.workorder_ids.write({"duration": 15})
analytic_items = self.env["account.analytic.line"].search(
[("manufacturing_order_id", "=", self.mo_lemonade.id)]
)
# Expected (4 * 1.00) + (0.25 * 40.00) => 14.00
analytic_qty = sum(analytic_items.mapped("unit_amount"))
self.assertEqual(analytic_qty, 4.25, "Expected Analytic Items total quantity")
analytic_amount = sum(analytic_items.mapped("amount"))
self.assertEqual(
analytic_amount, -14.00, "Expected Analytic Items total amount"
)
| 37.258621 | 4,322 |
2,857 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class StockMove(models.Model):
_inherit = "stock.move"
def _prepare_mrp_raw_material_analytic_line(self):
"""
Prepare additional values for Analytic Items created.
"""
self.ensure_one()
move = self
mrp_order = move.raw_material_production_id
return {
"date": move.date,
"name": "{} / {}".format(mrp_order.name, move.product_id.display_name),
"ref": mrp_order.name,
"account_id": mrp_order.analytic_account_id.id,
"manufacturing_order_id": mrp_order.id,
"company_id": mrp_order.company_id.id,
"stock_move_id": move.id,
"product_id": move.product_id.id,
"unit_amount": move.quantity_done,
}
def generate_mrp_raw_analytic_line(self):
"""
Generate Analytic Lines.
One Analytic Item for each Stock Move line.
If the Stock Move is updated, the existing Analytic Item is updated.
"""
AnalyticLine = self.env["account.analytic.line"].sudo()
existing_items = AnalyticLine.search([("stock_move_id", "in", self.ids)])
for move in self.filtered("raw_material_production_id.analytic_account_id"):
line_vals = move._prepare_mrp_raw_material_analytic_line()
if move in existing_items.mapped("stock_move_id"):
analytic_line = existing_items.filtered(
lambda x: x.stock_move_id == move
)
analytic_line.write(line_vals)
analytic_line.on_change_unit_amount()
elif line_vals.get("unit_amount"):
analytic_line = AnalyticLine.create(line_vals)
analytic_line.on_change_unit_amount()
def write(self, vals):
"""When material is consumed, generate Analytic Items"""
res = super().write(vals)
if vals.get("quantity_done"):
self.generate_mrp_raw_analytic_line()
return res
@api.model
def create(self, vals):
qty_done = vals.get("quantity_done")
res = super().create(vals)
if qty_done:
res.generate_mrp_raw_analytic_line()
return res
class StockMoveLine(models.Model):
_inherit = "stock.move.line"
def write(self, vals):
qty_done = vals.get("qty_done")
res = super().write(vals)
if qty_done:
self.mapped("move_id").generate_mrp_raw_analytic_line()
return res
@api.model
def create(self, vals):
qty_done = vals.get("qty_done")
res = super().create(vals)
if qty_done:
res.mapped("move_id").generate_mrp_raw_analytic_line()
return res
| 34.841463 | 2,857 |
1,671 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class MrpWorkcenterProductivity(models.Model):
_inherit = "mrp.workcenter.productivity"
def _prepare_mrp_workorder_analytic_item(self):
"""
Prepare additional values for Analytic Items created.
For compatibility with analytic_activity_cost
"""
self.ensure_one()
return {
"name": "{} / {}".format(self.production_id.name, self.workorder_id.name),
"account_id": self.production_id.analytic_account_id.id,
"date": fields.Date.today(),
"company_id": self.company_id.id,
"manufacturing_order_id": self.production_id.id,
"workorder_id": self.workorder_id.id,
"unit_amount": self.duration / 60, # convert minutes to hours
"amount": -self.duration / 60 * self.workcenter_id.costs_hour,
}
def generate_mrp_work_analytic_line(self):
AnalyticLine = self.env["account.analytic.line"].sudo()
for timelog in self:
line_vals = timelog._prepare_mrp_workorder_analytic_item()
analytic_line = AnalyticLine.create(line_vals)
analytic_line.on_change_unit_amount()
@api.model
def create(self, vals):
timelog = super().create(vals)
if vals.get("date_end"):
timelog.generate_mrp_work_analytic_line()
return timelog
def write(self, vals):
res = super().write(vals)
if vals.get("date_end"):
self.generate_mrp_work_analytic_line()
return res
| 36.326087 | 1,671 |
547 |
py
|
PYTHON
|
15.0
|
# Copyright (C) 2020 Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountAnalyticLine(models.Model):
_inherit = "account.analytic.line"
manufacturing_order_id = fields.Many2one(
"mrp.production",
string="Related Manufacturing Order",
)
stock_move_id = fields.Many2one(
"stock.move",
string="Related Stock Move",
)
workorder_id = fields.Many2one(
"mrp.workorder",
string="Work Order",
)
| 26.047619 | 547 |
607 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "MRP Warehouse Calendar",
"summary": "Considers the warehouse calendars in manufacturing",
"version": "15.0.1.0.1",
"license": "LGPL-3",
"website": "https://github.com/OCA/manufacture",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"category": "Manufacturing",
"depends": ["mrp", "stock_warehouse_calendar"],
"installable": True,
"development_status": "Production/Stable",
"maintainers": ["JordiBForgeFlow"],
}
| 37.9375 | 607 |
4,752 |
py
|
PYTHON
|
15.0
|
# Copyright 2018-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import fields
from odoo.tests.common import TransactionCase
class TestMrpWarehouseCalendar(TransactionCase):
def setUp(self):
super(TestMrpWarehouseCalendar, self).setUp()
self.move_obj = self.env["stock.move"]
self.pg_obj = self.env["procurement.group"]
self.company = self.env.ref("base.main_company")
self.warehouse = self.env.ref("stock.warehouse0")
self.customer_loc = self.env.ref("stock.stock_location_customers")
self.company_partner = self.env.ref("base.main_partner")
self.calendar = self.env.ref("resource.resource_calendar_std")
self.manufacture_route = self.env.ref("mrp.route_warehouse0_manufacture")
self.warehouse.calendar_id = self.calendar.id
self.warehouse_2 = self.env["stock.warehouse"].create(
{"code": "WH-T", "name": "Warehouse Test", "calendar_id": self.calendar.id}
)
self.product = self.env["product.product"].create(
{
"name": "test product",
"default_code": "PRD",
"type": "product",
"produce_delay": 1,
}
)
self.product_2 = self.env["product.product"].create(
{"name": "test product 2", "default_code": "PRD 2", "type": "product"}
)
self.bom = self.env["mrp.bom"].create(
{
"product_id": self.product.id,
"product_tmpl_id": self.product.product_tmpl_id.id,
"product_uom_id": self.product.uom_id.id,
"product_qty": 1.0,
"type": "normal",
}
)
self.env["mrp.bom.line"].create(
{"bom_id": self.bom.id, "product_id": self.product_2.id, "product_qty": 2}
)
self.product.route_ids = [(6, 0, self.manufacture_route.ids)]
def test_procurement_with_calendar(self):
values = {
"date_planned": "2097-01-07 09:00:00", # Monday
"warehouse_id": self.warehouse,
"company_id": self.company,
"rule_id": self.manufacture_route,
}
self.pg_obj.run(
[
self.pg_obj.Procurement(
self.product,
100,
self.product.uom_id,
self.warehouse.lot_stock_id,
"Test",
"Test",
self.warehouse.company_id,
values,
)
]
)
mo = self.env["mrp.production"].search(
[("product_id", "=", self.product.id)], limit=1
)
date_plan_start = fields.Date.to_date(mo.date_planned_start)
# Friday 4th Jan 2097
friday = fields.Date.to_date("2097-01-04 09:00:00")
self.assertEqual(date_plan_start, friday)
def test_procurement_with_calendar_02(self):
"""Test procuring at the beginning of the day, with no work intervals
before."""
values = {
"date_planned": "2097-01-07 01:00:00", # Monday
"warehouse_id": self.warehouse,
"company_id": self.company,
"rule_id": self.manufacture_route,
}
self.pg_obj.run(
[
self.pg_obj.Procurement(
self.product,
100,
self.product.uom_id,
self.warehouse.lot_stock_id,
"Test 2",
"Test 2",
self.warehouse.company_id,
values,
)
]
)
mo = self.env["mrp.production"].search(
[("product_id", "=", self.product.id)], limit=1
)
date_plan_start = fields.Date.to_date(mo.date_planned_start)
# Friday 4th Jan 2097
friday = fields.Date.to_date("2097-01-04 09:00:00")
self.assertEqual(date_plan_start, friday)
def test_onchange_date_planned(self):
mo = self.env["mrp.production"].new(
{
"product_id": self.product.id,
"bom_id": self.bom.id,
"product_qty": 1,
"picking_type_id": self.env[
"mrp.production"
]._get_default_picking_type(),
}
)
mo.date_planned_start = "2097-01-04 09:00:00"
mo._onchange_date_planned_start()
date_plan_finished = fields.Date.to_date(mo.date_planned_finished)
monday = fields.Date.to_date("2097-01-07 09:00:00")
self.assertEqual(date_plan_finished, monday)
| 36.837209 | 4,752 |
1,064 |
py
|
PYTHON
|
15.0
|
# Copyright 2018-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import fields, models
class StockRule(models.Model):
_inherit = "stock.rule"
def _get_date_planned(self, product_id, company_id, values):
date_planned = super()._get_date_planned(product_id, company_id, values)
picking_type = self.picking_type_id or values["warehouse_id"].manu_type_id
# We force the date planned to be at the beginning of the day.
# So no work intervals are found in planned date.
dt_planned = fields.Datetime.to_datetime(values["date_planned"]).replace(hour=0)
warehouse = picking_type.warehouse_id
if warehouse.calendar_id and product_id.produce_delay:
lead_days = (
values["company_id"].manufacturing_lead + product_id.produce_delay
)
date_expected = warehouse.calendar_id.plan_days(-1 * lead_days, dt_planned)
date_planned = date_expected
return date_planned
| 46.26087 | 1,064 |
1,782 |
py
|
PYTHON
|
15.0
|
# Copyright 2018-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, models
class MrpProduction(models.Model):
_inherit = "mrp.production"
@api.onchange("date_planned_start", "product_id")
def _onchange_date_planned_start(self):
res = super(MrpProduction, self)._onchange_date_planned_start()
if self.date_planned_start and not self.is_planned:
warehouse = self.picking_type_id.warehouse_id
if warehouse.calendar_id:
if self.product_id.produce_delay:
self.date_planned_finished = warehouse.calendar_id.plan_days(
+1 * self.product_id.produce_delay + 1, self.date_planned_start
)
if self.company_id.manufacturing_lead:
self.date_planned_finished = warehouse.calendar_id.plan_days(
+1 * self.company_id.manufacturing_lead + 1,
self.date_planned_finished,
)
self.move_finished_ids = [
(1, m.id, {"date": self.date_planned_finished})
for m in self.move_finished_ids
]
return res
@api.returns("self", lambda value: value.id)
def copy(self, default=None):
mo = super().copy(default=default)
dt_planned = mo.date_planned_start
warehouse = mo.picking_type_id.warehouse_id
if warehouse.calendar_id and mo.product_id.produce_delay:
date_expected = warehouse.calendar_id.plan_days(
+1 * self.product_id.produce_delay + 1, dt_planned
)
mo.date_planned_finished = date_expected
return mo
| 43.463415 | 1,782 |
532 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
def post_init_hook(cr, registry):
cr.execute(
"""
UPDATE mrp_workorder
SET sequence = n.sequence
FROM (
SELECT
id,
ROW_NUMBER() OVER (PARTITION BY production_id) AS sequence
FROM mrp_workorder
ORDER BY production_id, id
) AS n
WHERE mrp_workorder.id = n.id
"""
)
| 28 | 532 |
645 |
py
|
PYTHON
|
15.0
|
# Copyright 2019-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "MRP Work Order Sequence",
"summary": "adds sequence to production work orders.",
"version": "15.0.1.2.0",
"category": "Manufacturing",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"development_status": "Beta",
"maintainers": ["LoisRForgeFlow"],
"website": "https://github.com/OCA/manufacture",
"license": "LGPL-3",
"depends": ["mrp"],
"data": ["views/mrp_workorder_view.xml"],
"installable": True,
"post_init_hook": "post_init_hook",
}
| 35.833333 | 645 |
8,331 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import Command, fields
from odoo.tests import Form
from odoo.addons.mrp.tests.common import TestMrpCommon
class TestMrpWorkorderSequence(TestMrpCommon):
def setUp(self):
super().setUp()
self._create_bom()
def _create_bom(self):
return self.env["mrp.bom"].create(
{
"product_tmpl_id": self.product_7_template.id,
"product_uom_id": self.uom_unit.id,
"product_qty": 4.0,
"type": "normal",
"operation_ids": [
Command.create(
{
"name": "Cutting Machine",
"workcenter_id": self.workcenter_1.id,
"time_cycle": 12,
"sequence": 1,
}
),
Command.create(
{
"name": "Weld Machine",
"workcenter_id": self.workcenter_1.id,
"time_cycle": 18,
"sequence": 2,
"bom_product_template_attribute_value_ids": [
Command.link(self.product_7_attr1_v1.id)
],
}
),
Command.create(
{
"name": "Taking a coffee",
"workcenter_id": self.workcenter_1.id,
"time_cycle": 5,
"sequence": 3,
"bom_product_template_attribute_value_ids": [
Command.link(self.product_7_attr1_v2.id)
],
}
),
],
"byproduct_ids": [
Command.create(
{
"product_id": self.product_1.id,
"product_uom_id": self.product_1.uom_id.id,
"product_qty": 1,
}
),
Command.create(
{
"product_id": self.product_2.id,
"product_uom_id": self.product_2.uom_id.id,
"product_qty": 1,
"bom_product_template_attribute_value_ids": [
Command.link(self.product_7_attr1_v1.id)
],
}
),
Command.create(
{
"product_id": self.product_3.id,
"product_uom_id": self.product_3.uom_id.id,
"product_qty": 1,
"bom_product_template_attribute_value_ids": [
Command.link(self.product_7_attr1_v2.id)
],
}
),
],
"bom_line_ids": [
Command.create(
{
"product_id": self.product_2.id,
"product_qty": 2,
}
),
Command.create(
{
"product_id": self.product_3.id,
"product_qty": 2,
"bom_product_template_attribute_value_ids": [
Command.link(self.product_7_attr1_v1.id)
],
}
),
Command.create(
{
"product_id": self.product_4.id,
"product_qty": 2,
"bom_product_template_attribute_value_ids": [
Command.link(self.product_7_attr1_v2.id)
],
}
),
],
}
)
def _create_order(self, product):
mrp_order_form = Form(self.env["mrp.production"])
mrp_order_form.product_id = product
return mrp_order_form.save()
def test_mrp_workorder_sequence_new_production(self):
mrp_order = self._create_order(self.product_7_1)
self.assertEqual(len(mrp_order.workorder_ids), 2)
for seq, workorder in enumerate(mrp_order.workorder_ids, 1):
self.assertEqual(workorder.sequence, seq)
def test_mrp_workorder_sequence_new_production_new_workorder(self):
mrp_order = self._create_order(self.product_7_1)
self.assertEqual(len(mrp_order.workorder_ids), 2)
max_sequence = max(mrp_order.workorder_ids.mapped("sequence"))
mrp_order_form = Form(mrp_order)
with mrp_order_form.workorder_ids.new() as wo_form:
wo_form.name = "Extra operation"
wo_form.workcenter_id = self.workcenter_1
mrp_order = mrp_order_form.save()
self.assertEqual(len(mrp_order.workorder_ids), 3)
last_wo = fields.first(mrp_order.workorder_ids.sorted(reverse=True))
self.assertEqual(last_wo.sequence, max_sequence + 1)
def test_mrp_workorder_create_multi(self):
"""
Test automatic sequence assignation through create override
* WO 1: - each added operations without sequence defined
get the next sequence after existing WOs
* WO 2: - first added operation without sequence
get the next sequence after existing WOs
- second added operation with sequence defined stays unchanged
* WO 3: - first added operation with sequence defined stays unchanged
- second added operation without sequence defined
get the next sequence from previous operation created
"""
first_mrp_order = self._create_order(self.product_7_1)
second_mrp_order = self._create_order(self.product_7_1)
third_mrp_order = self._create_order(self.product_7_1)
create_values = [
{
"name": "Extra WO 1.1",
"production_id": first_mrp_order.id,
"workcenter_id": self.workcenter_1.id,
"product_uom_id": self.product_7_1.uom_id.id,
},
{
"name": "Extra WO 1.2",
"production_id": first_mrp_order.id,
"workcenter_id": self.workcenter_1.id,
"product_uom_id": self.product_7_1.uom_id.id,
},
{
"name": "Extra WO 2.1",
"production_id": second_mrp_order.id,
"workcenter_id": self.workcenter_1.id,
"product_uom_id": self.product_7_1.uom_id.id,
},
{
"name": "Extra WO 2.2",
"production_id": second_mrp_order.id,
"workcenter_id": self.workcenter_1.id,
"product_uom_id": self.product_7_1.uom_id.id,
"sequence": 6,
},
{
"name": "Extra WO 3.1",
"production_id": third_mrp_order.id,
"workcenter_id": self.workcenter_1.id,
"sequence": 4,
"product_uom_id": self.product_7_1.uom_id.id,
},
{
"name": "Extra WO 3.2",
"production_id": third_mrp_order.id,
"workcenter_id": self.workcenter_1.id,
"product_uom_id": self.product_7_1.uom_id.id,
},
]
created_wos = self.env["mrp.workorder"].create(create_values)
expected_res = {
"Extra WO 1.1": 3,
"Extra WO 1.2": 4,
"Extra WO 2.1": 3,
"Extra WO 2.2": 6,
"Extra WO 3.1": 4,
"Extra WO 3.2": 5,
}
for wo in created_wos:
self.assertEqual(wo.sequence, expected_res[wo.name])
| 41.242574 | 8,331 |
779 |
py
|
PYTHON
|
15.0
|
# Copyright 2019-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class MrpProduction(models.Model):
_inherit = "mrp.production"
def _reset_work_order_sequence(self):
for rec in self:
for current_seq, work in enumerate(rec.workorder_ids, 1):
work.sequence = current_seq
def _create_workorder(self):
# Bypass sequence assignation on create and make sure there is no gap
# using _reset_work_order_sequence
res = super(
MrpProduction,
self.with_context(_bypass_sequence_assignation_on_create=True),
)._create_workorder()
self._reset_work_order_sequence()
return res
| 33.869565 | 779 |
1,732 |
py
|
PYTHON
|
15.0
|
# Copyright 2019-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class MrpWorkOrder(models.Model):
_inherit = "mrp.workorder"
_order = "production_id, sequence, id"
sequence = fields.Integer()
def _assign_sequence_on_create(self, values_list):
"""Assign sequence number for manually added operations"""
new_wos_production_ids_without_seq = {
vals["production_id"] for vals in values_list if not vals.get("sequence")
}
if new_wos_production_ids_without_seq:
max_seq_by_production = self.read_group(
[("production_id", "in", list(new_wos_production_ids_without_seq))],
["sequence:max", "production_id"],
["production_id"],
)
max_seq_by_prod_id = {
res["production_id"][0]: res["sequence"]
for res in max_seq_by_production
}
for values in values_list:
prod_id = values["production_id"]
values_seq = values.get("sequence")
max_seq = max_seq_by_prod_id.setdefault(prod_id, 0)
if values_seq and values_seq > max_seq:
max_seq_by_prod_id[prod_id] = values_seq
continue
max_seq_by_prod_id[prod_id] += 1
values["sequence"] = max_seq_by_prod_id[prod_id]
@api.model_create_multi
def create(self, values_list):
if not self.env.context.get("_bypass_sequence_assignation_on_create"):
self._assign_sequence_on_create(values_list)
return super().create(values_list)
| 41.238095 | 1,732 |
533 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-19 ForgeFlow, S.L.
# (<https://www.forgeflow.com>)
# Copyright 2019 Rubén Bravo <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "MRP BOM Component Menu",
"version": "15.0.1.0.0",
"category": "Manufacturing",
"website": "https://github.com/OCA/manufacture",
"author": "ForgeFlow," "Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["mrp"],
"data": ["views/mrp_bom_component_view.xml"],
}
| 35.466667 | 532 |
656 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
{
"name": "MRP Serial Number Propagation",
"version": "15.0.0.3.0",
"development_status": "Alpha",
"license": "AGPL-3",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["sebalix"],
"summary": "Propagate a serial number from a component to a finished product",
"website": "https://github.com/OCA/manufacture",
"category": "Manufacturing",
"depends": ["mrp"],
"data": [
"views/mrp_bom.xml",
"views/mrp_production.xml",
],
"installable": True,
"application": False,
}
| 32.8 | 656 |
6,319 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo.exceptions import UserError
from odoo.fields import Command
from odoo.tests.common import Form
from .common import Common
class TestMrpProduction(Common):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Configure the BoM to propagate lot number
cls._configure_bom()
cls.order = cls._create_order(cls.bom_product_product, cls.bom)
@classmethod
def _configure_bom(cls):
with Form(cls.bom) as form:
form.lot_number_propagation = True
line_form = form.bom_line_ids.edit(0) # Line tracked by SN
line_form.propagate_lot_number = True
line_form.save()
form.save()
@classmethod
def _create_order(cls, product, bom):
with Form(cls.env["mrp.production"]) as form:
form.product_id = product
form.bom_id = bom
return form.save()
def _set_qty_done(self, order):
for line in order.move_raw_ids.move_line_ids:
line.qty_done = line.product_uom_qty
order.qty_producing = order.product_qty
def test_order_propagated_lot_producing(self):
self.assertTrue(self.order.is_lot_number_propagated) # set by onchange
self._update_stock_component_qty(self.order)
self.order.action_confirm()
self.assertTrue(self.order.is_lot_number_propagated) # set by action_confirm
self.assertTrue(any(self.order.move_raw_ids.mapped("propagate_lot_number")))
self._set_qty_done(self.order)
self.assertEqual(self.order.propagated_lot_producing, self.LOT_NAME)
def test_order_write_lot_producing_id_not_allowed(self):
with self.assertRaisesRegex(UserError, "not allowed"):
self.order.write({"lot_producing_id": False})
def test_order_post_inventory(self):
self._update_stock_component_qty(self.order)
self.order.action_confirm()
self._set_qty_done(self.order)
self.order.button_mark_done()
self.assertEqual(self.order.lot_producing_id.name, self.LOT_NAME)
def test_order_post_inventory_lot_already_exists_but_not_used(self):
self._update_stock_component_qty(self.order)
self.order.action_confirm()
self._set_qty_done(self.order)
self.assertEqual(self.order.propagated_lot_producing, self.LOT_NAME)
# Create a lot with the same number for the finished product
# without any stock/quants (so not used at all) before validating the MO
existing_lot = self.env["stock.production.lot"].create(
{
"product_id": self.order.product_id.id,
"company_id": self.order.company_id.id,
"name": self.order.propagated_lot_producing,
}
)
self.order.button_mark_done()
self.assertEqual(self.order.lot_producing_id, existing_lot)
def test_order_post_inventory_lot_already_exists_and_used(self):
self._update_stock_component_qty(self.order)
self.order.action_confirm()
self._set_qty_done(self.order)
self.assertEqual(self.order.propagated_lot_producing, self.LOT_NAME)
# Create a lot with the same number for the finished product
# with some stock/quants (so it is considered as used) before
# validating the MO
existing_lot = self.env["stock.production.lot"].create(
{
"product_id": self.order.product_id.id,
"company_id": self.order.company_id.id,
"name": self.order.propagated_lot_producing,
}
)
self._update_qty_in_location(
self.env.ref("stock.stock_location_stock"),
self.order.product_id,
1,
lot=existing_lot,
)
with self.assertRaisesRegex(UserError, "already exists and has been used"):
self.order.button_mark_done()
def test_confirm_with_variant_ok(self):
self._add_color_and_legs_variants(self.bom_product_template)
self._add_color_and_legs_variants(self.product_template_tracked_by_sn)
new_bom = self._create_bom_with_variants()
self.assertTrue(new_bom.lot_number_propagation)
# As all variants must have a single component
# where lot must be propagated, there should not be any error
for product in self.bom_product_template.product_variant_ids:
new_order = self._create_order(product, new_bom)
new_order.action_confirm()
def test_confirm_with_variant_multiple(self):
self._add_color_and_legs_variants(self.bom_product_template)
self._add_color_and_legs_variants(self.product_template_tracked_by_sn)
new_bom = self._create_bom_with_variants()
# Remove application on variant for first bom line
# with this only the first variant of the product template
# will have a single component where lot must be propagated
new_bom.bom_line_ids[0].bom_product_template_attribute_value_ids = [
Command.clear()
]
for cnt, product in enumerate(self.bom_product_template.product_variant_ids):
new_order = self._create_order(product, new_bom)
if cnt == 0:
new_order.action_confirm()
else:
with self.assertRaisesRegex(UserError, "multiple components"):
new_order.action_confirm()
def test_confirm_with_variant_no(self):
self._add_color_and_legs_variants(self.bom_product_template)
self._add_color_and_legs_variants(self.product_template_tracked_by_sn)
new_bom = self._create_bom_with_variants()
# Remove first bom line
# with this the first variant of the product template
# will not have any component where lot must be propagated
new_bom.bom_line_ids[0].unlink()
for cnt, product in enumerate(self.bom_product_template.product_variant_ids):
new_order = self._create_order(product, new_bom)
if cnt == 0:
with self.assertRaisesRegex(UserError, "no component"):
new_order.action_confirm()
else:
new_order.action_confirm()
| 43.881944 | 6,319 |
6,377 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
import random
import string
from odoo import fields
from odoo.tests import Form, common
class Common(common.TransactionCase):
LOT_NAME = "PROPAGATED-LOT"
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.bom = cls.env.ref("mrp.mrp_bom_desk")
cls.bom_product_template = cls.env.ref(
"mrp.product_product_computer_desk_product_template"
)
cls.bom_product_product = cls.env.ref("mrp.product_product_computer_desk")
cls.product_tracked_by_lot = cls.env.ref(
"mrp.product_product_computer_desk_leg"
)
cls.product_tracked_by_sn = cls.env.ref(
"mrp.product_product_computer_desk_head"
)
cls.product_template_tracked_by_sn = cls.env.ref(
"mrp.product_product_computer_desk_head_product_template"
)
cls.line_tracked_by_lot = cls.bom.bom_line_ids.filtered(
lambda o: o.product_id == cls.product_tracked_by_lot
)
cls.line_tracked_by_sn = cls.bom.bom_line_ids.filtered(
lambda o: o.product_id == cls.product_tracked_by_sn
)
cls.line_no_tracking = fields.first(
cls.bom.bom_line_ids.filtered(lambda o: o.product_id.tracking == "none")
)
@classmethod
def _update_qty_in_location(
cls, location, product, quantity, package=None, lot=None, in_date=None
):
quants = cls.env["stock.quant"]._gather(
product, location, lot_id=lot, package_id=package, strict=True
)
# this method adds the quantity to the current quantity, so remove it
quantity -= sum(quants.mapped("quantity"))
cls.env["stock.quant"]._update_available_quantity(
product,
location,
quantity,
package_id=package,
lot_id=lot,
in_date=in_date,
)
@classmethod
def _update_stock_component_qty(cls, order=None, bom=None, location=None):
if not order and not bom:
return
if order:
bom = order.bom_id
if not location:
location = cls.env.ref("stock.stock_location_stock")
for line in bom.bom_line_ids:
if line.product_id.type != "product":
continue
lot = None
if line.product_id.tracking != "none":
lot_name = "".join(
random.choice(string.ascii_lowercase) for i in range(10)
)
if line.propagate_lot_number:
lot_name = cls.LOT_NAME
vals = {
"product_id": line.product_id.id,
"company_id": line.company_id.id,
"name": lot_name,
}
lot = cls.env["stock.production.lot"].create(vals)
cls._update_qty_in_location(
location,
line.product_id,
line.product_qty,
lot=lot,
)
@classmethod
def _get_lot_quants(cls, lot, location=None):
quants = lot.quant_ids.filtered(lambda q: q.quantity > 0)
if location:
quants = quants.filtered(
lambda q: q.location_id.parent_path in location.parent_path
)
return quants
@classmethod
def _add_color_and_legs_variants(cls, product_template):
color_attribute = cls.env.ref("product.product_attribute_2")
color_att_value_white = cls.env.ref("product.product_attribute_value_3")
color_att_value_black = cls.env.ref("product.product_attribute_value_4")
legs_attribute = cls.env.ref("product.product_attribute_1")
legs_att_value_steel = cls.env.ref("product.product_attribute_value_1")
legs_att_value_alu = cls.env.ref("product.product_attribute_value_2")
cls._add_variants(
product_template,
{
color_attribute: [color_att_value_white, color_att_value_black],
legs_attribute: [legs_att_value_steel, legs_att_value_alu],
},
)
@classmethod
def _add_variants(cls, product_template, attribute_values_dict):
for attribute, att_values_list in attribute_values_dict.items():
cls.env["product.template.attribute.line"].create(
{
"product_tmpl_id": product_template.id,
"attribute_id": attribute.id,
"value_ids": [
fields.Command.set([att_val.id for att_val in att_values_list])
],
}
)
@classmethod
def _create_bom_with_variants(cls):
attribute_values_dict = {
att_val.product_attribute_value_id.name: att_val.id
for att_val in cls.env["product.template.attribute.value"].search(
[("product_tmpl_id", "=", cls.bom_product_template.id)]
)
}
new_bom_form = Form(cls.env["mrp.bom"])
new_bom_form.product_tmpl_id = cls.bom_product_template
new_bom = new_bom_form.save()
bom_line_create_values = []
for product in cls.product_template_tracked_by_sn.product_variant_ids:
create_values = {"bom_id": new_bom.id}
create_values["product_id"] = product.id
att_values_commands = []
for att_value in product.product_template_attribute_value_ids:
att_values_commands.append(
fields.Command.link(attribute_values_dict[att_value.name])
)
create_values[
"bom_product_template_attribute_value_ids"
] = att_values_commands
bom_line_create_values.append(create_values)
cls.env["mrp.bom.line"].create(bom_line_create_values)
new_bom_form = Form(new_bom)
new_bom_form.lot_number_propagation = True
for line_position, _bom_line in enumerate(new_bom.bom_line_ids):
new_bom_line_form = new_bom_form.bom_line_ids.edit(line_position)
new_bom_line_form.propagate_lot_number = True
new_bom_line_form.save()
return new_bom_form.save()
| 39.608696 | 6,377 |
3,085 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo.exceptions import ValidationError
from odoo.tests.common import Form
from .common import Common
class TestMrpBom(Common):
def test_bom_display_lot_number_propagation(self):
self.assertTrue(self.bom.display_lot_number_propagation)
self.bom.product_tmpl_id.tracking = "none"
self.assertFalse(self.bom.display_lot_number_propagation)
def test_bom_line_check_propagate_lot_number_not_tracked(self):
form = Form(self.bom)
form.lot_number_propagation = True
# Flag a line that can't be propagated
line_form = form.bom_line_ids.edit(2) # line without tracking
line_form.propagate_lot_number = True
line_form.save()
with self.assertRaisesRegex(ValidationError, "Only components tracked"):
form.save()
def test_bom_line_check_propagate_lot_number_tracked_by_lot(self):
form = Form(self.bom)
form.lot_number_propagation = True
# Flag a line tracked by lot (not SN) which is not supported
line_form = form.bom_line_ids.edit(1)
line_form.propagate_lot_number = True
line_form.save()
with self.assertRaisesRegex(ValidationError, "Only components tracked"):
form.save()
def test_bom_line_check_propagate_lot_number_same_tracking(self):
form = Form(self.bom)
form.lot_number_propagation = True
# Flag a line whose tracking type is the same than the finished product
line_form = form.bom_line_ids.edit(0)
line_form.propagate_lot_number = True
line_form.save()
form.save()
def test_bom_check_propagate_lot_number(self):
# Configure the BoM to propagate the lot/SN without enabling any line
with self.assertRaisesRegex(ValidationError, "a line has to be configured"):
self.bom.lot_number_propagation = True
def test_reset_tracking_on_bom_product(self):
# Configure the BoM to propagate the lot/SN
with Form(self.bom) as form:
form.lot_number_propagation = True
line_form = form.bom_line_ids.edit(0) # Line tracked by SN
line_form.propagate_lot_number = True
line_form.save()
form.save()
# Reset the tracking on the finished product
with self.assertRaisesRegex(ValidationError, "A BoM propagating"):
self.bom.product_tmpl_id.tracking = "none"
def test_reset_tracking_on_bom_component(self):
# Configure the BoM to propagate the lot/SN
with Form(self.bom) as form:
form.lot_number_propagation = True
line_form = form.bom_line_ids.edit(0) # Line tracked by SN
line_form.propagate_lot_number = True
line_form.save()
form.save()
# Reset the tracking on the component which propagates the SN
with self.assertRaisesRegex(ValidationError, "This component is"):
self.line_tracked_by_sn.product_id.tracking = "none"
| 42.847222 | 3,085 |
1,666 |
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
class MrpBomLine(models.Model):
_inherit = "mrp.bom.line"
propagate_lot_number = fields.Boolean(
default=False,
)
display_propagate_lot_number = fields.Boolean(
compute="_compute_display_propagate_lot_number"
)
@api.depends(
"bom_id.display_lot_number_propagation",
"bom_id.lot_number_propagation",
)
def _compute_display_propagate_lot_number(self):
for line in self:
line.display_propagate_lot_number = (
line.bom_id.display_lot_number_propagation
and line.bom_id.lot_number_propagation
)
@api.constrains("propagate_lot_number")
def _check_propagate_lot_number(self):
"""
This function should check:
- if the bom has lot_number_propagation marked, there is one and
only one line of this bom with propagate_lot_number marked.
- the bom line being marked with lot_number_propagation is of the same
tracking type as the finished product
"""
for line in self:
if not line.bom_id.lot_number_propagation:
continue
if line.propagate_lot_number and line.product_id.tracking != "serial":
raise ValidationError(
_(
"Only components tracked by serial number can propagate "
"its lot/serial number to the finished product."
)
)
| 34.708333 | 1,666 |
1,621 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import _, api, models
from odoo.exceptions import ValidationError
class ProductTemplate(models.Model):
_inherit = "product.template"
@api.constrains("tracking")
def _check_bom_propagate_lot_number(self):
"""Block tracking type updates if the product is used by a BoM."""
for product in self:
if product.tracking == "serial":
continue
# Check BoMs
for bom in product.bom_ids:
if bom.lot_number_propagation:
raise ValidationError(
_(
"A BoM propagating serial numbers requires "
"this product to be tracked as such."
)
)
# Check lines of BoMs
bom_lines = self.env["mrp.bom.line"].search(
[
("product_id", "in", product.product_variant_ids.ids),
("propagate_lot_number", "=", True),
("bom_id.lot_number_propagation", "=", True),
]
)
if bom_lines:
boms = "\n- ".join(bom_lines.mapped("bom_id.display_name"))
boms = "\n- " + boms
raise ValidationError(
_(
"This component is configured to propagate its "
"serial number in the following Bill of Materials:{boms}'"
).format(boms=boms)
)
| 38.595238 | 1,621 |
374 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import api, models
class ProductProduct(models.Model):
_inherit = "product.product"
@api.constrains("tracking")
def _check_bom_propagate_lot_number(self):
for product in self:
product.product_tmpl_id._check_bom_propagate_lot_number()
| 28.769231 | 374 |
284 |
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 StockMove(models.Model):
_inherit = "stock.move"
propagate_lot_number = fields.Boolean(
default=False,
readonly=True,
)
| 21.846154 | 284 |
7,648 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from lxml import etree
from odoo import _, api, fields, models, tools
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools.safe_eval import safe_eval
from odoo.addons.base.models.ir_ui_view import (
transfer_modifiers_to_node,
transfer_node_to_modifiers,
)
class MrpProduction(models.Model):
_inherit = "mrp.production"
is_lot_number_propagated = fields.Boolean(
default=False,
readonly=True,
help=(
"Lot/serial number is propagated "
"from a component to the finished product."
),
)
propagated_lot_producing = fields.Char(
compute="_compute_propagated_lot_producing",
help=(
"The BoM used on this manufacturing order is set to propagate "
"lot number from one of its components. The value will be "
"computed once the corresponding component is selected."
),
)
@api.depends(
"move_raw_ids.propagate_lot_number",
"move_raw_ids.move_line_ids.qty_done",
"move_raw_ids.move_line_ids.lot_id",
)
def _compute_propagated_lot_producing(self):
for order in self:
order.propagated_lot_producing = False
move_with_lot = order._get_propagating_component_move()
line_with_sn = move_with_lot.move_line_ids.filtered(
lambda l: (
l.lot_id
and l.product_id.tracking == "serial"
and tools.float_compare(
l.qty_done, 1, precision_rounding=l.product_uom_id.rounding
)
== 0
)
)
if len(line_with_sn) == 1:
order.propagated_lot_producing = line_with_sn.lot_id.name
@api.onchange("bom_id")
def _onchange_bom_id_lot_number_propagation(self):
self.is_lot_number_propagated = self.bom_id.lot_number_propagation
def action_confirm(self):
res = super().action_confirm()
self._set_lot_number_propagation_data_from_bom()
return res
def _get_propagating_component_move(self):
self.ensure_one()
return self.move_raw_ids.filtered(lambda o: o.propagate_lot_number)
def _set_lot_number_propagation_data_from_bom(self):
"""Copy information from BoM to the manufacturing order."""
for order in self:
propagate_lot = order.bom_id.lot_number_propagation
if not propagate_lot:
continue
order.is_lot_number_propagated = propagate_lot
propagate_move = order.move_raw_ids.filtered(
lambda m: m.bom_line_id.propagate_lot_number
)
if not propagate_move:
raise UserError(
_(
"Bill of material is marked for lot number propagation, but "
"there are no components propagating lot number. "
"Please check BOM configuration."
)
)
elif len(propagate_move) > 1:
raise UserError(
_(
"Bill of material is marked for lot number propagation, but "
"there are multiple components propagating lot number. "
"Please check BOM configuration."
)
)
else:
propagate_move.propagate_lot_number = True
def _post_inventory(self, cancel_backorder=False):
self._create_and_assign_propagated_lot_number()
return super()._post_inventory(cancel_backorder=cancel_backorder)
def _create_and_assign_propagated_lot_number(self):
for order in self:
if not order.is_lot_number_propagated or order.lot_producing_id:
continue
finish_moves = order.move_finished_ids.filtered(
lambda m: m.product_id == order.product_id
and m.state not in ("done", "cancel")
)
if finish_moves and not finish_moves.quantity_done:
lot_model = self.env["stock.production.lot"]
lot = lot_model.search(
[
("product_id", "=", order.product_id.id),
("company_id", "=", order.company_id.id),
("name", "=", order.propagated_lot_producing),
],
limit=1,
)
if lot.quant_ids:
raise UserError(
_(
"Lot/Serial number %s already exists and has been used. "
"Unable to propagate it."
)
)
if not lot:
lot = self.env["stock.production.lot"].create(
{
"product_id": order.product_id.id,
"company_id": order.company_id.id,
"name": order.propagated_lot_producing,
}
)
order.with_context(lot_propagation=True).lot_producing_id = lot
def write(self, vals):
for order in self:
if (
order.is_lot_number_propagated
and "lot_producing_id" in vals
and not self.env.context.get("lot_propagation")
):
raise UserError(
_(
"Lot/Serial number is propagated from a component, "
"you are not allowed to change it."
)
)
return super().write(vals)
def fields_view_get(
self, view_id=None, view_type="form", toolbar=False, submenu=False
):
# Override to hide the "lot_producing_id" field + "action_generate_serial"
# button if the MO is configured to propagate a serial number
result = super().fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu
)
if result.get("name") in self._views_to_adapt():
result["arch"] = self._fields_view_get_adapt_lot_tags_attrs(result)
return result
def _views_to_adapt(self):
"""Return the form view names bound to 'mrp.production' to adapt."""
return ["mrp.production.form"]
def _fields_view_get_adapt_lot_tags_attrs(self, view):
"""Hide elements related to lot if it is automatically propagated."""
doc = etree.XML(view["arch"])
tags = (
"//label[@for='lot_producing_id']",
"//field[@name='lot_producing_id']/..", # parent <div>
)
for xpath_expr in tags:
attrs_key = "invisible"
nodes = doc.xpath(xpath_expr)
for field in nodes:
attrs = safe_eval(field.attrib.get("attrs", "{}"))
if not attrs[attrs_key]:
continue
invisible_domain = expression.OR(
[attrs[attrs_key], [("is_lot_number_propagated", "=", True)]]
)
attrs[attrs_key] = invisible_domain
field.set("attrs", str(attrs))
modifiers = {}
transfer_node_to_modifiers(field, modifiers, self.env.context)
transfer_modifiers_to_node(modifiers, field)
return etree.tostring(doc, encoding="unicode")
| 39.626943 | 7,648 |
3,240 |
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, tools
from odoo.exceptions import ValidationError
class MrpBom(models.Model):
_inherit = "mrp.bom"
lot_number_propagation = fields.Boolean(
default=False,
help=(
"Allow to propagate the lot/serial number "
"from a component to the finished product."
),
)
display_lot_number_propagation = fields.Boolean(
compute="_compute_display_lot_number_propagation"
)
@api.depends(
"type",
"product_tmpl_id.tracking",
"product_qty",
"product_uom_id",
"bom_line_ids.product_id.tracking",
"bom_line_ids.product_qty",
"bom_line_ids.product_uom_id",
)
def _compute_display_lot_number_propagation(self):
"""Check if a lot number can be propagated.
A lot number can be propagated from a component to the finished product if:
- the type of the BoM is normal (Manufacture this product)
- the finished product is tracked by serial number
- the quantity of the finished product is 1 and its UoM is unit
- there is at least one bom line, with a component tracked by serial,
having a quantity of 1 and its UoM is unit
"""
uom_unit = self.env.ref("uom.product_uom_unit")
for bom in self:
bom.display_lot_number_propagation = (
bom.type in self._get_lot_number_propagation_bom_types()
and bom.product_tmpl_id.tracking == "serial"
and tools.float_compare(
bom.product_qty, 1, precision_rounding=bom.product_uom_id.rounding
)
== 0
and bom.product_uom_id == uom_unit
and bom._has_tracked_product_to_propagate()
)
def _get_lot_number_propagation_bom_types(self):
return ["normal"]
def _has_tracked_product_to_propagate(self):
self.ensure_one()
uom_unit = self.env.ref("uom.product_uom_unit")
for line in self.bom_line_ids:
if (
line.product_id.tracking == "serial"
and tools.float_compare(
line.product_qty, 1, precision_rounding=line.product_uom_id.rounding
)
== 0
and line.product_uom_id == uom_unit
):
return True
return False
@api.onchange("display_lot_number_propagation")
def onchange_display_lot_number_propagation(self):
if not self.display_lot_number_propagation:
self.lot_number_propagation = False
@api.constrains("lot_number_propagation")
def _check_propagate_lot_number(self):
for bom in self:
if not bom.lot_number_propagation:
continue
if not bom.bom_line_ids.filtered("propagate_lot_number"):
raise ValidationError(
_(
"With 'Lot Number Propagation' enabled, a line has "
"to be configured with the 'Propagate Lot Number' option."
)
)
| 36.818182 | 3,240 |
735 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2019 Rubén Bravo <[email protected]>
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "MRP Sale Info",
"summary": "Adds sale information to Manufacturing models",
"version": "15.0.1.0.0",
"category": "Manufacturing",
"website": "https://github.com/OCA/manufacture",
"author": "AvanzOSC, Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": [
"mrp",
"sale_stock",
],
"data": [
"views/mrp_production.xml",
"views/mrp_workorder.xml",
],
}
| 31.913043 | 734 |
2,751 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
class TestMrpSaleInfo(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
route_manufacture_1 = cls.env.ref("mrp.route_warehouse0_manufacture")
route_manufacture_2 = cls.env.ref("stock.route_warehouse0_mto")
route_manufacture_2.active = True
cls.product = cls.env["product.product"].create(
{
"name": "Test mrp_sale_info product",
"type": "product",
"route_ids": [
(4, route_manufacture_1.id),
(4, route_manufacture_2.id),
],
}
)
cls.bom = cls.env["mrp.bom"].create(
{
"product_tmpl_id": cls.product.product_tmpl_id.id,
"operation_ids": [
(
0,
0,
{
"name": "Test operation",
"workcenter_id": cls.env.ref("mrp.mrp_workcenter_3").id,
},
)
],
}
)
cls.partner = cls.env["res.partner"].create({"name": "Test client"})
cls.sale_order = cls.env["sale.order"].create(
{
"partner_id": cls.partner.id,
"client_order_ref": "SO1",
"order_line": [
(
0,
0,
{
"product_id": cls.product.id,
"product_uom_qty": 1,
"price_unit": 1,
},
),
],
}
)
def test_mrp_sale_info(self):
prev_productions = self.env["mrp.production"].search([])
self.sale_order.action_confirm()
production = self.env["mrp.production"].search([]) - prev_productions
self.assertEqual(production.sale_id, self.sale_order)
self.assertEqual(production.partner_id, self.partner)
self.assertEqual(production.client_order_ref, self.sale_order.client_order_ref)
def test_mrp_workorder(self):
prev_workorders = self.env["mrp.workorder"].search([])
self.sale_order.action_confirm()
workorder = self.env["mrp.workorder"].search([]) - prev_workorders
self.assertEqual(workorder.sale_id, self.sale_order)
self.assertEqual(workorder.partner_id, self.partner)
self.assertEqual(workorder.client_order_ref, self.sale_order.client_order_ref)
| 38.208333 | 2,751 |
867 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 Rubén Bravo <[email protected]>
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import models
class StockRule(models.Model):
_inherit = "stock.rule"
def _prepare_mo_vals(
self,
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
bom,
):
res = super()._prepare_mo_vals(
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
bom,
)
res["source_procurement_group_id"] = (
values.get("group_id").id if values.get("group_id", False) else False
)
return res
| 23.405405 | 866 |
1,059 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2019 Rubén Bravo <[email protected]>
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class MrpProduction(models.Model):
_inherit = "mrp.production"
source_procurement_group_id = fields.Many2one(
comodel_name="procurement.group",
readonly=True,
)
sale_id = fields.Many2one(
comodel_name="sale.order",
string="Sale order",
readonly=True,
store=True,
related="source_procurement_group_id.sale_id",
)
partner_id = fields.Many2one(
comodel_name="res.partner",
related="sale_id.partner_id",
string="Customer",
store=True,
)
commitment_date = fields.Datetime(
related="sale_id.commitment_date", string="Commitment Date", store=True
)
client_order_ref = fields.Char(
related="sale_id.client_order_ref", string="Customer Reference", store=True
)
| 31.117647 | 1,058 |
819 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Antiun Ingenieria S.L. - Javier Iniesta
# Copyright 2019 Rubén Bravo <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class MrpWorkorder(models.Model):
_inherit = "mrp.workorder"
sale_id = fields.Many2one(
related="production_id.sale_id", string="Sale order", readonly=True, store=True
)
partner_id = fields.Many2one(
related="sale_id.partner_id", readonly=True, string="Customer", store=True
)
commitment_date = fields.Datetime(
related="sale_id.commitment_date",
string="Commitment Date",
store=True,
readonly=True,
)
client_order_ref = fields.Char(
related="sale_id.client_order_ref", string="Customer Reference", store=True
)
| 32.72 | 818 |
623 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "MRP Production Date Planned Finished",
"summary": "Allows to plan production from the desired finish date",
"version": "15.0.1.0.0",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"website": "https://github.com/OCA/manufacture",
"license": "AGPL-3",
"category": "Manufacturing",
"depends": ["mrp"],
"data": ["views/mrp_production.xml"],
}
| 38.875 | 622 |
2,235 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo.tests import Form, TransactionCase
class TestDatePlannedFinished(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.company = cls.env.ref("base.main_company")
cls.company.manufacturing_lead = 1
cls.product = cls.env.ref("mrp.product_product_computer_desk")
cls.product.produce_delay = 1
cls.product_bom = cls.env.ref("mrp.mrp_bom_desk")
def test_mrp_production_date_planned_finished_onchange(self):
"""Test that date_planned_start is set when date_planned_finished is changed."""
with Form(self.env["mrp.production"]) as mo:
mo.product_id = self.product
mo.bom_id = self.product_bom
mo.product_qty = 1
mo.date_planned_finished = "2022-10-10 10:00:00"
self.assertEqual(mo.date_planned_start, "2022-10-08 10:00:00")
def test_mrp_production_date_planned_finished_decoration(self):
"""Test that the date_planned_finished field is decorated properly
Its decoration has to exactly match the date_planned_start one.
As this might change if odoo updates their code, or during migrations,
this test case will track any mismatches and fail.
"""
res = self.env["mrp.production"].fields_view_get(view_type="form")
doc = etree.XML(res["arch"])
date_planned_start = doc.xpath("//field[@name='date_planned_start']")[0]
date_planned_finished = doc.xpath("//field[@name='date_planned_finished']")[0]
decoration_attrs = [
attr
for attr in date_planned_start.attrib.keys()
if attr.startswith("decoration-")
]
for attr in decoration_attrs:
self.assertEqual(
date_planned_start.attrib[attr],
date_planned_finished.attrib[attr],
f"date_planned_finished decoration mismatch: {attr}",
)
| 43.803922 | 2,234 |
1,162 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta
from odoo import api, models
class MrpProduction(models.Model):
_inherit = "mrp.production"
@api.onchange("date_planned_finished")
def _onchange_date_planned_finished_set_date_planned_start(self):
if self.date_planned_finished and not self.is_planned:
date_planned_start = self.date_planned_finished
date_planned_start -= relativedelta(days=self.product_id.produce_delay)
date_planned_start -= relativedelta(days=self.company_id.manufacturing_lead)
if date_planned_start == self.date_planned_finished:
date_planned_start -= relativedelta(hours=1)
if self.date_planned_start != date_planned_start:
self.date_planned_start = date_planned_start
self.move_raw_ids = [
(1, m.id, {"date": self.date_planned_start})
for m in self.move_raw_ids
]
| 44.653846 | 1,161 |
589 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "MRP BOM Location",
"summary": "Adds location field to Bill of Materials and its components.",
"version": "15.0.1.0.0",
"category": "Manufacture",
"website": "https://github.com/OCA/manufacture",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "LGPL-3",
"application": False,
"depends": ["mrp"],
"data": ["views/mrp_view.xml", "views/report_mrpbomstructure.xml"],
"installable": True,
}
| 39.266667 | 589 |
684 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo import api, fields, models
class MrpBom(models.Model):
_inherit = "mrp.bom"
location_id = fields.Many2one(string="Location", comodel_name="stock.location")
@api.onchange("picking_type_id")
def _onchange_picking_type_id(self):
if self.picking_type_id and self.picking_type_id.default_location_src_id:
self.location_id = self.picking_type_id.default_location_src_id
class MrpBomLine(models.Model):
_inherit = "mrp.bom.line"
location_id = fields.Many2one(related="bom_id.location_id", store=True)
| 32.571429 | 684 |
1,390 |
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo import api, models
class BomStructureReport(models.AbstractModel):
_inherit = "report.mrp.report_bom_structure"
@api.model
def _get_bom_lines(self, bom, bom_quantity, product, line_id, level):
res = super(BomStructureReport, self)._get_bom_lines(
bom, bom_quantity, product, line_id, level
)
line_ids = self.env["mrp.bom.line"].search([("bom_id", "=", bom.id)])
for line in res[0]:
line_id = line_ids.filtered(
lambda l: l.location_id and l.id == line["line_id"]
)
line["location_id"] = line_id.location_id or ""
return res
@api.model
def _get_pdf_line(
self, bom_id, product_id=False, qty=1, child_bom_ids=None, unfolded=False
):
res = super(BomStructureReport, self)._get_pdf_line(
bom_id, product_id, qty, child_bom_ids, unfolded
)
line_ids = self.env["mrp.bom.line"].search([("bom_id", "=", bom_id)])
for line in res["lines"]:
line_id = line_ids.filtered(
lambda l: l.location_id and l.product_id.display_name == line["name"]
)
line["location_name"] = line_id.location_id.complete_name or ""
return res
| 38.611111 | 1,390 |
559 |
py
|
PYTHON
|
15.0
|
# Copyright 2015-22 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "MRP BoM Hierarchy",
"summary": "Make it easy to navigate through BoM hierarchy.",
"version": "15.0.1.0.0",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"category": "Manufacturing",
"depends": ["mrp"],
"website": "https://github.com/OCA/manufacture",
"license": "AGPL-3",
"data": [
"view/mrp.xml",
],
"installable": True,
"auto_install": False,
}
| 31.055556 | 559 |
9,306 |
py
|
PYTHON
|
15.0
|
# Copyright 2015-22 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
import operator as py_operator
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class MrpBom(models.Model):
_inherit = "mrp.bom"
_order = "sequence, code, product_default_code, id"
@api.depends("bom_line_ids.bom_id", "product_id", "product_tmpl_id")
def _compute_product_has_other_bom(self):
for bom in self:
if bom.product_id:
bom_ids = self.env["mrp.bom"].search(
[("product_id", "=", bom.product_id.id), ("id", "!=", bom.id)],
)
else:
bom_ids = self.env["mrp.bom"].search(
[
("product_tmpl_id", "=", bom.product_tmpl_id.id),
("id", "!=", bom.id),
],
)
if bom_ids:
bom.product_has_other_bom = True
else:
bom.product_has_other_bom = False
@api.depends("bom_line_ids.bom_id", "product_id", "product_tmpl_id")
def _compute_parent_bom_ids(self):
for bom in self:
parent_bom_line_ids = self.env["mrp.bom.line"]._bom_line_find(
product_tmpl=bom.product_id.product_tmpl_id or bom.product_tmpl_id,
product=bom.product_id,
)
if parent_bom_line_ids:
bom.parent_bom_ids = parent_bom_line_ids.bom_id
bom.has_parent = True
else:
bom.parent_bom_ids = False
bom.has_parent = False
@api.depends("bom_line_ids.bom_id", "bom_line_ids.product_id")
def _compute_child_bom_ids(self):
for bom in self:
bom_line_ids = bom.bom_line_ids
bom.child_bom_ids = bom_line_ids.child_bom_id
bom.has_child = bool(bom.child_bom_ids)
def _search_has_child(self, operator, value):
if operator not in ["=", "!="]:
raise UserError(_("This operator is not supported"))
if value == "True":
value = True
elif value == "False":
value = False
if not isinstance(value, bool):
raise UserError(_("Value should be True or False (not %s)") % value)
ops = {"=": py_operator.eq, "!=": py_operator.ne}
ids = []
for bom in self.search([]):
if ops[operator](value, bom.has_child):
ids.append(bom.id)
return [("id", "in", ids)]
def _search_has_parent(self, operator, value):
if operator not in ["=", "!="]:
raise UserError(_("This operator is not supported"))
if value == "True":
value = True
elif value == "False":
value = False
if not isinstance(value, bool):
raise UserError(_("Value should be True or False (not %s)") % value)
ops = {"=": py_operator.eq, "!=": py_operator.ne}
ids = []
for bom in self.search([]):
if ops[operator](value, bom.has_parent):
ids.append(bom.id)
return [("id", "in", ids)]
@api.depends(
"product_id",
"product_id.default_code",
"product_id.product_tmpl_id.default_code",
"product_tmpl_id.default_code",
)
def _compute_internal_reference(self):
for bom in self:
bom.product_default_code = (
bom.product_id.default_code
or bom.product_id.product_tmpl_id.default_code
or bom.product_tmpl_id.default_code
)
child_bom_ids = fields.One2many("mrp.bom", compute="_compute_child_bom_ids")
parent_bom_ids = fields.One2many("mrp.bom", compute="_compute_parent_bom_ids")
has_child = fields.Boolean(
string="Has components",
compute="_compute_child_bom_ids",
search="_search_has_child",
)
has_parent = fields.Boolean(
string="Is component",
compute="_compute_parent_bom_ids",
search="_search_has_parent",
)
product_has_other_bom = fields.Boolean(
string="Product has other BoMs",
compute="_compute_product_has_other_bom",
)
product_default_code = fields.Char(
string="Internal Reference",
compute="_compute_internal_reference",
store="True",
)
def action_open_child_tree_view(self):
self.ensure_one()
res = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_bom_form_action")
res["context"] = {"default_bom_line_ids": self.bom_line_ids.ids}
if self.child_bom_ids:
res["domain"] = (
"[('id', 'in', [" + ",".join(map(str, self.child_bom_ids.ids)) + "])]"
)
return res
def action_open_parent_tree_view(self):
self.ensure_one()
res = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_bom_form_action")
if self.parent_bom_ids:
res["domain"] = (
"[('id', 'in', [" + ",".join(map(str, self.parent_bom_ids.ids)) + "])]"
)
return res
def action_open_product_other_bom_tree_view(self):
self.ensure_one()
if self.product_id:
product_bom_ids = self.env["mrp.bom"].search(
[("product_id", "=", self.product_id.id), ("id", "!=", self.id)],
)
else:
product_bom_ids = self.env["mrp.bom"].search(
[
("product_tmpl_id", "=", self.product_tmpl_id.id),
("id", "!=", self.id),
],
)
res = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_bom_form_action")
if self.product_id:
res["context"] = {
"default_product_id": self.product_id.id,
"default_product_tmpl_id": self.product_id.product_tmpl_id.id,
}
elif self.product_tmpl_id:
res["context"] = {
"default_product_tmpl_id": self.product_tmpl_id.id,
}
res["domain"] = (
"[('id', 'in', [" + ",".join(map(str, product_bom_ids.ids)) + "])]"
)
return res
class MrpBomLine(models.Model):
_inherit = "mrp.bom.line"
has_bom = fields.Boolean(
string="Has sub BoM",
compute="_compute_child_bom_id",
)
@api.depends("product_id", "bom_id")
def _compute_child_bom_id(self):
res = super()._compute_child_bom_id()
for line in self:
line.has_bom = bool(line.child_bom_id)
return res
def action_open_product_bom_tree_view(self):
self.ensure_one()
res = self.env["ir.actions.actions"]._for_xml_id("mrp.mrp_bom_form_action")
res["domain"] = (
"[('id', 'in', [" + ",".join(map(str, self.child_bom_id.ids)) + "])]"
)
return res
@api.model
def _bom_line_find_domain(
self,
product_tmpl=None,
product=None,
picking_type=None,
company_id=False,
bom_type=False,
):
if product:
if not product_tmpl:
product_tmpl = product.product_tmpl_id
domain = [
"|",
("product_id", "=", product.id),
"&",
("product_id", "=", False),
("product_tmpl_id", "=", product_tmpl.id),
]
elif product_tmpl:
domain = [("product_tmpl_id", "=", product_tmpl.id)]
else:
# neither product nor template, makes no sense to search
raise UserError(
_(
"You should provide either a product or "
"a product template to search a BoM Line"
)
)
if picking_type:
domain += [
"|",
("bom_id.picking_type_id", "=", picking_type.id),
("bom_id.picking_type_id", "=", False),
]
if company_id or self.env.context.get("company_id"):
domain = domain + [
"|",
("company_id", "=", False),
("company_id", "=", company_id or self.env.context.get("company_id")),
]
if bom_type:
domain += [("bom_id.type", "=", bom_type)]
# order to prioritize bom line with product_id over the one without
return domain
@api.model
def _bom_line_find(
self,
product_tmpl=None,
product=None,
picking_type=None,
company_id=False,
bom_type=False,
):
"""Finds BoM lines for particular product, picking and company"""
if (
product
and product.type == "service"
or product_tmpl
and product_tmpl.type == "service"
):
return self.env["mrp.bom.line"]
domain = self._bom_line_find_domain(
product_tmpl=product_tmpl,
product=product,
picking_type=picking_type,
company_id=company_id,
bom_type=bom_type,
)
if domain is False:
return self.env["mrp.bom.line"]
return self.search(domain, order="sequence, product_id")
| 35.25 | 9,306 |
646 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "MRP Account BOM Attribute Match",
"summary": "Glue module between `mrp_account` and `mrp_bom_attribute_match`",
"version": "15.0.1.1.1",
"author": "Camptocamp, Odoo Community Association (OCA)",
"maintainers": ["ivantodorovich"],
"website": "https://github.com/OCA/manufacture",
"license": "AGPL-3",
"category": "Manufacturing",
"depends": ["mrp_account", "mrp_bom_attribute_match"],
"auto_install": True,
}
| 40.3125 | 645 |
882 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.addons.mrp_bom_attribute_match.tests.common import (
TestMrpBomAttributeMatchBase,
)
class TestMrpAccount(TestMrpBomAttributeMatchBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
def test_bom_cost(self):
sword_cyan, sword_magenta = self.product_sword.product_variant_ids
plastic_cyan, plastic_magenta = self.product_plastic.product_variant_ids
plastic_cyan.standard_price = 1.00
plastic_magenta.standard_price = 2.00
sword_cyan.button_bom_cost()
sword_magenta.button_bom_cost()
self.assertEqual(sword_cyan.standard_price, 1.00)
self.assertEqual(sword_magenta.standard_price, 2.00)
| 38.304348 | 881 |
1,509 |
py
|
PYTHON
|
15.0
|
# Copyright 2023 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <[email protected]>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import Command, models
class ProductProduct(models.Model):
_inherit = "product.product"
def _compute_bom_price(self, bom, boms_to_recompute=False, byproduct_bom=False):
# OVERRIDE to fill in the `line.product_id` if a component template is used.
# To avoid a complete override, we HACK the bom by replacing it with a virtual
# record, and modifying it's lines on-the-fly.
has_template_lines = bom and any(
line.component_template_id for line in bom.bom_line_ids
)
if has_template_lines:
bom = bom.new(origin=bom)
to_ignore_line_ids = []
for line in bom.bom_line_ids:
if line._skip_bom_line(self) or not line.component_template_id:
continue
line_product = bom._get_component_template_product(
line, self, line.product_id
)
if not line_product:
to_ignore_line_ids.append(line.id)
continue
else:
line.product_id = line_product
if to_ignore_line_ids:
bom.bom_line_ids = [Command.unlink(id) for id in to_ignore_line_ids]
return super()._compute_bom_price(bom, boms_to_recompute, byproduct_bom)
| 44.352941 | 1,508 |
763 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - Luis M. Ontalba
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Contract from Sale",
"version": "15.0.1.1.0",
"category": "Sales",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/contract",
"depends": ["sale", "contract"],
"development_status": "Production/Stable",
"data": [
"security/ir.model.access.csv",
"security/contract_security.xml",
"views/abstract_contract_line.xml",
"views/contract.xml",
"views/contract_line.xml",
"views/contract_template.xml",
"views/res_partner_view.xml",
],
"license": "AGPL-3",
"installable": True,
"auto_install": True,
}
| 31.791667 | 763 |
4,061 |
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow - Joan Mateu
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.tests.common import TransactionCase
class TestSaleContract(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestSaleContract, cls).setUpClass()
cls.user_sales_all_documents = cls.env["res.users"].create(
{
"name": "user rights all documents ",
"login": "test1",
"groups_id": [
(6, 0, [cls.env.ref("sales_team.group_sale_salesman_all_leads").id])
],
}
)
cls.user_sales_own_documents = cls.env["res.users"].create(
{
"name": "user rights own documents ",
"login": "test2",
"groups_id": [
(6, 0, [cls.env.ref("sales_team.group_sale_salesman").id])
],
}
)
cls.pricelist = cls.env["product.pricelist"].create(
{"name": "pricelist for contract test"}
)
cls.partner = cls.env["res.partner"].create(
{
"name": "Test contract partner",
"property_product_pricelist": cls.pricelist.id,
}
)
def _create_contract(self, user):
self.contract = (
self.env["contract.contract"]
.with_user(user)
.create(
{
"name": "Test Contract",
"partner_id": self.partner.id,
"pricelist_id": self.partner.property_product_pricelist.id,
"line_recurrence": False,
"contract_type": "sale",
"recurring_interval": 1,
"recurring_rule_type": "monthly",
"date_start": "2018-02-15",
"contract_line_ids": [],
}
)
)
def test_01_create_contract_with_sale_perm_not_acc(self):
self._create_contract(self.user_sales_all_documents)
contracts = (
self.env["contract.contract"]
.with_user(self.user_sales_all_documents)
.search([])
)
self.assertEqual(len(contracts), 1)
def test_02_see_just_own_contracts(self):
self._create_contract(self.user_sales_all_documents)
self._create_contract(self.user_sales_all_documents)
self._create_contract(self.user_sales_own_documents)
self._create_contract(self.user_sales_own_documents)
contracts = (
self.env["contract.contract"]
.with_user(self.user_sales_own_documents)
.search([])
)
self.assertEqual(len(contracts), 2)
def test_03_see_all_contracts(self):
self._create_contract(self.user_sales_all_documents)
self._create_contract(self.user_sales_all_documents)
self._create_contract(self.user_sales_own_documents)
self._create_contract(self.user_sales_own_documents)
contracts = (
self.env["contract.contract"]
.with_user(self.user_sales_all_documents)
.search([])
)
self.assertEqual(len(contracts), 4)
def test_04_edit_existing_contract(self):
self._create_contract(self.user_sales_own_documents)
contract_modify = (
self.env["contract.contract"]
.with_user(self.user_sales_own_documents)
.search([])
)
self.assertEqual(len(contract_modify), 1)
self.assertEqual(contract_modify.name, "Test Contract")
self.env["contract.contract"].with_user(self.user_sales_own_documents).search(
[]
).write(
{
"name": "Test_contract_to_modify",
}
)
contract_modify = (
self.env["contract.contract"]
.with_user(self.user_sales_own_documents)
.search([])
)
self.assertEqual(contract_modify.name, "Test_contract_to_modify")
| 34.12605 | 4,061 |
2,196 |
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 OpenERP SA
# Copyright 2014-2018 Tecnativa - Pedro M. Baeza
# Copyright 2015 Domatix
# Copyright 2016-2018 Tecnativa - Carlos Dauden
# Copyright 2017 Tecnativa - Vicent Cubells
# Copyright 2016-2017 LasLabs Inc.
# Copyright 2018-2019 ACSONE SA/NV
# Copyright 2020-2021 Tecnativa - Pedro M. Baeza
# Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Recurring - Contracts Management",
"version": "15.0.1.6.1",
"category": "Contract Management",
"license": "AGPL-3",
"author": "Tecnativa, ACSONE SA/NV, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/contract",
"depends": ["base", "account", "product", "portal"],
"development_status": "Production/Stable",
"data": [
"security/groups.xml",
"security/contract_tag.xml",
"security/ir.model.access.csv",
"security/contract_security.xml",
"security/contract_terminate_reason.xml",
"report/report_contract.xml",
"report/contract_views.xml",
"data/contract_cron.xml",
"data/contract_renew_cron.xml",
"data/mail_template.xml",
"data/template_mail_notification.xml",
"data/mail_message_subtype.xml",
"data/ir_ui_menu.xml",
"wizards/contract_line_wizard.xml",
"wizards/contract_manually_create_invoice.xml",
"wizards/contract_contract_terminate.xml",
"views/contract_tag.xml",
"views/abstract_contract_line.xml",
"views/contract.xml",
"views/contract_line.xml",
"views/contract_template.xml",
"views/contract_template_line.xml",
"views/res_partner_view.xml",
"views/res_config_settings.xml",
"views/contract_terminate_reason.xml",
"views/contract_portal_templates.xml",
],
"assets": {
"web.assets_backend": [
"contract/static/src/js/section_and_note_fields_backend.js",
],
"web.assets_frontend": ["contract/static/src/scss/frontend.scss"],
"web.assets_tests": ["contract/static/src/js/contract_portal_tour.js"],
},
"installable": True,
}
| 38.491228 | 2,194 |
436 |
py
|
PYTHON
|
15.0
|
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.load_data(
env.cr, "contract", "migrations/15.0.1.0.0/noupdate_changes.xml"
)
openupgrade.delete_record_translations(
env.cr,
"contract",
[
"email_contract_template",
"mail_template_contract_modification",
"mail_notification_contract",
],
)
| 25.647059 | 436 |
2,543 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018-2020 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import UserError
from .test_contract import TestContractBase
class TestContractManuallyCreateInvoice(TestContractBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.acct_line.date_start = "2018-01-01"
cls.acct_line.recurring_invoicing_type = "post-paid"
cls.acct_line.date_end = "2018-03-15"
cls.contract2.unlink()
def test_contract_manually_create_invoice(self):
contracts = self.contract
for _i in range(10):
contracts |= self.contract.copy()
wizard = self.env["contract.manually.create.invoice"].create(
{"invoice_date": self.today}
)
wizard.action_show_contract_to_invoice()
contract_to_invoice_count = wizard.contract_to_invoice_count
self.assertFalse(
contracts
- self.env["contract.contract"].search(
wizard.action_show_contract_to_invoice()["domain"]
),
)
action = wizard.create_invoice()
invoice_lines = self.env["account.move.line"].search(
[("contract_line_id", "in", contracts.mapped("contract_line_ids").ids)]
)
self.assertEqual(
len(contracts.mapped("contract_line_ids")),
len(invoice_lines),
)
invoices = self.env["account.move"].search(action["domain"])
self.assertFalse(invoice_lines.mapped("move_id") - invoices)
self.assertEqual(len(invoices), contract_to_invoice_count)
def test_contract_manually_create_invoice_with_usererror(self):
contracts = self.contract
accounts = self.product_1.product_tmpl_id.get_product_accounts()
accounts["income"].deprecated = True # To trigger a UserError
for _i in range(3):
contracts |= self.contract.copy()
wizard = self.env["contract.manually.create.invoice"].create(
{"invoice_date": self.acct_line.date_end}
)
with self.assertRaises(UserError):
# The UserError re-raise a UserError
wizard.create_invoice()
try:
wizard.create_invoice()
except Exception as e:
# The re-raised UserError message is the modified one.
self.assertTrue(str(e).startswith("Failed to process the contract"))
| 36.3 | 2,541 |
99,836 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Carlos Dauden
# Copyright 2018-2020 Tecnativa - Pedro M. Baeza
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from collections import namedtuple
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.exceptions import UserError, ValidationError
from odoo.tests import Form, common
def to_date(date):
return fields.Date.to_date(date)
class TestContractBase(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.today = fields.Date.today()
cls.pricelist = cls.env["product.pricelist"].create(
{"name": "pricelist for contract test"}
)
cls.partner = cls.env["res.partner"].create(
{
"name": "partner test contract",
"property_product_pricelist": cls.pricelist.id,
"email": "[email protected]",
}
)
cls.product_1 = cls.env.ref("product.product_product_1")
cls.product_2 = cls.env.ref("product.product_product_2")
cls.product_1.taxes_id += cls.env["account.tax"].search(
[("type_tax_use", "=", "sale")], limit=1
)
cls.product_1.description_sale = "Test description sale"
cls.line_template_vals = {
"product_id": cls.product_1.id,
"name": "Services from #START# to #END#",
"quantity": 1,
"uom_id": cls.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "yearly",
"recurring_interval": 1,
}
cls.section_template_vals = {
"display_type": "line_section",
"name": "Test section",
}
cls.template_vals = {
"name": "Test Contract Template",
"contract_line_ids": [
(0, 0, cls.section_template_vals),
(0, 0, cls.line_template_vals),
],
}
cls.template = cls.env["contract.template"].create(cls.template_vals)
# For being sure of the applied price
cls.env["product.pricelist.item"].create(
{
"pricelist_id": cls.partner.property_product_pricelist.id,
"product_id": cls.product_1.id,
"compute_price": "formula",
"base": "list_price",
}
)
cls.contract = cls.env["contract.contract"].create(
{
"name": "Test Contract",
"partner_id": cls.partner.id,
"pricelist_id": cls.partner.property_product_pricelist.id,
"line_recurrence": True,
}
)
cls.contract2 = cls.env["contract.contract"].create(
{
"name": "Test Contract 2",
"partner_id": cls.partner.id,
"pricelist_id": cls.partner.property_product_pricelist.id,
"line_recurrence": True,
"contract_type": "purchase",
"contract_line_ids": [
(
0,
0,
{
"product_id": cls.product_1.id,
"name": "Services from #START# to #END#",
"quantity": 1,
"uom_id": cls.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "monthly",
"recurring_interval": 1,
"date_start": "2018-02-15",
"recurring_next_date": "2018-02-22",
},
)
],
}
)
cls.line_vals = {
"contract_id": cls.contract.id,
"product_id": cls.product_1.id,
"name": "Services from #START# to #END#",
"quantity": 1,
"uom_id": cls.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "monthly",
"recurring_interval": 1,
"date_start": "2018-01-01",
"recurring_next_date": "2018-01-15",
"is_auto_renew": False,
}
cls.acct_line = cls.env["contract.line"].create(cls.line_vals)
cls.contract.company_id.create_new_line_at_contract_line_renew = True
cls.terminate_reason = cls.env["contract.terminate.reason"].create(
{"name": "terminate_reason"}
)
cls.contract3 = cls.env["contract.contract"].create(
{
"name": "Test Contract 3",
"partner_id": cls.partner.id,
"pricelist_id": cls.partner.property_product_pricelist.id,
"line_recurrence": False,
"contract_type": "sale",
"recurring_interval": 1,
"recurring_rule_type": "monthly",
"date_start": "2018-02-15",
"contract_line_ids": [
(
0,
0,
{
"product_id": False,
"name": "Header for Services",
"display_type": "line_section",
},
),
(
0,
0,
{
"product_id": False,
"name": "Services from #START# to #END#",
"quantity": 1,
"price_unit": 100,
},
),
(
0,
0,
{
"product_id": False,
"name": "Line",
"quantity": 1,
"price_unit": 120,
},
),
],
}
)
class TestContract(TestContractBase):
def _add_template_line(self, overrides=None):
if overrides is None:
overrides = {}
vals = self.line_vals.copy()
del vals["contract_id"]
del vals["date_start"]
vals["contract_id"] = self.template.id
vals.update(overrides)
return self.env["contract.template.line"].create(vals)
def _get_mail_messages_prev(self, contract, subtype):
return (
self.env["mail.message"]
.search(
[
("model", "=", "contract.contract"),
("res_id", "=", contract.id),
("subtype_id", "=", subtype.id),
]
)
.ids
)
def _get_mail_messages(self, exclude_ids, contract, subtype):
return self.env["mail.message"].search(
[
("model", "=", "contract.contract"),
("res_id", "=", contract.id),
("subtype_id", "=", subtype.id),
("id", "not in", exclude_ids),
]
)
def test_add_modifications(self):
partner2 = self.partner.copy()
self.contract.message_subscribe(
partner_ids=partner2.ids, subtype_ids=self.env.ref("mail.mt_comment").ids
)
subtype = self.env.ref("contract.mail_message_subtype_contract_modification")
partner_ids = self.contract.message_follower_ids.filtered(
lambda x: subtype in x.subtype_ids
).mapped("partner_id")
self.assertGreaterEqual(len(partner_ids), 1)
# Check initial modification auto-creation
self.assertEqual(len(self.contract.modification_ids), 1)
exclude_ids = self._get_mail_messages_prev(self.contract, subtype)
self.contract.write(
{
"modification_ids": [
(0, 0, {"date": "2020-01-01", "description": "Modification 1"}),
(0, 0, {"date": "2020-02-01", "description": "Modification 2"}),
]
}
)
mail_messages = self._get_mail_messages(exclude_ids, self.contract, subtype)
self.assertGreaterEqual(len(mail_messages), 1)
self.assertEqual(
mail_messages[0].notification_ids.mapped("res_partner_id").ids,
self.contract.partner_id.ids,
)
def test_check_discount(self):
with self.assertRaises(ValidationError):
self.acct_line.write({"discount": 120})
def test_automatic_price(self):
self.acct_line.automatic_price = True
self.product_1.list_price = 1100
self.assertEqual(self.acct_line.price_unit, 1100)
# Try to write other price
self.acct_line.price_unit = 10
self.acct_line.refresh()
self.assertEqual(self.acct_line.price_unit, 1100)
# Now disable automatic price
self.acct_line.automatic_price = False
self.acct_line.price_unit = 10
self.acct_line.refresh()
self.assertEqual(self.acct_line.price_unit, 10)
def test_contract(self):
self.assertEqual(self.contract.recurring_next_date, to_date("2018-01-15"))
self.assertAlmostEqual(self.acct_line.price_subtotal, 50.0)
self.acct_line.price_unit = 100.0
self.contract.partner_id = self.partner.id
self.contract.recurring_create_invoice()
self.invoice_monthly = self.contract._get_related_invoices()
self.assertTrue(self.invoice_monthly)
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-02-15"))
self.inv_line = self.invoice_monthly.invoice_line_ids[0]
self.assertTrue(self.inv_line.tax_ids)
self.assertAlmostEqual(self.inv_line.price_subtotal, 50.0)
self.assertEqual(self.contract.user_id, self.invoice_monthly.user_id)
def test_contract_level_recurrence(self):
self.contract3.recurring_create_invoice()
self.contract3.flush()
def test_contract_daily(self):
recurring_next_date = to_date("2018-02-23")
last_date_invoiced = to_date("2018-02-22")
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "daily"
self.contract.pricelist_id = False
self.contract.recurring_create_invoice()
invoice_daily = self.contract._get_related_invoices()
self.assertTrue(invoice_daily)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_invoice_followers(self):
self.acct_line.recurring_next_date = "2018-02-23"
self.acct_line.recurring_rule_type = "daily"
self.contract.pricelist_id = False
subtype_ids = self.contract.message_follower_ids.filtered(
lambda x: self.contract.partner_id.id == x.partner_id.id
).subtype_ids.ids
subtype_ids.append(
self.env.ref("contract.mail_message_subtype_invoice_created").id
)
self.contract.message_subscribe(
partner_ids=self.contract.partner_id.ids, subtype_ids=subtype_ids
)
self.contract._recurring_create_invoice()
invoice_daily = self.contract._get_related_invoices()
self.assertTrue(invoice_daily)
self.assertTrue(self.contract.partner_id in invoice_daily.message_partner_ids)
def test_contract_invoice_salesperson(self):
self.acct_line.recurring_next_date = "2018-02-23"
self.acct_line.recurring_rule_type = "daily"
new_salesperson = self.env["res.users"].create(
{"name": "Some Salesperson", "login": "salesperson_test"}
)
self.contract.user_id = new_salesperson
self.contract._recurring_create_invoice()
invoice_daily = self.contract._get_related_invoices()
self.assertTrue(invoice_daily)
self.assertEqual(self.contract.user_id, invoice_daily.user_id)
self.assertEqual(self.contract.user_id, invoice_daily.invoice_user_id)
def test_contract_weekly_post_paid(self):
recurring_next_date = to_date("2018-03-01")
last_date_invoiced = to_date("2018-02-21")
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "weekly"
self.acct_line.recurring_invoicing_type = "post-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_weekly_pre_paid(self):
recurring_next_date = to_date("2018-03-01")
last_date_invoiced = to_date("2018-02-28")
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "weekly"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_yearly_post_paid(self):
recurring_next_date = to_date("2019-02-22")
last_date_invoiced = to_date("2018-02-21")
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "yearly"
self.acct_line.recurring_invoicing_type = "post-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_yearly_pre_paid(self):
recurring_next_date = to_date("2019-02-22")
last_date_invoiced = to_date("2019-02-21")
self.acct_line.date_end = "2020-02-22"
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "yearly"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_monthly_lastday(self):
recurring_next_date = to_date("2018-02-28")
last_date_invoiced = to_date("2018-02-22")
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.recurring_rule_type = "monthlylastday"
self.contract.recurring_create_invoice()
invoices_monthly_lastday = self.contract._get_related_invoices()
self.assertTrue(invoices_monthly_lastday)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_quarterly_pre_paid(self):
recurring_next_date = to_date("2018-05-22")
last_date_invoiced = to_date("2018-05-21")
self.acct_line.date_end = "2020-02-22"
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "quarterly"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_quarterly_post_paid(self):
recurring_next_date = to_date("2018-05-22")
last_date_invoiced = to_date("2018-02-21")
self.acct_line.date_end = "2020-02-22"
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "quarterly"
self.acct_line.recurring_invoicing_type = "post-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_semesterly_pre_paid(self):
recurring_next_date = to_date("2018-08-22")
last_date_invoiced = to_date("2018-08-21")
self.acct_line.date_end = "2020-02-22"
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "semesterly"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_contract_semesterly_post_paid(self):
recurring_next_date = to_date("2018-08-22")
last_date_invoiced = to_date("2018-02-21")
self.acct_line.date_end = "2020-02-22"
self.acct_line.recurring_next_date = "2018-02-22"
self.acct_line.recurring_rule_type = "semesterly"
self.acct_line.recurring_invoicing_type = "post-paid"
self.contract.recurring_create_invoice()
invoices_weekly = self.contract._get_related_invoices()
self.assertTrue(invoices_weekly)
self.assertEqual(self.acct_line.recurring_next_date, recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, last_date_invoiced)
def test_last_invoice_post_paid(self):
self.acct_line.date_start = "2018-01-01"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.date_end = "2018-03-15"
self.assertTrue(self.acct_line.create_invoice_visibility)
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-02-01"))
self.assertFalse(self.acct_line.last_date_invoiced)
self.contract.recurring_create_invoice()
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-03-01"))
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-01-31"))
self.contract.recurring_create_invoice()
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-3-16"))
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-02-28"))
self.contract.recurring_create_invoice()
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-03-15"))
self.assertFalse(self.acct_line.recurring_next_date)
self.assertFalse(self.acct_line.create_invoice_visibility)
invoices = self.contract._get_related_invoices()
self.contract.recurring_create_invoice()
new_invoices = self.contract._get_related_invoices()
self.assertEqual(
invoices,
new_invoices,
"Should not create a new invoice after the last one",
)
def test_last_invoice_pre_paid(self):
self.acct_line.date_start = "2018-01-01"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.acct_line.date_end = "2018-03-15"
self.assertTrue(self.acct_line.create_invoice_visibility)
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-01-01"))
self.assertFalse(self.acct_line.last_date_invoiced)
self.contract.recurring_create_invoice()
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-02-01"))
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-01-31"))
self.contract.recurring_create_invoice()
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-02-28"))
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-02-28"))
self.contract.recurring_create_invoice()
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-03-15"))
self.assertFalse(self.acct_line.recurring_next_date)
self.assertFalse(self.acct_line.create_invoice_visibility)
invoices = self.contract._get_related_invoices()
self.contract.recurring_create_invoice()
new_invoices = self.contract._get_related_invoices()
self.assertEqual(
invoices,
new_invoices,
"Should not create a new invoice after the last one",
)
def test_onchange_partner_id(self):
self.contract._onchange_partner_id()
self.assertEqual(
self.contract.pricelist_id,
self.contract.partner_id.property_product_pricelist,
)
def test_uom(self):
uom_litre = self.env.ref("uom.product_uom_litre")
self.acct_line.uom_id = uom_litre.id
self.acct_line._onchange_product_id()
self.assertEqual(self.acct_line.uom_id, self.acct_line.product_id.uom_id)
def test_no_pricelist(self):
self.contract.pricelist_id = False
self.acct_line.quantity = 2
self.assertAlmostEqual(self.acct_line.price_subtotal, 100.0)
def test_check_journal(self):
journal = self.env["account.journal"].search([("type", "=", "sale")])
journal.write({"type": "general"})
with self.assertRaises(ValidationError):
self.contract.recurring_create_invoice()
def test_check_date_end(self):
with self.assertRaises(ValidationError):
self.acct_line.date_end = "2015-12-31"
def test_check_recurring_next_date_start_date(self):
with self.assertRaises(ValidationError):
self.acct_line.write(
{"date_start": "2018-01-01", "recurring_next_date": "2017-01-01"}
)
def test_onchange_contract_template_id(self):
"""It should change the contract values to match the template."""
self.contract.contract_template_id = False
self.contract._onchange_contract_template_id()
self.contract.contract_template_id = self.template
self.contract._onchange_contract_template_id()
res = {
"contract_line_ids": [
(0, 0, {"display_type": "line_section", "name": "Test section"}),
(
0,
0,
{
"product_id": self.product_1.id,
"name": "Services from #START# to #END#",
"quantity": 1,
"uom_id": self.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "yearly",
"recurring_interval": 1,
},
),
]
}
del self.template_vals["name"]
self.assertDictEqual(res, self.template_vals)
def test_onchange_contract_template_id_lines(self):
"""It should create invoice lines for the contract lines."""
self.acct_line.cancel()
self.acct_line.unlink()
self.contract.contract_template_id = self.template
self.assertFalse(
self.contract.contract_line_ids,
"Recurring lines were not removed.",
)
self.contract.contract_template_id = self.template
self.contract._onchange_contract_template_id()
self.assertEqual(len(self.contract.contract_line_ids), 2)
for index, vals in [
(0, self.section_template_vals),
(1, self.line_template_vals),
]:
contract_line = self.contract.contract_line_ids[index]
for key, value in vals.items():
test_value = contract_line[key]
try:
test_value = test_value.id
except AttributeError as ae:
# This try/except is for relation fields.
# For normal fields, test_value would be
# str, float, int ... without id
logging.info(
"Ignored AttributeError ('%s' is not a relation field): %s",
key,
ae,
)
self.assertEqual(test_value, value)
def test_send_mail_contract(self):
result = self.contract.action_contract_send()
self.assertEqual(result["res_model"], "mail.compose.message")
def test_onchange_contract_type(self):
self.contract._onchange_contract_type()
self.assertEqual(self.contract.journal_id.type, "sale")
self.assertEqual(self.contract.journal_id.company_id, self.contract.company_id)
self.contract.contract_type = "purchase"
self.contract._onchange_contract_type()
self.assertFalse(any(self.contract.contract_line_ids.mapped("automatic_price")))
def test_contract_onchange_product_id_uom(self):
"""It should update the UoM for the line."""
line = self._add_template_line(
{"uom_id": self.env.ref("uom.product_uom_litre").id}
)
line.product_id.uom_id = self.env.ref("uom.product_uom_day").id
line._onchange_product_id()
self.assertEqual(line.uom_id, line.product_id.uom_id)
def test_contract_onchange_product_id_name(self):
"""It should update the name for the line."""
line = self._add_template_line()
line.product_id.description_sale = "Test"
line._onchange_product_id()
self.assertEqual(
line.name, line.product_id.get_product_multiline_description_sale()
)
def test_contract_count(self):
"""It should return sale contract count."""
sale_count = self.partner.sale_contract_count + 2
self.contract.copy()
self.contract.copy()
purchase_count = self.partner.purchase_contract_count + 1
self.contract2.copy()
self.partner.refresh()
self.assertEqual(self.partner.sale_contract_count, sale_count)
self.assertEqual(self.partner.purchase_contract_count, purchase_count)
def test_same_date_start_and_date_end(self):
"""It should create one invoice with same start and end date."""
self.acct_line.write(
{
"date_start": self.today,
"date_end": self.today,
"recurring_next_date": self.today,
}
)
self.contract._compute_recurring_next_date()
init_count = len(self.contract._get_related_invoices())
self.contract.recurring_create_invoice()
last_count = len(self.contract._get_related_invoices())
self.assertEqual(last_count, init_count + 1)
self.contract.recurring_create_invoice()
last_count = len(self.contract._get_related_invoices())
self.assertEqual(last_count, init_count + 1)
def test_act_show_contract(self):
show_contract = self.partner.with_context(
contract_type="sale"
).act_show_contract()
self.assertEqual(
show_contract,
{
**show_contract,
**{
"name": "Customer Contracts",
"type": "ir.actions.act_window",
"res_model": "contract.contract",
"xml_id": "contract.action_customer_contract",
},
},
"There was an error and the view couldn't be opened.",
)
def test_get_default_recurring_invoicing_offset(self):
clm = self.env["contract.line"]
self.assertEqual(
clm._get_default_recurring_invoicing_offset("pre-paid", "monthly"), 0
)
self.assertEqual(
clm._get_default_recurring_invoicing_offset("post-paid", "monthly"), 1
)
self.assertEqual(
clm._get_default_recurring_invoicing_offset("pre-paid", "monthlylastday"), 0
)
self.assertEqual(
clm._get_default_recurring_invoicing_offset("post-paid", "monthlylastday"),
0,
)
def test_get_next_invoice_date(self):
"""Test different combination to compute recurring_next_date
Combination format
{
'recurring_next_date': ( # date
date_start, # date
recurring_invoicing_type, # ('pre-paid','post-paid',)
recurring_rule_type, # ('daily', 'weekly', 'monthly',
# 'monthlylastday', 'yearly'),
recurring_interval, # integer
max_date_end, # date
),
}
"""
def error_message(
date_start,
recurring_invoicing_type,
recurring_invoicing_offset,
recurring_rule_type,
recurring_interval,
max_date_end,
):
return (
"Error in %s-%d every %d %s case, "
"start with %s (max_date_end=%s)"
% (
recurring_invoicing_type,
recurring_invoicing_offset,
recurring_interval,
recurring_rule_type,
date_start,
max_date_end,
)
)
combinations = [
(
to_date("2018-01-01"),
(to_date("2018-01-01"), "pre-paid", 0, "monthly", 1, False),
),
(
to_date("2018-01-01"),
(
to_date("2018-01-01"),
"pre-paid",
0,
"monthly",
1,
to_date("2018-01-15"),
),
),
(
False,
(
to_date("2018-01-16"),
"pre-paid",
0,
"monthly",
1,
to_date("2018-01-15"),
),
),
(
to_date("2018-01-01"),
(to_date("2018-01-01"), "pre-paid", 0, "monthly", 2, False),
),
(
to_date("2018-02-01"),
(to_date("2018-01-01"), "post-paid", 1, "monthly", 1, False),
),
(
to_date("2018-01-16"),
(
to_date("2018-01-01"),
"post-paid",
1,
"monthly",
1,
to_date("2018-01-15"),
),
),
(
False,
(
to_date("2018-01-16"),
"post-paid",
1,
"monthly",
1,
to_date("2018-01-15"),
),
),
(
to_date("2018-03-01"),
(to_date("2018-01-01"), "post-paid", 1, "monthly", 2, False),
),
(
to_date("2018-01-31"),
(to_date("2018-01-05"), "post-paid", 0, "monthlylastday", 1, False),
),
(
to_date("2018-01-06"),
(to_date("2018-01-06"), "pre-paid", 0, "monthlylastday", 1, False),
),
(
to_date("2018-02-28"),
(to_date("2018-01-05"), "post-paid", 0, "monthlylastday", 2, False),
),
(
to_date("2018-01-05"),
(to_date("2018-01-05"), "pre-paid", 0, "monthlylastday", 2, False),
),
(
to_date("2018-01-05"),
(to_date("2018-01-05"), "pre-paid", 0, "yearly", 1, False),
),
(
to_date("2019-01-05"),
(to_date("2018-01-05"), "post-paid", 1, "yearly", 1, False),
),
]
contract_line_env = self.env["contract.line"]
for recurring_next_date, combination in combinations:
self.assertEqual(
recurring_next_date,
contract_line_env.get_next_invoice_date(*combination),
error_message(*combination),
)
def test_next_invoicing_period(self):
"""Test different combination for next invoicing period
{
(
'recurring_next_date', # date
'next_period_date_start', # date
'next_period_date_end' # date
): (
date_start, # date
date_end, # date
last_date_invoiced, # date
recurring_next_date, # date
recurring_invoicing_type, # ('pre-paid','post-paid',)
recurring_rule_type, # ('daily', 'weekly', 'monthly',
# 'monthlylastday', 'yearly'),
recurring_interval, # integer
max_date_end, # date
),
}
"""
def _update_contract_line(
case,
date_start,
date_end,
last_date_invoiced,
recurring_next_date,
recurring_invoicing_type,
recurring_rule_type,
recurring_interval,
max_date_end,
):
self.acct_line.write(
{
"date_start": date_start,
"date_end": date_end,
"last_date_invoiced": last_date_invoiced,
"recurring_next_date": recurring_next_date,
"recurring_invoicing_type": recurring_invoicing_type,
"recurring_rule_type": recurring_rule_type,
"recurring_interval": recurring_interval,
}
)
def _get_result():
return Result(
recurring_next_date=self.acct_line.recurring_next_date,
next_period_date_start=self.acct_line.next_period_date_start,
next_period_date_end=self.acct_line.next_period_date_end,
)
def _error_message(
case,
date_start,
date_end,
last_date_invoiced,
recurring_next_date,
recurring_invoicing_type,
recurring_rule_type,
recurring_interval,
max_date_end,
):
return (
"Error in case %s:"
"date_start: %s, "
"date_end: %s, "
"last_date_invoiced: %s, "
"recurring_next_date: %s, "
"recurring_invoicing_type: %s, "
"recurring_rule_type: %s, "
"recurring_interval: %s, "
"max_date_end: %s, "
) % (
case,
date_start,
date_end,
last_date_invoiced,
recurring_next_date,
recurring_invoicing_type,
recurring_rule_type,
recurring_interval,
max_date_end,
)
Result = namedtuple(
"Result",
["recurring_next_date", "next_period_date_start", "next_period_date_end"],
)
Combination = namedtuple(
"Combination",
[
"case",
"date_start",
"date_end",
"last_date_invoiced",
"recurring_next_date",
"recurring_invoicing_type",
"recurring_rule_type",
"recurring_interval",
"max_date_end",
],
)
combinations = {
Result(
recurring_next_date=to_date("2019-01-01"),
next_period_date_start=to_date("2019-01-01"),
next_period_date_end=to_date("2019-01-31"),
): Combination(
case="1",
date_start="2019-01-01",
date_end=False,
last_date_invoiced=False,
recurring_next_date="2019-01-01",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-01-01"),
next_period_date_start=to_date("2019-01-01"),
next_period_date_end=to_date("2019-01-15"),
): Combination(
case="2",
date_start="2019-01-01",
date_end="2019-01-15",
last_date_invoiced=False,
recurring_next_date="2019-01-01",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-01-05"),
next_period_date_start=to_date("2019-01-05"),
next_period_date_end=to_date("2019-01-15"),
): Combination(
case="3",
date_start="2019-01-05",
date_end="2019-01-15",
last_date_invoiced=False,
recurring_next_date="2019-01-05",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-01-05"),
next_period_date_start=to_date("2019-01-01"),
next_period_date_end=to_date("2019-01-15"),
): Combination(
case="4",
date_start="2019-01-01",
date_end="2019-01-15",
last_date_invoiced=False,
recurring_next_date="2019-01-05",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-02-01"),
next_period_date_start=to_date("2019-01-01"),
next_period_date_end=to_date("2019-01-31"),
): Combination(
case="5",
date_start="2019-01-01",
date_end=False,
last_date_invoiced=False,
recurring_next_date="2019-02-01",
recurring_invoicing_type="post-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-02-01"),
next_period_date_start=to_date("2019-01-01"),
next_period_date_end=to_date("2019-01-15"),
): Combination(
case="6",
date_start="2019-01-01",
date_end="2019-01-15",
last_date_invoiced=False,
recurring_next_date="2019-02-01",
recurring_invoicing_type="post-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-02-01"),
next_period_date_start=to_date("2019-01-05"),
next_period_date_end=to_date("2019-01-31"),
): Combination(
case="7",
date_start="2019-01-05",
date_end=False,
last_date_invoiced=False,
recurring_next_date="2019-02-01",
recurring_invoicing_type="post-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-01-05"),
next_period_date_start=to_date("2019-01-01"),
next_period_date_end=to_date("2019-01-15"),
): Combination(
case="8",
date_start="2019-01-01",
date_end="2019-01-15",
last_date_invoiced=False,
recurring_next_date="2019-01-05",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-01-01"),
next_period_date_start=to_date("2018-12-16"),
next_period_date_end=to_date("2019-01-31"),
): Combination(
case="9",
date_start="2018-01-01",
date_end="2020-01-15",
last_date_invoiced="2018-12-15",
recurring_next_date="2019-01-01",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2019-01-01"),
next_period_date_start=to_date("2018-12-16"),
next_period_date_end=to_date("2018-12-31"),
): Combination(
case="10",
date_start="2018-01-01",
date_end="2020-01-15",
last_date_invoiced="2018-12-15",
recurring_next_date="2019-01-01",
recurring_invoicing_type="post-paid",
recurring_rule_type="monthly",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2018-12-31"),
next_period_date_start=to_date("2018-12-16"),
next_period_date_end=to_date("2018-12-31"),
): Combination(
case="11",
date_start="2018-01-01",
date_end="2020-01-15",
last_date_invoiced="2018-12-15",
recurring_next_date="2018-12-31",
recurring_invoicing_type="post-paid",
recurring_rule_type="monthlylastday",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2018-12-16"),
next_period_date_start=to_date("2018-12-16"),
next_period_date_end=to_date("2018-12-31"),
): Combination(
case="12",
date_start="2018-01-01",
date_end="2020-01-15",
last_date_invoiced="2018-12-15",
recurring_next_date="2018-12-16",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthlylastday",
recurring_interval=1,
max_date_end=False,
),
Result(
recurring_next_date=to_date("2018-01-05"),
next_period_date_start=to_date("2018-01-05"),
next_period_date_end=to_date("2018-03-31"),
): Combination(
case="12",
date_start="2018-01-05",
date_end="2020-01-15",
last_date_invoiced=False,
recurring_next_date="2018-01-05",
recurring_invoicing_type="pre-paid",
recurring_rule_type="monthlylastday",
recurring_interval=3,
max_date_end=False,
),
}
for result, combination in combinations.items():
_update_contract_line(*combination)
self.assertEqual(result, _get_result(), _error_message(*combination))
def test_recurring_next_date(self):
"""recurring next date for a contract is the min for all lines"""
self.contract.recurring_create_invoice()
self.assertEqual(
self.contract.recurring_next_date,
min(self.contract.contract_line_ids.mapped("recurring_next_date")),
)
def test_date_end(self):
"""recurring next date for a contract is the min for all lines"""
self.acct_line.date_end = "2018-01-01"
self.acct_line.copy()
self.acct_line.write({"date_end": False, "is_auto_renew": False})
self.assertFalse(self.contract.date_end)
def test_cancel_contract_line(self):
"""It should raise a validation error"""
self.acct_line.cancel()
with self.assertRaises(ValidationError):
self.acct_line.stop(self.today)
def test_stop_contract_line(self):
"""It should put end to the contract line"""
self.acct_line.write(
{
"date_start": self.today,
"recurring_next_date": self.today,
"date_end": self.today + relativedelta(months=7),
"is_auto_renew": True,
}
)
self.acct_line.stop(self.today + relativedelta(months=5))
self.assertEqual(self.acct_line.date_end, self.today + relativedelta(months=5))
def test_stop_upcoming_contract_line(self):
"""It should put end to the contract line"""
self.acct_line.write(
{
"date_start": self.today + relativedelta(months=3),
"recurring_next_date": self.today + relativedelta(months=3),
"date_end": self.today + relativedelta(months=7),
"is_auto_renew": True,
}
)
self.acct_line.stop(self.today)
self.assertEqual(self.acct_line.date_end, self.today + relativedelta(months=7))
self.assertTrue(self.acct_line.is_canceled)
def test_stop_past_contract_line(self):
"""Past contract line are ignored on stop"""
self.acct_line.write(
{"date_end": self.today + relativedelta(months=5), "is_auto_renew": True}
)
self.acct_line.stop(self.today + relativedelta(months=7))
self.assertEqual(self.acct_line.date_end, self.today + relativedelta(months=5))
def test_stop_contract_line_without_date_end(self):
"""Past contract line are ignored on stop"""
self.acct_line.write({"date_end": False, "is_auto_renew": False})
self.acct_line.stop(self.today + relativedelta(months=7))
self.assertEqual(self.acct_line.date_end, self.today + relativedelta(months=7))
def test_stop_wizard(self):
self.acct_line.write(
{
"date_start": self.today,
"recurring_next_date": self.today,
"date_end": self.today + relativedelta(months=5),
"is_auto_renew": True,
}
)
wizard = self.env["contract.line.wizard"].create(
{
"date_end": self.today + relativedelta(months=3),
"contract_line_id": self.acct_line.id,
}
)
wizard.stop()
self.assertEqual(self.acct_line.date_end, self.today + relativedelta(months=3))
self.assertFalse(self.acct_line.is_auto_renew)
def test_stop_plan_successor_contract_line_0(self):
successor_contract_line = self.acct_line.copy(
{
"date_start": self.today + relativedelta(months=5),
"recurring_next_date": self.today + relativedelta(months=5),
}
)
self.acct_line.write(
{
"successor_contract_line_id": successor_contract_line.id,
"is_auto_renew": False,
"date_end": self.today,
}
)
suspension_start = self.today + relativedelta(months=5)
suspension_end = self.today + relativedelta(months=6)
with self.assertRaises(ValidationError):
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
def test_stop_plan_successor_contract_line_1(self):
"""
* contract line end's before the suspension period:
-> apply stop
"""
suspension_start = self.today + relativedelta(months=5)
suspension_end = self.today + relativedelta(months=6)
start_date = self.today
end_date = self.today + relativedelta(months=4)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(self.acct_line.date_end, end_date)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(new_line)
def test_stop_plan_successor_contract_line_2(self):
"""
* contract line start before the suspension period and end in it
-> apply stop at suspension start date
-> apply plan successor:
- date_start: suspension.date_end
- date_end: suspension.date_end + (contract_line.date_end
- suspension.date_start)
"""
suspension_start = self.today + relativedelta(months=3)
suspension_end = self.today + relativedelta(months=5)
start_date = self.today
end_date = self.today + relativedelta(months=4)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_end, suspension_start - relativedelta(days=1)
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertTrue(new_line)
new_date_end = (
suspension_end + (end_date - suspension_start) + relativedelta(days=1)
)
self.assertEqual(new_line.date_start, suspension_end + relativedelta(days=1))
self.assertEqual(new_line.date_end, new_date_end)
self.assertTrue(self.acct_line.manual_renew_needed)
def test_stop_plan_successor_contract_line_3(self):
"""
* contract line start before the suspension period and end after it
-> apply stop at suspension start date
-> apply plan successor:
- date_start: suspension.date_end
- date_end: suspension.date_end + (suspension.date_end
- suspension.date_start)
"""
suspension_start = self.today + relativedelta(months=3)
suspension_end = self.today + relativedelta(months=5)
start_date = self.today
end_date = self.today + relativedelta(months=6)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_end, suspension_start - relativedelta(days=1)
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertTrue(new_line)
new_date_end = (
end_date + (suspension_end - suspension_start) + relativedelta(days=1)
)
self.assertEqual(new_line.date_start, suspension_end + relativedelta(days=1))
self.assertEqual(new_line.date_end, new_date_end)
self.assertTrue(self.acct_line.manual_renew_needed)
def test_stop_plan_successor_contract_line_3_without_end_date(self):
"""
* contract line start before the suspension period and end after it
-> apply stop at suspension start date
-> apply plan successor:
- date_start: suspension.date_end
- date_end: suspension.date_end + (suspension.date_end
- suspension.date_start)
"""
suspension_start = self.today + relativedelta(months=3)
suspension_end = self.today + relativedelta(months=5)
start_date = self.today
end_date = False
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
"is_auto_renew": False,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, False)
self.assertEqual(
self.acct_line.date_end, suspension_start - relativedelta(days=1)
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertTrue(new_line)
self.assertEqual(new_line.date_start, suspension_end + relativedelta(days=1))
self.assertFalse(new_line.date_end)
self.assertTrue(self.acct_line.manual_renew_needed)
def test_stop_plan_successor_contract_line_4(self):
"""
* contract line start and end's in the suspension period
-> apply delay
- delay: suspension.date_end - contract_line.end_date
"""
suspension_start = self.today + relativedelta(months=2)
suspension_end = self.today + relativedelta(months=5)
start_date = self.today + relativedelta(months=3)
end_date = self.today + relativedelta(months=4)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_start,
start_date + (suspension_end - start_date) + timedelta(days=1),
)
self.assertEqual(
self.acct_line.date_end,
end_date + (suspension_end - start_date) + timedelta(days=1),
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(new_line)
def test_stop_plan_successor_contract_line_5(self):
"""
* contract line start in the suspension period and end after it
-> apply delay
- delay: suspension.date_end - contract_line.date_start
"""
suspension_start = self.today + relativedelta(months=2)
suspension_end = self.today + relativedelta(months=5)
start_date = self.today + relativedelta(months=3)
end_date = self.today + relativedelta(months=6)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_start,
start_date + (suspension_end - start_date) + timedelta(days=1),
)
self.assertEqual(
self.acct_line.date_end,
end_date + (suspension_end - start_date) + timedelta(days=1),
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(new_line)
def test_stop_plan_successor_contract_line_5_without_date_end(self):
"""
* contract line start in the suspension period and end after it
-> apply delay
- delay: suspension.date_end - contract_line.date_start
"""
suspension_start = self.today + relativedelta(months=2)
suspension_end = self.today + relativedelta(months=5)
start_date = self.today + relativedelta(months=3)
end_date = False
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
"is_auto_renew": False,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_start,
start_date + (suspension_end - start_date) + timedelta(days=1),
)
self.assertFalse(self.acct_line.date_end)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(new_line)
def test_stop_plan_successor_contract_line_6(self):
"""
* contract line start and end after the suspension period
-> apply delay
- delay: suspension.date_end - suspension.start_date
"""
suspension_start = self.today + relativedelta(months=2)
suspension_end = self.today + relativedelta(months=3)
start_date = self.today + relativedelta(months=4)
end_date = self.today + relativedelta(months=6)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_start,
start_date + (suspension_end - suspension_start) + timedelta(days=1),
)
self.assertEqual(
self.acct_line.date_end,
end_date + (suspension_end - suspension_start) + timedelta(days=1),
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(new_line)
def test_stop_plan_successor_contract_line_6_without_date_end(self):
"""
* contract line start and end after the suspension period
-> apply delay
- delay: suspension.date_end - suspension.start_date
"""
suspension_start = self.today + relativedelta(months=2)
suspension_end = self.today + relativedelta(months=3)
start_date = self.today + relativedelta(months=4)
end_date = False
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
"is_auto_renew": False,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_start,
start_date + (suspension_end - suspension_start) + timedelta(days=1),
)
self.assertFalse(self.acct_line.date_end)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(new_line)
def test_stop_plan_successor_wizard(self):
suspension_start = self.today + relativedelta(months=2)
suspension_end = self.today + relativedelta(months=3)
start_date = self.today + relativedelta(months=4)
end_date = self.today + relativedelta(months=6)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
wizard = self.env["contract.line.wizard"].create(
{
"date_start": suspension_start,
"date_end": suspension_end,
"is_auto_renew": False,
"contract_line_id": self.acct_line.id,
}
)
wizard.stop_plan_successor()
self.assertEqual(
self.acct_line.date_start,
start_date + (suspension_end - suspension_start) + timedelta(days=1),
)
self.assertEqual(
self.acct_line.date_end,
end_date + (suspension_end - suspension_start) + timedelta(days=1),
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(new_line)
def test_plan_successor_contract_line(self):
self.acct_line.write(
{
"date_start": self.today,
"recurring_next_date": self.today,
"date_end": self.today + relativedelta(months=3),
"is_auto_renew": False,
}
)
self.acct_line.plan_successor(
self.today + relativedelta(months=5),
self.today + relativedelta(months=7),
True,
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(self.acct_line.is_auto_renew)
self.assertTrue(new_line.is_auto_renew)
self.assertTrue(new_line, "should create a new contract line")
self.assertEqual(new_line.date_start, self.today + relativedelta(months=5))
self.assertEqual(new_line.date_end, self.today + relativedelta(months=7))
def test_overlap(self):
self.acct_line.write(
{
"date_start": self.today,
"recurring_next_date": self.today,
"date_end": self.today + relativedelta(months=3),
"is_auto_renew": False,
}
)
self.acct_line.plan_successor(
self.today + relativedelta(months=5),
self.today + relativedelta(months=7),
True,
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
with self.assertRaises(ValidationError):
new_line.date_start = self.today + relativedelta(months=2)
with self.assertRaises(ValidationError):
self.acct_line.date_end = self.today + relativedelta(months=6)
def test_plan_successor_wizard(self):
self.acct_line.write(
{
"date_start": self.today,
"recurring_next_date": self.today,
"date_end": self.today + relativedelta(months=2),
"is_auto_renew": False,
}
)
wizard = self.env["contract.line.wizard"].create(
{
"date_start": self.today + relativedelta(months=3),
"date_end": self.today + relativedelta(months=5),
"is_auto_renew": True,
"contract_line_id": self.acct_line.id,
}
)
wizard.plan_successor()
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertFalse(self.acct_line.is_auto_renew)
self.assertTrue(new_line.is_auto_renew)
self.assertTrue(new_line, "should create a new contract line")
self.assertEqual(new_line.date_start, self.today + relativedelta(months=3))
self.assertEqual(new_line.date_end, self.today + relativedelta(months=5))
def test_cancel(self):
self.acct_line.write(
{"date_end": self.today + relativedelta(months=5), "is_auto_renew": True}
)
self.acct_line.cancel()
self.assertTrue(self.acct_line.is_canceled)
self.assertFalse(self.acct_line.is_auto_renew)
with self.assertRaises(ValidationError):
self.acct_line.is_auto_renew = True
self.acct_line.uncancel(self.today)
self.assertFalse(self.acct_line.is_canceled)
def test_uncancel_wizard(self):
self.acct_line.cancel()
self.assertTrue(self.acct_line.is_canceled)
wizard = self.env["contract.line.wizard"].create(
{"recurring_next_date": self.today, "contract_line_id": self.acct_line.id}
)
wizard.uncancel()
self.assertFalse(self.acct_line.is_canceled)
def test_cancel_uncancel_with_predecessor(self):
suspension_start = self.today + relativedelta(months=3)
suspension_end = self.today + relativedelta(months=5)
start_date = self.today
end_date = self.today + relativedelta(months=4)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
self.assertEqual(
self.acct_line.date_end, suspension_start - relativedelta(days=1)
)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
self.assertEqual(self.acct_line.successor_contract_line_id, new_line)
new_line.cancel()
self.assertTrue(new_line.is_canceled)
self.assertFalse(self.acct_line.successor_contract_line_id)
self.assertEqual(new_line.predecessor_contract_line_id, self.acct_line)
new_line.uncancel(suspension_end + relativedelta(days=1))
self.assertFalse(new_line.is_canceled)
self.assertEqual(self.acct_line.successor_contract_line_id, new_line)
self.assertEqual(
new_line.recurring_next_date,
suspension_end + relativedelta(days=1),
)
def test_cancel_uncancel_with_predecessor_has_successor(self):
suspension_start = self.today + relativedelta(months=6)
suspension_end = self.today + relativedelta(months=7)
start_date = self.today
end_date = self.today + relativedelta(months=8)
self.acct_line.write(
{
"date_start": start_date,
"recurring_next_date": start_date,
"date_end": end_date,
}
)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
new_line = self.env["contract.line"].search(
[("predecessor_contract_line_id", "=", self.acct_line.id)]
)
new_line.cancel()
suspension_start = self.today + relativedelta(months=4)
suspension_end = self.today + relativedelta(months=5)
self.acct_line.stop_plan_successor(suspension_start, suspension_end, True)
with self.assertRaises(ValidationError):
new_line.uncancel(suspension_end)
def test_check_has_not_date_end_has_successor(self):
self.acct_line.write({"date_end": False, "is_auto_renew": False})
with self.assertRaises(ValidationError):
self.acct_line.plan_successor(
to_date("2016-03-01"), to_date("2016-09-01"), False
)
def test_check_has_not_date_end_is_auto_renew(self):
with self.assertRaises(ValidationError):
self.acct_line.write({"date_end": False, "is_auto_renew": True})
def test_check_has_successor_is_auto_renew(self):
with self.assertRaises(ValidationError):
self.acct_line.plan_successor(
to_date("2016-03-01"), to_date("2018-09-01"), False
)
def test_search_contract_line_to_renew(self):
self.acct_line.write({"date_end": self.today, "is_auto_renew": True})
line_1 = self.acct_line.copy({"date_end": self.today + relativedelta(months=1)})
line_2 = self.acct_line.copy({"date_end": self.today - relativedelta(months=1)})
line_3 = self.acct_line.copy({"date_end": self.today - relativedelta(months=2)})
line_4 = self.acct_line.copy({"date_end": self.today + relativedelta(months=2)})
to_renew = self.acct_line.search(
self.acct_line._contract_line_to_renew_domain()
)
self.assertEqual(set(to_renew), {self.acct_line, line_1, line_2, line_3})
self.acct_line.cron_renew_contract_line()
self.assertTrue(self.acct_line.successor_contract_line_id)
self.assertTrue(line_1.successor_contract_line_id)
self.assertTrue(line_2.successor_contract_line_id)
self.assertTrue(line_3.successor_contract_line_id)
self.assertFalse(line_4.successor_contract_line_id)
def test_renew_create_new_line(self):
date_start = fields.Date.from_string("2022-01-01")
self.acct_line.write(
{
"is_auto_renew": True,
"date_start": date_start,
"recurring_next_date": date_start,
"date_end": self.today,
}
)
self.acct_line._onchange_is_auto_renew()
self.assertEqual(self.acct_line.date_end, fields.Date.from_string("2022-12-31"))
new_line = self.acct_line.renew()
self.assertFalse(self.acct_line.is_auto_renew)
self.assertTrue(new_line.is_auto_renew)
self.assertEqual(new_line.date_start, fields.Date.from_string("2023-01-01"))
self.assertEqual(new_line.date_end, fields.Date.from_string("2023-12-31"))
def test_renew_extend_original_line(self):
self.contract.company_id.create_new_line_at_contract_line_renew = False
date_start = fields.Date.from_string("2022-01-01")
self.acct_line.write(
{
"is_auto_renew": True,
"date_start": date_start,
"recurring_next_date": date_start,
"date_end": self.today,
}
)
self.acct_line._onchange_is_auto_renew()
self.assertEqual(self.acct_line.date_end, fields.Date.from_string("2022-12-31"))
self.acct_line.renew()
self.assertTrue(self.acct_line.is_auto_renew)
self.assertEqual(
self.acct_line.date_start, fields.Date.from_string("2022-01-01")
)
self.assertEqual(self.acct_line.date_end, fields.Date.from_string("2023-12-31"))
def test_cron_recurring_create_invoice(self):
self.acct_line.date_start = "2018-01-01"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.date_end = "2018-03-15"
contracts = self.contract2
for _i in range(10):
contracts |= self.contract.copy()
self.env["contract.contract"].cron_recurring_create_invoice()
invoice_lines = self.env["account.move.line"].search(
[("contract_line_id", "in", contracts.mapped("contract_line_ids").ids)]
)
self.assertEqual(
len(contracts.mapped("contract_line_ids")),
len(invoice_lines),
)
def test_get_period_to_invoice_monthlylastday_postpaid(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.recurring_rule_type = "monthlylastday"
self.acct_line.date_end = "2018-03-15"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-01-05"))
self.assertEqual(last, to_date("2018-01-31"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-01"))
self.assertEqual(last, to_date("2018-02-28"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-03-01"))
self.assertEqual(last, to_date("2018-03-15"))
self.acct_line.manual_renew_needed = True
def test_get_period_to_invoice_monthlylastday_prepaid(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.acct_line.recurring_rule_type = "monthlylastday"
self.acct_line.date_end = "2018-03-15"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-01-05"))
self.assertEqual(last, to_date("2018-01-31"))
self.assertEqual(recurring_next_date, to_date("2018-01-05"))
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-01-05"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-01"))
self.assertEqual(last, to_date("2018-02-28"))
self.assertEqual(recurring_next_date, to_date("2018-02-01"))
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-02-01"))
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-01-31"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-03-01"))
self.assertEqual(last, to_date("2018-03-15"))
self.assertEqual(recurring_next_date, to_date("2018-03-01"))
self.assertEqual(self.acct_line.recurring_next_date, to_date("2018-03-01"))
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-02-28"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertFalse(first)
self.assertFalse(last)
self.assertFalse(recurring_next_date)
self.assertFalse(self.acct_line.recurring_next_date)
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-03-15"))
def test_get_period_to_invoice_monthly_pre_paid_2(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.acct_line.recurring_rule_type = "monthly"
self.acct_line.date_end = "2018-08-15"
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-05"))
self.assertEqual(last, to_date("2018-03-04"))
self.acct_line.recurring_next_date = "2018-06-05"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-05"))
self.assertEqual(last, to_date("2018-07-04"))
def test_get_period_to_invoice_monthly_post_paid_2(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.recurring_rule_type = "monthly"
self.acct_line.date_end = "2018-08-15"
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-05"))
self.assertEqual(last, to_date("2018-03-04"))
self.acct_line.recurring_next_date = "2018-06-05"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-05"))
self.assertEqual(last, to_date("2018-06-04"))
def test_get_period_to_invoice_monthly_post_paid(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.recurring_rule_type = "monthly"
self.acct_line.date_end = "2018-03-15"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-01-05"))
self.assertEqual(last, to_date("2018-02-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-05"))
self.assertEqual(last, to_date("2018-03-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-03-05"))
self.assertEqual(last, to_date("2018-03-15"))
def test_get_period_to_invoice_monthly_pre_paid(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.acct_line.recurring_rule_type = "monthly"
self.acct_line.date_end = "2018-03-15"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-01-05"))
self.assertEqual(last, to_date("2018-02-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-02-05"))
self.assertEqual(last, to_date("2018-03-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-03-05"))
self.assertEqual(last, to_date("2018-03-15"))
def test_get_period_to_invoice_yearly_post_paid(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.recurring_rule_type = "yearly"
self.acct_line.date_end = "2020-03-15"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-01-05"))
self.assertEqual(last, to_date("2019-01-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2019-01-05"))
self.assertEqual(last, to_date("2020-01-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2020-01-05"))
self.assertEqual(last, to_date("2020-03-15"))
def test_get_period_to_invoice_yearly_pre_paid(self):
self.acct_line.date_start = "2018-01-05"
self.acct_line.recurring_invoicing_type = "pre-paid"
self.acct_line.recurring_rule_type = "yearly"
self.acct_line.date_end = "2020-03-15"
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2018-01-05"))
self.assertEqual(last, to_date("2019-01-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2019-01-05"))
self.assertEqual(last, to_date("2020-01-04"))
self.contract.recurring_create_invoice()
first, last, recurring_next_date = self.acct_line._get_period_to_invoice(
self.acct_line.last_date_invoiced,
self.acct_line.recurring_next_date,
)
self.assertEqual(first, to_date("2020-01-05"))
self.assertEqual(last, to_date("2020-03-15"))
def test_unlink(self):
with self.assertRaises(ValidationError):
self.acct_line.unlink()
def test_contract_line_state(self):
lines = self.env["contract.line"]
# upcoming
lines |= self.acct_line.copy(
{
"date_start": self.today + relativedelta(months=3),
"recurring_next_date": self.today + relativedelta(months=3),
"date_end": self.today + relativedelta(months=5),
}
)
# in-progress
lines |= self.acct_line.copy(
{
"date_start": self.today,
"recurring_next_date": self.today,
"date_end": self.today + relativedelta(months=5),
}
)
# in-progress
lines |= self.acct_line.copy(
{
"date_start": self.today,
"recurring_next_date": self.today,
"date_end": self.today + relativedelta(months=5),
"manual_renew_needed": True,
}
)
# to-renew
lines |= self.acct_line.copy(
{
"date_start": self.today - relativedelta(months=5),
"recurring_next_date": self.today - relativedelta(months=5),
"date_end": self.today - relativedelta(months=2),
"manual_renew_needed": True,
}
)
# upcoming-close
lines |= self.acct_line.copy(
{
"date_start": self.today - relativedelta(months=5),
"recurring_next_date": self.today - relativedelta(months=5),
"date_end": self.today + relativedelta(days=20),
"is_auto_renew": False,
}
)
# closed
lines |= self.acct_line.copy(
{
"date_start": self.today - relativedelta(months=5),
"recurring_next_date": self.today - relativedelta(months=5),
"date_end": self.today - relativedelta(months=2),
"is_auto_renew": False,
}
)
# canceled
lines |= self.acct_line.copy(
{
"date_start": self.today - relativedelta(months=5),
"recurring_next_date": self.today - relativedelta(months=5),
"date_end": self.today - relativedelta(months=2),
"is_canceled": True,
}
)
# section
lines |= self.env["contract.line"].create(
{
"contract_id": self.contract.id,
"display_type": "line_section",
"name": "Test section",
}
)
states = [
"upcoming",
"in-progress",
"to-renew",
"upcoming-close",
"closed",
"canceled",
False,
]
self.assertEqual(set(lines.mapped("state")), set(states))
# Test search method
lines.flush() # Needed for computed stored fields like termination_notice_date
for state in states:
lines = self.env["contract.line"].search([("state", "=", state)])
self.assertTrue(lines, state)
self.assertTrue(state in lines.mapped("state"), state)
lines = self.env["contract.line"].search([("state", "!=", state)])
self.assertFalse(state in lines.mapped("state"), state)
lines = self.env["contract.line"].search([("state", "in", states)])
self.assertEqual(set(lines.mapped("state")), set(states))
lines = self.env["contract.line"].search([("state", "in", [])])
self.assertFalse(lines.mapped("state"))
with self.assertRaises(TypeError):
self.env["contract.line"].search([("state", "in", "upcoming")])
lines = self.env["contract.line"].search([("state", "not in", [])])
self.assertEqual(set(lines.mapped("state")), set(states))
lines = self.env["contract.line"].search([("state", "not in", states)])
self.assertFalse(lines.mapped("state"))
state2 = ["upcoming", "in-progress"]
lines = self.env["contract.line"].search([("state", "not in", state2)])
self.assertEqual(set(lines.mapped("state")), set(states) - set(state2))
def test_check_auto_renew_contract_line_with_successor(self):
"""
A contract line with a successor can't be set to auto-renew
"""
successor_contract_line = self.acct_line.copy()
with self.assertRaises(ValidationError):
self.acct_line.write(
{
"is_auto_renew": True,
"successor_contract_line_id": successor_contract_line.id,
}
)
def test_check_no_date_end_contract_line_with_successor(self):
"""
A contract line with a successor must have a end date
"""
successor_contract_line = self.acct_line.copy()
with self.assertRaises(ValidationError):
self.acct_line.write(
{
"date_end": False,
"successor_contract_line_id": successor_contract_line.id,
}
)
def test_check_last_date_invoiced_1(self):
"""
start end can't be before the date of last invoice
"""
with self.assertRaises(ValidationError):
self.acct_line.write(
{
"last_date_invoiced": self.acct_line.date_start
- relativedelta(days=1)
}
)
def test_check_last_date_invoiced_2(self):
"""
start date can't be after the date of last invoice
"""
self.acct_line.write({"date_end": self.today})
with self.assertRaises(ValidationError):
self.acct_line.write(
{"last_date_invoiced": self.acct_line.date_end + relativedelta(days=1)}
)
def test_delay_invoiced_contract_line(self):
self.acct_line.write(
{"last_date_invoiced": self.acct_line.date_start + relativedelta(days=1)}
)
with self.assertRaises(ValidationError):
self.acct_line._delay(relativedelta(months=1))
def test_cancel_invoiced_contract_line(self):
self.acct_line.write(
{"last_date_invoiced": self.acct_line.date_start + relativedelta(days=1)}
)
with self.assertRaises(ValidationError):
self.acct_line.cancel()
def test_action_uncancel(self):
action = self.acct_line.action_uncancel()
self.assertEqual(
action["context"]["default_contract_line_id"], self.acct_line.id
)
def test_action_plan_successor(self):
action = self.acct_line.action_plan_successor()
self.assertEqual(
action["context"]["default_contract_line_id"], self.acct_line.id
)
def test_action_stop(self):
action = self.acct_line.action_stop()
self.assertEqual(
action["context"]["default_contract_line_id"], self.acct_line.id
)
def test_action_stop_plan_successor(self):
action = self.acct_line.action_stop_plan_successor()
self.assertEqual(
action["context"]["default_contract_line_id"], self.acct_line.id
)
def test_purchase_fields_view_get(self):
purchase_tree_view = self.env.ref("contract.contract_line_supplier_tree_view")
purchase_form_view = self.env.ref("contract.contract_line_supplier_form_view")
view = self.acct_line.with_context(
default_contract_type="purchase"
).fields_view_get(view_type="tree")
self.assertEqual(view["view_id"], purchase_tree_view.id)
view = self.acct_line.with_context(
default_contract_type="purchase"
).fields_view_get(view_type="form")
self.assertEqual(view["view_id"], purchase_form_view.id)
def test_multicompany_partner_edited(self):
"""Editing a partner with contracts in several companies works."""
company2 = self.env["res.company"].create({"name": "Company 2"})
unprivileged_user = self.env["res.users"].create(
{
"name": "unprivileged test user",
"login": "test",
"company_id": company2.id,
"company_ids": [(4, company2.id, False)],
}
)
parent_partner = self.env["res.partner"].create(
{"name": "parent partner", "is_company": True}
)
# Assume contract 2 is for company 2
self.contract2.company_id = company2
# Update the partner attached to both contracts
self.partner.with_user(unprivileged_user).with_company(company2).with_context(
company_id=company2.id
).write({"is_company": False, "parent_id": parent_partner.id})
def test_sale_fields_view_get(self):
sale_form_view = self.env.ref("contract.contract_line_customer_form_view")
view = self.acct_line.with_context(
default_contract_type="sale"
).fields_view_get(view_type="form")
self.assertEqual(view["view_id"], sale_form_view.id)
def test_contract_count_invoice(self):
self.contract.recurring_create_invoice()
self.contract.recurring_create_invoice()
self.contract.recurring_create_invoice()
self.contract._compute_invoice_count()
self.assertEqual(self.contract.invoice_count, 3)
def test_contract_count_invoice_2(self):
invoices = self.env["account.move"]
invoices |= self.contract.recurring_create_invoice()
invoices |= self.contract.recurring_create_invoice()
invoices |= self.contract.recurring_create_invoice()
action = self.contract.action_show_invoices()
self.assertEqual(set(action["domain"][0][2]), set(invoices.ids))
def test_compute_create_invoice_visibility(self):
self.assertTrue(self.contract.create_invoice_visibility)
self.acct_line.write(
{
"date_start": "2018-01-01",
"date_end": "2018-12-31",
"last_date_invoiced": "2018-12-31",
"recurring_next_date": False,
}
)
self.assertFalse(self.acct_line.create_invoice_visibility)
self.assertFalse(self.contract.create_invoice_visibility)
section = self.env["contract.line"].create(
{
"contract_id": self.contract.id,
"display_type": "line_section",
"name": "Test section",
}
)
self.assertFalse(section.create_invoice_visibility)
def test_invoice_contract_without_lines(self):
self.contract.contract_line_ids.cancel()
self.contract.contract_line_ids.unlink()
self.assertFalse(self.contract.recurring_create_invoice())
def test_stop_at_last_date_invoiced(self):
self.contract.recurring_create_invoice()
self.assertTrue(self.acct_line.recurring_next_date)
self.acct_line.stop(self.acct_line.last_date_invoiced)
self.assertFalse(self.acct_line.recurring_next_date)
def test_check_last_date_invoiced_before_next_invoice_date(self):
with self.assertRaises(ValidationError):
self.acct_line.write(
{
"date_start": "2019-01-01",
"date_end": "2019-12-01",
"recurring_next_date": "2019-01-01",
"last_date_invoiced": "2019-06-01",
}
)
def test_stop_and_update_recurring_invoice_date(self):
self.acct_line.write(
{
"date_start": "2019-01-01",
"date_end": "2019-12-31",
"recurring_next_date": "2020-01-01",
"recurring_invoicing_type": "post-paid",
"recurring_rule_type": "yearly",
}
)
self.acct_line.stop(to_date("2019-05-31"))
self.assertEqual(self.acct_line.date_end, to_date("2019-05-31"))
self.assertEqual(self.acct_line.recurring_next_date, to_date("2019-06-01"))
def test_action_terminate_contract(self):
action = self.contract.action_terminate_contract()
wizard = (
self.env[action["res_model"]]
.with_context(**action["context"])
.create(
{
"terminate_date": "2018-03-01",
"terminate_reason_id": self.terminate_reason.id,
"terminate_comment": "terminate_comment",
}
)
)
self.assertEqual(wizard.contract_id, self.contract)
with self.assertRaises(UserError):
wizard.terminate_contract()
group_can_terminate_contract = self.env.ref("contract.can_terminate_contract")
group_can_terminate_contract.users |= self.env.user
wizard.terminate_contract()
self.assertTrue(self.contract.is_terminated)
self.assertEqual(self.contract.terminate_date, to_date("2018-03-01"))
self.assertEqual(self.contract.terminate_reason_id.id, self.terminate_reason.id)
self.assertEqual(self.contract.terminate_comment, "terminate_comment")
self.contract.action_cancel_contract_termination()
self.assertFalse(self.contract.is_terminated)
self.assertFalse(self.contract.terminate_reason_id)
self.assertFalse(self.contract.terminate_comment)
def test_terminate_date_before_last_date_invoiced(self):
self.contract.recurring_create_invoice()
self.assertEqual(self.acct_line.last_date_invoiced, to_date("2018-02-14"))
group_can_terminate_contract = self.env.ref("contract.can_terminate_contract")
group_can_terminate_contract.users |= self.env.user
with self.assertRaises(ValidationError):
self.contract._terminate_contract(
self.terminate_reason,
"terminate_comment",
to_date("2018-02-13"),
)
def test_recurrency_propagation(self):
# Existing contract
vals = {
"recurring_rule_type": "yearly",
"recurring_interval": 2,
"date_start": to_date("2020-01-01"),
}
vals2 = vals.copy()
vals2["line_recurrence"] = False
self.contract.write(vals2)
for field in vals:
self.assertEqual(vals[field], self.acct_line[field])
# New contract
contract_form = Form(self.env["contract.contract"])
contract_form.partner_id = self.partner
contract_form.name = "Test new contract"
contract_form.line_recurrence = False
for field in vals:
setattr(contract_form, field, vals[field])
with contract_form.contract_line_fixed_ids.new() as line_form:
line_form.product_id = self.product_1
contract2 = contract_form.save()
for field in vals:
self.assertEqual(vals[field], contract2.contract_line_ids[field])
def test_currency(self):
currency_eur = self.env.ref("base.EUR")
currency_cad = self.env.ref("base.CAD")
# Get currency from company
self.contract2.journal_id = False
self.assertEqual(
self.contract2.currency_id, self.contract2.company_id.currency_id
)
# Get currency from journal
journal = self.env["account.journal"].create(
{
"name": "Test journal CAD",
"code": "TCAD",
"type": "sale",
"currency_id": currency_cad.id,
}
)
self.contract2.journal_id = journal.id
self.assertEqual(self.contract2.currency_id, currency_cad)
# Get currency from contract pricelist
pricelist = self.env["product.pricelist"].create(
{"name": "Test pricelist", "currency_id": currency_eur.id}
)
self.contract2.pricelist_id = pricelist.id
self.contract2.contract_line_ids.automatic_price = True
self.assertEqual(self.contract2.currency_id, currency_eur)
# Get currency from partner pricelist
self.contract2.pricelist_id = False
self.contract2.partner_id.property_product_pricelist = pricelist.id
pricelist.currency_id = currency_cad.id
self.assertEqual(self.contract2.currency_id, currency_cad)
# Assign manual currency
self.contract2.manual_currency_id = currency_eur.id
self.assertEqual(self.contract2.currency_id, currency_eur)
# Assign same currency as computed one
self.contract2.currency_id = currency_cad.id
self.assertFalse(self.contract2.manual_currency_id)
def test_contract_action_preview(self):
action = self.contract.action_preview()
self.assertIn("/my/contracts/", action["url"])
self.assertIn("access_token=", action["url"])
| 42.070796 | 99,834 |
1,358 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Víctor Martínez
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl)
import odoo.tests
from odoo import http
@odoo.tests.tagged("post_install", "-at_install")
class TestContractPortal(odoo.tests.HttpCase):
def test_tour(self):
partner = self.env["res.partner"].create({"name": "partner test contract"})
contract = self.env["contract.contract"].create(
{"name": "Test Contract", "partner_id": partner.id}
)
user_portal = self.env.ref("base.demo_user0")
contract.message_subscribe(partner_ids=user_portal.partner_id.ids)
self.browser_js(
"/",
"odoo.__DEBUG__.services['web_tour.tour'].run('contract_portal_tour')",
"odoo.__DEBUG__.services['web_tour.tour'].tours.contract_portal_tour.ready",
login="portal",
)
# Contract access
self.authenticate("portal", "portal")
http.root.session_store.save(self.session)
url_contract = "/my/contracts/{}?access_token={}".format(
contract.id,
contract.access_token,
)
self.assertEqual(self.url_open(url=url_contract).status_code, 200)
contract.message_unsubscribe(partner_ids=user_portal.partner_id.ids)
self.assertEqual(self.url_open(url=url_contract).status_code, 200)
| 42.375 | 1,356 |
4,392 |
py
|
PYTHON
|
15.0
|
# Copyright 2021 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from .test_contract import TestContractBase
class ContractMulticompanyCase(TestContractBase):
@classmethod
def setUpClass(cls):
super().setUpClass()
chart_template = cls.env.ref("l10n_generic_coa.configurable_chart_template")
cls.company_obj = cls.env["res.company"]
cls.company_1 = cls.env.ref("base.main_company")
vals = {"name": "Company 2"}
cls.company_2 = cls.company_obj.create(vals)
chart_template.try_loading(company=cls.company_2)
cls.env.user.company_ids |= cls.company_2
cls.contract_mc = (
cls.env["contract.contract"]
.with_company(cls.company_2)
.create(
{
"name": "Test Contract MC",
"partner_id": cls.partner.id,
"pricelist_id": cls.partner.property_product_pricelist.id,
"line_recurrence": True,
"contract_type": "purchase",
"contract_line_ids": [
(
0,
0,
{
"product_id": cls.product_1.id,
"name": "Services from #START# to #END#",
"quantity": 1,
"uom_id": cls.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "monthly",
"recurring_interval": 1,
"date_start": "2018-02-15",
"recurring_next_date": "2018-02-22",
},
)
],
}
)
)
cls.line_vals = {
"contract_id": cls.contract_mc.id,
"product_id": cls.product_1.id,
"name": "Services from #START# to #END#",
"quantity": 1,
"uom_id": cls.product_1.uom_id.id,
"price_unit": 100,
"discount": 50,
"recurring_rule_type": "monthly",
"recurring_interval": 1,
"date_start": "2018-01-01",
"recurring_next_date": "2018-01-15",
"is_auto_renew": False,
}
cls.acct_line_mc = (
cls.env["contract.line"].with_company(cls.company_2).create(cls.line_vals)
)
def test_cron_recurring_create_invoice_multi_company(self):
self.acct_line.date_start = "2018-01-01"
self.acct_line.recurring_invoicing_type = "post-paid"
self.acct_line.date_end = "2018-03-15"
self.acct_line_mc.date_start = "2018-01-01"
self.acct_line_mc.recurring_invoicing_type = "post-paid"
self.acct_line_mc.date_end = "2018-03-15"
contracts = self.contract2
contracts_company_2 = self.env["contract.contract"].browse()
for _i in range(10):
contracts |= self.contract.copy()
for _i in range(10):
vals = (
self.contract_mc.with_company(company=self.company_2)
.with_context(active_test=False)
.copy_data({"company_id": self.company_2.id})
)
contracts_company_2 |= self.contract_mc.with_company(
company=self.company_2
).create(vals)
self.env["contract.contract"].cron_recurring_create_invoice()
# Check company 1
invoice_lines_company_1 = self.env["account.move.line"].search(
[("contract_line_id", "in", contracts.mapped("contract_line_ids").ids)]
)
invoice_lines_company_2 = self.env["account.move.line"].search(
[
(
"contract_line_id",
"in",
contracts_company_2.mapped("contract_line_ids").ids,
)
]
)
self.assertEqual(
len(contracts.mapped("contract_line_ids")), len(invoice_lines_company_1)
)
self.assertEqual(
len(contracts_company_2.mapped("contract_line_ids")),
len(invoice_lines_company_2),
)
| 39.927273 | 4,392 |
568 |
py
|
PYTHON
|
15.0
|
# Copyright 2016 Tecnativa - Carlos Dauden
# Copyright 2018 ACSONE SA/NV.
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountMove(models.Model):
_inherit = "account.move"
# We keep this field for migration purpose
old_contract_id = fields.Many2one("contract.contract")
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
contract_line_id = fields.Many2one(
"contract.line", string="Contract Line", index=True
)
| 27.047619 | 568 |
721 |
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 OpenERP SA
# Copyright 2014 Angel Moya <[email protected]>
# Copyright 2015 Pedro M. Baeza <[email protected]>
# Copyright 2016-2018 Carlos Dauden <[email protected]>
# Copyright 2016-2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractTemplate(models.Model):
_name = "contract.template"
_inherit = "contract.abstract.contract"
_description = "Contract Template"
contract_line_ids = fields.One2many(
comodel_name="contract.template.line",
inverse_name="contract_id",
copy=True,
string="Contract template lines",
)
| 32.772727 | 721 |
9,657 |
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 OpenERP SA
# Copyright 2014 Angel Moya <[email protected]>
# Copyright 2015 Pedro M. Baeza <[email protected]>
# Copyright 2016-2018 Carlos Dauden <[email protected]>
# Copyright 2016-2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV
# 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.translate import _
class ContractAbstractContractLine(models.AbstractModel):
_inherit = "contract.recurrency.basic.mixin"
_name = "contract.abstract.contract.line"
_description = "Abstract Recurring Contract Line"
product_id = fields.Many2one("product.product", string="Product")
name = fields.Text(string="Description", required=True)
quantity = fields.Float(default=1.0, required=True)
product_uom_category_id = fields.Many2one( # Used for domain of field uom_id
comodel_name="uom.category",
related="product_id.uom_id.category_id",
)
uom_id = fields.Many2one(
comodel_name="uom.uom",
string="Unit of Measure",
domain="[('category_id', '=', product_uom_category_id)]",
)
automatic_price = fields.Boolean(
string="Auto-price?",
help="If this is marked, the price will be obtained automatically "
"applying the pricelist to the product. If not, you will be "
"able to introduce a manual price",
)
specific_price = fields.Float()
price_unit = fields.Float(
string="Unit Price",
compute="_compute_price_unit",
inverse="_inverse_price_unit",
)
price_subtotal = fields.Float(
compute="_compute_price_subtotal",
digits="Account",
string="Sub Total",
)
discount = fields.Float(
string="Discount (%)",
digits="Discount",
help="Discount that is applied in generated invoices."
" It should be less or equal to 100",
)
sequence = fields.Integer(
default=10,
help="Sequence of the contract line when displaying contracts",
)
recurring_rule_type = fields.Selection(
compute="_compute_recurring_rule_type",
store=True,
readonly=False,
required=True,
copy=True,
)
recurring_invoicing_type = fields.Selection(
compute="_compute_recurring_invoicing_type",
store=True,
readonly=False,
required=True,
copy=True,
)
recurring_interval = fields.Integer(
compute="_compute_recurring_interval",
store=True,
readonly=False,
required=True,
copy=True,
)
date_start = fields.Date(
compute="_compute_date_start",
store=True,
readonly=False,
copy=True,
)
last_date_invoiced = fields.Date()
is_canceled = fields.Boolean(string="Canceled", default=False)
is_auto_renew = fields.Boolean(string="Auto Renew", default=False)
auto_renew_interval = fields.Integer(
default=1,
string="Renew Every",
help="Renew every (Days/Week/Month/Year)",
)
auto_renew_rule_type = fields.Selection(
[
("daily", "Day(s)"),
("weekly", "Week(s)"),
("monthly", "Month(s)"),
("yearly", "Year(s)"),
],
default="yearly",
string="Renewal type",
help="Specify Interval for automatic renewal.",
)
termination_notice_interval = fields.Integer(
default=1, string="Termination Notice Before"
)
termination_notice_rule_type = fields.Selection(
[("daily", "Day(s)"), ("weekly", "Week(s)"), ("monthly", "Month(s)")],
default="monthly",
string="Termination Notice type",
)
contract_id = fields.Many2one(
string="Contract",
comodel_name="contract.abstract.contract",
required=True,
ondelete="cascade",
)
display_type = fields.Selection(
selection=[("line_section", "Section"), ("line_note", "Note")],
default=False,
help="Technical field for UX purpose.",
)
note_invoicing_mode = fields.Selection(
selection=[
("with_previous_line", "With previous line"),
("with_next_line", "With next line"),
("custom", "Custom"),
],
default="with_previous_line",
help="Defines when the Note is invoiced:\n"
"- With previous line: If the previous line can be invoiced.\n"
"- With next line: If the next line can be invoiced.\n"
"- Custom: Depending on the recurrence to be define.",
)
is_recurring_note = fields.Boolean(compute="_compute_is_recurring_note")
company_id = fields.Many2one(related="contract_id.company_id", store=True)
def _set_recurrence_field(self, field):
"""Helper method for computed methods that gets the equivalent field
in the header.
We need to re-assign the original value for avoiding a missing error.
"""
for record in self:
if record.contract_id.line_recurrence:
record[field] = record[field]
else:
record[field] = record.contract_id[field]
@api.depends("contract_id.recurring_rule_type", "contract_id.line_recurrence")
def _compute_recurring_rule_type(self):
self._set_recurrence_field("recurring_rule_type")
@api.depends("contract_id.recurring_invoicing_type", "contract_id.line_recurrence")
def _compute_recurring_invoicing_type(self):
self._set_recurrence_field("recurring_invoicing_type")
@api.depends("contract_id.recurring_interval", "contract_id.line_recurrence")
def _compute_recurring_interval(self):
self._set_recurrence_field("recurring_interval")
@api.depends("contract_id.date_start", "contract_id.line_recurrence")
def _compute_date_start(self):
self._set_recurrence_field("date_start")
# pylint: disable=missing-return
@api.depends("contract_id.recurring_next_date", "contract_id.line_recurrence")
def _compute_recurring_next_date(self):
super()._compute_recurring_next_date()
self._set_recurrence_field("recurring_next_date")
@api.depends("display_type", "note_invoicing_mode")
def _compute_is_recurring_note(self):
for record in self:
record.is_recurring_note = (
record.display_type == "line_note"
and record.note_invoicing_mode == "custom"
)
@api.depends(
"automatic_price",
"specific_price",
"product_id",
"quantity",
"contract_id.pricelist_id",
"contract_id.partner_id",
)
def _compute_price_unit(self):
"""Get the specific price if no auto-price, and the price obtained
from the pricelist otherwise.
"""
for line in self:
if line.automatic_price:
pricelist = (
line.contract_id.pricelist_id
or line.contract_id.partner_id.with_company(
line.contract_id.company_id
).property_product_pricelist
)
product = line.product_id.with_context(
quantity=line.env.context.get(
"contract_line_qty",
line.quantity,
),
pricelist=pricelist.id,
partner=line.contract_id.partner_id.id,
date=line.env.context.get(
"old_date", fields.Date.context_today(line)
),
)
line.price_unit = product.price
else:
line.price_unit = line.specific_price
# Tip in https://github.com/odoo/odoo/issues/23891#issuecomment-376910788
@api.onchange("price_unit")
def _inverse_price_unit(self):
"""Store the specific price in the no auto-price records."""
for line in self.filtered(lambda x: not x.automatic_price):
line.specific_price = line.price_unit
@api.depends("quantity", "price_unit", "discount")
def _compute_price_subtotal(self):
for line in self:
subtotal = line.quantity * line.price_unit
discount = line.discount / 100
subtotal *= 1 - discount
if line.contract_id.pricelist_id:
cur = line.contract_id.pricelist_id.currency_id
line.price_subtotal = cur.round(subtotal)
else:
line.price_subtotal = subtotal
@api.constrains("discount")
def _check_discount(self):
for line in self:
if line.discount > 100:
raise ValidationError(_("Discount should be less or equal to 100"))
@api.onchange("product_id")
def _onchange_product_id(self):
vals = {}
if not self.uom_id or (
self.product_id.uom_id.category_id.id != self.uom_id.category_id.id
):
vals["uom_id"] = self.product_id.uom_id
date = self.recurring_next_date or fields.Date.context_today(self)
partner = self.contract_id.partner_id or self.env.user.partner_id
product = self.product_id.with_context(
lang=partner.lang,
partner=partner.id,
quantity=self.quantity,
date=date,
pricelist=self.contract_id.pricelist_id.id,
uom=self.uom_id.id,
)
vals["name"] = self.product_id.get_product_multiline_description_sale()
vals["price_unit"] = product.price
self.update(vals)
| 37 | 9,657 |
737 |
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 OpenERP SA
# Copyright 2014 Angel Moya <[email protected]>
# Copyright 2015 Pedro M. Baeza <[email protected]>
# Copyright 2016-2018 Carlos Dauden <[email protected]>
# Copyright 2016-2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractTemplateLine(models.Model):
_name = "contract.template.line"
_inherit = "contract.abstract.contract.line"
_description = "Contract Template Line"
_order = "sequence,id"
contract_id = fields.Many2one(
string="Contract",
comodel_name="contract.template",
required=True,
ondelete="cascade",
)
| 32.043478 | 737 |
1,161 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ContractModification(models.Model):
_name = "contract.modification"
_description = "Contract Modification"
_order = "date desc"
date = fields.Date(required=True)
description = fields.Text(required=True)
contract_id = fields.Many2one(
string="Contract",
comodel_name="contract.contract",
required=True,
ondelete="cascade",
index=True,
)
sent = fields.Boolean(default=False)
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
if not self.env.context.get("bypass_modification_send"):
records.check_modification_ids_need_sent()
return records
def write(self, vals):
res = super().write(vals)
if not self.env.context.get("bypass_modification_send"):
self.check_modification_ids_need_sent()
return res
def check_modification_ids_need_sent(self):
self.mapped("contract_id")._modification_mail_send()
| 30.5 | 1,159 |
419 |
py
|
PYTHON
|
15.0
|
# Copyright 2020 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ContractTerminateReason(models.Model):
_name = "contract.terminate.reason"
_description = "Contract Termination Reason"
name = fields.Char(required=True)
terminate_comment_required = fields.Boolean(
string="Require a termination comment", default=True
)
| 27.933333 | 419 |
509 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
create_new_line_at_contract_line_renew = fields.Boolean(
help="If checked, a new line will be generated at contract line renew "
"and linked to the original one as successor. The default "
"behavior is to extend the end date of the contract by a new "
"subscription period",
)
| 31.8125 | 509 |
41,485 |
py
|
PYTHON
|
15.0
|
# Copyright 2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV.
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from .contract_line_constraints import get_allowed
class ContractLine(models.Model):
_name = "contract.line"
_description = "Contract Line"
_inherit = [
"contract.abstract.contract.line",
"contract.recurrency.mixin",
]
_order = "sequence,id"
sequence = fields.Integer()
contract_id = fields.Many2one(
comodel_name="contract.contract",
string="Contract",
required=True,
index=True,
auto_join=True,
ondelete="cascade",
)
analytic_account_id = fields.Many2one(
string="Analytic account",
comodel_name="account.analytic.account",
)
analytic_tag_ids = fields.Many2many(
comodel_name="account.analytic.tag",
string="Analytic Tags",
)
date_start = fields.Date(required=True)
date_end = fields.Date(compute="_compute_date_end", store=True, readonly=False)
termination_notice_date = fields.Date(
compute="_compute_termination_notice_date",
store=True,
copy=False,
)
create_invoice_visibility = fields.Boolean(
compute="_compute_create_invoice_visibility"
)
successor_contract_line_id = fields.Many2one(
comodel_name="contract.line",
string="Successor Contract Line",
required=False,
readonly=True,
index=True,
copy=False,
help="In case of restart after suspension, this field contain the new "
"contract line created.",
)
predecessor_contract_line_id = fields.Many2one(
comodel_name="contract.line",
string="Predecessor Contract Line",
required=False,
readonly=True,
index=True,
copy=False,
help="Contract Line origin of this one.",
)
manual_renew_needed = fields.Boolean(
default=False,
help="This flag is used to make a difference between a definitive stop"
"and temporary one for which a user is not able to plan a"
"successor in advance",
)
is_plan_successor_allowed = fields.Boolean(
string="Plan successor allowed?", compute="_compute_allowed"
)
is_stop_plan_successor_allowed = fields.Boolean(
string="Stop/Plan successor allowed?", compute="_compute_allowed"
)
is_stop_allowed = fields.Boolean(string="Stop allowed?", compute="_compute_allowed")
is_cancel_allowed = fields.Boolean(
string="Cancel allowed?", compute="_compute_allowed"
)
is_un_cancel_allowed = fields.Boolean(
string="Un-Cancel allowed?", compute="_compute_allowed"
)
state = fields.Selection(
selection=[
("upcoming", "Upcoming"),
("in-progress", "In-progress"),
("to-renew", "To renew"),
("upcoming-close", "Upcoming Close"),
("closed", "Closed"),
("canceled", "Canceled"),
],
compute="_compute_state",
search="_search_state",
)
active = fields.Boolean(
string="Active",
related="contract_id.active",
store=True,
readonly=True,
)
# pylint: disable=missing-return
@api.depends(
"last_date_invoiced", "date_start", "date_end", "contract_id.last_date_invoiced"
)
def _compute_next_period_date_start(self):
"""Rectify next period date start if another line in the contract has been
already invoiced previously when the recurrence is by contract.
"""
rest = self.filtered(lambda x: x.contract_id.line_recurrence)
for rec in self - rest:
lines = rec.contract_id.contract_line_ids
if not rec.last_date_invoiced and any(lines.mapped("last_date_invoiced")):
next_period_date_start = max(
lines.filtered("last_date_invoiced").mapped("last_date_invoiced")
) + relativedelta(days=1)
if rec.date_end and next_period_date_start > rec.date_end:
next_period_date_start = False
rec.next_period_date_start = next_period_date_start
else:
rest |= rec
super(ContractLine, rest)._compute_next_period_date_start()
@api.depends("contract_id.date_end", "contract_id.line_recurrence")
def _compute_date_end(self):
self._set_recurrence_field("date_end")
@api.depends(
"date_end",
"termination_notice_rule_type",
"termination_notice_interval",
)
def _compute_termination_notice_date(self):
for rec in self:
if rec.date_end:
rec.termination_notice_date = rec.date_end - self.get_relative_delta(
rec.termination_notice_rule_type,
rec.termination_notice_interval,
)
else:
rec.termination_notice_date = False
@api.depends("is_canceled", "date_start", "date_end", "is_auto_renew")
def _compute_state(self):
today = fields.Date.context_today(self)
for rec in self:
rec.state = False
if rec.display_type:
continue
if rec.is_canceled:
rec.state = "canceled"
continue
if rec.date_start and rec.date_start > today:
# Before period
rec.state = "upcoming"
continue
if (
rec.date_start
and rec.date_start <= today
and (not rec.date_end or rec.date_end >= today)
):
# In period
if (
rec.termination_notice_date
and rec.termination_notice_date < today
and not rec.is_auto_renew
and not rec.manual_renew_needed
):
rec.state = "upcoming-close"
else:
rec.state = "in-progress"
continue
if rec.date_end and rec.date_end < today:
# After
if (
rec.manual_renew_needed
and not rec.successor_contract_line_id
or rec.is_auto_renew
):
rec.state = "to-renew"
else:
rec.state = "closed"
@api.model
def _get_state_domain(self, state):
today = fields.Date.context_today(self)
if state == "upcoming":
return [
"&",
("date_start", ">", today),
("is_canceled", "=", False),
]
if state == "in-progress":
return [
"&",
"&",
"&",
("date_start", "<=", today),
("is_canceled", "=", False),
"|",
("date_end", ">=", today),
("date_end", "=", False),
"|",
("is_auto_renew", "=", True),
"&",
("is_auto_renew", "=", False),
("termination_notice_date", ">", today),
]
if state == "to-renew":
return [
"&",
"&",
("is_canceled", "=", False),
("date_end", "<", today),
"|",
"&",
("manual_renew_needed", "=", True),
("successor_contract_line_id", "=", False),
("is_auto_renew", "=", True),
]
if state == "upcoming-close":
return [
"&",
"&",
"&",
"&",
"&",
("date_start", "<=", today),
("is_auto_renew", "=", False),
("manual_renew_needed", "=", False),
("is_canceled", "=", False),
("termination_notice_date", "<", today),
("date_end", ">=", today),
]
if state == "closed":
return [
"&",
"&",
"&",
("is_canceled", "=", False),
("date_end", "<", today),
("is_auto_renew", "=", False),
"|",
"&",
("manual_renew_needed", "=", True),
("successor_contract_line_id", "!=", False),
("manual_renew_needed", "=", False),
]
if state == "canceled":
return [("is_canceled", "=", True)]
if not state:
return [("display_type", "!=", False)]
@api.model
def _search_state(self, operator, value):
states = [
"upcoming",
"in-progress",
"to-renew",
"upcoming-close",
"closed",
"canceled",
False,
]
if operator == "=":
return self._get_state_domain(value)
if operator == "!=":
domain = []
for state in states:
if state != value:
if domain:
domain.insert(0, "|")
domain.extend(self._get_state_domain(state))
return domain
if operator == "in":
domain = []
for state in value:
if domain:
domain.insert(0, "|")
domain.extend(self._get_state_domain(state))
return domain
if operator == "not in":
if set(value) == set(states):
return [("id", "=", False)]
return self._search_state(
"in", [state for state in states if state not in value]
)
@api.depends(
"date_start",
"date_end",
"last_date_invoiced",
"is_auto_renew",
"successor_contract_line_id",
"predecessor_contract_line_id",
"is_canceled",
"contract_id.is_terminated",
)
def _compute_allowed(self):
for rec in self:
rec.update(
{
"is_plan_successor_allowed": False,
"is_stop_plan_successor_allowed": False,
"is_stop_allowed": False,
"is_cancel_allowed": False,
"is_un_cancel_allowed": False,
}
)
if rec.contract_id.is_terminated:
continue
if rec.date_start:
allowed = get_allowed(
rec.date_start,
rec.date_end,
rec.last_date_invoiced,
rec.is_auto_renew,
rec.successor_contract_line_id,
rec.predecessor_contract_line_id,
rec.is_canceled,
)
if allowed:
rec.update(
{
"is_plan_successor_allowed": allowed.plan_successor,
"is_stop_plan_successor_allowed": (
allowed.stop_plan_successor
),
"is_stop_allowed": allowed.stop,
"is_cancel_allowed": allowed.cancel,
"is_un_cancel_allowed": allowed.uncancel,
}
)
@api.constrains("is_auto_renew", "successor_contract_line_id", "date_end")
def _check_allowed(self):
"""
logical impossible combination:
* a line with is_auto_renew True should have date_end and
couldn't have successor_contract_line_id
* a line without date_end can't have successor_contract_line_id
"""
for rec in self:
if rec.is_auto_renew:
if rec.successor_contract_line_id:
raise ValidationError(
_(
"A contract line with a successor "
"can't be set to auto-renew"
)
)
if not rec.date_end:
raise ValidationError(_("An auto-renew line must have a end date"))
else:
if not rec.date_end and rec.successor_contract_line_id:
raise ValidationError(
_("A contract line with a successor " "must have a end date")
)
@api.constrains("successor_contract_line_id", "date_end")
def _check_overlap_successor(self):
for rec in self:
if rec.date_end and rec.successor_contract_line_id:
if rec.date_end >= rec.successor_contract_line_id.date_start:
raise ValidationError(
_("Contract line and its successor overlapped")
)
@api.constrains("predecessor_contract_line_id", "date_start")
def _check_overlap_predecessor(self):
for rec in self:
if (
rec.predecessor_contract_line_id
and rec.predecessor_contract_line_id.date_end
):
if rec.date_start <= rec.predecessor_contract_line_id.date_end:
raise ValidationError(
_("Contract line and its predecessor overlapped")
)
@api.model
def _compute_first_recurring_next_date(
self,
date_start,
recurring_invoicing_type,
recurring_rule_type,
recurring_interval,
):
# deprecated method for backward compatibility
return self.get_next_invoice_date(
date_start,
recurring_invoicing_type,
self._get_default_recurring_invoicing_offset(
recurring_invoicing_type, recurring_rule_type
),
recurring_rule_type,
recurring_interval,
max_date_end=False,
)
@api.model
def _get_first_date_end(
self, date_start, auto_renew_rule_type, auto_renew_interval
):
return (
date_start
+ self.get_relative_delta(auto_renew_rule_type, auto_renew_interval)
- relativedelta(days=1)
)
@api.onchange(
"date_start",
"is_auto_renew",
"auto_renew_rule_type",
"auto_renew_interval",
)
def _onchange_is_auto_renew(self):
"""Date end should be auto-computed if a contract line is set to
auto_renew"""
for rec in self.filtered("is_auto_renew"):
if rec.date_start:
rec.date_end = self._get_first_date_end(
rec.date_start,
rec.auto_renew_rule_type,
rec.auto_renew_interval,
)
@api.constrains("is_canceled", "is_auto_renew")
def _check_auto_renew_canceled_lines(self):
for rec in self:
if rec.is_canceled and rec.is_auto_renew:
raise ValidationError(
_("A canceled contract line can't be set to auto-renew")
)
@api.constrains("recurring_next_date", "date_start")
def _check_recurring_next_date_start_date(self):
for line in self:
if line.display_type == "line_section" or not line.recurring_next_date:
continue
if line.date_start and line.recurring_next_date:
if line.date_start > line.recurring_next_date:
raise ValidationError(
_(
"You can't have a date of next invoice anterior "
"to the start of the contract line '%s'"
)
% line.name
)
@api.constrains(
"date_start", "date_end", "last_date_invoiced", "recurring_next_date"
)
def _check_last_date_invoiced(self):
for rec in self.filtered("last_date_invoiced"):
if rec.date_end and rec.date_end < rec.last_date_invoiced:
raise ValidationError(
_(
"You can't have the end date before the date of last "
"invoice for the contract line '%s'"
)
% rec.name
)
if not rec.contract_id.line_recurrence:
continue
if rec.date_start and rec.date_start > rec.last_date_invoiced:
raise ValidationError(
_(
"You can't have the start date after the date of last "
"invoice for the contract line '%s'"
)
% rec.name
)
if (
rec.recurring_next_date
and rec.recurring_next_date <= rec.last_date_invoiced
):
raise ValidationError(
_(
"You can't have the next invoice date before the date "
"of last invoice for the contract line '%s'"
)
% rec.name
)
@api.constrains("recurring_next_date")
def _check_recurring_next_date_recurring_invoices(self):
for rec in self:
if not rec.recurring_next_date and (
not rec.date_end
or not rec.last_date_invoiced
or rec.last_date_invoiced < rec.date_end
):
raise ValidationError(
_(
"You must supply a date of next invoice for contract "
"line '%s'"
)
% rec.name
)
@api.constrains("date_start", "date_end")
def _check_start_end_dates(self):
for line in self.filtered("date_end"):
if line.date_start and line.date_end:
if line.date_start > line.date_end:
raise ValidationError(
_(
"Contract line '%s' start date can't be later than"
" end date"
)
% line.name
)
@api.depends(
"display_type",
"is_recurring_note",
"recurring_next_date",
"date_start",
"date_end",
)
def _compute_create_invoice_visibility(self):
# TODO: depending on the lines, and their order, some sections
# have no meaning in certain invoices
today = fields.Date.context_today(self)
for rec in self:
if (
(not rec.display_type or rec.is_recurring_note)
and rec.date_start
and today >= rec.date_start
):
rec.create_invoice_visibility = bool(rec.recurring_next_date)
else:
rec.create_invoice_visibility = False
def _prepare_invoice_line(self, move_form):
self.ensure_one()
dates = self._get_period_to_invoice(
self.last_date_invoiced, self.recurring_next_date
)
line_form = move_form.invoice_line_ids.new()
line_form.display_type = self.display_type
line_form.product_id = self.product_id
invoice_line_vals = line_form._values_to_save(all_fields=True)
name = self._insert_markers(dates[0], dates[1])
invoice_line_vals.update(
{
"account_id": invoice_line_vals["account_id"]
if "account_id" in invoice_line_vals and not self.display_type
else False,
"quantity": self._get_quantity_to_invoice(*dates),
"product_uom_id": self.uom_id.id,
"discount": self.discount,
"contract_line_id": self.id,
"sequence": self.sequence,
"name": name,
"analytic_account_id": self.analytic_account_id.id,
"analytic_tag_ids": [(6, 0, self.analytic_tag_ids.ids)],
"price_unit": self.price_unit,
}
)
return invoice_line_vals
def _get_period_to_invoice(
self, last_date_invoiced, recurring_next_date, stop_at_date_end=True
):
# TODO this method can now be removed, since
# TODO self.next_period_date_start/end have the same values
self.ensure_one()
if not recurring_next_date:
return False, False, False
first_date_invoiced = (
last_date_invoiced + relativedelta(days=1)
if last_date_invoiced
else self.date_start
)
last_date_invoiced = self.get_next_period_date_end(
first_date_invoiced,
self.recurring_rule_type,
self.recurring_interval,
max_date_end=(self.date_end if stop_at_date_end else False),
next_invoice_date=recurring_next_date,
recurring_invoicing_type=self.recurring_invoicing_type,
recurring_invoicing_offset=self.recurring_invoicing_offset,
)
return first_date_invoiced, last_date_invoiced, recurring_next_date
def _insert_markers(self, first_date_invoiced, last_date_invoiced):
self.ensure_one()
lang_obj = self.env["res.lang"]
lang = lang_obj.search([("code", "=", self.contract_id.partner_id.lang)])
date_format = lang.date_format or "%m/%d/%Y"
name = self.name
name = name.replace("#START#", first_date_invoiced.strftime(date_format))
name = name.replace("#END#", last_date_invoiced.strftime(date_format))
return name
def _update_recurring_next_date(self):
# FIXME: Change method name according to real updated field
# e.g.: _update_last_date_invoiced()
for rec in self:
last_date_invoiced = rec.next_period_date_end
rec.write(
{
"last_date_invoiced": last_date_invoiced,
}
)
def _delay(self, delay_delta):
"""
Delay a contract line
:param delay_delta: delay relative delta
:return: delayed contract line
"""
for rec in self:
if rec.last_date_invoiced:
raise ValidationError(
_("You can't delay a contract line " "invoiced at least one time.")
)
new_date_start = rec.date_start + delay_delta
if rec.date_end:
new_date_end = rec.date_end + delay_delta
else:
new_date_end = False
new_recurring_next_date = self.get_next_invoice_date(
new_date_start,
rec.recurring_invoicing_type,
rec.recurring_invoicing_offset,
rec.recurring_rule_type,
rec.recurring_interval,
max_date_end=new_date_end,
)
rec.write(
{
"date_start": new_date_start,
"date_end": new_date_end,
"recurring_next_date": new_recurring_next_date,
}
)
def _prepare_value_for_stop(self, date_end, manual_renew_needed):
self.ensure_one()
return {
"date_end": date_end,
"is_auto_renew": False,
"manual_renew_needed": manual_renew_needed,
"recurring_next_date": self.get_next_invoice_date(
self.next_period_date_start,
self.recurring_invoicing_type,
self.recurring_invoicing_offset,
self.recurring_rule_type,
self.recurring_interval,
max_date_end=date_end,
),
}
def stop(self, date_end, manual_renew_needed=False, post_message=True):
"""
Put date_end on contract line
We don't consider contract lines that end's before the new end date
:param date_end: new date end for contract line
:return: True
"""
if not all(self.mapped("is_stop_allowed")):
raise ValidationError(_("Stop not allowed for this line"))
for rec in self:
if date_end < rec.date_start:
rec.cancel()
else:
if not rec.date_end or rec.date_end > date_end:
old_date_end = rec.date_end
rec.write(
rec._prepare_value_for_stop(date_end, manual_renew_needed)
)
if post_message:
msg = (
_(
"""Contract line for <strong>%(product)s</strong>
stopped: <br/>
- <strong>End</strong>: %(old_end)s -- %(new_end)s
"""
)
% {
"product": rec.name,
"old_end": old_date_end,
"new_end": rec.date_end,
}
)
rec.contract_id.message_post(body=msg)
else:
rec.write(
{
"is_auto_renew": False,
"manual_renew_needed": manual_renew_needed,
}
)
return True
def _prepare_value_for_plan_successor(
self, date_start, date_end, is_auto_renew, recurring_next_date=False
):
self.ensure_one()
if not recurring_next_date:
recurring_next_date = self.get_next_invoice_date(
date_start,
self.recurring_invoicing_type,
self.recurring_invoicing_offset,
self.recurring_rule_type,
self.recurring_interval,
max_date_end=date_end,
)
new_vals = self.read()[0]
new_vals.pop("id", None)
new_vals.pop("last_date_invoiced", None)
values = self._convert_to_write(new_vals)
values["date_start"] = date_start
values["date_end"] = date_end
values["recurring_next_date"] = recurring_next_date
values["is_auto_renew"] = is_auto_renew
values["predecessor_contract_line_id"] = self.id
return values
def plan_successor(
self,
date_start,
date_end,
is_auto_renew,
recurring_next_date=False,
post_message=True,
):
"""
Create a copy of a contract line in a new interval
:param date_start: date_start for the successor_contract_line
:param date_end: date_end for the successor_contract_line
:param is_auto_renew: is_auto_renew option for successor_contract_line
:param recurring_next_date: recurring_next_date for the
successor_contract_line
:return: successor_contract_line
"""
contract_line = self.env["contract.line"]
for rec in self:
if not rec.is_plan_successor_allowed:
raise ValidationError(_("Plan successor not allowed for this line"))
rec.is_auto_renew = False
new_line = self.create(
rec._prepare_value_for_plan_successor(
date_start, date_end, is_auto_renew, recurring_next_date
)
)
rec.successor_contract_line_id = new_line
contract_line |= new_line
if post_message:
msg = (
_(
"""Contract line for <strong>%(product)s</strong>
planned a successor: <br/>
- <strong>Start</strong>: %(new_date_start)s
<br/>
- <strong>End</strong>: %(new_date_end)s
"""
)
% {
"product": rec.name,
"new_date_start": new_line.date_start,
"new_date_end": new_line.date_end,
}
)
rec.contract_id.message_post(body=msg)
return contract_line
def stop_plan_successor(self, date_start, date_end, is_auto_renew):
"""
Stop a contract line for a defined period and start it later
Cases to consider:
* contract line end's before the suspension period:
-> apply stop
* contract line start before the suspension period and end in it
-> apply stop at suspension start date
-> apply plan successor:
- date_start: suspension.date_end
- date_end: date_end + (contract_line.date_end
- suspension.date_start)
* contract line start before the suspension period and end after it
-> apply stop at suspension start date
-> apply plan successor:
- date_start: suspension.date_end
- date_end: date_end + (suspension.date_end
- suspension.date_start)
* contract line start and end's in the suspension period
-> apply delay
- delay: suspension.date_end - contract_line.date_start
* contract line start in the suspension period and end after it
-> apply delay
- delay: suspension.date_end - contract_line.date_start
* contract line start and end after the suspension period
-> apply delay
- delay: suspension.date_end - suspension.start_date
:param date_start: suspension start date
:param date_end: suspension end date
:param is_auto_renew: is the new line is set to auto_renew
:return: created contract line
"""
if not all(self.mapped("is_stop_plan_successor_allowed")):
raise ValidationError(_("Stop/Plan successor not allowed for this line"))
contract_line = self.env["contract.line"]
for rec in self:
if rec.date_start >= date_start:
if rec.date_start < date_end:
delay = (date_end - rec.date_start) + timedelta(days=1)
else:
delay = (date_end - date_start) + timedelta(days=1)
rec._delay(delay)
contract_line |= rec
else:
if rec.date_end and rec.date_end < date_start:
rec.stop(date_start, post_message=False)
elif (
rec.date_end
and rec.date_end > date_start
and rec.date_end < date_end
):
new_date_start = date_end + relativedelta(days=1)
new_date_end = (
date_end + (rec.date_end - date_start) + relativedelta(days=1)
)
rec.stop(
date_start - relativedelta(days=1),
manual_renew_needed=True,
post_message=False,
)
contract_line |= rec.plan_successor(
new_date_start,
new_date_end,
is_auto_renew,
post_message=False,
)
else:
new_date_start = date_end + relativedelta(days=1)
if rec.date_end:
new_date_end = (
rec.date_end
+ (date_end - date_start)
+ relativedelta(days=1)
)
else:
new_date_end = rec.date_end
rec.stop(
date_start - relativedelta(days=1),
manual_renew_needed=True,
post_message=False,
)
contract_line |= rec.plan_successor(
new_date_start,
new_date_end,
is_auto_renew,
post_message=False,
)
msg = (
_(
"""Contract line for <strong>%(product)s</strong>
suspended: <br/>
- <strong>Suspension Start</strong>: %(new_date_start)s
<br/>
- <strong>Suspension End</strong>: %(new_date_end)s
"""
)
% {
"product": rec.name,
"new_date_start": date_start,
"new_date_end": date_end,
}
)
rec.contract_id.message_post(body=msg)
return contract_line
def cancel(self):
if not all(self.mapped("is_cancel_allowed")):
raise ValidationError(_("Cancel not allowed for this line"))
for contract in self.mapped("contract_id"):
lines = self.filtered(lambda l, c=contract: l.contract_id == c)
msg = _(
"Contract line canceled: %s",
"<br/>- ".join(
[
"<strong>%(product)s</strong>" % {"product": name}
for name in lines.mapped("name")
]
),
)
contract.message_post(body=msg)
self.mapped("predecessor_contract_line_id").write(
{"successor_contract_line_id": False}
)
return self.write({"is_canceled": True, "is_auto_renew": False})
def uncancel(self, recurring_next_date):
if not all(self.mapped("is_un_cancel_allowed")):
raise ValidationError(_("Un-cancel not allowed for this line"))
for contract in self.mapped("contract_id"):
lines = self.filtered(lambda l, c=contract: l.contract_id == c)
msg = _(
"Contract line Un-canceled: %s",
"<br/>- ".join(
[
"<strong>%(product)s</strong>" % {"product": name}
for name in lines.mapped("name")
]
),
)
contract.message_post(body=msg)
for rec in self:
if rec.predecessor_contract_line_id:
predecessor_contract_line = rec.predecessor_contract_line_id
assert not predecessor_contract_line.successor_contract_line_id
predecessor_contract_line.successor_contract_line_id = rec
rec.is_canceled = False
rec.recurring_next_date = recurring_next_date
return True
def action_uncancel(self):
self.ensure_one()
context = {
"default_contract_line_id": self.id,
"default_recurring_next_date": fields.Date.context_today(self),
}
context.update(self.env.context)
view_id = self.env.ref("contract.contract_line_wizard_uncancel_form_view").id
return {
"type": "ir.actions.act_window",
"name": "Un-Cancel Contract Line",
"res_model": "contract.line.wizard",
"view_mode": "form",
"views": [(view_id, "form")],
"target": "new",
"context": context,
}
def action_plan_successor(self):
self.ensure_one()
context = {
"default_contract_line_id": self.id,
"default_is_auto_renew": self.is_auto_renew,
}
context.update(self.env.context)
view_id = self.env.ref(
"contract.contract_line_wizard_plan_successor_form_view"
).id
return {
"type": "ir.actions.act_window",
"name": "Plan contract line successor",
"res_model": "contract.line.wizard",
"view_mode": "form",
"views": [(view_id, "form")],
"target": "new",
"context": context,
}
def action_stop(self):
self.ensure_one()
context = {
"default_contract_line_id": self.id,
"default_date_end": self.date_end,
}
context.update(self.env.context)
view_id = self.env.ref("contract.contract_line_wizard_stop_form_view").id
return {
"type": "ir.actions.act_window",
"name": "Terminate contract line",
"res_model": "contract.line.wizard",
"view_mode": "form",
"views": [(view_id, "form")],
"target": "new",
"context": context,
}
def action_stop_plan_successor(self):
self.ensure_one()
context = {
"default_contract_line_id": self.id,
"default_is_auto_renew": self.is_auto_renew,
}
context.update(self.env.context)
view_id = self.env.ref(
"contract.contract_line_wizard_stop_plan_successor_form_view"
).id
return {
"type": "ir.actions.act_window",
"name": "Suspend contract line",
"res_model": "contract.line.wizard",
"view_mode": "form",
"views": [(view_id, "form")],
"target": "new",
"context": context,
}
def _get_renewal_new_date_end(self):
self.ensure_one()
date_start = self.date_end + relativedelta(days=1)
date_end = self._get_first_date_end(
date_start, self.auto_renew_rule_type, self.auto_renew_interval
)
return date_end
def _renew_create_line(self, date_end):
self.ensure_one()
date_start = self.date_end + relativedelta(days=1)
is_auto_renew = self.is_auto_renew
self.stop(self.date_end, post_message=False)
new_line = self.plan_successor(
date_start, date_end, is_auto_renew, post_message=False
)
return new_line
def _renew_extend_line(self, date_end):
self.ensure_one()
self.date_end = date_end
return self
def renew(self):
res = self.env["contract.line"]
for rec in self:
company = rec.contract_id.company_id
date_end = rec._get_renewal_new_date_end()
date_start = rec.date_end + relativedelta(days=1)
if company.create_new_line_at_contract_line_renew:
new_line = rec._renew_create_line(date_end)
else:
new_line = rec._renew_extend_line(date_end)
res |= new_line
msg = (
_(
"""Contract line for <strong>%(product)s</strong>
renewed: <br/>
- <strong>Start</strong>: %(new_date_start)s
<br/>
- <strong>End</strong>: %(new_date_end)s
"""
)
% {
"product": rec.name,
"new_date_start": date_start,
"new_date_end": date_end,
}
)
rec.contract_id.message_post(body=msg)
return res
@api.model
def _contract_line_to_renew_domain(self):
return [
("contract_id.is_terminated", "=", False),
("is_auto_renew", "=", True),
("is_canceled", "=", False),
("termination_notice_date", "<=", fields.Date.context_today(self)),
]
@api.model
def cron_renew_contract_line(self):
domain = self._contract_line_to_renew_domain()
to_renew = self.search(domain)
to_renew.renew()
@api.model
def fields_view_get(
self, view_id=None, view_type="form", toolbar=False, submenu=False
):
default_contract_type = self.env.context.get("default_contract_type")
if view_type == "tree" and default_contract_type == "purchase":
view_id = self.env.ref("contract.contract_line_supplier_tree_view").id
if view_type == "form":
if default_contract_type == "purchase":
view_id = self.env.ref("contract.contract_line_supplier_form_view").id
elif default_contract_type == "sale":
view_id = self.env.ref("contract.contract_line_customer_form_view").id
return super().fields_view_get(view_id, view_type, toolbar, submenu)
def unlink(self):
"""stop unlink uncnacled lines"""
for record in self:
if not (record.is_canceled or record.display_type):
raise ValidationError(_("Contract line must be canceled before delete"))
return super().unlink()
def _get_quantity_to_invoice(
self, period_first_date, period_last_date, invoice_date
):
self.ensure_one()
return self.quantity if not self.display_type else 0.0
| 37.747953 | 41,485 |
8,865 |
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV.
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
class ContractRecurrencyBasicMixin(models.AbstractModel):
_name = "contract.recurrency.basic.mixin"
_description = "Basic recurrency mixin for abstract contract models"
recurring_rule_type = fields.Selection(
[
("daily", "Day(s)"),
("weekly", "Week(s)"),
("monthly", "Month(s)"),
("monthlylastday", "Month(s) last day"),
("quarterly", "Quarter(s)"),
("semesterly", "Semester(s)"),
("yearly", "Year(s)"),
],
default="monthly",
string="Recurrence",
help="Specify Interval for automatic invoice generation.",
)
recurring_invoicing_type = fields.Selection(
[("pre-paid", "Pre-paid"), ("post-paid", "Post-paid")],
default="pre-paid",
string="Invoicing type",
help=(
"Specify if the invoice must be generated at the beginning "
"(pre-paid) or end (post-paid) of the period."
),
)
recurring_invoicing_offset = fields.Integer(
compute="_compute_recurring_invoicing_offset",
string="Invoicing offset",
help=(
"Number of days to offset the invoice from the period end "
"date (in post-paid mode) or start date (in pre-paid mode)."
),
)
recurring_interval = fields.Integer(
default=1,
string="Invoice Every",
help="Invoice every (Days/Week/Month/Year)",
)
date_start = fields.Date()
recurring_next_date = fields.Date(string="Date of Next Invoice")
@api.depends("recurring_invoicing_type", "recurring_rule_type")
def _compute_recurring_invoicing_offset(self):
for rec in self:
method = self._get_default_recurring_invoicing_offset
rec.recurring_invoicing_offset = method(
rec.recurring_invoicing_type, rec.recurring_rule_type
)
@api.model
def _get_default_recurring_invoicing_offset(
self, recurring_invoicing_type, recurring_rule_type
):
if (
recurring_invoicing_type == "pre-paid"
or recurring_rule_type == "monthlylastday"
):
return 0
else:
return 1
class ContractRecurrencyMixin(models.AbstractModel):
_inherit = "contract.recurrency.basic.mixin"
_name = "contract.recurrency.mixin"
_description = "Recurrency mixin for contract models"
date_start = fields.Date(default=lambda self: fields.Date.context_today(self))
recurring_next_date = fields.Date(
compute="_compute_recurring_next_date", store=True, readonly=False, copy=True
)
date_end = fields.Date(index=True)
next_period_date_start = fields.Date(
string="Next Period Start",
compute="_compute_next_period_date_start",
)
next_period_date_end = fields.Date(
string="Next Period End",
compute="_compute_next_period_date_end",
)
last_date_invoiced = fields.Date(readonly=True, copy=False)
@api.depends("next_period_date_start")
def _compute_recurring_next_date(self):
for rec in self:
rec.recurring_next_date = self.get_next_invoice_date(
rec.next_period_date_start,
rec.recurring_invoicing_type,
rec.recurring_invoicing_offset,
rec.recurring_rule_type,
rec.recurring_interval,
max_date_end=rec.date_end,
)
@api.depends("last_date_invoiced", "date_start", "date_end")
def _compute_next_period_date_start(self):
for rec in self:
if rec.last_date_invoiced:
next_period_date_start = rec.last_date_invoiced + relativedelta(days=1)
else:
next_period_date_start = rec.date_start
if (
rec.date_end
and next_period_date_start
and next_period_date_start > rec.date_end
):
next_period_date_start = False
rec.next_period_date_start = next_period_date_start
@api.depends(
"next_period_date_start",
"recurring_invoicing_type",
"recurring_invoicing_offset",
"recurring_rule_type",
"recurring_interval",
"date_end",
"recurring_next_date",
)
def _compute_next_period_date_end(self):
for rec in self:
rec.next_period_date_end = self.get_next_period_date_end(
rec.next_period_date_start,
rec.recurring_rule_type,
rec.recurring_interval,
max_date_end=rec.date_end,
next_invoice_date=rec.recurring_next_date,
recurring_invoicing_type=rec.recurring_invoicing_type,
recurring_invoicing_offset=rec.recurring_invoicing_offset,
)
@api.model
def get_relative_delta(self, recurring_rule_type, interval):
"""Return a relativedelta for one period.
When added to the first day of the period,
it gives the first day of the next period.
"""
if recurring_rule_type == "daily":
return relativedelta(days=interval)
elif recurring_rule_type == "weekly":
return relativedelta(weeks=interval)
elif recurring_rule_type == "monthly":
return relativedelta(months=interval)
elif recurring_rule_type == "monthlylastday":
return relativedelta(months=interval, day=1)
elif recurring_rule_type == "quarterly":
return relativedelta(months=3 * interval)
elif recurring_rule_type == "semesterly":
return relativedelta(months=6 * interval)
else:
return relativedelta(years=interval)
@api.model
def get_next_period_date_end(
self,
next_period_date_start,
recurring_rule_type,
recurring_interval,
max_date_end,
next_invoice_date=False,
recurring_invoicing_type=False,
recurring_invoicing_offset=False,
):
"""Compute the end date for the next period.
The next period normally depends on recurrence options only.
It is however possible to provide it a next invoice date, in
which case this method can adjust the next period based on that
too. In that scenario it required the invoicing type and offset
arguments.
"""
if not next_period_date_start:
return False
if max_date_end and next_period_date_start > max_date_end:
# start is past max date end: there is no next period
return False
if not next_invoice_date:
# regular algorithm
next_period_date_end = (
next_period_date_start
+ self.get_relative_delta(recurring_rule_type, recurring_interval)
- relativedelta(days=1)
)
else:
# special algorithm when the next invoice date is forced
if recurring_invoicing_type == "pre-paid":
next_period_date_end = (
next_invoice_date
- relativedelta(days=recurring_invoicing_offset)
+ self.get_relative_delta(recurring_rule_type, recurring_interval)
- relativedelta(days=1)
)
else: # post-paid
next_period_date_end = next_invoice_date - relativedelta(
days=recurring_invoicing_offset
)
if max_date_end and next_period_date_end > max_date_end:
# end date is past max_date_end: trim it
next_period_date_end = max_date_end
return next_period_date_end
@api.model
def get_next_invoice_date(
self,
next_period_date_start,
recurring_invoicing_type,
recurring_invoicing_offset,
recurring_rule_type,
recurring_interval,
max_date_end,
):
next_period_date_end = self.get_next_period_date_end(
next_period_date_start,
recurring_rule_type,
recurring_interval,
max_date_end=max_date_end,
)
if not next_period_date_end:
return False
if recurring_invoicing_type == "pre-paid":
recurring_next_date = next_period_date_start + relativedelta(
days=recurring_invoicing_offset
)
else: # post-paid
recurring_next_date = next_period_date_end + relativedelta(
days=recurring_invoicing_offset
)
return recurring_next_date
| 37.09205 | 8,865 |
683 |
py
|
PYTHON
|
15.0
|
# Copyright 2019 ACSONE SA/NV
# 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"
create_new_line_at_contract_line_renew = fields.Boolean(
related="company_id.create_new_line_at_contract_line_renew",
readonly=False,
string="Create New Line At Contract Line Renew",
help="If checked, a new line will be generated at contract line renew "
"and linked to the original one as successor. The default "
"behavior is to extend the end date of the contract by a new "
"subscription period",
)
| 35.947368 | 683 |
2,942 |
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 OpenERP SA
# Copyright 2014 Angel Moya <[email protected]>
# Copyright 2015-2020 Tecnativa - Pedro M. Baeza
# Copyright 2016-2018 Carlos Dauden <[email protected]>
# Copyright 2016-2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ContractAbstractContract(models.AbstractModel):
_inherit = "contract.recurrency.basic.mixin"
_name = "contract.abstract.contract"
_description = "Abstract Recurring Contract"
# These fields will not be synced to the contract
NO_SYNC = ["name", "partner_id", "company_id"]
name = fields.Char(required=True)
# Needed for avoiding errors on several inherited behaviors
partner_id = fields.Many2one(
comodel_name="res.partner", string="Partner", index=True
)
pricelist_id = fields.Many2one(comodel_name="product.pricelist", string="Pricelist")
contract_type = fields.Selection(
selection=[("sale", "Customer"), ("purchase", "Supplier")],
default="sale",
index=True,
)
journal_id = fields.Many2one(
comodel_name="account.journal",
string="Journal",
domain="[('type', '=', contract_type)," "('company_id', '=', company_id)]",
compute="_compute_journal_id",
store=True,
readonly=False,
index=True,
)
company_id = fields.Many2one(
"res.company",
string="Company",
required=True,
default=lambda self: self.env.company.id,
)
line_recurrence = fields.Boolean(
string="Recurrence at line level?",
help="Mark this check if you want to control recurrrence at line level instead"
" of all together for the whole contract.",
)
generation_type = fields.Selection(
selection=lambda self: self._selection_generation_type(),
default=lambda self: self._default_generation_type(),
help="Choose the document that will be automatically generated by cron.",
)
@api.model
def _selection_generation_type(self):
return [("invoice", "Invoice")]
@api.model
def _default_generation_type(self):
return "invoice"
@api.onchange("contract_type")
def _onchange_contract_type(self):
if self.contract_type == "purchase":
self.contract_line_ids.filtered("automatic_price").update(
{"automatic_price": False}
)
@api.depends("contract_type", "company_id")
def _compute_journal_id(self):
AccountJournal = self.env["account.journal"]
for contract in self:
domain = [
("type", "=", contract.contract_type),
("company_id", "=", contract.company_id.id),
]
journal = AccountJournal.search(domain, limit=1)
if journal:
contract.journal_id = journal.id
| 35.878049 | 2,942 |
27,079 |
py
|
PYTHON
|
15.0
|
# Copyright 2004-2010 OpenERP SA
# Copyright 2014 Angel Moya <[email protected]>
# Copyright 2015-2020 Tecnativa - Pedro M. Baeza
# Copyright 2016-2018 Tecnativa - Carlos Dauden
# Copyright 2016-2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
from odoo.tests import Form
from odoo.tools.translate import _
_logger = logging.getLogger(__name__)
class ContractContract(models.Model):
_name = "contract.contract"
_description = "Contract"
_order = "code, name asc"
_inherit = [
"mail.thread",
"mail.activity.mixin",
"contract.abstract.contract",
"contract.recurrency.mixin",
"portal.mixin",
]
active = fields.Boolean(
default=True,
)
code = fields.Char(
string="Reference",
)
group_id = fields.Many2one(
string="Group",
comodel_name="account.analytic.account",
ondelete="restrict",
)
currency_id = fields.Many2one(
compute="_compute_currency_id",
inverse="_inverse_currency_id",
comodel_name="res.currency",
string="Currency",
)
manual_currency_id = fields.Many2one(
comodel_name="res.currency",
readonly=True,
)
contract_template_id = fields.Many2one(
string="Contract Template", comodel_name="contract.template"
)
contract_line_ids = fields.One2many(
string="Contract lines",
comodel_name="contract.line",
inverse_name="contract_id",
copy=True,
context={"active_test": False},
)
# Trick for being able to have 2 different views for the same o2m
# We need this as one2many widget doesn't allow to define in the view
# the same field 2 times with different views. 2 views are needed because
# one of them must be editable inline and the other not, which can't be
# parametrized through attrs.
contract_line_fixed_ids = fields.One2many(
string="Contract lines (fixed)",
comodel_name="contract.line",
inverse_name="contract_id",
context={"active_test": False},
)
user_id = fields.Many2one(
comodel_name="res.users",
string="Responsible",
index=True,
default=lambda self: self.env.user,
)
create_invoice_visibility = fields.Boolean(
compute="_compute_create_invoice_visibility"
)
date_end = fields.Date(compute="_compute_date_end", store=True, readonly=False)
payment_term_id = fields.Many2one(
comodel_name="account.payment.term", string="Payment Terms", index=True
)
invoice_count = fields.Integer(compute="_compute_invoice_count")
fiscal_position_id = fields.Many2one(
comodel_name="account.fiscal.position",
string="Fiscal Position",
ondelete="restrict",
)
invoice_partner_id = fields.Many2one(
string="Invoicing contact",
comodel_name="res.partner",
ondelete="restrict",
domain="['|',('id', 'parent_of', partner_id), ('id', 'child_of', partner_id)]",
)
partner_id = fields.Many2one(
comodel_name="res.partner", inverse="_inverse_partner_id", required=True
)
commercial_partner_id = fields.Many2one(
"res.partner",
compute_sudo=True,
related="partner_id.commercial_partner_id",
store=True,
string="Commercial Entity",
index=True,
)
tag_ids = fields.Many2many(comodel_name="contract.tag", string="Tags")
note = fields.Text(string="Notes")
is_terminated = fields.Boolean(string="Terminated", readonly=True, copy=False)
terminate_reason_id = fields.Many2one(
comodel_name="contract.terminate.reason",
string="Termination Reason",
ondelete="restrict",
readonly=True,
copy=False,
tracking=True,
)
terminate_comment = fields.Text(
string="Termination Comment",
readonly=True,
copy=False,
tracking=True,
)
terminate_date = fields.Date(
string="Termination Date",
readonly=True,
copy=False,
tracking=True,
)
modification_ids = fields.One2many(
comodel_name="contract.modification",
inverse_name="contract_id",
string="Modifications",
)
def get_formview_id(self, access_uid=None):
if self.contract_type == "sale":
return self.env.ref("contract.contract_contract_customer_form_view").id
else:
return self.env.ref("contract.contract_contract_supplier_form_view").id
@api.model_create_multi
def create(self, vals_list):
records = super().create(vals_list)
records._set_start_contract_modification()
return records
def write(self, vals):
if "modification_ids" in vals:
res = super(
ContractContract, self.with_context(bypass_modification_send=True)
).write(vals)
self._modification_mail_send()
else:
res = super(ContractContract, self).write(vals)
return res
@api.model
def _set_start_contract_modification(self):
subtype_id = self.env.ref("contract.mail_message_subtype_contract_modification")
for record in self:
if record.contract_line_ids:
date_start = min(record.contract_line_ids.mapped("date_start"))
else:
date_start = record.create_date
record.message_subscribe(
partner_ids=[record.partner_id.id], subtype_ids=[subtype_id.id]
)
record.with_context(skip_modification_mail=True).write(
{
"modification_ids": [
(0, 0, {"date": date_start, "description": _("Contract start")})
]
}
)
@api.model
def _modification_mail_send(self):
for record in self:
modification_ids_not_sent = record.modification_ids.filtered(
lambda x: not x.sent
)
if modification_ids_not_sent:
if not self.env.context.get("skip_modification_mail"):
record.with_context(
default_subtype_id=self.env.ref(
"contract.mail_message_subtype_contract_modification"
).id,
).message_post_with_template(
self.env.ref("contract.mail_template_contract_modification").id,
email_layout_xmlid="contract.template_contract_modification",
)
modification_ids_not_sent.write({"sent": True})
def _compute_access_url(self):
for record in self:
record.access_url = "/my/contracts/{}".format(record.id)
def action_preview(self):
"""Invoked when 'Preview' button in contract form view is clicked."""
self.ensure_one()
return {
"type": "ir.actions.act_url",
"target": "self",
"url": self.get_portal_url(),
}
def _inverse_partner_id(self):
for rec in self:
if not rec.invoice_partner_id:
rec.invoice_partner_id = rec.partner_id.address_get(["invoice"])[
"invoice"
]
def _get_related_invoices(self):
self.ensure_one()
invoices = (
self.env["account.move.line"]
.search(
[
(
"contract_line_id",
"in",
self.contract_line_ids.ids,
)
]
)
.mapped("move_id")
)
# we are forced to always search for this for not losing possible <=v11
# generated invoices
invoices |= self.env["account.move"].search([("old_contract_id", "=", self.id)])
return invoices
def _get_computed_currency(self):
"""Helper method for returning the theoretical computed currency."""
self.ensure_one()
currency = self.env["res.currency"]
if any(self.contract_line_ids.mapped("automatic_price")):
# Use pricelist currency
currency = (
self.pricelist_id.currency_id
or self.partner_id.with_company(
self.company_id
).property_product_pricelist.currency_id
)
return currency or self.journal_id.currency_id or self.company_id.currency_id
@api.depends(
"manual_currency_id",
"pricelist_id",
"partner_id",
"journal_id",
"company_id",
)
def _compute_currency_id(self):
for rec in self:
if rec.manual_currency_id:
rec.currency_id = rec.manual_currency_id
else:
rec.currency_id = rec._get_computed_currency()
def _inverse_currency_id(self):
"""If the currency is different from the computed one, then save it
in the manual field.
"""
for rec in self:
if rec._get_computed_currency() != rec.currency_id:
rec.manual_currency_id = rec.currency_id
else:
rec.manual_currency_id = False
def _compute_invoice_count(self):
for rec in self:
rec.invoice_count = len(rec._get_related_invoices())
def action_show_invoices(self):
self.ensure_one()
tree_view = self.env.ref("account.view_invoice_tree", raise_if_not_found=False)
form_view = self.env.ref("account.view_move_form", raise_if_not_found=False)
ctx = dict(self.env.context)
if ctx.get("default_contract_type"):
ctx["default_move_type"] = (
"out_invoice"
if ctx.get("default_contract_type") == "sale"
else "in_invoice"
)
action = {
"type": "ir.actions.act_window",
"name": "Invoices",
"res_model": "account.move",
"view_mode": "tree,kanban,form,calendar,pivot,graph,activity",
"domain": [("id", "in", self._get_related_invoices().ids)],
"context": ctx,
}
if tree_view and form_view:
action["views"] = [(tree_view.id, "tree"), (form_view.id, "form")]
return action
@api.depends("contract_line_ids.date_end")
def _compute_date_end(self):
for contract in self:
contract.date_end = False
date_end = contract.contract_line_ids.mapped("date_end")
if date_end and all(date_end):
contract.date_end = max(date_end)
# pylint: disable=missing-return
@api.depends(
"contract_line_ids.recurring_next_date",
"contract_line_ids.is_canceled",
)
def _compute_recurring_next_date(self):
for contract in self:
recurring_next_date = contract.contract_line_ids.filtered(
lambda l: (
l.recurring_next_date
and not l.is_canceled
and (not l.display_type or l.is_recurring_note)
)
).mapped("recurring_next_date")
# we give priority to computation from date_start if modified
if (
contract._origin
and contract._origin.date_start != contract.date_start
or not recurring_next_date
):
super(ContractContract, contract)._compute_recurring_next_date()
else:
contract.recurring_next_date = min(recurring_next_date)
@api.depends("contract_line_ids.create_invoice_visibility")
def _compute_create_invoice_visibility(self):
for contract in self:
contract.create_invoice_visibility = any(
contract.contract_line_ids.mapped("create_invoice_visibility")
)
@api.onchange("contract_template_id")
def _onchange_contract_template_id(self):
"""Update the contract fields with that of the template.
Take special consideration with the `contract_line_ids`,
which must be created using the data from the contract lines. Cascade
deletion ensures that any errant lines that are created are also
deleted.
"""
contract_template_id = self.contract_template_id
if not contract_template_id:
return
for field_name, field in contract_template_id._fields.items():
if field.name == "contract_line_ids":
lines = self._convert_contract_lines(contract_template_id)
self.contract_line_ids += lines
elif not any(
(
field.compute,
field.related,
field.automatic,
field.readonly,
field.company_dependent,
field.name in self.NO_SYNC,
)
):
if self.contract_template_id[field_name]:
self[field_name] = self.contract_template_id[field_name]
@api.onchange("partner_id", "company_id")
def _onchange_partner_id(self):
partner = (
self.partner_id
if not self.company_id
else self.partner_id.with_company(self.company_id)
)
self.pricelist_id = partner.property_product_pricelist.id
self.fiscal_position_id = partner.env[
"account.fiscal.position"
].get_fiscal_position(partner.id)
if self.contract_type == "purchase":
self.payment_term_id = partner.property_supplier_payment_term_id
else:
self.payment_term_id = partner.property_payment_term_id
self.invoice_partner_id = self.partner_id.address_get(["invoice"])["invoice"]
def _convert_contract_lines(self, contract):
self.ensure_one()
new_lines = self.env["contract.line"]
contract_line_model = self.env["contract.line"]
for contract_line in contract.contract_line_ids:
vals = contract_line._convert_to_write(contract_line.read()[0])
# Remove template link field
vals.pop("contract_template_id", False)
vals["date_start"] = fields.Date.context_today(contract_line)
vals["recurring_next_date"] = fields.Date.context_today(contract_line)
new_lines += contract_line_model.new(vals)
new_lines._onchange_is_auto_renew()
return new_lines
def _prepare_invoice(self, date_invoice, journal=None):
"""Prepare in a Form the values for the generated invoice record.
:return: A tuple with the vals dictionary and the Form with the
preloaded values for being used in lines.
"""
self.ensure_one()
if not journal:
journal = (
self.journal_id
if self.journal_id.type == self.contract_type
else self.env["account.journal"].search(
[
("type", "=", self.contract_type),
("company_id", "=", self.company_id.id),
],
limit=1,
)
)
if not journal:
raise ValidationError(
_(
"Please define a %(contract_type)s journal "
"for the company '%(company)s'."
)
% {
"contract_type": self.contract_type,
"company": self.company_id.name or "",
}
)
invoice_type = "out_invoice"
if self.contract_type == "purchase":
invoice_type = "in_invoice"
move_form = Form(
self.env["account.move"]
.with_company(self.company_id)
.with_context(default_move_type=invoice_type)
)
move_form.partner_id = self.invoice_partner_id
if self.payment_term_id:
move_form.invoice_payment_term_id = self.payment_term_id
if self.fiscal_position_id:
move_form.fiscal_position_id = self.fiscal_position_id
if invoice_type == "out_invoice" and self.user_id:
move_form.invoice_user_id = self.user_id
invoice_vals = move_form._values_to_save(all_fields=True)
invoice_vals.update(
{
"ref": self.code,
"company_id": self.company_id.id,
"currency_id": self.currency_id.id,
"invoice_date": date_invoice,
"journal_id": journal.id,
"invoice_origin": self.name,
}
)
return invoice_vals, move_form
def action_contract_send(self):
self.ensure_one()
template = self.env.ref("contract.email_contract_template", False)
compose_form = self.env.ref("mail.email_compose_message_wizard_form")
ctx = dict(
default_model="contract.contract",
default_res_id=self.id,
default_use_template=bool(template),
default_template_id=template and template.id or False,
default_composition_mode="comment",
)
return {
"name": _("Compose Email"),
"type": "ir.actions.act_window",
"view_mode": "form",
"res_model": "mail.compose.message",
"views": [(compose_form.id, "form")],
"view_id": compose_form.id,
"target": "new",
"context": ctx,
}
@api.model
def _get_contracts_to_invoice_domain(self, date_ref=None):
"""
This method builds the domain to use to find all
contracts (contract.contract) to invoice.
:param date_ref: optional reference date to use instead of today
:return: list (domain) usable on contract.contract
"""
domain = []
if not date_ref:
date_ref = fields.Date.context_today(self)
domain.extend([("recurring_next_date", "<=", date_ref)])
return domain
def _get_lines_to_invoice(self, date_ref):
"""
This method fetches and returns the lines to invoice on the contract
(self), based on the given date.
:param date_ref: date used as reference date to find lines to invoice
:return: contract lines (contract.line recordset)
"""
self.ensure_one()
def can_be_invoiced(contract_line):
return (
not contract_line.is_canceled
and contract_line.recurring_next_date
and contract_line.recurring_next_date <= date_ref
)
lines2invoice = previous = self.env["contract.line"]
current_section = current_note = False
for line in self.contract_line_ids:
if line.display_type == "line_section":
current_section = line
elif line.display_type == "line_note" and not line.is_recurring_note:
if line.note_invoicing_mode == "with_previous_line":
if previous in lines2invoice:
lines2invoice |= line
current_note = False
elif line.note_invoicing_mode == "with_next_line":
current_note = line
elif line.is_recurring_note or not line.display_type:
if can_be_invoiced(line):
if current_section:
lines2invoice |= current_section
current_section = False
if current_note:
lines2invoice |= current_note
lines2invoice |= line
current_note = False
previous = line
return lines2invoice.sorted()
def _prepare_recurring_invoices_values(self, date_ref=False):
"""
This method builds the list of invoices values to create, based on
the lines to invoice of the contracts in self.
!!! The date of next invoice (recurring_next_date) is updated here !!!
:return: list of dictionaries (invoices values)
"""
invoices_values = []
for contract in self:
if not date_ref:
date_ref = contract.recurring_next_date
if not date_ref:
# this use case is possible when recurring_create_invoice is
# called for a finished contract
continue
contract_lines = contract._get_lines_to_invoice(date_ref)
if not contract_lines:
continue
invoice_vals, move_form = contract._prepare_invoice(date_ref)
invoice_vals["invoice_line_ids"] = []
for line in contract_lines:
invoice_line_vals = line._prepare_invoice_line(move_form=move_form)
if invoice_line_vals:
# Allow extension modules to return an empty dictionary for
# nullifying line. We should then cleanup certain values.
del invoice_line_vals["company_id"]
del invoice_line_vals["company_currency_id"]
invoice_vals["invoice_line_ids"].append((0, 0, invoice_line_vals))
invoices_values.append(invoice_vals)
# Force the recomputation of journal items
del invoice_vals["line_ids"]
contract_lines._update_recurring_next_date()
return invoices_values
def recurring_create_invoice(self):
"""
This method triggers the creation of the next invoices of the contracts
even if their next invoicing date is in the future.
"""
invoice = self._recurring_create_invoice()
if invoice:
self.message_post(
body=_(
"Contract manually invoiced: "
"<a"
' href="#" data-oe-model="%(model_name)s" '
' data-oe-id="%(rec_id)s"'
">Invoice"
"</a>"
)
% {
"model_name": invoice._name,
"rec_id": invoice.id,
}
)
return invoice
@api.model
def _invoice_followers(self, invoices):
invoice_create_subtype = self.env.ref(
"contract.mail_message_subtype_invoice_created"
)
for item in self:
partner_ids = item.message_follower_ids.filtered(
lambda x: invoice_create_subtype in x.subtype_ids
).mapped("partner_id")
if partner_ids:
(invoices & item._get_related_invoices()).message_subscribe(
partner_ids=partner_ids.ids
)
@api.model
def _add_contract_origin(self, invoices):
for item in self:
for move in invoices & item._get_related_invoices():
move.message_post(
body=(
_(
(
"%(msg)s by contract <a href=# data-oe-model=contract.contract"
" data-oe-id=%(contract_id)d>%(contract)s</a>."
),
msg=move._creation_message(),
contract_id=item.id,
contract=item.display_name,
)
)
)
def _recurring_create_invoice(self, date_ref=False):
invoices_values = self._prepare_recurring_invoices_values(date_ref)
moves = self.env["account.move"].create(invoices_values)
self._add_contract_origin(moves)
self._invoice_followers(moves)
self._compute_recurring_next_date()
return moves
@api.model
def _get_recurring_create_func(self, create_type="invoice"):
"""
Allows to retrieve the recurring create function depending
on generate_type attribute
"""
if create_type == "invoice":
return self.__class__._recurring_create_invoice
@api.model
def _cron_recurring_create(self, date_ref=False, create_type="invoice"):
"""
The cron function in order to create recurrent documents
from contracts.
"""
_recurring_create_func = self._get_recurring_create_func(
create_type=create_type
)
if not date_ref:
date_ref = fields.Date.context_today(self)
domain = self._get_contracts_to_invoice_domain(date_ref)
domain = expression.AND(
[
domain,
[("generation_type", "=", create_type)],
]
)
contracts = self.search(domain)
companies = set(contracts.mapped("company_id"))
# Invoice by companies, so assignation emails get correct context
for company in companies:
contracts_to_invoice = contracts.filtered(
lambda c: c.company_id == company
and (not c.date_end or c.recurring_next_date <= c.date_end)
).with_company(company)
_recurring_create_func(contracts_to_invoice, date_ref)
return True
@api.model
def cron_recurring_create_invoice(self, date_ref=None):
return self._cron_recurring_create(date_ref, create_type="invoice")
def action_terminate_contract(self):
self.ensure_one()
context = {"default_contract_id": self.id}
return {
"type": "ir.actions.act_window",
"name": _("Terminate Contract"),
"res_model": "contract.contract.terminate",
"view_mode": "form",
"target": "new",
"context": context,
}
def _terminate_contract(
self, terminate_reason_id, terminate_comment, terminate_date
):
self.ensure_one()
if not self.env.user.has_group("contract.can_terminate_contract"):
raise UserError(_("You are not allowed to terminate contracts."))
self.contract_line_ids.filtered("is_stop_allowed").stop(terminate_date)
self.write(
{
"is_terminated": True,
"terminate_reason_id": terminate_reason_id.id,
"terminate_comment": terminate_comment,
"terminate_date": terminate_date,
}
)
return True
def action_cancel_contract_termination(self):
self.ensure_one()
self.write(
{
"is_terminated": False,
"terminate_reason_id": False,
"terminate_comment": False,
"terminate_date": False,
}
)
| 37.817039 | 27,077 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.