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
|
|---|---|---|---|---|---|---|
303
|
py
|
PYTHON
|
15.0
|
from odoo import models
class Picking(models.Model):
_inherit = "stock.picking"
def action_confirm(self):
res = super().action_confirm()
picking_priority = self.env.context.get("sale_priority", False)
self.write({"priority": picking_priority or 0})
return res
| 27.545455
| 303
|
1,500
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.addons.stock.models import stock_move
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
priority = fields.Selection(stock_move.PROCUREMENT_PRIORITIES, default="0")
class SaleOrder(models.Model):
_inherit = "sale.order"
priority = fields.Selection(
stock_move.PROCUREMENT_PRIORITIES,
compute="_compute_priority",
inverse="_inverse_priority",
store=True,
index=True,
tracking=True,
states={"done": [("readonly", True)], "cancel": [("readonly", True)]},
help="Priority for this sale order. "
"Setting manually a value here would set it as priority "
"for all the order lines",
)
@api.depends("order_line.priority")
def _compute_priority(self):
for order in self.filtered(lambda x: x.order_line):
priority = order.mapped("order_line.priority")
order.priority = max([x for x in priority if x] or "0")
def _inverse_priority(self):
for order in self:
priority = order.priority
for line in order.order_line.filtered(lambda x: x.priority != priority):
line.priority = priority
def action_confirm(self):
return super(
SaleOrder, self.with_context(sale_priority=self.priority)
).action_confirm()
| 32.608696
| 1,500
|
468
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Sale Stock Cancel Restriction",
"version": "15.0.1.0.1",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"category": "Sales Management",
"license": "AGPL-3",
"development_status": "Production/Stable",
"depends": ["sale_stock"],
"installable": True,
}
| 33.428571
| 468
|
1,645
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.exceptions import UserError
from odoo.tests import Form, TransactionCase
class TestSaleStockCancelRestriction(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.product = cls.env["product.product"].create(
{"name": "Product test", "type": "product"}
)
cls.partner = cls.env["res.partner"].create({"name": "Partner test"})
so_form = Form(cls.env["sale.order"])
so_form.partner_id = cls.partner
with so_form.order_line.new() as soline_form:
soline_form.product_id = cls.product
soline_form.product_uom_qty = 2
cls.sale_order = so_form.save()
cls.sale_order.action_confirm()
cls.picking = cls.sale_order.picking_ids
cls.picking.move_lines.quantity_done = 2
def test_cancel_sale_order_restrict(self):
"""Validates the picking and do the assertRaises cancelling the
order for checking that it's forbidden
"""
self.picking.button_validate()
with self.assertRaises(UserError):
self.sale_order.action_cancel()
def test_cancel_sale_order_ok(self):
"""Don't validate the picking and cancel the order, being completed."""
# check the status of invoices after cancelling the order
self.sale_order.action_cancel()
self.assertEqual(
self.sale_order.picking_ids.state,
"cancel",
"After cancelling a picking, the state should be cancelled",
)
| 39.166667
| 1,645
|
539
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def action_cancel(self):
"""Force to call the cancel method on done picking for having the
expected error, as Odoo has now filter out such pickings from the
cancel operation.
"""
self.mapped("picking_ids").filtered(lambda r: r.state == "done").action_cancel()
return super().action_cancel()
| 33.6875
| 539
|
474
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
def pre_init_hook(cr):
"""Create computed columns if not exists when the module is instelled"""
cr.execute(
"""
ALTER TABLE sale_order_line
ADD COLUMN IF NOT EXISTS is_elaboration BOOLEAN;
"""
)
cr.execute(
"""
ALTER TABLE sale_order_line ADD COLUMN IF NOT EXISTS elaboration_note VARCHAR;
"""
)
| 27.882353
| 474
|
1,043
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Sale Elaboration",
"summary": "Set an elaboration for any sale line",
"version": "15.0.3.2.0",
"development_status": "Production/Stable",
"category": "Sale",
"website": "https://github.com/OCA/sale-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["sale_stock"],
"data": [
"security/ir.model.access.csv",
"security/security.xml",
"views/product_views.xml",
"views/res_config_settings_views.xml",
"views/sale_elaboration_profile_views.xml",
"views/sale_elaboration_views.xml",
"views/sale_order_views.xml",
"views/sale_elaboration_report_views.xml",
"views/stock_move_views.xml",
"views/stock_picking_views.xml",
"reports/report_deliveryslip.xml",
],
"pre_init_hook": "pre_init_hook",
}
| 35.965517
| 1,043
|
799
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
# Copy elaborations from sale order lines to stock moves
openupgrade.logged_query(
env.cr,
"""
INSERT INTO product_elaboration_stock_move_rel
(stock_move_id, product_elaboration_id)
SELECT sm.id AS stock_move_id,
pesol.product_elaboration_id AS product_elaboration_id
FROM stock_move sm
LEFT JOIN product_elaboration_sale_order_line_rel pesol
ON pesol.sale_order_line_id = sm.sale_line_id
WHERE sm.sale_line_id is not null AND pesol.product_elaboration_id is not null
""",
)
| 34.73913
| 799
|
289
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.rename_columns(env.cr, {"sale_order_line": [("elaboration_id", None)]})
| 32.111111
| 289
|
393
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.m2o_to_x2m(
env.cr,
env["sale.order.line"],
"sale_order_line",
"elaboration_ids",
openupgrade.get_legacy_name("elaboration_id"),
)
| 24.5625
| 393
|
6,983
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import Form, TransactionCase, tagged
@tagged("post_install", "-at_install")
class TestSaleElaboration(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.Elaboration = cls.env["product.elaboration"]
cls.product = cls.env["product.product"].create(
{"name": "test", "tracking": "none", "list_price": 1000}
)
cls.product_elaboration_A = cls.env["product.product"].create(
{
"name": "Product Elaboration A",
"type": "service",
"list_price": 50.0,
"invoice_policy": "order",
"is_elaboration": True,
}
)
cls.product_elaboration_B = cls.env["product.product"].create(
{
"name": "Product Elaboration B",
"type": "service",
"list_price": 25.0,
"invoice_policy": "order",
"is_elaboration": True,
}
)
cls.pricelist = cls.env["product.pricelist"].create(
{
"name": "Test pricelist",
"item_ids": [
(
0,
0,
{
"applied_on": "3_global",
"compute_price": "formula",
"base": "list_price",
},
)
],
}
)
cls.partner = cls.env["res.partner"].create(
{"name": "test - partner", "property_product_pricelist": cls.pricelist.id}
)
cls.elaboration_a = cls.Elaboration.create(
{
"code": "AA",
"name": "Elaboration A",
"product_id": cls.product_elaboration_A.id,
}
)
cls.elaboration_b = cls.Elaboration.create(
{
"code": "BB",
"name": "Elaboration B",
"product_id": cls.product_elaboration_B.id,
}
)
cls.order = cls._create_sale_order(
cls, [(cls.product, 10, [cls.elaboration_a])]
)
def _create_sale_order(self, products_info):
order_form = Form(self.env["sale.order"])
order_form.partner_id = self.partner
for product, qty, elaborations in products_info:
with order_form.order_line.new() as line_form:
line_form.product_id = product
line_form.product_uom_qty = qty
for elaboration in elaborations:
line_form.elaboration_ids.add(elaboration)
return order_form.save()
def test_search_elaboration(self):
elaboration = self.Elaboration.name_search("Elaboration")
self.assertEqual(len(elaboration), 2)
elaboration = self.Elaboration.name_search("AA")
self.assertEqual(len(elaboration), 1)
def test_sale_elaboration_change(self):
self.order.order_line.elaboration_ids = self.elaboration_b
self.assertEqual(self.order.order_line.elaboration_note, "Elaboration B")
def test_sale_elaboration(self):
self.order.action_confirm()
self.order.picking_ids.move_lines.quantity_done = 10.0
self.order.picking_ids._action_done()
elaboration_lines = self.order.order_line.filtered("is_elaboration")
self.assertEqual(len(elaboration_lines), 1)
self.assertEqual(elaboration_lines.price_unit, 50.0)
def test_sale_elaboration_multi(self):
self.order.order_line.create(
{
"order_id": self.order.id,
"product_id": self.product_elaboration_A.id,
"product_uom_qty": 1.0,
"price_unit": 50.0,
"is_elaboration": True,
}
)
self.order.action_confirm()
self.order.picking_ids.move_lines.quantity_done = 10.0
self.order.picking_ids._action_done()
elaboration_lines = self.order.order_line.filtered("is_elaboration")
self.assertEqual(len(elaboration_lines), 1)
self.assertEqual(elaboration_lines.product_uom_qty, 11.0)
def test_invoice_elaboration(self):
self.order = self._create_sale_order(
[
(self.product_elaboration_A, 1, []),
(self.product_elaboration_B, 1, []),
]
)
self.order.order_line.filtered(
lambda l: l.product_id == self.product_elaboration_B
).is_elaboration = False
self.order.action_confirm()
invoice = self.order._create_invoices()
so_line_elaboration = self.order.order_line.filtered("is_elaboration")
so_line_no_elaboration = self.order.order_line - so_line_elaboration
inv_line_elaboration = invoice.invoice_line_ids.filtered(
lambda x: x.sale_line_ids == so_line_elaboration
)
inv_line_no_elaboration = invoice.invoice_line_ids.filtered(
lambda x: x.sale_line_ids == so_line_no_elaboration
)
self.assertEqual(
inv_line_elaboration.name,
"{} - {}".format(self.order.name, so_line_elaboration.name),
)
self.assertNotEqual(
inv_line_no_elaboration.name,
"{} - {}".format(self.order.name, so_line_no_elaboration.name),
)
def test_sale_elaboration_change_product(self):
self.order.order_line.product_id = self.product_elaboration_A
self.order.order_line.product_id_change()
self.assertTrue(self.order.order_line.is_elaboration)
self.order.order_line.product_id = self.product
self.order.order_line.product_id_change()
self.assertFalse(self.order.order_line.is_elaboration)
def test_multi_elaboration_per_line(self):
product2 = self.env["product.product"].create({"name": "product 2"})
with Form(self.order) as order_form:
with order_form.order_line.new() as line_form:
line_form.product_id = product2
line_form.product_uom_qty = 1
line_form.elaboration_ids.add(self.elaboration_a)
line_form.elaboration_ids.add(self.elaboration_b)
self.order.action_confirm()
move_lines = self.order.picking_ids.move_lines
move_line_a = move_lines.filtered(lambda r: r.product_id == self.product)
move_line_a.quantity_done = 10.0
move_line_b = move_lines.filtered(lambda r: r.product_id == product2)
move_line_b.quantity_done = 1.0
self.order.picking_ids._action_done()
elaboration_lines = self.order.order_line.filtered("is_elaboration")
self.assertEqual(len(elaboration_lines), 2)
self.assertEqual(sum(elaboration_lines.mapped("product_uom_qty")), 12.0)
| 41.076471
| 6,983
|
1,310
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Sergio Teruel
# Copyright 2023 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ProductElaborationMixin(models.AbstractModel):
_name = "product.elaboration.mixin"
_description = "Product Elaboration Mixin"
elaboration_ids = fields.Many2many(
comodel_name="product.elaboration",
string="Elaborations",
)
elaboration_note = fields.Char(
store=True,
compute="_compute_elaboration_note",
readonly=False,
)
is_elaboration = fields.Boolean(
store=True,
compute="_compute_is_elaboration",
readonly=False,
)
@api.depends("elaboration_ids")
def _compute_elaboration_note(self):
for line in self:
line.elaboration_note = ", ".join(line.elaboration_ids.mapped("name"))
@api.depends("product_id")
def _compute_is_elaboration(self):
"""We use computed instead of a related field because related fields are not
initialized with their value on one2many which related field is the
inverse_name, so with this we get immediately the value on NewIds.
"""
for line in self:
line.is_elaboration = line.product_id.is_elaboration
| 34.473684
| 1,310
|
3,128
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Sergio Teruel
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
def _execute_onchanges(records, field_name):
"""Helper methods that executes all onchanges associated to a field."""
for onchange in records._onchange_methods.get(field_name, []):
for record in records:
onchange(record)
class SaleOrder(models.Model):
_inherit = "sale.order"
def _create_elaboration_line(self, product, qty):
"""Create a sale order line from a elaboration product, search a line
with the same elaboration product to add qty
:param product:
:param qty:
:return: the sale order line record created
"""
SaleOrderLine = self.env["sale.order.line"]
sol_for_product = self.order_line.filtered(lambda x: x.product_id == product)[
:1
]
if sol_for_product:
sol_for_product.product_uom_qty += qty
return sol_for_product
sol = SaleOrderLine.new(
{"order_id": self.id, "product_id": product.id, "is_elaboration": True}
)
_execute_onchanges(sol, "product_id")
sol.update({"product_uom_qty": qty})
_execute_onchanges(sol, "product_uom_qty")
vals = sol._convert_to_write(sol._cache)
if self.order_line:
vals["sequence"] = self.order_line[-1].sequence + 1
return SaleOrderLine.sudo().create(vals)
class SaleOrderLine(models.Model):
_inherit = ["sale.order.line", "product.elaboration.mixin"]
_name = "sale.order.line"
date_order = fields.Datetime(related="order_id.date_order", string="Date")
route_id = fields.Many2one(compute="_compute_route_id", store=True, readonly=False)
elaboration_profile_id = fields.Many2one(
related="product_id.elaboration_profile_id"
)
elaboration_price_unit = fields.Float(
"Elab. Price", compute="_compute_elaboration_price_unit", store=True
)
def get_elaboration_stock_route(self):
self.ensure_one()
return self.elaboration_ids.route_ids[:1]
@api.depends("elaboration_ids")
def _compute_route_id(self):
for line in self:
route_id = line.get_elaboration_stock_route()
if route_id:
line.route_id = route_id
@api.depends("elaboration_ids", "order_id.pricelist_id")
def _compute_elaboration_price_unit(self):
for line in self:
elab_price = 0.0
for elaboration in line.elaboration_ids:
elab_price += elaboration.product_id.with_context(
pricelist=line.order_id.pricelist_id.id,
uom=elaboration.product_id.uom_id.id,
).price
line.elaboration_price_unit = elab_price
def _prepare_invoice_line(self, **optional_values):
vals = super()._prepare_invoice_line(**optional_values)
if self.is_elaboration:
vals["name"] = "{} - {}".format(self.order_id.name, self.name)
return vals
| 38.146341
| 3,128
|
1,717
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
is_elaboration = fields.Boolean()
elaboration_profile_id = fields.Many2one(
comodel_name="product.elaboration.profile",
compute="_compute_elaboration_profile_id",
inverse="_inverse_elaboration_profile_id",
store=True,
)
@api.depends("product_variant_ids", "product_variant_ids.elaboration_profile_id")
def _compute_elaboration_profile_id(self):
unique_variants = self.filtered(lambda tmpl: tmpl.product_variant_count == 1)
for template in unique_variants:
template.elaboration_profile_id = (
template.product_variant_ids.elaboration_profile_id
)
for template in self - unique_variants:
template.elaboration_profile_id = False
def _inverse_elaboration_profile_id(self):
for template in self:
if len(template.product_variant_ids) == 1:
template.product_variant_ids.elaboration_profile_id = (
template.elaboration_profile_id
)
@api.model_create_multi
def create(self, vals_list):
templates = super(ProductTemplate, self).create(vals_list)
# This is needed to set given values to first variant after creation
for template, vals in zip(templates, vals_list):
if vals.get("elaboration_profile_id"):
template.write(
{"elaboration_profile_id": vals["elaboration_profile_id"]}
)
return templates
| 39.930233
| 1,717
|
819
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Sergio Teruel
# Copyright 2023 Tecnativa - Carlos Dauden
# 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", "product.elaboration.mixin"]
_name = "stock.move"
@api.model
def _prepare_merge_moves_distinct_fields(self):
"""Don't merge moves with distinct elaborations"""
distinct_fields = super()._prepare_merge_moves_distinct_fields()
distinct_fields += ["elaboration_ids", "elaboration_note"]
return distinct_fields
class StockMoveLine(models.Model):
_inherit = "stock.move.line"
elaboration_ids = fields.Many2many(related="move_id.elaboration_ids")
elaboration_note = fields.Char(related="move_id.elaboration_note")
| 35.608696
| 819
|
1,869
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Sergio Teruel
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class Elaboration(models.Model):
_name = "product.elaboration"
_description = "Product elaborations"
name = fields.Char(required=True, translate=True)
code = fields.Char(string="Short Code")
product_id = fields.Many2one(
comodel_name="product.product",
string="Product",
ondelete="restrict",
domain=[("type", "=", "service"), ("is_elaboration", "=", True)],
required=True,
)
active = fields.Boolean(
default=True,
help="If unchecked, it will allow you to hide the product "
"elaborations without removing it.",
)
route_ids = fields.Many2many(
comodel_name="stock.location.route",
string="Routes",
domain=[("sale_selectable", "=", True)],
ondelete="restrict",
check_company=True,
)
profile_ids = fields.Many2many(
comodel_name="product.elaboration.profile",
relation="product_elaboration_profile_rel",
column1="elaboration_id",
column2="profile_id",
)
_sql_constraints = [
("name_uniq", "unique(name)", "Name must be unique!"),
("code_uniq", "unique(code)", "Code must be unique!"),
]
@api.model
def name_search(self, name, args=None, operator="ilike", limit=100):
"""Give preference to codes on name search, appending
the rest of the results after.
"""
args = args or []
recs = self.browse()
if name:
recs = self.search([("code", "=ilike", name)] + args, limit=limit)
if not recs:
recs = self.search([("name", operator, name)] + args, limit=limit)
return recs.name_get()
| 33.981818
| 1,869
|
702
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Sergio Teruel
# Copyright 2023 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductElaborationProfile(models.Model):
_name = "product.elaboration.profile"
_description = "Product elaboration profiles"
name = fields.Char(required=True, translate=True)
code = fields.Char(string="Short Code")
active = fields.Boolean(default=True)
elaboration_ids = fields.Many2many(
string="Elaborations",
comodel_name="product.elaboration",
relation="product_elaboration_profile_rel",
column1="profile_id",
column2="elaboration_id",
)
| 35.1
| 702
|
700
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class StockPicking(models.Model):
_inherit = "stock.picking"
def _action_done(self):
res = super()._action_done()
for pick in self.filtered(lambda x: x.picking_type_code == "outgoing"):
elaboration_lines = pick.move_lines.filtered(
lambda x: x.sale_line_id.elaboration_ids
)
for line in elaboration_lines:
for product in line.sale_line_id.elaboration_ids.product_id:
pick.sale_id._create_elaboration_line(product, line.quantity_done)
return res
| 38.888889
| 700
|
336
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ProductProduct(models.Model):
_inherit = "product.product"
elaboration_profile_id = fields.Many2one(
comodel_name="product.elaboration.profile", ondelete="restrict"
)
| 30.545455
| 336
|
1,267
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import models
class StockRule(models.Model):
_inherit = "stock.rule"
def _get_stock_move_values(
self,
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
):
res = super()._get_stock_move_values(
product_id,
product_qty,
product_uom,
location_id,
name,
origin,
company_id,
values,
)
sale_line_id = values.get("sale_line_id", False)
# Record can be a sale order line or a stock move depending of pull
# and push rules
if sale_line_id:
record = self.env["sale.order.line"].browse(sale_line_id)
else:
record = values.get("move_dest_ids", self.env["stock.move"].browse())[:1]
if record and record.elaboration_ids:
res.update(
{
"elaboration_ids": [(6, 0, record.elaboration_ids.ids)],
"elaboration_note": record.elaboration_note,
}
)
return res
| 28.795455
| 1,267
|
434
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
group_elaboration_note_on_delivery_slip = fields.Boolean(
"Display Elaboration notes on Delivery Slips",
implied_group="sale_elaboration.group_elaboration_note_on_delivery_slip",
)
| 33.384615
| 434
|
483
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2020 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Sale Order Archive",
"summary": "Archive Sale Orders",
"author": "Onestein, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"category": "Sales",
"version": "15.0.1.0.1",
"license": "AGPL-3",
"depends": ["sale"],
"data": ["views/sale_order.xml"],
"installable": True,
}
| 32.2
| 483
|
1,538
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.exceptions import UserError
from odoo.tests import Form, TransactionCase
class TestSaleOrderArchive(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
test_context = cls.env.context.copy()
test_context["test_carrier_auto_assign"] = True
cls.env = cls.env(context=dict(test_context, tracking_disable=True))
cls.partner = cls.env.ref("base.res_partner_2")
product = cls.env.ref("product.product_product_9")
cls.normal_delivery_carrier = cls.env.ref("delivery.normal_delivery_carrier")
cls.normal_delivery_carrier.fixed_price = 10
sale_order_form = Form(cls.env["sale.order"])
sale_order_form.partner_id = cls.partner
with sale_order_form.order_line.new() as line_form:
line_form.product_id = product
cls.sale_order = sale_order_form.save()
def test_sale_order_archive_toggle_active(self):
self.assertTrue(self.sale_order.active)
self.sale_order.state = "done"
self.sale_order.toggle_active()
self.assertFalse(self.sale_order.active)
def test_sale_order_archive_donot_toggle_active(self):
self.assertTrue(self.sale_order.active)
regex = r"Only 'Locked' or 'Canceled' orders can be archived"
with self.assertRaisesRegex(UserError, regex):
self.sale_order.toggle_active()
self.assertTrue(self.sale_order.active)
| 43.942857
| 1,538
|
543
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-2020 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, fields, models
from odoo.exceptions import UserError
class SaleOrder(models.Model):
_inherit = "sale.order"
active = fields.Boolean(default=True)
def toggle_active(self):
if self.filtered(lambda so: so.state not in ["done", "cancel"] and so.active):
raise UserError(_("Only 'Locked' or 'Canceled' orders can be archived"))
return super().toggle_active()
| 33.9375
| 543
|
537
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-15 Agile Business Group sagl (<http://www.agilebg.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sale order line description",
"version": "15.0.1.0.0",
"category": "Sales Management",
"author": "Agile Business Group, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"license": "AGPL-3",
"depends": ["sale"],
"data": ["security/sale_security.xml", "views/res_config_settings_views.xml"],
"installable": True,
}
| 41.307692
| 537
|
2,873
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import odoo.tests.common as common
from odoo.tests import tagged
@tagged("post_install", "-at_install")
class TestSaleOrderLineDescriptionChange(common.TransactionCase):
def setUp(self):
super(TestSaleOrderLineDescriptionChange, self).setUp()
# Create models
self.sale_order_model = self.env["sale.order"]
self.sale_order_line_model = self.env["sale.order.line"]
self.partner_model = self.env["res.partner"]
self.product_model = self.env["product.product"]
self.user_model = self.env["res.users"].with_context(
no_reset_password=True, mail_create_nosubscribe=True
)
# Create two different users
self.group_only_sale_description = self.env.ref(
"sale_order_line_description.group_use_product_description_per_so_line"
)
self.user_1 = self._create_user("TestUser1")
self.user_2 = self._create_user("TestUser2", self.group_only_sale_description)
# Create the sale order
self.partner = self.partner_model.create({"name": "Test partner"})
self.sale_order = self.sale_order_model.create({"partner_id": self.partner.id})
self.product = self.product_model.create(
{
"name": "Test product",
"description_sale": "Sale description for test product",
}
)
def _create_user(self, name, group=None):
groups_id = self.env.user.groups_id
if group:
groups_id += group
return self.user_model.create(
{
"name": name,
"login": name,
"email": name + "@example.com",
"groups_id": groups_id,
}
)
def test_check_sale_order_line_description(self):
line_values = {"order_id": self.sale_order.id, "product_id": self.product.id}
# Create sale order line with TestUser1
sale_order_line = self.sale_order_line_model.with_user(self.user_1).create(
line_values.copy()
)
self.assertEqual(
sale_order_line.name,
"\n".join([self.product.name, self.product.description_sale]),
"Standard behavior does not concatenate "
"product description and product sale description",
)
# Create sale order line with TestUser2
sale_order_line = self.sale_order_line_model.with_user(self.user_2).create(
line_values.copy()
)
self.assertEqual(
sale_order_line.name,
self.product.description_sale,
"Adding group "
+ self.group_only_sale_description.name
+ " does not modify sale order line description",
)
| 37.311688
| 2,873
|
936
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-15 Agile Business Group sagl (<http://www.agilebg.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
@api.onchange("product_id")
def product_id_change(self):
res = super(SaleOrderLine, self).product_id_change()
if not self.product_id: # pragma: no cover
return res
if (
self.user_has_groups(
"sale_order_line_description."
"group_use_product_description_per_so_line"
)
and self.product_id.description_sale
):
product = self.product_id
if self.order_id.partner_id:
product = product.with_context(
lang=self.order_id.partner_id.lang,
)
self.name = product.description_sale
return res
| 33.428571
| 936
|
634
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-15 Agile Business Group sagl (<http://www.agilebg.com>)
# 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"
group_use_product_description_per_so_line = fields.Boolean(
string="Allow using only the product sale description on the sales order "
"lines",
implied_group="sale_order_line_description."
"group_use_product_description_per_so_line",
help="Allows you to use only product sale description on the "
"sales order line.",
)
| 37.294118
| 634
|
498
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Sale Partner Selectable Option",
"version": "15.0.1.0.1",
"category": "Sales Management",
"website": "https://github.com/OCA/sale-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["sale"],
"data": ["views/res_partner_view.xml"],
"installable": True,
"maintainers": ["victoralmau"],
}
| 35.428571
| 496
|
697
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo.tests import common
class TestSalePartnerSelectableOption(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
def test_sale_order(self):
result = self.env["sale.order"].fields_view_get(
view_id=self.env.ref("sale.view_order_form").id,
view_type="form",
)
doc = etree.XML(result["arch"])
field = doc.xpath("//field[@name='partner_id']")
domain = field[0].get("domain")
self.assertTrue("('sale_selectable', '=', True)" in domain)
| 33.095238
| 695
|
1,050
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo import api, models
class SaleOrder(models.Model):
_inherit = "sale.order"
@api.model
def fields_view_get(
self, view_id=None, view_type="form", toolbar=False, submenu=False
):
res = super().fields_view_get(
view_id=view_id,
view_type=view_type,
toolbar=toolbar,
submenu=submenu,
)
if view_type == "form":
order_xml = etree.XML(res["arch"])
partner_id_fields = order_xml.xpath("//field[@name='partner_id']")
if partner_id_fields:
partner_id_field = partner_id_fields[0]
domain = partner_id_field.get("domain", "[]").replace(
"[", "[('sale_selectable', '=', True),"
)
partner_id_field.attrib["domain"] = domain
res["arch"] = etree.tostring(order_xml)
return res
| 32.75
| 1,048
|
293
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class Partner(models.Model):
_inherit = "res.partner"
sale_selectable = fields.Boolean(string="Selectable in sale orders", default=True)
| 29.1
| 291
|
705
|
py
|
PYTHON
|
15.0
|
# © 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sale Commercial Partner",
"summary": "Add stored related field 'Commercial Entity' on sale orders",
"version": "15.0.1.0.2",
"development_status": "Production/Stable",
"author": "Akretion,Odoo Community Association (OCA)",
"maintainers": ["alexis-via"],
"website": "https://github.com/OCA/sale-workflow",
"category": "Sales",
"license": "AGPL-3",
"contributors": ["Serpent Consulting Services Pvt. Ltd. <support@serpentcs.com>"],
"depends": ["sale"],
"data": ["views/sale_views.xml"],
"installable": True,
}
| 39.111111
| 704
|
443
|
py
|
PYTHON
|
15.0
|
# © 2016 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
commercial_partner_id = fields.Many2one(
comodel_name="res.partner",
string="Commercial Entity",
related="partner_id.commercial_partner_id",
store=True,
index=True,
)
| 27.625
| 442
|
607
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Cédric Pigeon, ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Sale Product Multi Add",
"summary": """
Sale Product Multi Add """,
"author": "ACSONE SA/NV, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"category": "Sale Management",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"depends": ["sale"],
"data": [
"security/ir.model.access.csv",
"wizards/sale_import_products_view.xml",
"views/sale_view.xml",
],
}
| 33.666667
| 606
|
1,342
|
py
|
PYTHON
|
15.0
|
# © 2016 Cédric Pigeon, Acsone SA/NV (http://www.acsone.eu)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import odoo.tests.common as common
class TestSale(common.TransactionCase):
def setUp(self):
super(TestSale, self).setUp()
self.product_9 = self.env.ref("product.product_product_9")
self.product_11 = self.env.ref("product.product_product_11")
def test_import_product(self):
"""Create SO
Import products
Check products are presents
"""
so = self.env["sale.order"].create(
{"partner_id": self.env.ref("base.res_partner_2").id}
)
wiz_obj = self.env["sale.import.products"]
wizard = wiz_obj.with_context(active_id=so.id, active_model="sale.order")
products = [(6, 0, [self.product_9.id, self.product_11.id])]
wizard_id = wizard.create({"products": products})
wizard_id.create_items()
wizard_id.items[0].quantity = 4
wizard_id.items[1].quantity = 6
wizard_id.select_products()
self.assertEqual(len(so.order_line), 2)
for line in so.order_line:
if line.product_id.id == self.product_9.id:
self.assertEqual(line.product_uom_qty, 4)
else:
self.assertEqual(line.product_uom_qty, 6)
| 33.5
| 1,340
|
2,621
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Cédric Pigeon, ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class SaleImportProducts(models.TransientModel):
_name = "sale.import.products"
_description = "Sale Import Products"
products = fields.Many2many(comodel_name="product.product")
items = fields.One2many(
comodel_name="sale.import.products.items",
inverse_name="wizard_id",
)
def create_items(self):
for wizard in self:
for product in wizard.products:
self.env["sale.import.products.items"].create(
{"wizard_id": wizard.id, "product_id": product.id}
)
view = self.env.ref("sale_product_multi_add.view_import_product_to_sale2")
return {
"type": "ir.actions.act_window",
"res_model": self._name,
"view_type": "form",
"view_mode": "form",
"views": [(view.id, "form")],
"target": "new",
"res_id": self.id,
"context": self.env.context,
}
@api.model
def _get_line_values(self, sale, item):
sale_line = self.env["sale.order.line"].new(
{
"order_id": sale.id,
"name": item.product_id.name,
"product_id": item.product_id.id,
"product_uom_qty": item.quantity,
"product_uom": item.product_id.uom_id.id,
"price_unit": item.product_id.list_price,
}
)
sale_line.product_id_change()
line_values = sale_line._convert_to_write(sale_line._cache)
return line_values
def select_products(self):
so_obj = self.env["sale.order"]
for wizard in self:
sale = so_obj.browse(self.env.context.get("active_id", False))
if sale:
for item in wizard.items:
vals = self._get_line_values(sale, item)
if vals:
self.env["sale.order.line"].create(vals)
return {"type": "ir.actions.act_window_close"}
class SaleImportProductsItem(models.TransientModel):
_name = "sale.import.products.items"
_description = "Sale Import Products Items"
wizard_id = fields.Many2one(string="Wizard", comodel_name="sale.import.products")
product_id = fields.Many2one(
string="Product", comodel_name="product.product", required=True
)
quantity = fields.Float(
digits="Product Unit of Measure", default=1.0, required=True
)
| 34.933333
| 2,620
|
604
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Alex Comba - Agile Business Group
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sale Delivery Split Date",
"version": "15.0.1.0.0",
"summary": "Sale Deliveries split by date",
"category": "Sales Management",
"license": "AGPL-3",
"author": "Agile Business Group, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"depends": [
"sale_order_line_date",
"sale_procurement_group_by_line",
],
"data": [
"views/stock_picking.xml",
],
"installable": True,
}
| 30.2
| 604
|
4,920
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Alex Comba - Agile Business Group
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import datetime
from odoo.tests.common import TransactionCase
from odoo.tools import format_date
class TestSaleDelivery(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
customer = cls.env.ref("base.res_partner_3")
p1 = cls.env.ref("product.product_product_16")
p2 = cls.env.ref("product.product_product_25")
today = datetime.datetime(2020, 1, 1)
cls.dt1 = today + datetime.timedelta(days=9)
cls.dt2 = today + datetime.timedelta(days=10)
cls.date_sooner = cls.dt1
cls.date_later = cls.dt2
cls.so = cls._create_sale_order(customer)
cls.so_line1 = cls._create_sale_order_line(cls.so, p1, 10, 100.0, cls.dt1)
cls.so_line2 = cls._create_sale_order_line(cls.so, p2, 10, 200.0, cls.dt1)
@classmethod
def _create_sale_order(cls, customer):
return cls.env["sale.order"].create({"partner_id": customer.id})
@classmethod
def _create_sale_order_line(cls, sale, product, qty, price, date):
return cls.env["sale.order.line"].create(
{
"product_id": product.id,
"name": "cool product",
"order_id": sale.id,
"price_unit": price,
"product_uom_qty": qty,
"commitment_date": date,
}
)
def test_check_single_date(self):
self.assertEqual(
len(self.so.picking_ids),
0,
"There must not be pickings for the SO when draft",
)
self.so.action_confirm()
self.assertEqual(
len(self.so.picking_ids),
1,
"There must be 1 picking for the SO when confirmed",
)
self.assertEqual(
self.so.picking_ids[0].scheduled_date,
self.date_sooner,
"The picking must be planned at the expected date",
)
self.assertEqual(
self.so_line1.procurement_group_id,
self.so_line2.procurement_group_id,
"The procurement group must be the same",
)
self.assertIn(
format_date(self.env, self.date_sooner.date()),
self.so_line1.procurement_group_id.name,
)
def test_check_multiple_dates(self):
# Change the date of the second line
self.so_line2.commitment_date = self.dt2
self.assertEqual(
len(self.so.picking_ids),
0,
"There must not be pickings for the SO when draft",
)
self.so.action_confirm()
self.assertEqual(
len(self.so.picking_ids),
2,
"There must be 2 pickings for the SO when confirmed",
)
sorted_pickings = self.so.picking_ids.sorted(lambda x: x.scheduled_date)
self.assertEqual(
sorted_pickings[0].scheduled_date,
self.date_sooner,
"The first picking must be planned at the soonest date",
)
self.assertEqual(
sorted_pickings[1].scheduled_date,
self.date_later,
"The second picking must be planned at the latest date",
)
self.assertNotEqual(
self.so_line1.procurement_group_id,
self.so_line2.procurement_group_id,
"The procurement group must be different",
)
self.assertIn(
format_date(self.env, self.date_sooner.date()),
self.so_line1.procurement_group_id.name,
)
self.assertIn(
format_date(self.env, self.date_later.date()),
self.so_line2.procurement_group_id.name,
)
def test_check_same_dates(self):
# Change the date of the second line by just adding 1 hour
same_date = self.dt1 + datetime.timedelta(hours=1)
self.so_line2.commitment_date = same_date
self.assertEqual(
len(self.so.picking_ids),
0,
"There must not be pickings for the SO when draft",
)
self.so.action_confirm()
self.assertEqual(
len(self.so.picking_ids),
1,
"There must be only one picking for the SO when confirmed",
)
self.assertEqual(
self.so.picking_ids.scheduled_date,
self.date_sooner,
"The picking must be planned at the expected date",
)
self.assertEqual(
self.so_line1.procurement_group_id,
self.so_line2.procurement_group_id,
"The procurement group must be the same",
)
self.assertIn(
format_date(self.env, self.date_sooner.date()),
self.so_line1.procurement_group_id.name,
)
| 35.652174
| 4,920
|
1,257
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Alex Comba - Agile Business Group
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
from odoo.tools import format_date
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
def _prepare_procurement_group_vals(self):
vals = super()._prepare_procurement_group_vals()
if self._get_procurement_group_key()[0] == 24:
if self.commitment_date:
vals["name"] += "/" + format_date(self.env, self.commitment_date.date())
return vals
def _get_procurement_group_key(self):
"""Return a key with priority to be used to regroup lines in multiple
procurement groups
"""
priority = 24
key = super()._get_procurement_group_key()
# Check priority
if key[0] < priority:
if self.commitment_date:
# group by date instead of datetime
return (priority, self.commitment_date.date())
return key
def _prepare_procurement_values(self, group_id=False):
vals = super()._prepare_procurement_values(group_id=group_id)
if self.commitment_date:
vals.update({"date_planned": self.commitment_date})
return vals
| 35.914286
| 1,257
|
584
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Partner contact sale info propagation",
"summary": "Propagate Salesperson and Sales Channel " "from Company to Contacts",
"version": "15.0.1.0.0",
"category": "Sales Management",
"website": "https://github.com/OCA/sale-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["sales_team"],
"data": ["views/res_partner_view.xml"],
}
| 38.933333
| 584
|
2,741
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo.tests.common import TransactionCase
class TestPartnerContactSaleInfoPropagation(TransactionCase):
def setUp(self):
super().setUp()
self.partner_model = self.env["res.partner"].with_context(test_propagation=True)
self.parent_company = self.partner_model.create(
{
"name": "Parent company",
"company_type": "company",
"user_id": self.ref("base.user_demo"),
"team_id": self.ref("sales_team.crm_team_1"),
}
)
def check_same_user_id_team_id(self, parent, child):
self.assertEqual(parent.user_id, child.user_id)
self.assertEqual(parent.team_id, child.team_id)
def test_create_partner_child(self):
partner_child = self.partner_model.create(
{"name": "Parent child", "parent_id": self.parent_company.id}
)
self.check_same_user_id_team_id(self.parent_company, partner_child)
def test_write_parent_company(self):
partner_child = self.partner_model.create(
{"name": "Parent child", "parent_id": self.parent_company.id}
)
self.parent_company.write(
{
"user_id": self.ref("base.demo_user0"),
"team_id": self.ref("sales_team.team_sales_department"),
}
)
self.check_same_user_id_team_id(self.parent_company, partner_child)
partner_child.write({"user_id": False, "team_id": False})
self.parent_company.write(
{
"user_id": self.ref("base.user_demo"),
"team_id": self.ref("sales_team.crm_team_1"),
}
)
self.check_same_user_id_team_id(self.parent_company, partner_child)
def test_onchange_parent_id_with_values_false(self):
partner_child = self.partner_model.create({"name": "Parent child"})
partner_child.write({"parent_id": self.parent_company.id})
onchange_result = partner_child.onchange_parent_id()
self.assertEqual(
onchange_result["value"]["user_id"], self.parent_company.user_id
)
self.assertEqual(
onchange_result["value"]["team_id"], self.parent_company.team_id
)
def test_fields_view_get(self):
partner_xml = etree.XML(self.partner_model.fields_view_get()["arch"])
partner_field = partner_xml.xpath("//field[@name='child_ids']")[0]
context = partner_field.attrib.get("context", "{}")
sub_ctx = "{'default_user_id': user_id, 'default_team_id': team_id,"
self.assertIn(sub_ctx, context)
| 39.724638
| 2,741
|
3,326
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Ernesto Tejeda
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo import api, models
from odoo.tools import config
class ResPartner(models.Model):
_inherit = "res.partner"
def _check_propagation_allowed(self):
return bool(
not config["test_enable"]
or (config["test_enable"] and self.env.context.get("test_propagation"))
)
def write(self, vals):
"""Propagate Salesperson and Sales Channel change in the partner to the
child contacts."""
if not self._check_propagation_allowed():
return super().write(vals)
for record in self:
if "user_id" in vals:
childs = record.mapped("child_ids").filtered(
lambda r: not r.user_id or r.user_id == record.user_id
)
if childs:
childs.write({"user_id": vals["user_id"]})
if "team_id" in vals:
childs = record.mapped("child_ids").filtered(
lambda r: not r.team_id or r.team_id == record.team_id
)
if childs:
childs.write({"team_id": vals["team_id"]})
return super().write(vals)
@api.model_create_multi
def create(self, vals_list):
if not self._check_propagation_allowed():
return super().create(vals_list)
for vals in vals_list:
if "parent_id" in vals:
if "user_id" not in vals:
vals.update(user_id=self.browse(vals["parent_id"]).user_id.id)
if "team_id" not in vals:
vals.update(team_id=self.browse(vals["parent_id"]).team_id.id)
return super().create(vals_list)
@api.onchange("parent_id")
def onchange_parent_id(self):
"""Change Salesperson or Sales Channel if the parent company changes
and there's no Salesperson or Sales Channel defined yet"""
res = super().onchange_parent_id()
if self.parent_id and self.parent_id != self:
parent = self.parent_id
if not self.user_id:
res.setdefault("value", {}).update(user_id=parent.user_id)
if not self.team_id:
res.setdefault("value", {}).update(team_id=parent.team_id)
return res
@api.model
def fields_view_get(
self, view_id=None, view_type="form", toolbar=False, submenu=False
):
res = super().fields_view_get(
view_id=view_id,
view_type=view_type,
toolbar=toolbar,
submenu=submenu,
)
if view_type == "form":
partner_xml = etree.XML(res["arch"])
partner_fields = partner_xml.xpath("//field[@name='child_ids']")
if partner_fields:
partner_field = partner_fields[0]
context = partner_field.attrib.get("context", "{}").replace(
"{",
"{'default_user_id': user_id, 'default_team_id': team_id,",
1,
)
partner_field.attrib["context"] = context
res["arch"] = etree.tostring(partner_xml)
return res
| 38.206897
| 3,324
|
1,228
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Carlos Sánchez Cifuentes <csanchez@grupovermon.com>
# Copyright 2015-2016 Oihane Crucelaegui <oihane@avanzosc.com>
# Copyright 2015-2020 Tecnativa - Pedro M. Baeza
# Copyright 2016 Lorenzo Battistini
# Copyright 2016 Carlos Dauden <carlos.dauden@tecnativa.com>
# Copyright 2018 David Vidal <david.vidal@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sale Order Type",
"version": "15.0.2.0.5",
"category": "Sales Management",
"author": "Grupo Vermon,"
"AvanzOSC,"
"Tecnativa,"
"Agile Business Group,"
"Niboo,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"license": "AGPL-3",
"depends": ["sale_stock", "account", "sale_management"],
"demo": ["demo/sale_order_demo.xml"],
"data": [
"security/ir.model.access.csv",
"security/security.xml",
"views/sale_order_view.xml",
"views/sale_order_type_view.xml",
"views/account_move_views.xml",
"views/res_partner_view.xml",
"data/default_type.xml",
"reports/account_invoice_report_view.xml",
"reports/sale_report_view.xml",
],
"installable": True,
}
| 35.057143
| 1,227
|
1,931
|
py
|
PYTHON
|
15.0
|
from odoo.tests import tagged
from odoo.addons.sale.tests.common import TestSaleCommon
@tagged("post_install", "-at_install")
class TestSaleReport(TestSaleCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.sale_order_types = cls.env["sale.order.type"].create(
[
{
"name": "Normal Order",
},
{
"name": "Special Order",
},
]
)
# Create the SO with one order line
cls.sale_order = (
cls.env["sale.order"]
.with_context(tracking_disable=True)
.create(
{
"partner_id": cls.partner_a.id,
"partner_invoice_id": cls.partner_a.id,
"partner_shipping_id": cls.partner_a.id,
"pricelist_id": cls.company_data["default_pricelist"].id,
"type_id": cls.sale_order_types[0].id, # Normal Order
}
)
)
SaleOrderLine = cls.env["sale.order.line"].with_context(tracking_disable=True)
cls.sol_prod_order = SaleOrderLine.create(
{
"name": cls.company_data["product_order_no"].name,
"product_id": cls.company_data["product_order_no"].id,
"product_uom_qty": 5,
"product_uom": cls.company_data["product_order_no"].uom_id.id,
"price_unit": cls.company_data["product_order_no"].list_price,
"order_id": cls.sale_order.id,
"tax_id": False,
}
)
def test_sale_report_sale_order_type(self):
self.env["sale.report"].read_group(
domain=[],
fields=["product_id, quantity, type_id"],
groupby="type_id",
)
| 35.109091
| 1,931
|
1,930
|
py
|
PYTHON
|
15.0
|
from odoo import fields
from odoo.tests import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
@tagged("post_install", "-at_install")
class TestAccountInvoiceReport(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.sale_order_types = cls.env["sale.order.type"].create(
[
{
"name": "Normal Order",
},
{
"name": "Special Order",
},
]
)
cls.invoices = cls.env["account.move"].create(
{
"move_type": "out_invoice",
"partner_id": cls.partner_a.id,
"invoice_date": fields.Date.from_string("2021-01-01"),
"sale_type_id": cls.sale_order_types[0].id, # Normal Order
"currency_id": cls.currency_data["currency"].id,
"invoice_line_ids": [
(
0,
None,
{
"product_id": cls.product_a.id,
"quantity": 3,
"price_unit": 750,
},
),
(
0,
None,
{
"product_id": cls.product_a.id,
"quantity": 1,
"price_unit": 3000,
},
),
],
}
)
def test_invoice_report_sale_order_type(self):
self.env["account.invoice.report"].read_group(
domain=[],
fields=["product_id, quantity, sale_type_id"],
groupby="sale_type_id",
)
| 32.711864
| 1,930
|
11,372
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Oihane Crucelaegui - AvanzOSC
# Copyright 2017 Pierre Faniel - Niboo SPRL (<https://www.niboo.be/>)
# Copyright 2020 Tecnativa - Pedro M. Baeza
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from freezegun import freeze_time
import odoo.tests.common as common
from odoo import fields
from odoo.tests import Form, tagged
@tagged("post_install", "-at_install")
class TestSaleOrderType(common.TransactionCase):
def setUp(self):
super(TestSaleOrderType, self).setUp()
self.sale_type_model = self.env["sale.order.type"]
self.sale_order_model = self.env["sale.order"]
self.invoice_model = self.env["account.move"].with_context(
default_move_type="out_invoice"
)
self.account_model = self.env["account.account"]
self.user_type_id = self.env.ref("account.data_account_type_revenue")
self.account = self.account_model.create(
{"code": "income", "name": "Income", "user_type_id": self.user_type_id.id}
)
self.partner = self.env.ref("base.res_partner_1")
self.partner_child_1 = self.env["res.partner"].create(
{"name": "Test child", "parent_id": self.partner.id, "sale_type": False}
)
self.sequence = self.env["ir.sequence"].create(
{
"name": "Test Sales Order",
"code": "sale.order",
"prefix": "TSO",
"padding": 3,
}
)
self.sequence_quot = self.env["ir.sequence"].create(
{
"name": "Test Quotation Update",
"code": "sale.order",
"prefix": "TQU",
"padding": 3,
}
)
self.journal = self.env["account.journal"].search(
[("type", "=", "sale")], limit=1
)
self.default_sale_type_id = self.env["sale.order.type"].search([], limit=1)
self.default_sale_type_id.sequence_id = False
self.warehouse = self.env["stock.warehouse"].create(
{"name": "Warehouse Test", "code": "WT"}
)
self.product = self.env["product.product"].create(
{"type": "service", "invoice_policy": "order", "name": "Test product"}
)
self.immediate_payment = self.env.ref("account.account_payment_term_immediate")
self.sale_pricelist = self.env.ref("product.list0")
self.free_carrier = self.env.ref("account.incoterm_FCA")
self.sale_type = self.sale_type_model.create(
{
"name": "Test Sale Order Type",
"sequence_id": self.sequence.id,
"journal_id": self.journal.id,
"warehouse_id": self.warehouse.id,
"picking_policy": "one",
"payment_term_id": self.immediate_payment.id,
"pricelist_id": self.sale_pricelist.id,
"incoterm_id": self.free_carrier.id,
"quotation_validity_days": 10,
}
)
self.sale_type_quot = self.sale_type_model.create(
{
"name": "Test Quotation Type",
"sequence_id": self.sequence_quot.id,
"journal_id": self.journal.id,
"warehouse_id": self.warehouse.id,
"picking_policy": "one",
"payment_term_id": self.immediate_payment.id,
"pricelist_id": self.sale_pricelist.id,
"incoterm_id": self.free_carrier.id,
}
)
self.sale_type_sequence_default = self.sale_type_quot.copy(
{
"name": "Test Sequence default",
"sequence_id": self.env["sale.order"]
.with_company(self.env.company.id)
._default_sequence_id()
.id,
}
)
self.partner.sale_type = self.sale_type
self.sale_route = self.env["stock.location.route"].create(
{
"name": "SO -> Customer",
"product_selectable": True,
"sale_selectable": True,
"rule_ids": [
(
0,
0,
{
"name": "SO -> Customer",
"action": "pull",
"picking_type_id": self.ref("stock.picking_type_in"),
"location_src_id": self.ref(
"stock.stock_location_components"
),
"location_id": self.ref("stock.stock_location_customers"),
},
)
],
}
)
self.sale_type_route = self.sale_type_model.create(
{
"name": "Test Sale Order Type-1",
"sequence_id": self.sequence.id,
"journal_id": self.journal.id,
"warehouse_id": self.warehouse.id,
"picking_policy": "one",
"payment_term_id": self.immediate_payment.id,
"pricelist_id": self.sale_pricelist.id,
"incoterm_id": self.free_carrier.id,
"route_id": self.sale_route.id,
}
)
def create_sale_order(self, partner=False):
# Set a custom context to "disable" the behavior of sale_isolated_quotation
sale_form = Form(self.env["sale.order"].with_context(order_sequence="test"))
sale_form.partner_id = partner or self.partner
with sale_form.order_line.new() as order_line:
order_line.product_id = self.product
order_line.product_uom_qty = 1.0
return sale_form.save()
def create_invoice(self, partner=False, sale_type=False):
inv_form = Form(
self.env["account.move"].with_context(default_move_type="out_invoice")
)
inv_form.partner_id = partner or self.partner
inv_form.sale_type_id = sale_type or self.sale_type
with inv_form.invoice_line_ids.new() as inv_line:
inv_line.product_id = self.product
inv_line.account_id = self.account
inv_line.quantity = 1.0
return inv_form.save()
def test_sale_order_flow(self):
sale_type = self.sale_type
order = self.create_sale_order()
self.assertEqual(order.type_id, sale_type)
order.onchange_type_id()
self.assertEqual(order.warehouse_id, sale_type.warehouse_id)
self.assertEqual(order.picking_policy, sale_type.picking_policy)
self.assertEqual(order.payment_term_id, sale_type.payment_term_id)
self.assertEqual(order.pricelist_id, sale_type.pricelist_id)
self.assertEqual(order.incoterm, sale_type.incoterm_id)
order.action_confirm()
invoice = order._create_invoices()
self.assertEqual(invoice.sale_type_id, sale_type)
self.assertEqual(invoice.journal_id, sale_type.journal_id)
def test_sale_order_change_partner(self):
order = self.create_sale_order()
self.assertEqual(order.type_id, self.sale_type)
order = self.create_sale_order(partner=self.partner_child_1)
self.assertEqual(order.type_id, self.sale_type)
def test_invoice_onchange_type(self):
sale_type = self.sale_type
invoice = self.create_invoice()
invoice.onchange_sale_type_id()
self.assertEqual(invoice.invoice_payment_term_id, sale_type.payment_term_id)
self.assertEqual(invoice.journal_id, sale_type.journal_id)
def test_invoice_change_partner(self):
invoice = self.create_invoice()
self.assertEqual(invoice.sale_type_id, self.sale_type)
invoice = self.create_invoice(partner=self.partner_child_1)
self.assertEqual(invoice.sale_type_id, self.sale_type)
def test_invoice_without_partner(self):
invoice = self.invoice_model.new()
self.assertEqual(invoice.sale_type_id, self.default_sale_type_id)
def test_sale_order_flow_route(self):
order = self.create_sale_order()
order.type_id = self.sale_type_route.id
order.onchange_type_id()
self.assertEqual(order.type_id.route_id, order.order_line[0].route_id)
sale_line_dict = {
"product_id": self.product.id,
"name": self.product.name,
"product_uom_qty": 2.0,
"price_unit": self.product.lst_price,
}
order.write({"order_line": [(0, 0, sale_line_dict)]})
order.onchange_type_id()
self.assertEqual(order.type_id.route_id, order.order_line[1].route_id)
def test_sale_order_in_draft_state_update_name(self):
order = self.create_sale_order()
order.onchange_partner_id()
order.onchange_type_id()
self.assertEqual(order.type_id, self.sale_type)
self.assertEqual(order.state, "draft")
self.assertTrue(order.name.startswith("TSO"))
# change order type on sale order
order.type_id = self.sale_type_quot
order.onchange_type_id()
self.assertEqual(order.type_id, self.sale_type_quot)
self.assertTrue(order.name.startswith("TQU"))
def test_sale_order_in_sent_state_update_name(self):
order = self.create_sale_order()
order.onchange_partner_id()
order.onchange_type_id()
self.assertEqual(order.type_id, self.sale_type)
self.assertEqual(order.state, "draft")
self.assertTrue(order.name.startswith("TSO"))
# send quotation
order.action_quotation_sent()
self.assertTrue(order.state == "sent", "Sale: state after sending is wrong")
# change order type on sale order
order.type_id = self.sale_type_quot
order.onchange_type_id()
self.assertEqual(order.type_id, self.sale_type_quot)
self.assertTrue(order.name.startswith("TQU"))
@freeze_time("2022-01-01")
def test_sale_order_quotation_validity(self):
order = self.create_sale_order()
order.onchange_type_id()
self.assertEqual(fields.Date.to_string(order.validity_date), "2022-01-11")
def test_sale_order_create_invoice_down_payment(self):
order = self.create_sale_order()
wizard = (
self.env["sale.advance.payment.inv"]
.with_context(
active_model="sale.order", active_id=order.id, active_ids=order.ids
)
.create(
{
"advance_payment_method": "percentage",
"amount": 10,
}
)
)
wizard.create_invoices()
self.assertEqual(order.type_id.journal_id, order.invoice_ids[0].journal_id)
self.assertEqual(order.type_id, order.invoice_ids[0].sale_type_id)
def test_sequence_default(self):
"""When the previous type had no sequence the order gets the default one. The
sequence change shouldn't be triggered, otherwise we'd get a different number
from the same sequence"""
self.partner.sale_type = self.default_sale_type_id
order = self.create_sale_order()
order.onchange_partner_id()
name = order.name
order.type_id = self.sale_type_sequence_default
self.assertEqual(name, order.name, "The sequence shouldn't change!")
| 42.59176
| 11,372
|
2,156
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# Copyright 2020 Tecnativa - Pedro M. Baeza
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
sale_type_id = fields.Many2one(
comodel_name="sale.order.type",
string="Sale Type",
compute="_compute_sale_type_id",
store=True,
readonly=True,
states={"draft": [("readonly", False)]},
ondelete="restrict",
copy=True,
)
@api.depends("partner_id", "company_id")
def _compute_sale_type_id(self):
# If create invoice from sale order, sale type will not computed.
if not self.env.context.get("default_move_type", False) or self.env.context.get(
"active_model", False
) in ["sale.order", "sale.advance.payment.inv"]:
return
self.sale_type_id = self.env["sale.order.type"]
for record in self:
if record.move_type not in ["out_invoice", "out_refund"]:
record.sale_type_id = self.env["sale.order.type"]
continue
else:
record.sale_type_id = record.sale_type_id
if not record.partner_id:
record.sale_type_id = self.env["sale.order.type"].search(
[("company_id", "in", [self.env.company.id, False])], limit=1
)
else:
sale_type = (
record.partner_id.with_company(record.company_id).sale_type
or record.partner_id.commercial_partner_id.with_company(
record.company_id
).sale_type
)
if sale_type:
record.sale_type_id = sale_type
@api.onchange("sale_type_id")
def onchange_sale_type_id(self):
# TODO: To be changed to computed stored readonly=False if possible in v14?
if self.sale_type_id.payment_term_id:
self.invoice_payment_term_id = self.sale_type_id.payment_term_id.id
if self.sale_type_id.journal_id:
self.journal_id = self.sale_type_id.journal_id.id
| 39.2
| 2,156
|
2,567
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class SaleOrderTypology(models.Model):
_name = "sale.order.type"
_description = "Type of sale order"
_check_company_auto = True
@api.model
def _get_domain_sequence_id(self):
seq_type = self.env.ref("sale.seq_sale_order")
return [("code", "=", seq_type.code)]
@api.model
def _get_selection_picking_policy(self):
return self.env["sale.order"].fields_get(allfields=["picking_policy"])[
"picking_policy"
]["selection"]
@api.model
def default_picking_policy(self):
default_dict = self.env["sale.order"].default_get(["picking_policy"])
return default_dict.get("picking_policy")
name = fields.Char(required=True, translate=True)
description = fields.Text(translate=True)
sequence_id = fields.Many2one(
comodel_name="ir.sequence",
string="Entry Sequence",
copy=False,
domain=_get_domain_sequence_id,
)
journal_id = fields.Many2one(
comodel_name="account.journal",
string="Billing Journal",
domain="[('type', '=', 'sale'), '|', ('company_id', '=', False), "
"('company_id', '=', company_id)]",
check_company=True,
)
warehouse_id = fields.Many2one(
comodel_name="stock.warehouse", string="Warehouse", check_company=True
)
picking_policy = fields.Selection(
selection="_get_selection_picking_policy",
string="Shipping Policy",
default=default_picking_policy,
)
company_id = fields.Many2one(
comodel_name="res.company",
default=lambda self: self.env.company,
store=True,
)
payment_term_id = fields.Many2one(
comodel_name="account.payment.term", string="Payment Term", check_company=True
)
pricelist_id = fields.Many2one(
comodel_name="product.pricelist", string="Pricelist", check_company=True
)
incoterm_id = fields.Many2one(comodel_name="account.incoterms", string="Incoterm")
route_id = fields.Many2one(
"stock.location.route",
string="Route",
domain=[("sale_selectable", "=", True)],
ondelete="restrict",
check_company=True,
)
analytic_account_id = fields.Many2one(
comodel_name="account.analytic.account",
string="Analytic account",
check_company=True,
)
active = fields.Boolean(default=True)
quotation_validity_days = fields.Integer(string="Quotation Validity (Days)")
| 34.226667
| 2,567
|
603
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
sale_type = fields.Many2one(
comodel_name="sale.order.type", string="Sale Order Type", company_dependent=True
)
def copy_data(self, default=None):
result = super().copy_data(default=default)
for idx, partner in enumerate(self):
values = result[idx]
if partner.sale_type and not values.get("sale_type"):
values["sale_type"] = partner.sale_type
return result
| 31.736842
| 603
|
6,137
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Pedro M. Baeza
# Copyright 2023 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from datetime import datetime, timedelta
from odoo import _, api, fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
type_id = fields.Many2one(
comodel_name="sale.order.type",
string="Type",
compute="_compute_sale_type_id",
store=True,
readonly=False,
states={
"sale": [("readonly", True)],
"done": [("readonly", True)],
"cancel": [("readonly", True)],
},
ondelete="restrict",
copy=True,
check_company=True,
)
@api.model
def _default_type_id(self):
return self.env["sale.order.type"].search(
[("company_id", "in", [self.env.company.id, False])], limit=1
)
@api.model
def _default_sequence_id(self):
"""We get the sequence in same way the core next_by_code method does so we can
get the proper default sequence"""
force_company = self.company_id.id or self.env.company.id
return self.env["ir.sequence"].search(
[("code", "=", "sale.order"), ("company_id", "in", [force_company, False])],
order="company_id",
limit=1,
)
@api.depends("partner_id", "company_id")
def _compute_sale_type_id(self):
for record in self:
# Specific partner sale type value
sale_type = (
record.partner_id.with_company(record.company_id).sale_type
or record.partner_id.commercial_partner_id.with_company(
record.company_id
).sale_type
)
# Default user sale type value
if not sale_type:
sale_type = record.default_get(["type_id"]).get("type_id", False)
# Get first sale type value
if not sale_type:
sale_type = record._default_type_id()
record.type_id = sale_type
@api.onchange("type_id")
def onchange_type_id(self):
# TODO: To be changed to computed stored readonly=False if possible in v14?
vals = {}
for order in self:
order_type = order.type_id
# Order values
vals = {}
if order_type.warehouse_id:
vals.update({"warehouse_id": order_type.warehouse_id})
if order_type.picking_policy:
vals.update({"picking_policy": order_type.picking_policy})
if order_type.payment_term_id:
vals.update({"payment_term_id": order_type.payment_term_id})
if order_type.pricelist_id:
vals.update({"pricelist_id": order_type.pricelist_id})
if order_type.incoterm_id:
vals.update({"incoterm": order_type.incoterm_id})
if order_type.analytic_account_id:
vals.update({"analytic_account_id": order_type.analytic_account_id})
if order_type.quotation_validity_days:
vals.update(
{
"validity_date": fields.Date.to_string(
datetime.now()
+ timedelta(order_type.quotation_validity_days)
)
}
)
if vals:
order.update(vals)
# Order line values
line_vals = {}
line_vals.update({"route_id": order_type.route_id.id})
order.order_line.update(line_vals)
@api.model
def create(self, vals):
if vals.get("name", _("New")) == _("New") and vals.get("type_id"):
sale_type = self.env["sale.order.type"].browse(vals["type_id"])
if sale_type.sequence_id:
vals["name"] = sale_type.sequence_id.next_by_id(
sequence_date=vals.get("date_order")
)
return super(SaleOrder, self).create(vals)
def write(self, vals):
"""A sale type could have a different order sequence, so we could
need to change it accordingly"""
default_sequence = self._default_sequence_id()
if vals.get("type_id"):
sale_type = self.env["sale.order.type"].browse(vals["type_id"])
if sale_type.sequence_id:
for record in self:
# An order with a type without sequence would get the default one.
# We want to avoid changing the order reference when the new
# sequence has the same default sequence.
ignore_default_sequence = (
not record.type_id.sequence_id
and sale_type.sequence_id == default_sequence
)
if (
record.state in {"draft", "sent"}
and record.type_id.sequence_id != sale_type.sequence_id
and not ignore_default_sequence
):
new_vals = vals.copy()
new_vals["name"] = sale_type.sequence_id.next_by_id(
sequence_date=vals.get("date_order")
)
super(SaleOrder, record).write(new_vals)
else:
super(SaleOrder, record).write(vals)
return True
return super().write(vals)
def _prepare_invoice(self):
res = super(SaleOrder, self)._prepare_invoice()
if self.type_id.journal_id:
res["journal_id"] = self.type_id.journal_id.id
if self.type_id:
res["sale_type_id"] = self.type_id.id
return res
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
@api.onchange("product_id")
def product_id_change(self):
res = super(SaleOrderLine, self).product_id_change()
if self.order_id.type_id.route_id:
self.update({"route_id": self.order_id.type_id.route_id})
return res
| 39.089172
| 6,137
|
630
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# Copyright 2021 Ecosoft Co., Ltd (http://ecosoft.co.th)
from odoo import models
class SaleAdvancePaymentInv(models.TransientModel):
_inherit = "sale.advance.payment.inv"
def _prepare_invoice_values(self, order, name, amount, so_line):
res = super(SaleAdvancePaymentInv, self)._prepare_invoice_values(
order, name, amount, so_line
)
if order.type_id.journal_id:
res["journal_id"] = order.type_id.journal_id.id
if order.type_id:
res["sale_type_id"] = order.type_id.id
return res
| 35
| 630
|
478
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountInvoiceReport(models.Model):
_inherit = "account.invoice.report"
sale_type_id = fields.Many2one(
comodel_name="sale.order.type",
string="Sale Order Type",
)
def _select(self):
select_str = super()._select()
select_str += """
, move.sale_type_id as sale_type_id
"""
return select_str
| 25.157895
| 478
|
579
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SaleReport(models.Model):
_inherit = "sale.report"
type_id = fields.Many2one(
comodel_name="sale.order.type",
string="Type",
)
# flake8: noqa
# pylint:disable=dangerous-default-value
def _query(self, with_clause="", fields={}, groupby="", from_clause=""):
fields["type_id"] = ", s.type_id as type_id"
groupby += ", s.type_id"
return super(SaleReport, self)._query(with_clause, fields, groupby, from_clause)
| 30.473684
| 579
|
920
|
py
|
PYTHON
|
15.0
|
# Copyright 2013 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright 2016 Serpent Consulting Services Pvt. Ltd.
# Copyright 2018 Dreambits Technologies Pvt. Ltd. (<http://dreambits.in>)
# Copyright 2020 Ecosoft Co., Ltd. (<http://ecosoft.co.th>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Sale order revisions",
"summary": "Keep track of revised quotations",
"version": "15.0.1.0.0",
"category": "Sale Management",
"author": "Agile Business Group,"
"Dreambits,"
"Camptocamp,"
"Akretion,"
"Serpent Consulting Services Pvt. Ltd.,"
"Ecosoft,"
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"license": "AGPL-3",
"depends": ["base_revision", "sale_management"],
"data": ["view/sale_order.xml"],
"installable": True,
"post_init_hook": "populate_unrevisioned_name",
}
| 36.8
| 920
|
3,167
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.tests import Form
from odoo.addons.base_revision.tests import test_base_revision
class TestSaleOrderRevision(test_base_revision.TestBaseRevision):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.revision_model = cls.env["sale.order"]
cls.partner = cls.env["res.partner"].create({"name": "Mr Odoo"})
cls.product = cls.env["product.product"].create({"name": "Test product"})
def _create_tester(self):
sale_form = Form(self.revision_model)
sale_form.partner_id = self.partner
with sale_form.order_line.new() as line_form:
line_form.product_id = self.product
return sale_form.save()
@staticmethod
def _revision_sale_order(sale_order):
# Cancel the tester
sale_order.action_cancel()
# Create a new revision
return sale_order.create_revision()
def test_order_revision(self):
sale_order_1 = self._create_tester()
# Create a revision of the Sale Order
self._revision_sale_order(sale_order_1)
# Check the previous revision of the sale order
revision_1 = sale_order_1.current_revision_id
self.assertEqual(sale_order_1.state, "cancel")
# Check the current revision of the sale order
self.assertEqual(revision_1.unrevisioned_name, sale_order_1.name)
self.assertEqual(revision_1.state, "draft")
self.assertTrue(revision_1.active)
self.assertEqual(revision_1.old_revision_ids, sale_order_1)
self.assertEqual(revision_1.revision_number, 1)
self.assertEqual(revision_1.name.endswith("-01"), True)
self.assertEqual(revision_1.has_old_revisions, True)
# Create a new revision of the Sale Order
self._revision_sale_order(revision_1)
revision_2 = revision_1.current_revision_id
# Check the previous revision of the sale order
self.assertEqual(revision_1.state, "cancel")
self.assertFalse(revision_1.active)
# Check the current revision of the sale order
self.assertEqual(revision_2.unrevisioned_name, sale_order_1.name)
self.assertEqual(revision_2, sale_order_1.current_revision_id)
self.assertEqual(revision_2.state, "draft")
self.assertTrue(revision_2.active)
self.assertEqual(revision_2.old_revision_ids, sale_order_1 + revision_1)
self.assertEqual(revision_2.revision_number, 2)
self.assertEqual(revision_2.name.endswith("-02"), True)
self.assertEqual(revision_2.has_old_revisions, True)
def test_simple_copy(self):
"""Check copy process"""
# Create a Sale Order
sale_order_2 = self._create_tester()
# Check the 'Order Reference' of the Sale Order
self.assertEqual(sale_order_2.name, sale_order_2.unrevisioned_name)
# Copy the Sale Order
sale_order_3 = sale_order_2.copy()
# Check the 'Order Reference' of the copied Sale Order
self.assertEqual(sale_order_3.name, sale_order_3.unrevisioned_name)
| 40.576923
| 3,165
|
1,516
|
py
|
PYTHON
|
15.0
|
# Copyright 2013 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright 2016 Serpent Consulting Services Pvt. Ltd.
# Copyright 2018 Dreambits Technologies Pvt. Ltd. (<http://dreambits.in>)
# Copyright 2020 Ecosoft Co., Ltd. (<http://ecosoft.co.th>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class SaleOrder(models.Model):
_name = "sale.order"
_inherit = ["sale.order", "base.revision"]
current_revision_id = fields.Many2one(
comodel_name="sale.order",
)
old_revision_ids = fields.One2many(
comodel_name="sale.order",
)
# Overwrite as sales.order can be multi-company
_sql_constraints = [
(
"revision_unique",
"unique(unrevisioned_name, revision_number, company_id)",
"Order Reference and revision must be unique per Company.",
)
]
def _prepare_revision_data(self, new_revision):
vals = super()._prepare_revision_data(new_revision)
vals.update({"state": "cancel"})
return vals
def action_view_revisions(self):
self.ensure_one()
action = self.env.ref("sale.action_orders")
result = action.read()[0]
result["domain"] = ["|", ("active", "=", False), ("active", "=", True)]
result["context"] = {
"active_test": 0,
"search_default_current_revision_id": self.id,
"default_current_revision_id": self.id,
}
return result
| 33.688889
| 1,516
|
665
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID, api
def post_init_hook(cr, registry, vals=None):
"""Archive the ir.rules we want to override"""
env = api.Environment(cr, SUPERUSER_ID, {})
env.ref("sale.sale_order_rule_portal").active = False
env.ref("sale.sale_order_line_rule_portal").active = False
def uninstall_hook(cr, registry, vals=None):
"""Unarchive the overriden ir.rules"""
env = api.Environment(cr, SUPERUSER_ID, {})
env.ref("sale.sale_order_rule_portal").active = True
env.ref("sale.sale_order_line_rule_portal").active = True
| 39.117647
| 665
|
594
|
py
|
PYTHON
|
15.0
|
# Copyright 2018-19 Tecnativa S.L. - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Portal Sale Personal Data Only",
"version": "15.0.1.0.0",
"category": "Sale",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"license": "AGPL-3",
"depends": ["sale", "portal_account_personal_data_only"],
"auto_install": True,
"data": ["security/security.xml"],
"installable": True,
"post_init_hook": "post_init_hook",
"uninstall_hook": "uninstall_hook",
}
| 37.125
| 594
|
3,069
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Víctor Martínez
# Copyright 2022 Moduon
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.tests.common import Form, tagged
from odoo.addons.account.tests.common import TestAccountReconciliationCommon
@tagged("post_install", "-at_install")
class TestPartnerAccess(TestAccountReconciliationCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.group_portal = cls.env.ref("base.group_portal")
cls.user_a = cls._create_user(cls, "A")
cls.user_b = cls._create_user(cls, "B")
cls.user_c = cls._create_user(cls, "C")
cls.partner_a = cls._create_partner(cls, cls.user_a)
cls.partner_b = cls._create_partner(cls, cls.user_b)
cls.partner_c = cls._create_partner(cls, cls.user_c)
cls.product = cls.env["product.product"].create(
{
"name": "Test product",
"type": "service",
"lst_price": 10,
"invoice_policy": "order",
}
)
cls.order_a = cls._create_sale_order(cls, cls.partner_a)
cls.order_b = cls._create_sale_order(cls, cls.partner_b)
cls.order_c = cls._create_sale_order(cls, cls.partner_c)
def _create_user(self, letter):
return self.env["res.users"].create(
{
"name": "User %s" % letter,
"login": "user_%s" % letter,
"groups_id": [(6, 0, [self.group_portal.id])],
}
)
def _create_partner(self, user):
return self.env["res.partner"].create(
{
"name": user.name,
"user_ids": [(6, 0, [user.id])],
}
)
def _create_sale_order(self, partner):
sale_form = Form(self.env["sale.order"])
sale_form.partner_id = partner
with sale_form.order_line.new() as line_form:
line_form.product_id = self.product
sale = sale_form.save()
sale.action_confirm()
sale._create_invoices()
return sale
def test_access_sale_order(self):
orders_a = self.env["sale.order"].with_user(self.user_a).search([])
self.assertTrue(self.order_a in orders_a)
self.assertTrue(self.order_b not in orders_a)
self.assertTrue(self.order_c not in orders_a)
orders_b = self.env["sale.order"].with_user(self.user_b).search([])
self.assertTrue(self.order_a not in orders_b)
self.assertTrue(self.order_b in orders_b)
self.assertTrue(self.order_c not in orders_b)
orders_c = self.env["sale.order"].with_user(self.user_c).search([])
self.assertTrue(self.order_a not in orders_c)
self.assertTrue(self.order_b not in orders_c)
self.assertTrue(self.order_c in orders_c)
def test_access_sale_order_followers(self):
self.order_a.message_subscribe(partner_ids=self.partner_b.ids)
orders_b = self.env["sale.order"].with_user(self.user_b).search([])
self.assertTrue(self.order_a in orders_b)
| 39.320513
| 3,067
|
652
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
{
"name": "Sale Order Invoice Amount",
"version": "15.0.1.0.0",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"category": "Sales",
"license": "LGPL-3",
"summary": "Display the invoiced and uninvoiced total in the sale order",
"depends": ["sale", "account"],
"data": ["views/sale_order_view.xml"],
"installable": True,
"assets": {
"web.assets_qweb": [
"sale_order_invoice_amount/static/src/xml/**/*",
],
},
}
| 32.6
| 652
|
4,070
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
from odoo.tests import common
class TestSaleOrderInvoiceAmount(common.TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Partners
cls.res_partner_1 = cls.env["res.partner"].create({"name": "Wood Corner"})
cls.res_partner_address_1 = cls.env["res.partner"].create(
{"name": "Willie Burke", "parent_id": cls.res_partner_1.id}
)
cls.res_partner_2 = cls.env["res.partner"].create({"name": "Partner 12"})
# Products
cls.product_1 = cls.env["product.product"].create(
{"name": "Desk Combination", "type": "product"}
)
cls.product_2 = cls.env["product.product"].create(
{"name": "Conference Chair", "type": "product"}
)
cls.product_3 = cls.env["product.product"].create(
{"name": "Repair Services", "type": "service"}
)
# Location
cls.stock_warehouse = cls.env["stock.warehouse"].search(
[("company_id", "=", cls.env.company.id)], limit=1
)
cls.stock_location_14 = cls.env["stock.location"].create(
{"name": "Shelf 2", "location_id": cls.stock_warehouse.lot_stock_id.id}
)
# Replenish products
cls.env["stock.quant"]._update_available_quantity(
cls.product_1, cls.stock_location_14, 10
)
cls.env["stock.quant"]._update_available_quantity(
cls.product_2, cls.stock_location_14, 10
)
# Sale Order
cls.tax = cls.env["account.tax"].create(
{"name": "Tax 15", "type_tax_use": "sale", "amount": 21}
)
cls.sale_order_1 = cls.env["sale.order"].create(
{"partner_id": cls.res_partner_1.id}
)
cls.order_line_1 = cls.env["sale.order.line"].create(
{
"order_id": cls.sale_order_1.id,
"product_id": cls.product_1.id,
"product_uom": cls.product_1.uom_id.id,
"product_uom_qty": 10.0,
"price_unit": 10.0,
"tax_id": cls.tax,
}
)
cls.order_line_2 = cls.env["sale.order.line"].create(
{
"order_id": cls.sale_order_1.id,
"product_id": cls.product_2.id,
"product_uom": cls.product_2.uom_id.id,
"product_uom_qty": 25.0,
"price_unit": 4.0,
"tax_id": cls.tax,
}
)
cls.order_line_3 = cls.env["sale.order.line"].create(
{
"order_id": cls.sale_order_1.id,
"product_id": cls.product_3.id,
"product_uom": cls.product_3.uom_id.id,
"product_uom_qty": 20.0,
"price_unit": 5.0,
"tax_id": cls.tax,
}
)
def test_sale_order_invoiced_amount(self):
self.assertEqual(
self.sale_order_1.invoiced_amount,
0.0,
"Invoiced Amount should be 0.0",
)
context_payment = {
"active_ids": [self.sale_order_1.id],
"active_id": self.sale_order_1.id,
}
payment = (
self.env["sale.advance.payment.inv"]
.with_context(**context_payment)
.create({"advance_payment_method": "fixed", "fixed_amount": 100})
)
payment.create_invoices()
self.assertEqual(
self.sale_order_1.invoiced_amount,
100.0,
"Invoiced Amount should be 100",
)
self.assertEqual(
self.sale_order_1.uninvoiced_amount,
263.0,
"Uninvoiced Amount should be 263",
)
self.sale_order_1.action_confirm()
self.sale_order_1._create_invoices(final=True)
self.assertEqual(
self.sale_order_1.invoiced_amount,
363.0,
"Invoiced Amount should be calculated",
)
| 35.701754
| 4,070
|
2,387
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2021 ForgeFlow S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html)
import json
from odoo import api, fields, models
from odoo.tools.misc import formatLang
class SaleOrder(models.Model):
_inherit = "sale.order"
invoiced_amount = fields.Monetary(
compute="_compute_invoice_amount",
store=True,
)
uninvoiced_amount = fields.Monetary(
compute="_compute_invoice_amount",
store=True,
)
@api.depends(
"state",
"invoice_ids",
"invoice_ids.amount_total_signed",
"amount_total",
"invoice_ids.state",
)
def _compute_invoice_amount(self):
for rec in self:
if rec.state != "cancel" and rec.invoice_ids:
rec.invoiced_amount = 0.0
for invoice in rec.invoice_ids:
if invoice.state != "cancel":
rec.invoiced_amount += invoice.amount_total_signed
rec.uninvoiced_amount = max(0, rec.amount_total - rec.invoiced_amount)
else:
rec.invoiced_amount = 0.0
if rec.state in ["draft", "sent", "cancel"]:
rec.uninvoiced_amount = 0.0
else:
rec.uninvoiced_amount = rec.amount_total
@api.depends(
"order_line.tax_id",
"order_line.price_unit",
"amount_total",
"amount_untaxed",
"state",
"invoice_ids",
"invoice_ids.amount_total_signed",
"amount_total",
"invoice_ids.state",
)
def _compute_tax_totals_json(self):
res = super(SaleOrder, self)._compute_tax_totals_json()
lang_env = self.with_context(lang=self.partner_id.lang).env
total_json = json.loads(self.tax_totals_json)
total_json.update(
{
"invoiced_amount": self.invoiced_amount,
"formatted_invoiced_amount": formatLang(
lang_env, self.invoiced_amount, currency_obj=self.currency_id
),
"uninvoiced_amount": self.uninvoiced_amount,
"formatted_uninvoiced_amount": formatLang(
lang_env, self.uninvoiced_amount, currency_obj=self.currency_id
),
}
)
self.tax_totals_json = json.dumps(total_json)
return res
| 33.152778
| 2,387
|
626
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Akretion (http://www.akretion.com).
# @author Pierrick BRUN <pierrick.brun@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sale delivery State",
"summary": "Show the delivery state on the sale order",
"version": "15.0.1.0.0",
"category": "Product",
"website": "https://github.com/OCA/sale-workflow",
"author": "Akretion, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["sale"],
"data": [
"views/sale_order_views.xml",
],
"demo": [
"demo/sale_demo.xml",
],
}
| 29.809524
| 626
|
3,422
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Akretion (http://www.akretion.com).
# @author Benoît GUILLOT <benoit.guillot@akretion.com>
# Copyright 2018 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import mock
from odoo.tests import TransactionCase
class TestDeliveryState(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.order = cls.env.ref("sale_delivery_state.sale_order_1")
cls.delivery_cost = cls.env["product.product"].create(
{"name": "delivery", "type": "service"}
)
def _mock_delivery(self, delivery_prod=None):
delivery_prod = delivery_prod or self.delivery_cost
return mock.patch.object(
type(self.env["sale.order.line"]),
"_is_delivery",
lambda self: self.product_id == delivery_prod,
)
def _add_delivery_cost_line(self):
self.env["sale.order.line"].create(
{
"order_id": self.order.id,
"name": "Delivery cost",
"product_id": self.delivery_cost.id,
"product_uom_qty": 1,
"product_uom": self.env.ref("uom.product_uom_unit").id,
"price_unit": 10.0,
}
)
def test_no_delivery(self):
self.assertEqual(self.order.delivery_state, "no")
def test_unprocessed_delivery(self):
self.order.action_confirm()
self.assertEqual(self.order.delivery_state, "unprocessed")
def test_partially(self):
self.order.action_confirm()
self.order.order_line[0].qty_delivered = 2
self.assertEqual(self.order.delivery_state, "partially")
def test_delivery_done(self):
self.order.action_confirm()
for line in self.order.order_line:
line.qty_delivered = line.product_uom_qty
self.assertEqual(self.order.delivery_state, "done")
def test_no_delivery_delivery_cost(self):
self._add_delivery_cost_line()
with self._mock_delivery():
self.assertEqual(self.order.delivery_state, "no")
def test_unprocessed_delivery_delivery_cost(self):
self._add_delivery_cost_line()
with self._mock_delivery():
self.order.action_confirm()
self.assertEqual(self.order.delivery_state, "unprocessed")
def test_partially_delivery_cost(self):
self._add_delivery_cost_line()
with self._mock_delivery():
self.order.action_confirm()
self.order.order_line[0].qty_delivered = 2
self.assertEqual(self.order.delivery_state, "partially")
def test_forced_delivery_cost(self):
self._add_delivery_cost_line()
with self._mock_delivery():
self.order.action_confirm()
self.order.order_line[0].qty_delivered = 2
self.order.force_delivery_state = True
self.assertEqual(self.order.delivery_state, "done")
def test_delivery_done_delivery_cost(self):
self._add_delivery_cost_line()
with self._mock_delivery():
self.order.action_confirm()
for line in self.order.order_line:
if line._is_delivery():
continue
line.qty_delivered = line.product_uom_qty
self.assertEqual(self.order.delivery_state, "done")
| 36.784946
| 3,421
|
2,990
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Akretion (http://www.akretion.com).
# @author Pierrick BRUN <pierrick.brun@akretion.com>
# Copyright 2018 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.tools import float_compare, float_is_zero
class SaleOrder(models.Model):
_inherit = "sale.order"
delivery_state = fields.Selection(
[
("no", "No delivery"),
("unprocessed", "Unprocessed"),
("partially", "Partially processed"),
("done", "Done"),
],
# Compute method have a different name then the field because
# the method _compute_delivery_state already exist to compute
# the field delivery_set
compute="_compute_sale_delivery_state",
store=True,
)
force_delivery_state = fields.Boolean(
help=(
"Allow to enforce done state of delivery, for instance if some"
" quantities were cancelled"
),
)
def _all_qty_delivered(self):
"""
Returns True if all line have qty_delivered >= to ordered quantities
If `delivery` module is installed, ignores the lines with delivery costs
:returns: boolean
"""
self.ensure_one()
# Skip delivery costs lines
sale_lines = self.order_line.filtered(lambda rec: not rec._is_delivery())
precision = self.env["decimal.precision"].precision_get(
"Product Unit of Measure"
)
return all(
float_compare(
line.qty_delivered, line.product_uom_qty, precision_digits=precision
)
>= 0
for line in sale_lines
)
def _partially_delivered(self):
"""
Returns True if at least one line is delivered
:returns: boolean
"""
self.ensure_one()
# Skip delivery costs lines
sale_lines = self.order_line.filtered(lambda rec: not rec._is_delivery())
precision = self.env["decimal.precision"].precision_get(
"Product Unit of Measure"
)
return any(
not float_is_zero(line.qty_delivered, precision_digits=precision)
for line in sale_lines
)
@api.depends("order_line.qty_delivered", "state", "force_delivery_state")
def _compute_sale_delivery_state(self):
for order in self:
if order.state in ("draft", "cancel"):
order.delivery_state = "no"
elif order.force_delivery_state or order._all_qty_delivered():
order.delivery_state = "done"
elif order._partially_delivered():
order.delivery_state = "partially"
else:
order.delivery_state = "unprocessed"
def action_force_delivery_state(self):
self.write({"force_delivery_state": True})
def action_unforce_delivery_state(self):
self.write({"force_delivery_state": False})
| 33.595506
| 2,990
|
1,397
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Sale planner calendar",
"summary": "Sale planner calendar",
"version": "15.0.1.2.1",
"development_status": "Beta",
"category": "Sale",
"website": "https://github.com/OCA/sale-workflow",
"author": "Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["calendar", "sale", "sale_payment_sheet"],
"data": [
"security/ir.model.access.csv",
"security/sale_planner_calendar_security.xml",
"data/sale_planner_calendar_action_server.xml",
"data/sale_planner_calendar_cron.xml",
"data/sale_planner_calendar_data.xml",
"views/calendar_event_type_view.xml",
"views/calendar_view.xml",
"views/res_config_settings_views.xml",
"views/res_partner_view.xml",
"views/sale_planner_calendar_event_view.xml",
"views/sale_planner_calendar_summary_view.xml",
"wizard/sale_planner_calendar_reassign.xml",
"wizard/sale_planner_calendar_wizard.xml",
# # Menu position fixed
"views/sale_planner_calendar_menu.xml",
],
"assets": {
"web.assets_backend": [
"sale_planner_calendar/static/src/scss/sale_planner_calendar.scss"
]
},
}
| 37.756757
| 1,397
|
780
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openupgradelib import openupgrade # pylint: disable=W7936
def link_target_partner_id_to_recurrent_events(env):
events = env["calendar.event"].search([("target_partner_id", "!=", False)])
for event in events:
to_assign_events = event.search(
[
("target_partner_id", "=", False),
("recurrence_id", "=", event.recurrence_id.id),
]
)
to_assign_events.target_partner_id = event.target_partner_id
@openupgrade.migrate()
def migrate(env, version):
openupgrade.load_data(
env.cr, "sale_planner_calendar", "migrations/15.0.1.0.1/noupdate_changes.xml"
)
link_target_partner_id_to_recurrent_events(env)
| 33.913043
| 780
|
11,619
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from freezegun import freeze_time
from odoo.exceptions import AccessError
from odoo.tests.common import Form, TransactionCase, tagged
@tagged("-at_install", "post_install")
@freeze_time("2022-02-04 09:00:00")
class TestSalePlannerCalendar(TransactionCase):
def setUp(self):
super().setUp()
self.env = self.env(context=dict(self.env.context, tracking_disable=True))
self.CalendarEvent = self.env["calendar.event"]
self.ResUsers = self.env["res.users"]
self.Partner = self.env["res.partner"]
self.ProductTemplate = self.env["product.template"]
self.Product = self.env["product.product"]
self.AccountInvoice = self.env["account.move"]
self.AccountInvoiceLine = self.env["account.move.line"]
self.AccountJournal = self.env["account.journal"]
self.SaleOrder = self.env["sale.order"]
self.event_type_commercial_visit = self.env.ref(
"sale_planner_calendar.event_type_commercial_visit"
)
self.event_type_delivery = self.env.ref(
"sale_planner_calendar.event_type_delivery"
)
self.pricelist = self.env["product.pricelist"].create(
{"name": "Test pricelist", "currency_id": self.env.company.currency_id.id}
)
# Create some products
self._create_products()
# Create some commercial users
self._create_commercial_users()
# Create some partners
self._create_partners()
# Create some calendar planner events
self.create_calendar_planner_event()
# Some account data
account_type_income = self.env.ref("account.data_account_type_revenue")
self.account = self.env["account.account"].create(
{
"code": "test",
"name": "Test account",
"user_type_id": account_type_income.id,
}
)
def _create_commercial_users(self):
# Create commercial_user_1 and commercial_user_2 with Own Documents
# Only security group
self.commercial_users = self.ResUsers.browse()
for i in range(2):
index = i + 1
user = self.ResUsers.create(
{
"name": "Commercial user %s" % index,
"login": "Commercial user %s" % index,
"groups_id": [
(4, self.env.ref("sales_team.group_sale_salesman").id)
],
}
)
setattr(self, "commercial_user_%s" % index, user)
self.commercial_users |= user
def _create_partners(self):
self.partners = self.Partner.browse()
self.partner_1 = self.Partner.create(
{
"name": "Partner 1",
"user_id": self.commercial_user_1.id,
"property_product_pricelist": self.pricelist.id,
}
)
self.partner_2 = self.Partner.create(
{
"name": "Partner 2",
"user_id": self.commercial_user_1.id,
"property_product_pricelist": self.pricelist.id,
}
)
self.partner_3 = self.Partner.create(
{
"name": "Partner 3",
"user_id": self.commercial_user_2.id,
"property_product_pricelist": self.pricelist.id,
}
)
self.partners = self.partner_1 + self.partner_2 + self.partner_3
def _create_products(self):
self.product = self.Product.create(
{
"name": "Product test 1",
"list_price": 100.00,
}
)
def _create_sale_order(self):
so_form = Form(self.SaleOrder)
so_form.partner_id = self.partner_1
with so_form.order_line.new() as line_form:
line_form.product_id = self.product
line_form.tax_id.remove(index=0)
return so_form.save()
def create_calendar_planner_event(self):
# Create one planned recurrent event for every partner.
self.planned_events = self.CalendarEvent.browse()
for i, partner in enumerate(self.partners):
action = partner.action_calendar_planner()
context = dict(action["context"], default_wed=True, default_fri=True)
# We use Form for auto-computing the recurrence model, that is triggered
# directly from the initialization of it
event_form = Form(self.CalendarEvent.with_context(**context))
self.planned_events |= event_form.save()
if i == 0:
# Create a delivery event for partner 1. We can delivery goods
# all mondays at 09:00
context = dict(
action["context"],
default_name="Delivery",
default_start="2022-02-07 09:00:00",
default_stop="2022-02-07 10:00:00",
default_mon=True,
default_categ_ids=[(4, self.event_type_delivery.id)],
)
event_form = Form(self.CalendarEvent.with_context(**context))
self.planned_events |= event_form.save()
def _create_sale_order_from_planner(self, event_planner_id):
so_form = Form(
self.SaleOrder.with_context(
default_user_id=event_planner_id.user_id.id,
default_sale_planner_calendar_event_id=event_planner_id.id,
default_partner_id=event_planner_id.partner_id.id,
)
)
with so_form.order_line.new() as line_form:
line_form.product_id = self.product
line_form.product_uom_qty = 1
line_form.tax_id.remove(index=0)
return so_form.save()
def _create_invoice(self, partner):
with Form(
self.env["account.move"].with_context(default_move_type="out_invoice")
) as invoice_form:
invoice_form.partner_id = partner
with invoice_form.invoice_line_ids.new() as line_form:
line_form.name = "invoice test"
line_form.account_id = self.account
line_form.quantity = 1.0
line_form.price_unit = 100.00
line_form.tax_ids.remove(index=0)
return invoice_form.save()
def test_create_calendar_planner_event(self):
# Test the values for one planned recurrent event created
event = self.planned_events[0]
self.assertTrue(event.user_id in self.commercial_users)
self.assertEqual(event.rrule_type, "weekly")
self.assertEqual(event.location, event.target_partner_id._display_address())
def test_planner_calendar_wizard(self):
wiz_form = Form(self.env["sale.planner.calendar.wizard"])
# This user has three planned events
wiz_form.user_id = self.commercial_user_1
self.assertEqual(len(wiz_form.calendar_event_ids), 3)
wiz_form.event_type_id = self.event_type_delivery
self.assertEqual(len(wiz_form.calendar_event_ids), 1)
wiz_form.event_type_id = self.event_type_commercial_visit
self.assertEqual(len(wiz_form.calendar_event_ids), 2)
def test_summary_and_event_today(self):
summary_obj = self.env["sale.planner.calendar.summary"]
summary_form = Form(summary_obj)
summary_form.user_id = self.commercial_user_1
summary = summary_form.save()
summary.action_process()
self.assertEqual(summary.event_total_count, 2)
event_planner_id = summary.sale_planner_calendar_event_ids[0]
# Create a new sale order from planner event
self._create_sale_order_from_planner(event_planner_id)
self.assertEqual(summary.sale_order_count, 1)
self.assertEqual(summary.sale_order_subtotal, 100)
self._create_sale_order_from_planner(event_planner_id)
self.assertEqual(summary.sale_order_count, 2)
self.assertEqual(summary.sale_order_subtotal, 200)
# Create a new invoice from planner event
self.invoice1 = self._create_invoice(event_planner_id.partner_id)
self.invoice1.action_post()
self.assertEqual(event_planner_id.invoice_amount_residual, 100)
# Set event to done state
event_planner_id.action_done()
self.assertEqual(summary.event_total_count, 2)
self.assertEqual(summary.event_done_count, 1)
self.assertEqual(summary.event_effective_count, 1)
def test_reassign_wizard(self):
wiz_form = Form(self.env["sale.planner.calendar.reassign.wiz"])
wiz_form.user_id = self.commercial_user_1
record = wiz_form.save()
# Recover all planned event lines for commercial user 1
record.action_get_lines()
self.assertEqual(len(record.line_ids), 3)
# Select line behaviour for update new commercial user
wiz_form.new_user_id = self.commercial_user_2
record = wiz_form.save()
record.select_all_lines()
record.action_assign_new_salesperson()
self.assertEqual(len(record.line_ids.mapped("new_user_id")), 1)
wiz_form.new_user_id = self.commercial_user_2
record = wiz_form.save()
record.line_ids = False
record.action_get_lines()
record.line_ids[0].selected = True
record.action_assign_new_salesperson()
self.assertEqual(len(record.line_ids.filtered(lambda ln: ln.new_user_id)), 1)
def test_reassign_wizard_subscriptions(self):
# Create a SO for partner 1 and user commercial 1
sale_order = self._create_sale_order()
invoice = self._create_invoice(self.partner_1)
# Check document permissions based on followers
with self.assertRaises(AccessError):
self.assertIsNotNone(
sale_order.with_user(self.commercial_user_2).check_access_rule("read")
)
self.assertIsNotNone(
sale_order.with_user(self.commercial_user_2).check_access_rule("write")
)
self.assertIsNotNone(
invoice.with_user(self.commercial_user_2).check_access_rule("read")
)
self.assertIsNotNone(
invoice.with_user(self.commercial_user_2).check_access_rule("write")
)
wiz_form = Form(self.env["sale.planner.calendar.reassign.wiz"])
wiz_form.user_id = self.commercial_user_1
record = wiz_form.save()
# Recover all planned event lines for commercial user 1
record.action_get_lines()
wiz_form.new_user_id = self.commercial_user_2
record = wiz_form.save()
event_planner_partner_1 = record.line_ids.filtered(
lambda ln: ln.partner_id == self.partner_1
)
event_planner_partner_1.selected = True
record.action_assign_new_salesperson()
record.apply()
# Check document permissions based on followers
# Sale order
self.assertIsNone(
sale_order.with_user(self.commercial_user_2).check_access_rule("read")
)
self.assertIsNone(
sale_order.with_user(self.commercial_user_2).check_access_rule("write")
)
# Account move (Invoice)
self.assertIsNone(
invoice.with_user(self.commercial_user_2).check_access_rule("read")
)
self.assertIsNone(
invoice.with_user(self.commercial_user_2).check_access_rule("write")
)
| 41.645161
| 11,619
|
9,739
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# Copyright 2021 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import timedelta
from odoo import api, fields, models
class SalePlannerCalendarReassignWiz(models.TransientModel):
_name = "sale.planner.calendar.reassign.wiz"
_description = "Sale planner calendar reassign wizard"
user_id = fields.Many2one(
comodel_name="res.users",
string="Salesperson",
default=lambda self: self.env.user,
domain="[('share','=',False)]",
)
event_type_id = fields.Many2one(
comodel_name="calendar.event.type", string="Event type"
)
week_list = fields.Selection(
[
("MO", "Monday"),
("TU", "Tuesday"),
("WE", "Wednesday"),
("TH", "Thursday"),
("FR", "Friday"),
("SA", "Saturday"),
("SU", "Sunday"),
],
string="Weekday",
)
partner_id = fields.Many2one(comodel_name="res.partner")
partner_user_id = fields.Many2one(
comodel_name="res.users",
domain="[('share','=',False)]",
)
new_user_id = fields.Many2one(
comodel_name="res.users",
string="New salesperson",
domain="[('share','=',False)]",
)
new_start = fields.Date(default=fields.Date.today, required=True)
new_end = fields.Date()
assign_new_salesperson_to_partner = fields.Boolean()
unsuscribe_old_salesperson = fields.Boolean()
line_ids = fields.One2many(
comodel_name="sale.planner.calendar.reassign.line.wiz",
inverse_name="reassign_wiz_id",
)
@api.onchange(
"user_id", "event_type_id", "week_list", "partner_user_id", "partner_id"
)
def onchange_filter_values(self):
self.line_ids = False
def action_get_lines(self):
domain = [
("recurrency", "=", True),
("recurrence_id.until", ">", self.new_start or fields.Date.today()),
]
if self.user_id:
domain.append(("user_id", "=", self.user_id.id))
if self.partner_user_id:
domain.append(("target_partner_id.user_id", "=", self.partner_user_id.id))
if self.partner_id:
domain.append(("target_partner_id", "=", self.partner_id.id))
if self.event_type_id:
domain.append(("categ_ids", "in", self.event_type_id.ids))
if self.week_list:
domain.append((self.week_list.lower(), "=", True))
calendar_events = (
self.env["calendar.event"]
.with_context(calendar_event_primary_only=True)
.search(domain)
)
self.line_ids = False
for calendar_event in calendar_events:
self.env["sale.planner.calendar.reassign.line.wiz"].create(
{
"reassign_wiz_id": self.id,
"calendar_event_id": calendar_event.id,
"event_user_id": calendar_event.user_id.id,
"partner_id": calendar_event.target_partner_id.id,
"event_start": calendar_event.start,
"until": calendar_event.until,
}
)
def action_assign_new_salesperson(self):
lines = self.line_ids.filtered("selected")
lines.new_user_id = self.new_user_id
lines.selected = False
self.new_user_id = False
def select_all_lines(self):
self.line_ids.selected = True
def unselect_all_lines(self):
self.line_ids.selected = False
def apply(self):
for line in self.line_ids:
if not line.new_user_id:
continue
old_event = line.calendar_event_id
recurrence_events = old_event.recurrence_id.calendar_event_ids
new_base_event_start = recurrence_events.filtered(
lambda ce: ce.start.date() >= self.new_start
).sorted("start")[:1]
partner_ids = (
new_base_event_start.partner_ids
- line.event_user_id.partner_id
+ line.new_user_id.partner_id
).ids
new_base_event_start.with_context(create_recurrence_new_user=True).write(
{
"recurrence_update": "future_events",
"user_id": line.new_user_id.id,
"partner_ids": [
(6, False, partner_ids),
],
# Next fields has different behavior if 'self.new_end' field has a
# value
"is_dynamic_end_date": False
if self.new_end
else old_event.is_dynamic_end_date,
"unsubscribe_date": self.new_end,
}
)
if self.new_end:
new_base_event_end = recurrence_events.filtered(
lambda ce: ce.start.date() >= self.new_end
).sorted("start")[:1]
partner_ids = (
new_base_event_end.partner_ids
+ line.event_user_id.partner_id
- line.new_user_id.partner_id
).ids
new_base_event_end.with_context(create_recurrence_new_user=True).write(
{
"recurrence_update": "future_events",
"user_id": line.event_user_id.id,
"partner_ids": [
(6, False, partner_ids),
],
"is_dynamic_end_date": old_event.is_dynamic_end_date,
}
)
old_event_vals = {
"recurrence_update": "all_events",
"is_dynamic_end_date": False,
}
if self.unsuscribe_old_salesperson and not self.new_end:
old_event_vals["unsubscribe_date"] = self.new_start
old_event.write(old_event_vals)
if self.assign_new_salesperson_to_partner:
line.partner_id.with_context(
skip_sale_planner_check=True
).user_id = line.new_user_id
line.update_subscriptions()
self.action_get_lines()
@api.model
def _unsubscribe(self, partner, user):
if partner.user_id != user:
partner.message_unsubscribe(partner_ids=user.partner_id.ids)
unsubscribe_domain = [
("message_partner_ids", "in", partner.ids),
("user_id", "!=", user.id),
"|",
("partner_id", "=", partner.id),
("partner_shipping_id", "=", partner.id),
]
self.env["sale.order"].search(unsubscribe_domain).message_unsubscribe(
partner_ids=user.partner_id.ids
)
self.env["account.move"].search(unsubscribe_domain).message_unsubscribe(
partner_ids=user.partner_id.ids
)
@api.model
def cron_unsubscribe(self, date=None):
if date is None:
date = fields.Date.today()
events = self.env["calendar.event"].search(
[
("unsubscribe_date", "<=", date),
]
)
for event in events:
self._unsubscribe(event.target_partner_id, event.user_id)
events.unsubscribe_date = False
class SalePlannerCalendarReassignLineWiz(models.TransientModel):
_name = "sale.planner.calendar.reassign.line.wiz"
_description = "Sale planner calendar reassign lines wizard"
reassign_wiz_id = fields.Many2one(comodel_name="sale.planner.calendar.reassign.wiz")
selected = fields.Boolean()
calendar_event_id = fields.Many2one(comodel_name="calendar.event", readonly=True)
partner_id = fields.Many2one(comodel_name="res.partner", readonly=True)
partner_user_id = fields.Many2one(
string="Partner salesperson",
comodel_name="res.users",
related="partner_id.user_id",
)
event_user_id = fields.Many2one(
comodel_name="res.users",
string="Planned user",
readonly=True,
domain="[('share','=',False)]",
)
new_user_id = fields.Many2one(
comodel_name="res.users",
domain="[('share','=',False)]",
)
event_start = fields.Datetime(readonly=True)
until = fields.Datetime(readonly=True)
def update_subscriptions(self):
for line in self:
backward_date = fields.Date.today() - timedelta(
days=self.env.company.susbscriptions_backward_days
)
sale_orders = self.env["sale.order"].search(
[
("date_order", ">=", backward_date),
("partner_id", "=", line.partner_id.id),
("user_id", "!=", line.new_user_id.id),
]
)
invoices = (
self.env["account.move"]
.sudo()
.search(
[
("move_type", "in", ["out_invoice", "out_refund"]),
("user_id", "!=", line.new_user_id.id),
"|",
("invoice_date", ">=", backward_date),
("payment_state", "!=", "paid"),
"|",
("partner_id", "=", line.partner_id.id),
("partner_shipping_id", "=", line.partner_id.id),
]
)
)
for records in [line.partner_id, sale_orders, invoices]:
records.message_subscribe(partner_ids=line.new_user_id.partner_id.ids)
self.reassign_wiz_id.cron_unsubscribe()
| 38.192157
| 9,739
|
2,227
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class SalePlannerCalendarWizard(models.TransientModel):
_name = "sale.planner.calendar.wizard"
_description = "Sale planner calendar Wizard"
user_id = fields.Many2one(
comodel_name="res.users",
string="Salesperson",
default=lambda self: self.env.user,
domain="[('share','=',False)]",
)
event_type_id = fields.Many2one(
comodel_name="calendar.event.type", string="Event type"
)
week_list = fields.Selection(
[
("MON", "Monday"),
("TUE", "Tuesday"),
("WED", "Wednesday"),
("THU", "Thursday"),
("FRI", "Friday"),
("SAT", "Saturday"),
("SUN", "Sunday"),
],
string="Weekday",
)
calendar_event_ids = fields.Many2many(
comodel_name="calendar.event",
compute="_compute_calendar_event_ids",
readonly=False,
)
@api.depends("user_id", "event_type_id", "week_list")
def _compute_calendar_event_ids(self):
for rec in self:
domain = [
("recurrency", "=", True),
("recurrence_id.until", ">", fields.Date.today()),
]
if rec.user_id:
domain.append(("user_id", "=", rec.user_id.id))
if rec.event_type_id:
domain.append(("categ_ids", "in", rec.event_type_id.ids))
if rec.week_list:
domain.append(("recurrence_id." + rec.week_list.lower(), "=", True))
rec.calendar_event_ids = (
self.env["calendar.event"]
.with_context(calendar_event_primary_only=True)
.search(domain)
.sorted("hour")
)
# TODO: Remove when control_panel_hidden works
@api.depends("user_id", "event_type_id")
def name_get(self):
result = []
for wiz in self:
name = "{} - {}".format(wiz.user_id.name, wiz.event_type_id.name or "Plan")
result.append((wiz.id, name))
return result
def apply(self):
pass
| 32.75
| 2,227
|
676
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Tecnativa - Carlos Dauden
# Copyright 2020 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class SaleInvoicePaymentWiz(models.TransientModel):
_inherit = "sale.invoice.payment.wiz"
sale_planner_calendar_event_id = fields.Many2one(
comodel_name="sale.planner.calendar.event"
)
def _prepare_sheet_line_values(self, invoice, amount_pay):
values = super()._prepare_sheet_line_values(invoice, amount_pay)
values.update(
{"sale_planner_calendar_event_id": self.sale_planner_calendar_event_id.id}
)
return values
| 33.8
| 676
|
317
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SaleEventPlannerIssueType(models.Model):
_name = "sale.planner.calendar.issue.type"
_description = "Sale planner calendar issue type"
name = fields.Char()
| 28.818182
| 317
|
338
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SalePaymentSheetLine(models.Model):
_inherit = "sale.payment.sheet.line"
sale_planner_calendar_event_id = fields.Many2one(
comodel_name="sale.planner.calendar.event"
)
| 28.166667
| 338
|
8,056
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.tools.safe_eval import safe_eval
class SalePlannerCalendarEvent(models.Model):
_name = "sale.planner.calendar.event"
_description = "Sale planner calendar event"
name = fields.Char(string="Subject")
company_id = fields.Many2one(
comodel_name="res.company", default=lambda self: self.env.company.id
)
currency_id = fields.Many2one(
comodel_name="res.currency",
related="partner_id.currency_id",
)
date = fields.Datetime(default=fields.Datetime.now)
calendar_event_id = fields.Many2one(
comodel_name="calendar.event",
)
calendar_event_date = fields.Datetime(index=True)
user_id = fields.Many2one(
comodel_name="res.users",
default=lambda self: self.env.user.id,
index=True,
domain="[('share','=',False)]",
)
partner_id = fields.Many2one(comodel_name="res.partner", index=True)
sale_ids = fields.One2many(
comodel_name="sale.order",
inverse_name="sale_planner_calendar_event_id",
)
state = fields.Selection(
[
("pending", "Pending"),
("done", "Done"),
("cancel", "Cancelled"),
],
default="pending",
readonly=True,
)
calendar_issue_type_id = fields.Many2one(
comodel_name="sale.planner.calendar.issue.type", ondelete="restrict"
)
comment = fields.Text()
sale_order_subtotal = fields.Monetary(
compute="_compute_sale_order_subtotal", currency_field="currency_id"
)
calendar_summary_id = fields.Many2one(
comodel_name="sale.planner.calendar.summary",
)
invoice_amount_residual = fields.Monetary(
string="Invoice amount due",
compute="_compute_invoice_amount_residual",
compute_sudo=True,
)
off_planning = fields.Boolean()
payment_sheet_line_ids = fields.One2many(
comodel_name="sale.payment.sheet.line",
inverse_name="sale_planner_calendar_event_id",
)
# Helper fields to kanban views
partner_ref = fields.Char(related="partner_id.ref")
partner_name = fields.Char(compute="_compute_partner_name")
partner_commercial_name = fields.Char(
string="Commercial partner name",
related="partner_id.commercial_partner_id.name",
)
partner_street = fields.Char(related="partner_id.street")
partner_mobile = fields.Char(compute="_compute_contact")
partner_contact_name = fields.Char(compute="_compute_contact")
partner_city = fields.Char(related="partner_id.city")
@api.depends("sale_ids.amount_untaxed")
def _compute_sale_order_subtotal(self):
for rec in self:
rec.sale_order_subtotal = sum(rec.mapped("sale_ids.amount_untaxed"))
# @api.depends("target_partner_id")
def _compute_invoice_amount_residual(self):
groups = self.env["account.move"].read_group(
[
("state", "=", "posted"),
("payment_state", "!=", "paid"),
(
"partner_id",
"in",
self.mapped("partner_id.commercial_partner_id").ids,
),
],
["amount_residual_signed"],
["partner_id"],
)
invoice_dic = {g["partner_id"][0]: g["amount_residual_signed"] for g in groups}
for rec in self:
amount_residual = invoice_dic.get(
rec.partner_id.commercial_partner_id.id, 0.0
)
rec.invoice_amount_residual = amount_residual - sum(
rec.payment_sheet_line_ids.filtered(
lambda p: p.sheet_id.state == "open"
).mapped("amount")
)
def _compute_partner_name(self):
field_name = (
self.env["ir.config_parameter"]
.sudo()
.get_param(
"sale_planner_calendar.partner_name_field",
default="name",
)
)
for event in self:
# If more flexibility is needed use event.mapped(field_name)[0]
event.partner_name = (
event.partner_id[field_name]
or event.partner_id.name
or event.partner_id.commercial_partner_id.name
)
def _compute_contact(self):
for rec in self:
contact = rec.partner_id.child_ids.filtered("is_sale_planner_contact")[:1]
rec.partner_mobile = (contact.mobile or contact.phone) or (
rec.partner_id.mobile or rec.partner_id.phone
)
rec.partner_contact_name = contact.name
def action_open_sale_order(self):
"""
Search or Create an event planner linked to sale order
"""
action_xml_id = (
self.env["ir.config_parameter"]
.sudo()
.get_param(
"sale_planner_calendar.action_open_sale_order",
"sale.action_quotations_with_onboarding",
)
)
action = self.env["ir.actions.act_window"]._for_xml_id(action_xml_id)
action["context"] = {
"default_sale_planner_calendar_event_id": self.id,
"default_partner_id": self.partner_id.id,
"default_user_id": self.user_id.id,
}
if len(self.sale_ids) > 1:
action["domain"] = [("sale_planner_calendar_event_id", "=", self.id)]
else:
action["views"] = list(filter(lambda v: v[1] == "form", action["views"]))
action["res_id"] = self.sale_ids.id
return action
def action_open_invoices(self):
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale_payment_sheet.action_invoice_sale_payment_sheet"
)
ctx = safe_eval(action["context"])
ctx.update(
{
"default_partner_id": self.partner_id.id,
}
)
action["context"] = ctx
domain = safe_eval(action["domain"])
domain.append(
("partner_id", "=", self.partner_id.commercial_partner_id.id),
)
action["domain"] = domain
return action
def action_open_unpaid_invoice(self):
domain = [
("state", "=", "posted"),
("move_type", "in", ["out_invoice", "out_refund"]),
("partner_id", "=", self.partner_id.commercial_partner_id.id),
("payment_state", "!=", "paid"),
]
unpaid_invoices = self.env["account.move"].search(domain)
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale_payment_sheet.action_sale_invoice_payment_wiz"
)
ctx = safe_eval(action["context"])
ctx.update(
{
"default_invoice_ids": [(6, 0, unpaid_invoices.ids)],
"default_sale_planner_calendar_event_id": self.id,
"default_partner_id": self.partner_id.id,
}
)
action["context"] = ctx
return action
def action_done(self):
self.write(
{
"state": "done",
"date": fields.Datetime.now(),
# "comment": 'Done',
}
)
def action_cancel(self):
self.write(
{
"state": "cancel",
"comment": "Not done",
"date": fields.Datetime.now(),
}
)
def action_pending(self):
self.write(
{
"state": "pending",
"comment": False,
"date": self.calendar_event_date,
}
)
def action_open_issue(self):
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale_planner_calendar.action_sale_planner_calendar_issue"
)
action["res_id"] = self.id
return action
def action_apply_issue(self):
pass
| 34.42735
| 8,056
|
4,895
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, fields, models
from odoo.tools import relativedelta
class SaleOrder(models.Model):
_inherit = "sale.order"
sale_planner_calendar_event_id = fields.Many2one(
comodel_name="sale.planner.calendar.event"
)
def _action_confirm(self):
event_obj = self.env["calendar.event"]
event_type_delivery = self.env.ref("sale_planner_calendar.event_type_delivery")
for order in self:
if not order.expected_date or order.commitment_date:
continue
delivery_event = event_obj.search(
[
("target_partner_id", "=", order.partner_id.id),
("start", ">", fields.Datetime.to_string(order.expected_date)),
("categ_ids", "in", event_type_delivery.ids),
],
order="start",
limit=1,
)
if delivery_event:
order.commitment_date = delivery_event.start_datetime
return super()._action_confirm()
def _prepare_calendar_event_planner(self):
return {
"name": _("Sale off planning"),
"partner_id": self.partner_id.id,
"user_id": self.user_id.id,
"date": self.date_order,
"off_planning": True,
"state": "done",
}
def action_set_planner_calendar_event(self, planner_summary=False):
orders = self.filtered(lambda so: not so.sale_planner_calendar_event_id)
if not orders:
return
order_dates = orders.mapped("date_order")
if not planner_summary:
planner_summary = self.env["sale.planner.calendar.summary"]
date_from = planner_summary._get_datetime_from_date_tz_hour(
min(order_dates), self.env.company.sale_planner_order_cut_hour
)
date_to = planner_summary._get_datetime_from_date_tz_hour(
max(order_dates), self.env.company.sale_planner_order_cut_hour
) + relativedelta(days=1)
calendar_event_domain = [
("partner_id", "in", orders.partner_id.ids),
("user_id", "in", orders.user_id.ids),
("date", ">=", date_from),
("date", "<", date_to),
]
if planner_summary.event_type_id:
calendar_event_domain.append(
("calendar_event_id.categ_ids", "in", planner_summary.event_type_id.ids)
)
calendar_events = self.env["sale.planner.calendar.event"].search(
calendar_event_domain
)
planner_summary_domain = [
("user_id", "in", orders.user_id.ids),
("user_id", "in", orders.user_id.ids),
("date", ">=", date_from.date()),
("date", "<", date_to.date()),
]
if planner_summary.event_type_id:
planner_summary_domain.append(
("event_type_id", "=", planner_summary.event_type_id.id)
)
event_summaries = planner_summary or self.env[
"sale.planner.calendar.summary"
].search(planner_summary_domain)
if not event_summaries:
return
cut_time = date_from.time()
for order in orders:
event = calendar_events.filtered(
lambda ev: ev.partner_id == order.partner_id
and ev.user_id == order.user_id
and (ev.date.combine(ev.date.date(), cut_time) <= order.date_order)
and (
ev.date.combine(ev.date.date(), cut_time) + relativedelta(days=1)
> order.date_order
)
)[:1]
if not event:
event_summary = event_summaries.filtered(
lambda sm: sm.user_id == order.user_id
and (
(
sm.date == order.date_order.date()
and order.date_order.time() >= cut_time
)
or (
sm.date == order.date_order.date() + relativedelta(days=1)
and order.date_order.time() < cut_time
)
)
)
if len(event_summary) > 1:
# Sorted to select first summary without event_type
event_summary = event_summary.sorted("event_type_id")[:1]
if not event_summary:
continue
event_vals = order._prepare_calendar_event_planner()
event_vals["calendar_summary_id"] = event_summary.id
event = self.env["sale.planner.calendar.event"].create(event_vals)
order.sale_planner_calendar_event_id = event
| 41.483051
| 4,895
|
250
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class CalendarEventType(models.Model):
_inherit = "calendar.event.type"
duration = fields.Float()
| 25
| 250
|
8,032
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import timedelta
import pytz
from odoo import api, fields, models
from odoo.osv import expression
from odoo.tools.date_utils import relativedelta
# from odoo.addons.calendar.models.calendar import calendar_id2real_id
class CalendarEvent(models.Model):
_inherit = "calendar.event"
target_partner_id = fields.Many2one(
comodel_name="res.partner",
string="Target partner",
help="Is the partner used in planner",
)
currency_id = fields.Many2one(
comodel_name="res.currency", related="target_partner_id.currency_id"
)
hour = fields.Float(compute="_compute_hour", inverse="_inverse_hour")
target_partner_mobile = fields.Char(related="target_partner_id.mobile")
sale_planner_calendar_event_id = fields.Many2one(
comodel_name="sale.planner.calendar.event",
compute="_compute_sale_planner_calendar_event_id",
)
event_planner_state = fields.Char(
compute="_compute_sale_planner_calendar_event_id",
)
# When arrive this date we will unsubscribe user from partner documents
unsubscribe_date = fields.Date()
is_dynamic_end_date = fields.Boolean(copy=False)
# dynamic_end_date = fields.Date(compute="_compute_dynamic_end_date")
advanced_cycle = fields.Boolean()
cycle_number = fields.Integer()
cycle_skip = fields.Integer()
# Field to know which event creates the recurrence
is_base_recurrent_event = fields.Boolean(
compute="_compute_is_base_recurrent_event", store=True
)
def _apply_recurrence_values(self, values, future=True):
"""Method to apply recurrence when 'create_recurrence_new_user' key is set on
the context.
"""
if not self.env.context.get("create_recurrence_new_user") or not future:
return super()._apply_recurrence_values(values, future=future)
to_update = self.env["calendar.recurrence"]
for event in self:
to_update |= event.recurrence_id._split_from(event, values)
self.with_context(create_recurrence_new_user=False).write(
{"recurrency": True, "follow_recurrence": True}
)
return to_update._apply_recurrence()
@api.depends("recurrence_id", "recurrence_id.base_event_id")
def _compute_is_base_recurrent_event(self):
for record in self:
record.is_base_recurrent_event = (
record == record.recurrence_id.base_event_id
)
@api.depends("start")
def _compute_hour(self):
for rec in self:
date = rec._get_hour_tz_offset()
rec.hour = date.hour + date.minute / 60
@api.depends("start", "target_partner_id", "user_id")
def _compute_sale_planner_calendar_event_id(self):
# TODO: Adjust order or use [:1] or [-1:] when know model order
domain = [
("calendar_event_date", "in", self.mapped("start")),
("partner_id", "in", self.mapped("target_partner_id").ids),
("user_id", "=", self.user_id.id),
]
events = self.env["sale.planner.calendar.event"].search(domain)
for rec in self:
rec.sale_planner_calendar_event_id = events.filtered(
lambda r: (
r.calendar_event_date == fields.Datetime.to_datetime(rec.start)
and r.partner_id == rec.target_partner_id
and r.user_id == rec.user_id
)
)[:1]
rec.event_planner_state = rec.sale_planner_calendar_event_id.state
def _get_hour_tz_offset(self):
timezone = self._context.get("tz") or self.env.user.partner_id.tz or "UTC"
self_tz = self.with_context(tz=timezone)
date = fields.Datetime.context_timestamp(self_tz, self.start)
return date
def _inverse_hour(self):
for rec in self:
duration = rec.duration
date = self._get_hour_tz_offset()
new_time = date.replace(
hour=int(rec.hour), minute=int(round((rec.hour % 1) * 60))
)
# Force to onchange get correct value
new_time = new_time.astimezone(pytz.utc).replace(tzinfo=None)
rec.write(
{
"recurrence_update": "all_events",
"start": new_time,
"stop": new_time + timedelta(minutes=round((duration or 0.5) * 60)),
}
)
def search(self, args, offset=0, limit=None, order=None, count=False):
if self.env.context.get("calendar_event_primary_only", False):
args = expression.AND([args, [("is_base_recurrent_event", "=", True)]])
return super().search(
args, offset=offset, limit=limit, order=order, count=count
)
def _create_event_planner(self):
return self.env["sale.planner.calendar.event"].create(
{
"name": self.name,
"partner_id": self.target_partner_id.id,
"user_id": self.user_id.id,
"calendar_event_date": self.start,
"calendar_event_id": self.id,
}
)
def get_planner_calendar_event(self):
return self.sale_planner_calendar_event_id or self._create_event_planner()
@api.onchange("start", "stop", "duration")
def _onchange_duration(self):
"""Show warning if duration more than max duration set in config."""
if not self.target_partner_id:
return
max_duration = float(
self.env["ir.config_parameter"]
.sudo()
.get_param(
"sale_planner_calendar.max_duration",
default="0.0",
)
)
if max_duration and self.duration > max_duration:
return {
"warning": {
"title": "Max duration exceeded",
"message": "Max duration set in config parameters is {} hours".format(
max_duration
),
"type": "notification",
}
}
def action_create_sale_order(self):
"""
Search or Create an event planner linked to sale order
"""
planner_event = self.get_planner_calendar_event()
return planner_event.action_open_sale_order()
def action_create_event_planner(self):
planner_event = self.get_planner_calendar_event()
return planner_event.get_formview_action()
@api.model
def cron_update_dynamic_final_date(self):
events_to_update = self.with_context(calendar_event_primary_only=True).search(
[("is_dynamic_end_date", "=", True)]
)
new_date = fields.Date.today() + relativedelta(
months=self.env.company.sale_planner_forward_months, day=31
)
events_to_update.until = new_date
def get_week_days_count(self):
days = ["mo", "tu", "we", "th", "fr", "sa"]
days_count = 0
for day in days:
if self[day]:
days_count += 1
return days_count
def _get_recurrent_dates_by_event(self):
dates_list = super()._get_recurrent_dates_by_event()
if not self.advanced_cycle:
return dates_list
new_dates = []
index = 0
skip_count = 0
cycle_number = self.cycle_number
cycle_skip = self.cycle_skip
if self.rrule_type == "weekly":
days_count = self.get_week_days_count()
cycle_number *= days_count
cycle_skip *= days_count
for dates in dates_list:
if index < cycle_number:
new_dates.append(dates)
index += 1
else:
skip_count += 1
if skip_count >= cycle_skip:
index = 0
skip_count = 0
return new_dates
| 37.70892
| 8,032
|
12,517
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import timedelta
import pytz
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class SalePlannerCalendarSummary(models.Model):
_name = "sale.planner.calendar.summary"
_description = "Sale planner calendar summary"
_inherit = "mail.thread"
company_id = fields.Many2one(
comodel_name="res.company", default=lambda self: self.env.company.id
)
currency_id = fields.Many2one(
comodel_name="res.currency",
related="company_id.currency_id",
)
date = fields.Date(default=fields.Date.context_today)
sale_planner_calendar_event_ids = fields.One2many(
comodel_name="sale.planner.calendar.event",
inverse_name="calendar_summary_id",
)
user_id = fields.Many2one(
comodel_name="res.users",
default=lambda self: self.env.user.id,
index=True,
domain="[('share','=',False)]",
)
sale_ids = fields.One2many(
comodel_name="sale.order",
compute="_compute_sale_ids",
)
state = fields.Selection(
[
("pending", "Pending"),
("done", "Done"),
("cancel", "Cancelled"),
],
default="pending",
)
comment = fields.Text()
sale_order_subtotal = fields.Monetary(
compute="_compute_sale_ids", currency_field="currency_id"
)
event_type_id = fields.Many2one(
comodel_name="calendar.event.type",
string="Event type",
)
# Summary data results
event_total_count = fields.Integer(compute="_compute_event_planner_count")
event_done_count = fields.Integer(compute="_compute_event_planner_count")
event_effective_count = fields.Integer(compute="_compute_event_planner_count")
event_off_planning_count = fields.Integer(compute="_compute_event_planner_count")
sale_order_count = fields.Integer(compute="_compute_sale_ids")
payment_count = fields.Integer(compute="_compute_event_planner_count")
payment_amount = fields.Monetary(compute="_compute_event_planner_count")
@api.depends("sale_planner_calendar_event_ids")
def _compute_sale_ids(self):
for rec in self:
sales = rec.sale_planner_calendar_event_ids.mapped("sale_ids")
rec.sale_ids = sales
rec.sale_order_subtotal = sum(sales.mapped("amount_untaxed"))
rec.sale_order_count = len(sales)
@api.depends(
"sale_planner_calendar_event_ids",
"sale_planner_calendar_event_ids.state",
"sale_planner_calendar_event_ids.sale_ids",
"sale_planner_calendar_event_ids.off_planning",
)
def _compute_event_planner_count(self):
for summary in self:
event_total_count = 0
event_done_count = 0
event_effective_count = 0
event_off_planning_count = 0
payment_count = 0
payment_amount = 0.0
for event in summary.sale_planner_calendar_event_ids:
event_total_count += 1
if event.state == "done":
event_done_count += 1
if event.sale_ids:
event_effective_count += 1
if event.off_planning:
event_off_planning_count += 1
for payment in event.payment_sheet_line_ids:
payment_count += 1
payment_amount += payment.amount
summary.event_total_count = event_total_count
summary.event_done_count = event_done_count
summary.event_effective_count = event_effective_count
summary.event_off_planning_count = event_off_planning_count
summary.payment_count = payment_count
summary.payment_amount = payment_amount
@api.constrains("user_id", "date", "event_type_id")
def _check_existing_summaries(self):
for rec in self:
summaries = self.search(
[
("user_id", "=", rec.user_id.id),
("date", "=", rec.date),
("event_type_id", "=", rec.event_type_id.id),
("id", "!=", rec.id),
]
)
if summaries:
raise ValidationError(
_(
"Already exists a summary with same user, date and event type)\n"
"Access with 'Sale planner calendar summary' menu option"
)
)
def name_get(self):
res = []
DateField = self.env["ir.qweb.field.date"]
for line in self:
name = "{} {}".format(
DateField.value_to_html(line.date, {}), line.user_id.name
)
res.append((line.id, name))
return res
def action_open_sale_order(self):
"""
Search or Create an event planner linked to sale order
"""
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale.action_quotations_with_onboarding"
)
action["context"] = {
"default_user_id": self.user_id.id,
}
if len(self.sale_ids) > 1:
action["domain"] = [
(
"sale_planner_calendar_event_id",
"in",
self.sale_planner_calendar_event_ids.ids,
)
]
else:
action["views"] = [(self.env.ref("sale.view_order_form").id, "form")]
action["res_id"] = self.sale_ids.id
return action
@api.model
def action_get_today_summary(self):
domain = [
("user_id", "=", self.env.user.id),
("date", "=", fields.Date.today()),
]
summary = self.search(domain)
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale_planner_calendar.action_sale_planner_calendar_summary"
)
if len(summary) > 1:
action["domain"] = [("id", "in", summary.ids)]
else:
action["views"] = [
(
self.env.ref(
"sale_planner_calendar.view_sale_planner_calendar_summary_form"
).id,
"form",
)
]
action["res_id"] = summary.id
return action
def action_done(self):
self.write(
{
"state": "done",
# "comment": 'Done',
}
)
def action_cancel(self):
self.write(
{
"state": "cancel",
"comment": "Not done",
}
)
def action_pending(self):
self.write(
{
"state": "pending",
"comment": False,
}
)
def action_process(self):
calendar_event_domain = [
("start", ">=", self.date.strftime("%Y-%m-%d 00:00:00")),
("start", "<=", self.date.strftime("%Y-%m-%d 23:59:59")),
("user_id", "=", self.user_id.id),
]
if self.event_type_id:
calendar_event_domain.append(("categ_ids", "in", self.event_type_id.ids))
calendar_events = self.env["calendar.event"].search(calendar_event_domain)
event_planner_domain = [
("calendar_event_date", ">=", self.date.strftime("%Y-%m-%d 00:00:00")),
("calendar_event_date", "<=", self.date.strftime("%Y-%m-%d 23:59:59")),
("user_id", "=", self.user_id.id),
"|",
("calendar_summary_id", "=", False),
("calendar_summary_id", "=", self.id),
]
events_planner = self.env["sale.planner.calendar.event"].search(
event_planner_domain
)
# We can not do a typical search due to returned virtual ids like this
# ("calendar_event_id.categ_ids", "in", self.event_type_id.ids)
if self.event_type_id:
events_planner = events_planner.filtered(
lambda p: self.event_type_id.id in p.calendar_event_id.categ_ids.ids
)
for calendar_event in calendar_events:
event_planner = events_planner.filtered(
lambda r: r.calendar_event_date
== fields.Datetime.to_datetime(calendar_event.start)
and r.partner_id == calendar_event.target_partner_id
and r.user_id == calendar_event.user_id
)
if event_planner:
if event_planner.calendar_summary_id != self:
event_planner.calendar_summary_id = self
event_planner.off_planning = True
else:
calendar_event.with_context(
default_calendar_summary_id=self.id,
default_date=calendar_event.start,
)._create_event_planner()
# Search sale orders off planning
date_from = self._get_datetime_from_date_tz_hour(
self.date, self.env.company.sale_planner_order_cut_hour
)
date_to = date_from + timedelta(days=1)
sales = self.env["sale.order"].search(
[
("user_id", "=", self.user_id.id),
("date_order", ">=", date_from),
("date_order", "<", date_to),
("sale_planner_calendar_event_id", "=", False),
]
)
sales.action_set_planner_calendar_event(self)
@api.model
def _get_datetime_from_date_tz_hour(self, date, hour_float):
"""
Compute date in UTC format
:return: Datetime in UTC format
"""
hour_str = str(timedelta(hours=hour_float)).zfill(8)
date_str = "{} {}".format(fields.Date.to_string(date), hour_str)
date_time = fields.Datetime.to_datetime(date_str)
user_tz = pytz.timezone(self.env.user.tz)
utc_tz = pytz.timezone("UTC")
time_utc = user_tz.localize(date_time).astimezone(utc_tz).replace(tzinfo=None)
return time_utc
def action_event_planner(self):
if not self.sale_planner_calendar_event_ids:
self.action_process()
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale_planner_calendar.action_sale_planner_calendar_event"
)
action["domain"] = [("id", "in", self.sale_planner_calendar_event_ids.ids)]
action["context"] = {
"default_off_planning": True,
"default_calendar_summary_id": self.id,
"search_default_state_pending": 1,
}
action["views"] = [
(
self.env.ref(
"sale_planner_calendar.view_sale_planner_calendar_kanban"
).id,
"kanban",
),
(
self.env.ref(
"sale_planner_calendar.view_sale_planner_calendar_form"
).id,
"form",
),
(
self.env.ref(
"sale_planner_calendar.view_sale_planner_calendar_tree"
).id,
"tree",
),
]
action["view_mode"] = "kanban,form,tree"
return action
def action_open_payment_sheet(self):
"""
Open payments sheets related to any event
"""
payment_sheets = self.sale_planner_calendar_event_ids.mapped(
"payment_sheet_line_ids.sheet_id"
)
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale_payment_sheet.action_sale_payment_sheet"
)
if len(payment_sheets) > 1:
action["domain"] = [("id", "in", payment_sheets.ids)]
else:
action["views"] = [
(
self.env.ref("sale_payment_sheet.view_sale_payment_sheet_form").id,
"form",
)
]
action["res_id"] = payment_sheets.id
return action
def action_open_issue(self):
"""
Open issues related to any event
"""
issues = self.sale_planner_calendar_event_ids.filtered("calendar_issue_type_id")
action = self.env["ir.actions.act_window"]._for_xml_id(
"sale_planner_calendar.action_sale_planner_calendar_issue_tree"
)
action["domain"] = [("id", "in", issues.ids)]
return action
| 36.386628
| 12,517
|
1,391
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Sergio Teruel - Tecnativa
# Copyright 2021 Tecnativa - Carlos Dauden
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
susbscriptions_backward_days = fields.Integer(
related="company_id.susbscriptions_backward_days",
readonly=False,
)
sale_planner_forward_months = fields.Integer(
related="company_id.sale_planner_forward_months",
readonly=False,
)
sale_planner_mail_to_attendees = fields.Boolean(
related="company_id.sale_planner_mail_to_attendees",
readonly=False,
)
sale_planner_order_cut_hour = fields.Float(
related="company_id.sale_planner_order_cut_hour",
readonly=False,
)
sale_planner_calendar_max_duration = fields.Float(
string="Calendar event max duration",
config_parameter="sale_planner_calendar.max_duration",
)
class ResCompany(models.Model):
_inherit = "res.company"
susbscriptions_backward_days = fields.Integer(
default=180,
)
sale_planner_forward_months = fields.Integer(
default=12,
)
sale_planner_mail_to_attendees = fields.Boolean(
string="Send invitation to attendees", default=True
)
sale_planner_order_cut_hour = fields.Float()
| 30.911111
| 1,391
|
3,264
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Tecnativa - Sergio Teruel
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from datetime import timedelta
from odoo import _, fields, models
from odoo.exceptions import ValidationError
from odoo.tools.date_utils import relativedelta
class ResPartner(models.Model):
_inherit = "res.partner"
is_sale_planner_contact = fields.Boolean()
def action_calendar_planner(self):
categ = self.env.ref("sale_planner_calendar.event_type_commercial_visit")
action = self.env["ir.actions.act_window"]._for_xml_id(
"calendar.action_calendar_event"
)
sale_planner_forward_months = self.env.company.sale_planner_forward_months
# TODO: Get default values from res.config.settings
action["context"] = {
"no_mail_to_attendees": False
if self.env.company.sale_planner_mail_to_attendees
else True,
"calendar_event_primary_only": True,
"default_target_partner_id": self.id,
"default_categ_ids": [(4, categ.id)],
"default_location": self._display_address(),
"default_duration": categ.duration,
"default_name": categ.name,
"default_start": fields.Datetime.now(),
"default_stop": fields.Datetime.now()
+ timedelta(minutes=round((categ.duration or 1.0) * 60)),
"default_recurrency": True,
"default_rrule_type": "weekly",
"default_end_type": "end_date",
"default_until": fields.Date.today()
+ relativedelta(months=sale_planner_forward_months),
"default_is_dynamic_end_date": True,
"default_user_id": self.user_id.id or self.env.user.id,
"default_partner_ids": [
(
6,
0,
[
self.id,
self.user_id.partner_id.id or self.env.user.partner_id.id,
],
)
],
}
action["view_mode"] = "tree,form"
action["view_id"] = False
action["views"] = []
action["domain"] = [
("target_partner_id", "=", self.id),
("recurrency", "=", True),
("recurrence_id.until", ">", fields.Date.today()),
]
return action
def write(self, vals):
if (
"user_id" in vals
and vals.get("user_id")
and not self.env.context.get("skip_sale_planner_check", False)
):
calendar_events = (
self.env["calendar.event"]
.with_context(calendar_event_primary_only=True)
.search(
[
("target_partner_id", "in", self.ids),
("recurrency", "!=", False),
("user_id", "!=", vals["user_id"]),
]
)
)
if calendar_events:
msg = _(
"This partner has sale planned events\n"
"You must change salesperson from the planner wizard"
)
raise ValidationError(msg)
return super().write(vals)
| 37.953488
| 3,264
|
587
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Sale Order Partner Restrict",
"summary": "Apply restrictions when selecting from the list of customers on SO.",
"version": "15.0.1.0.0",
"category": "Sales Management",
"website": "https://github.com/OCA/sale-workflow",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["sale_management"],
"data": ["views/res_config_settings_views.xml", "views/sale_order_view.xml"],
"installable": True,
"maintainers": ["OriolVForgeFlow"],
}
| 41.928571
| 587
|
4,345
|
py
|
PYTHON
|
15.0
|
from odoo.exceptions import ValidationError
from odoo.tests import tagged
from odoo.tests.common import TransactionCase
@tagged("post_install", "-at_install")
class TestSaleOrderPartnerRestrict(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.main_company = cls.env.ref("base.main_company")
cls.second_company = cls.env["res.company"].create({"name": "Second Company"})
cls.partner_model = cls.env["res.partner"]
cls.partner_parent = cls.partner_model.create(
{"name": "Partner Parent", "type": "contact"}
)
cls.partner_child = cls.partner_model.create(
{
"name": "Partner Child",
"type": "contact",
"parent_id": cls.partner_parent.id,
}
)
cls.partner_diff_company = cls.partner_model.create(
{
"name": "Partner Different Company",
"type": "contact",
"company_id": cls.second_company.id,
}
)
cls.partner_delivery = cls.partner_model.create(
{
"name": "Partner Delivery",
"type": "other",
"parent_id": cls.partner_parent.id,
}
)
def _create_sale_order(self, partner):
so = self.env["sale.order"].create(
{"partner_id": partner.id, "company_id": self.main_company.id}
)
return so
def test_sale_order_partner_restrict_option_all(self):
self.main_company.sale_order_partner_restrict = "all"
self.assertTrue(
self._create_sale_order(self.partner_parent),
"Parent and contact type partner " "should be available on 'all' option",
)
self.assertTrue(
self._create_sale_order(self.partner_child),
"Child and contact type partner " "should be available in 'all' option",
)
# Partner from another company
# shouldn't be available on this company (option 'all')
with self.assertRaises(ValidationError):
self._create_sale_order(self.partner_diff_company)
self.assertTrue(
self._create_sale_order(self.partner_delivery),
"Child and other type partner " "should be available in 'all' option",
)
def test_sale_order_partner_restrict_option_only_parents(self):
self.main_company.sale_order_partner_restrict = "only_parents"
self.assertTrue(
self._create_sale_order(self.partner_parent),
"Parent and contact type partner "
"should be available in 'only_parents' option",
)
# Child and contact type partner shouldn't be available in 'only_parents' option
with self.assertRaises(ValidationError):
self._create_sale_order(self.partner_child)
# Partner from another company
# shouldn't be available on this company (option 'only_parents')
with self.assertRaises(ValidationError):
self._create_sale_order(self.partner_diff_company)
# Child and other type partner
# shouldn't be available in 'only_parents' option
with self.assertRaises(ValidationError):
self._create_sale_order(self.partner_delivery)
def test_sale_order_partner_restrict_option_parents_and_contacts(self):
self.main_company.sale_order_partner_restrict = "parents_and_contacts"
self.assertTrue(
self._create_sale_order(self.partner_parent),
"Parent and contact type partner "
"should be available in 'parents_and_contacts' option",
)
self.assertTrue(
self._create_sale_order(self.partner_child),
"Child and contact type partner "
"should be available in 'parents_and_contacts' option",
)
# Partner from another company
# shouldn't be available on this company (option 'parents_and_contacts')
with self.assertRaises(ValidationError):
self._create_sale_order(self.partner_diff_company)
# Child and other type partner
# shouldn't be available in 'parents_and_contacts' option
with self.assertRaises(ValidationError):
self._create_sale_order(self.partner_delivery)
| 37.136752
| 4,345
|
495
|
py
|
PYTHON
|
15.0
|
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
sale_order_partner_restrict = fields.Selection(
[
("all", "All partners"),
("only_parents", "Only parent accounts (no contacts)"),
("parents_and_contacts", "Parent accounts and contacts"),
],
"Partner Restriction on Sale Orders",
default="all",
)
| 29.117647
| 495
|
379
|
py
|
PYTHON
|
15.0
|
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
sale_order_partner_restrict = fields.Selection(
related="company_id.sale_order_partner_restrict",
string="Partner Restriction on Sale Orders",
readonly=False,
)
| 29.153846
| 379
|
2,379
|
py
|
PYTHON
|
15.0
|
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.osv import expression
class SaleOrder(models.Model):
_inherit = "sale.order"
sale_order_partner_restrict = fields.Selection(
related="company_id.sale_order_partner_restrict",
string="Partner Restriction on Sale Orders",
)
def _get_partner_restrict_domain(self):
partner_restrict_domain = []
if (
self.sale_order_partner_restrict == "all"
or self.sale_order_partner_restrict is None
):
partner_restrict_domain = [
"|",
("company_id", "=", False),
("company_id", "=", self.company_id.id),
]
elif self.sale_order_partner_restrict == "only_parents":
partner_restrict_domain = [
"&",
("parent_id", "=", False),
"|",
("company_id", "=", False),
("company_id", "=", self.company_id.id),
]
elif self.sale_order_partner_restrict == "parents_and_contacts":
partner_restrict_domain = [
"&",
"|",
("company_id", "=", False),
("company_id", "=", self.company_id.id),
"|",
("parent_id", "=", False),
("type", "=", "contact"),
]
return partner_restrict_domain
@api.onchange("sale_order_partner_restrict")
def _onchange_sale_order_partner_restrict(self):
self.ensure_one()
return {"domain": {"partner_id": self._get_partner_restrict_domain()}}
@api.constrains("partner_id")
def _check_order_partner_restrict(self):
for order in self:
domain = order._get_partner_restrict_domain()
if not order.partner_id.search(
expression.AND([[("id", "=", order.partner_id.id)], domain])
):
raise ValidationError(
_(
"The Customer %(partner_name)s is not available for this "
"company (%(company_name)s)."
)
% {
"partner_name": order.partner_id.name,
"company_name": order.company_id.name,
}
)
| 36.045455
| 2,379
|
788
|
py
|
PYTHON
|
15.0
|
# Copyright 2010-2012 Andy Lu <andy.lu@elico-corp.com> (Elico Corp)
# Copyright 2013 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright 2017 valentin vinagre <valentin.vinagre@qubiq.es> (QubiQ)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
{
"name": "Sale Quotation Numeration",
"summary": "Different sequence for sale quotations",
"version": "15.0.1.0.1",
"category": "Sales Management",
"website": "https://github.com/OCA/sale-workflow",
"author": "Elico Corp, "
"Agile Business Group, "
"Qubiq, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["sale_management"],
"data": ["data/ir_sequence_data.xml", "views/sales_config.xml"],
}
| 37.52381
| 788
|
3,018
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 Simone Rubino - Agile Business Group
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
class TestSaleOrder(TransactionCase):
def setUp(self, *args, **kwargs):
super(TestSaleOrder, self).setUp()
self.sale_order_model = self.env["sale.order"]
company = self.env.company
company.keep_name_so = False
def test_enumeration(self):
order1 = self.sale_order_model.create(
{"partner_id": self.env.ref("base.res_partner_1").id}
)
quotation1_name = order1.name
order2 = self.sale_order_model.create(
{"partner_id": self.env.ref("base.res_partner_1").id}
)
quotation2_name = order2.name
self.assertRegex(quotation1_name, "SQ")
self.assertRegex(quotation2_name, "SQ")
self.assertLess(int(quotation1_name[2:]), int(quotation2_name[2:]))
order2.action_confirm()
order1.action_confirm()
self.assertRegex(order1.name, "S")
self.assertEqual(order1.origin, quotation1_name)
self.assertRegex(order2.name, "S")
self.assertEqual(order2.origin, quotation2_name)
self.assertLess(int(order2.name[1:]), int(order1.name[1:]))
def test_with_origin(self):
origin = "origin"
order1 = self.sale_order_model.create(
{"origin": origin, "partner_id": self.env.ref("base.res_partner_1").id}
)
quotation1_name = order1.name
order1.action_confirm()
self.assertRegex(order1.name, "S")
self.assertEqual(order1.origin, ", ".join([origin, quotation1_name]))
def test_copy_no_origin(self):
order1 = self.sale_order_model.create(
{"partner_id": self.env.ref("base.res_partner_1").id}
)
order_copy = order1.copy()
self.assertEqual(order1.name, order_copy.origin)
def test_copy_with_origin(self):
origin = "origin"
order1 = self.sale_order_model.create(
{"origin": origin, "partner_id": self.env.ref("base.res_partner_1").id}
)
order_copy = order1.copy()
self.assertEqual(", ".join([origin, order1.name]), order_copy.origin)
def test_error_confirmation_sequence(self):
order = self.sale_order_model.create(
{"partner_id": self.env.ref("base.res_partner_1").id, "state": "done"}
)
# An exception is forced
sequence_id = self.env["ir.sequence"].search(
[
("code", "=", "sale.order"),
("company_id", "in", [order.company_id.id, False]),
]
)
next_name = sequence_id.get_next_char(sequence_id.number_next_actual)
with self.assertRaises(UserError):
order.action_confirm()
order.update({"state": "draft"})
# Now the SQ can be confirmed
order.action_confirm()
self.assertEqual(next_name, order.name)
| 35.928571
| 3,018
|
1,843
|
py
|
PYTHON
|
15.0
|
# © 2010-2012 Andy Lu <andy.lu@elico-corp.com> (Elico Corp)
# © 2013 Agile Business Group sagl (<http://www.agilebg.com>)
# © 2017 valentin vinagre <valentin.vinagre@qubiq.es> (QubiQ)
# © 2020 Manuel Regidor <manuel.regidor@sygel.es>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import api, models
class SaleOrder(models.Model):
_inherit = "sale.order"
@api.model
def create(self, vals):
if self.is_using_quotation_number(vals):
sequence = self.env["ir.sequence"].next_by_code("sale.quotation")
vals["name"] = sequence or "/"
return super(SaleOrder, self).create(vals)
@api.model
def is_using_quotation_number(self, vals):
company = False
if "company_id" in vals:
company = self.env["res.company"].browse(vals.get("company_id"))
else:
company = self.env.company
return not company.keep_name_so
def copy(self, default=None):
self.ensure_one()
if default is None:
default = {}
if self.origin and self.origin != "":
default["origin"] = self.origin + ", " + self.name
else:
default["origin"] = self.name
return super(SaleOrder, self).copy(default)
def action_confirm(self):
for order in self:
if self.name[:2] != "SQ":
continue
if order.state not in ("draft", "sent") or order.company_id.keep_name_so:
continue
if order.origin and order.origin != "":
quo = order.origin + ", " + order.name
else:
quo = order.name
sequence = self.env["ir.sequence"].next_by_code("sale.order")
order.write({"origin": quo, "name": sequence})
return super().action_confirm()
| 36.058824
| 1,839
|
777
|
py
|
PYTHON
|
15.0
|
# © 2010-2012 Andy Lu <andy.lu@elico-corp.com> (Elico Corp)
# © 2013 Agile Business Group sagl (<http://www.agilebg.com>)
# © 2017 valentin vinagre <valentin.vinagre@qubiq.es> (QubiQ)
# © 2020 Manuel Regidor <manuel.regidor@sygel.es>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
keep_name_so = fields.Boolean(
string="Use Same Enumeration",
help="If this is unchecked, quotations use a different sequence from "
"sale orders",
default=True,
)
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
keep_name_so = fields.Boolean(related="company_id.keep_name_so", readonly=False)
| 32.208333
| 773
|
1,381
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo import SUPERUSER_ID
from odoo.api import Environment
from odoo.tools.sql import column_exists, create_column
_logger = logging.getLogger(__name__)
COLUMNS = (
("sale_order", "price_total_no_discount"),
("sale_order", "discount_total"),
("sale_order_line", "price_total_no_discount"),
("sale_order_line", "discount_total"),
)
def pre_init_hook(cr):
for table, column in COLUMNS:
if not column_exists(cr, table, column):
_logger.info("Create discount column %s in database", column)
create_column(cr, table, column, "numeric")
def post_init_hook(cr, registry):
_logger.info("Compute discount columns")
env = Environment(cr, SUPERUSER_ID, {})
query = """
update sale_order_line
set price_total_no_discount = price_total
where discount = 0.0
"""
cr.execute(query)
query = """
update sale_order
set price_total_no_discount = amount_total
"""
cr.execute(query)
query = """
select distinct order_id from sale_order_line where discount > 0.0;
"""
cr.execute(query)
order_ids = cr.fetchall()
orders = env["sale.order"].search([("id", "in", order_ids)])
orders.mapped("order_line")._update_discount_display_fields()
| 27.078431
| 1,381
|
611
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sale Discount Display Amount",
"summary": """
This addon intends to display the amount of the discount computed on
sale_order_line and sale_order level""",
"version": "15.0.1.0.1",
"license": "AGPL-3",
"author": "ACSONE SA/NV,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"depends": ["sale_management"],
"data": ["views/sale_view.xml"],
"pre_init_hook": "pre_init_hook",
"post_init_hook": "post_init_hook",
}
| 35.941176
| 611
|
1,680
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestDiscountDisplay(TransactionCase):
def test_sale_discount_value(self):
product1 = self.env["product.product"].create(
{"name": "Product TEST", "type": "consu"}
)
customer = self.env["res.partner"].create(
{"name": "Customer TEST", "is_company": False, "email": "test@tes.ttest"}
)
so = self.env["sale.order"].create({"partner_id": customer.id})
self.env["sale.order.line"].create(
{"order_id": so.id, "product_id": product1.id, "price_unit": 30.75}
)
first_line = so.order_line[0]
first_line.discount = 10
self.assertAlmostEqual(first_line.price_total_no_discount, 35.36)
self.assertAlmostEqual(first_line.discount_total, 3.53)
self.assertAlmostEqual(so.discount_total, 3.53)
self.assertAlmostEqual(so.price_total_no_discount, 35.36)
def test_sale_without_discount_value(self):
product2 = self.env["product.product"].create(
{"name": "Product TEST", "type": "consu"}
)
customer2 = self.env["res.partner"].create(
{"name": "Customer TEST", "is_company": False, "email": "test@tes.ttest"}
)
so2 = self.env["sale.order"].create({"partner_id": customer2.id})
self.env["sale.order.line"].create(
{"order_id": so2.id, "product_id": product2.id, "price_unit": 30.75}
)
first_line = so2.order_line[0]
self.assertEqual(first_line.price_total_no_discount, first_line.price_total)
| 43.076923
| 1,680
|
1,127
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
discount_total = fields.Monetary(
compute="_compute_discount_total",
string="Discount Subtotal",
currency_field="currency_id",
store=True,
)
price_total_no_discount = fields.Monetary(
compute="_compute_discount_total",
string="Subtotal Without Discount",
currency_field="currency_id",
store=True,
)
@api.depends("order_line.discount_total", "order_line.price_total_no_discount")
def _compute_discount_total(self):
for order in self:
discount_total = sum(order.order_line.mapped("discount_total"))
price_total_no_discount = sum(
order.order_line.mapped("price_total_no_discount")
)
order.update(
{
"discount_total": discount_total,
"price_total_no_discount": price_total_no_discount,
}
)
| 31.305556
| 1,127
|
1,600
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
discount_total = fields.Monetary(
compute="_compute_amount", string="Discount Subtotal", store=True
)
price_total_no_discount = fields.Monetary(
compute="_compute_amount", string="Subtotal Without Discount", store=True
)
def _update_discount_display_fields(self):
for line in self:
line.price_total_no_discount = 0
line.discount_total = 0
if not line.discount:
line.price_total_no_discount = line.price_total
continue
price = line.price_unit
taxes = line.tax_id.compute_all(
price,
line.order_id.currency_id,
line.product_uom_qty,
product=line.product_id,
partner=line.order_id.partner_shipping_id,
)
price_total_no_discount = taxes["total_included"]
discount_total = price_total_no_discount - line.price_total
line.update(
{
"discount_total": discount_total,
"price_total_no_discount": price_total_no_discount,
}
)
@api.depends("product_uom_qty", "discount", "price_unit", "tax_id")
def _compute_amount(self):
res = super(SaleOrderLine, self)._compute_amount()
self._update_discount_display_fields()
return res
| 33.333333
| 1,600
|
815
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-2017 Agile Business Group sagl
# (<http://www.agilebg.com>)
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Product Supplierinfo for Customer Sale",
"version": "15.0.1.1.0",
"summary": "Loads in every sale order line the customer code defined "
"in the product",
"author": "Agile Business Group,Vauxoo,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/sale-workflow",
"category": "Sales Management",
"license": "AGPL-3",
"depends": ["sale", "product_supplierinfo_for_customer"],
"data": [
"security/ir.model.access.csv",
"views/product_customerinfo_views.xml",
"views/sale_view.xml",
],
"installable": True,
}
| 38.809524
| 815
|
3,354
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Vauxoo (https://www.vauxoo.com) info@vauxoo.com
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestProductNameSearch(TransactionCase):
"""Test for:
- Assign a configuration customer for product.
- Test product name_search
"""
def setUp(self):
super(TestProductNameSearch, self).setUp()
self.supplier = self.env.ref("base.res_partner_1")
self.customer = self.env.ref("base.res_partner_2")
self.product = (
self.env["product.product"]
.create({"name": "Name_product", "default_code": "code_product"})
.with_context(**{"partner_id": self.customer.id})
)
self.supplierinfo = self.env["product.supplierinfo"]
self.customerinfo = self.env["product.customerinfo"]
self.customerinfo_dict = {
"product_code": "code_test",
"product_name": "Name_test",
"name": self.customer.id,
"product_tmpl_id": self.product.product_tmpl_id.id,
}
def test_10_find_product_customer_code(self):
"""Assign a product_customerinfo to the product and then search it
using name_search
"""
self.assertFalse(self.product.customer_ids)
self.customerinfo.create(self.customerinfo_dict)
self.assertTrue(self.product.customer_ids)
# Search by product customer code
product_names = self.product.name_search(name="code_test")
self.assertEqual(len(product_names), 1)
self.assertEqual(self.product.id, product_names[0][0])
self.assertEqual("[code_test] Name_test", product_names[0][1])
# Search by product default code with the customer used in
# configuration customer
product_names = self.product.name_search(name="code_product")
self.assertEqual(len(product_names), 1)
self.assertEqual(self.product.id, product_names[0][0])
self.assertEqual("[code_test] Name_test", product_names[0][1])
# Search by product default code with a different customer used in
# configuration customer
product_names = self.product.with_context(
partner_id=self.supplier.id
).name_search(name="code_product")
self.assertEqual(len(product_names), 1)
self.assertEqual(self.product.id, product_names[0][0])
self.assertEqual("[code_product] Name_product", product_names[0][1])
# Create a product_1 with default_code similar to customer_code of
# product, then name_search must find two products
self.product_1 = (
self.env["product.product"]
.create({"name": "Name_test_1", "default_code": "code_test_1"})
.with_context(**{"partner_id": self.customer.id})
)
self.assertFalse(self.product_1.customer_ids)
# Search by product customer code
product_names = self.product.name_search(name="code_test")
self.assertEqual(len(product_names), 2)
product_names = product_names[0] + product_names[1]
self.assertIn(self.product.id, product_names)
self.assertIn(self.product_1.id, product_names)
self.assertIn("[code_test] Name_test", product_names)
self.assertIn("[code_test_1] Name_test_1", product_names)
| 42.455696
| 3,354
|
6,590
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestProductSupplierinfoForCustomerSale(TransactionCase):
def setUp(self):
super(TestProductSupplierinfoForCustomerSale, self).setUp()
self.supplierinfo_model = self.env["product.supplierinfo"]
self.customerinfo_model = self.env["product.customerinfo"]
self.pricelist_item_model = self.env["product.pricelist.item"]
self.pricelist_model = self.env["product.pricelist"]
self.customer = self._create_customer("customer1")
self.product = self.env.ref("product.product_product_4")
self.product_variant_1 = self.env.ref("product.product_product_4b")
self.product_variant_2 = self.env.ref("product.product_product_4c")
self.customerinfo = self._create_partnerinfo(
"customer", self.customer, self.product
)
self.pricelist = self._create_pricelist("Test Pricelist", self.product)
self.pricelist_item = self._create_pricelist_item(
"Test Pricelist Item", self.pricelist, self.product
)
self.company = self.env.ref("base.main_company")
self._create_partnerinfo("customer", self.customer, self.product_variant_1)
self._create_partnerinfo(
"customer", self.customer, self.product_variant_2, empty_variant=True
)
self.product_template = self.env["product.template"].create(
{"name": "product wo variants"}
)
self._create_partnerinfo(
"customer",
self.customer,
self.product_template.product_variant_ids[:1],
empty_variant=True,
)
self.pricelist_template = self._create_pricelist(
"Test Pricelist Template", self.product_template.product_variant_ids[:1]
)
def _create_customer(self, name):
return self.env["res.partner"].create(
{"name": name, "email": "example@yourcompany.com", "phone": 123456}
)
def _create_partnerinfo(
self, supplierinfo_type, partner, product, empty_variant=False
):
vals = {
"name": partner.id,
"product_id": product.id,
"product_name": "product4",
"product_code": "00001",
"price": 100.0,
"min_qty": 15.0,
}
if empty_variant:
vals.pop("product_id", None)
vals["product_tmpl_id"] = product.product_tmpl_id.id
return self.env["product." + supplierinfo_type + "info"].create(vals)
def _create_pricelist(self, name, product):
return self.pricelist_model.create(
{"name": name, "currency_id": self.env.ref("base.USD").id}
)
def _create_pricelist_item(self, name, pricelist, product):
return self.pricelist_item_model.create(
{
"name": name,
"pricelist_id": pricelist.id,
"applied_on": "0_product_variant",
"product_id": product.id,
"compute_price": "formula",
"base": "partner",
}
)
def test_product_supplierinfo_for_customer_sale(self):
so = self.env["sale.order"].create(
{"partner_id": self.customer.id, "pricelist_id": self.pricelist.id}
)
line = self.env["sale.order.line"].create(
{"product_id": self.product.id, "order_id": so.id}
)
line.product_id_change()
self.assertEqual(
line.product_customer_code,
self.customerinfo.product_code,
"Error: Customer product code was not passed to sale order line",
)
self.assertEqual(
line.product_uom_qty,
self.customerinfo.min_qty,
"Error: Min qty was not passed to the sale order line",
)
def test_product_supplierinfo_for_customer_sale_variant(self):
so = self.env["sale.order"].create(
{"partner_id": self.customer.id, "pricelist_id": self.pricelist.id}
)
line = self.env["sale.order.line"].create(
{"product_id": self.product_variant_1.id, "order_id": so.id}
)
line.product_id_change()
self.assertEqual(
line.product_customer_code,
self.customerinfo.product_code,
"Error: Customer product code was not passed to sale order line",
)
def test_product_supplierinfo_for_customer_sale_template(self):
customerinfo = self._create_partnerinfo(
"customer", self.customer, self.product_variant_2
)
so = self.env["sale.order"].create(
{"partner_id": self.customer.id, "pricelist_id": self.pricelist.id}
)
line = self.env["sale.order.line"].create(
{"product_id": self.product_variant_2.id, "order_id": so.id}
)
line.product_id_change()
self.assertEqual(
line.product_customer_code,
customerinfo.product_code,
"Error: Customer product code was not passed to sale order line",
)
# Test with product without variants
so2 = self.env["sale.order"].create(
{
"partner_id": self.customer.id,
"pricelist_id": self.pricelist_template.id,
}
)
line2 = self.env["sale.order.line"].create(
{
"product_id": self.product_template.product_variant_ids.id,
"order_id": so2.id,
}
)
line2.product_id_change()
self.assertEqual(
line2.product_customer_code,
customerinfo.product_code,
"Error: Customer product code was not passed to sale order line",
)
def test_product_supplierinfo_for_customer_sale_variant_wo_template(self):
customerinfo = self._create_partnerinfo(
"customer", self.customer, self.product_variant_2, empty_variant=True
)
so = self.env["sale.order"].create(
{"partner_id": self.customer.id, "pricelist_id": self.pricelist.id}
)
line = self.env["sale.order.line"].create(
{"product_id": self.product_variant_2.id, "order_id": so.id}
)
line.product_id_change()
self.assertEqual(
line.product_customer_code,
customerinfo.product_code,
"Error: Customer product code was not passed to sale order line",
)
| 39.939394
| 6,590
|
2,321
|
py
|
PYTHON
|
15.0
|
# Copyright 2013-2017 Agile Business Group sagl
# (<http://www.agilebg.com>)
# Copyright 2021 ForgeFlow S.L. (https://www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
product_customer_code = fields.Char(
compute="_compute_product_customer_code",
)
@api.depends("product_id")
def _compute_product_customer_code(self):
for line in self:
if line.product_id:
supplierinfo = line.product_id._select_customerinfo(
partner=line.order_partner_id
)
code = supplierinfo.product_code
else:
code = ""
line.product_customer_code = code
@api.onchange("product_id")
def product_id_change(self):
result = super(SaleOrderLine, self).product_id_change()
for line in self.filtered(
lambda sol: sol.product_id.product_tmpl_id.customer_ids
and sol.order_id.pricelist_id.item_ids
):
product = line.product_id
items = self.env["product.pricelist.item"].search(
[
("pricelist_id", "=", line.order_id.pricelist_id.id),
("compute_price", "=", "formula"),
("base", "=", "partner"),
"|",
("applied_on", "=", "3_global"),
"|",
"&",
("categ_id", "=", product.categ_id.id),
("applied_on", "=", "2_product_category"),
"|",
"&",
("product_tmpl_id", "=", product.product_tmpl_id.id),
("applied_on", "=", "1_product"),
"&",
("product_id", "=", product.id),
("applied_on", "=", "0_product_variant"),
]
)
if items:
supplierinfo = line.product_id._select_customerinfo(
partner=line.order_partner_id
)
if supplierinfo and supplierinfo.min_qty:
line.product_uom_qty = supplierinfo.min_qty
return result
| 37.435484
| 2,321
|
655
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
{
"name": "Sales Stock Invoice Plan",
"summary": "Add to sales order, ability to manage future invoice plan",
"version": "15.0.1.0.1",
"author": "Ecosoft,Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/sale-workflow",
"category": "Sales",
"depends": ["sale_invoice_plan", "sale_stock"],
"data": ["security/ir.model.access.csv"],
"installable": True,
"development_status": "Alpha",
"maintainers": ["kittiu"],
"auto_install": True,
}
| 36.388889
| 655
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.