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
|
|---|---|---|---|---|---|---|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
100
|
py
|
PYTHON
|
15.0
|
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| 16.666667
| 100
|
479
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Account Invoice Blocking",
"summary": "Set a blocking (No Follow-up) flag on invoices",
"version": "15.0.1.0.1",
"license": "AGPL-3",
"category": "Accounting",
"author": "Acsone SA/NV,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"depends": ["account"],
"data": ["views/account_move.xml"],
}
| 34.214286
| 479
|
1,906
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
@tagged("post_install", "-at_install")
class TestAccountMoveBlocking(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.in_invoice = cls.init_invoice(
"in_invoice", products=cls.product_a + cls.product_b
)
cls.in_invoice._post()
cls.out_invoice = cls.init_invoice(
"out_invoice", products=cls.product_a + cls.product_b
)
cls.out_invoice._post()
def test_in_invoice_blocking(self):
self.assertFalse(self.in_invoice.blocked)
line = self.in_invoice.line_ids.filtered(
lambda r: r.account_id.user_type_id
== self.env.ref("account.data_account_type_payable")
)
self.assertTrue(line)
self.assertFalse(line.blocked)
self.assertFalse(any(il.blocked for il in (self.in_invoice.line_ids - line)))
self.in_invoice.blocked = True
self.assertTrue(line.blocked)
self.assertFalse(any(il.blocked for il in (self.in_invoice.line_ids - line)))
def test_out_invoice_blocking(self):
self.assertFalse(self.out_invoice.blocked)
line = self.out_invoice.line_ids.filtered(
lambda r: r.account_id.user_type_id
== self.env.ref("account.data_account_type_receivable")
)
self.assertTrue(line)
self.assertFalse(line.blocked)
self.assertFalse(any(il.blocked for il in (self.out_invoice.line_ids - line)))
self.out_invoice.blocked = True
self.assertTrue(line.blocked)
self.assertFalse(any(il.blocked for il in (self.out_invoice.line_ids - line)))
| 40.553191
| 1,906
|
2,037
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
blocked = fields.Boolean(
"No Follow-up",
states={"draft": [("readonly", True)]},
compute="_compute_move_blocked",
inverse="_inverse_move_blocked",
)
def _get_move_line(self):
"""
This method searches for payable or receivable move line
of the invoice
:returns payable or receivable move line of the invoice
"""
self.ensure_one()
type_receivable = self.env.ref("account.data_account_type_receivable")
type_payable = self.env.ref("account.data_account_type_payable")
user_type = type_receivable | type_payable
return self.line_ids.filtered(lambda r: r.account_id.user_type_id in user_type)
def _update_blocked(self, value):
"""
This method updates the boolean field 'blocked' of the move line
of the passed invoice with the passed value
:param value: value to set to the 'blocked' field of the move line
"""
self.ensure_one()
move_line_ids = self._get_move_line()
move_line_ids.write({"blocked": value})
def _inverse_move_blocked(self):
"""
Inverse method of the computed field 'blocked'
This method calls the update of the invoice's move line based on
the value of the field 'blocked'
"""
for invoice in self:
invoice._update_blocked(invoice.blocked)
@api.depends("line_ids", "line_ids.blocked")
def _compute_move_blocked(self):
"""
This method set the value of the field 'blocked' to True
If every line of the move is actually blocked
"""
for move in self:
move_lines = move._get_move_line()
move.blocked = (
all(line.blocked for line in move_lines) if move_lines else False
)
| 35.12069
| 2,037
|
667
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Creu Blanca
# Copyright 2022 Moduon
# License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html).
{
"name": "Purchase Self Invoice",
"version": "15.0.1.3.0",
"author": "CreuBlanca, Moduon, Odoo Community Association (OCA)",
"category": "Accounting & Finance",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"depends": ["account"],
"data": [
"data/mail_template_data.xml",
"views/res_config_settings_views.xml",
"views/res_partner_views.xml",
"views/account_move_views.xml",
"views/report_self_invoice.xml",
],
"installable": True,
}
| 31.761905
| 667
|
925
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Creu Blanca
# License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html).
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
companies = env["res.company"].search([]).ids
main_company = env.ref("base.main_company", False) or companies[0]
openupgrade.logged_query(
env.cr,
"""
SELECT id, self_invoice_sequence_id, company_id
FROM res_partner
WHERE self_invoice
""",
)
for row in env.cr.fetchall():
partner = env["res.partner"].browse(row[0])
partner_companies = companies
if row[2] is not None:
partner_companies = [row[2]]
for company in partner_companies:
partner.with_company(company).write({"self_invoice": True})
partner.with_company(row[2] or main_company).write(
{"self_invoice_sequence_id": row[1]}
)
| 33.035714
| 925
|
5,378
|
py
|
PYTHON
|
15.0
|
# © 2017 Creu Blanca
# Copyright 2022 - Moduon
# License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html).
from odoo.tests import Form, common
class TestSelfInvoice(common.TransactionCase):
def setUp(self):
res = super(TestSelfInvoice, self).setUp()
self.user = self.env.ref("base.user_admin")
self.partner = self.env["res.partner"].create(
{"name": "Partner", "supplier_rank": 1}
)
self.child_partner = self.env["res.partner"].create(
{
"name": "Partner",
"parent_id": self.partner.id,
}
)
self.simple_partner = self.env["res.partner"].create(
{"name": "Partner", "supplier_rank": 1}
)
main_company = self.env.ref("base.main_company")
main_company.self_invoice_prefix = "MC"
main_company.external_report_layout_id = self.env.ref(
"web.report_layout_standard"
).view_id
self.invoice = self.env["account.move"].create(
{
"company_id": main_company.id,
"partner_id": self.simple_partner.id,
"move_type": "in_invoice",
"invoice_date": "2016-03-12",
}
)
self.refund = self.env["account.move"].create(
{
"company_id": main_company.id,
"partner_id": self.simple_partner.id,
"move_type": "in_refund",
"invoice_date": "2016-03-12",
}
)
product = self.env["product.product"].create({"name": "Lemonade"})
account = self.env["account.account"].create(
{
"company_id": main_company.id,
"name": "Testing Product account",
"code": "test_product",
"user_type_id": self.env.ref("account.data_account_type_revenue").id,
}
)
self.env["account.move.line"].create(
{
"move_id": self.invoice.id,
"product_id": product.id,
"quantity": 1,
"account_id": account.id,
"name": "Test product",
# "price_unit": 20,
}
)
self.env["account.move.line"].create(
{
"move_id": self.refund.id,
"product_id": product.id,
"quantity": 1,
"account_id": account.id,
"name": "Test product",
# "price_unit": 20,
}
)
self.invoice._onchange_invoice_line_ids()
self.refund._onchange_invoice_line_ids()
return res
def test_check_set_self_invoice(self):
self.assertFalse(self.partner.self_invoice)
self.assertFalse(self.partner.self_invoice_report_footer)
with Form(self.partner) as f:
f.self_invoice = True
self.assertFalse(self.partner.self_invoice_sequence_id)
self.assertTrue(self.partner.self_invoice_report_footer)
self.invoice.partner_id = self.partner
self.invoice._onchange_partner_id()
self.invoice.action_post()
self.assertTrue(self.partner.self_invoice_sequence_id)
self.assertRegex(self.invoice.ref, r"/INV/")
self.assertFalse(self.partner.self_invoice_refund_sequence_id)
def test_check_set_self_invoice_refund(self):
self.assertFalse(self.partner.self_invoice)
with Form(self.partner) as f:
f.self_invoice = True
self.assertFalse(self.partner.self_invoice_sequence_id)
self.refund.partner_id = self.partner
self.refund._onchange_partner_id()
self.refund.action_post()
self.assertFalse(self.partner.self_invoice_sequence_id)
self.assertRegex(self.refund.ref, r"/RINV/")
self.assertTrue(self.partner.self_invoice_refund_sequence_id)
def test_none_self_invoice(self):
self.assertFalse(self.invoice.self_invoice_number)
self.invoice.action_post()
self.assertFalse(self.invoice.self_invoice_number)
def test_self_invoice(self):
with Form(self.partner) as f:
f.self_invoice = True
self.assertFalse(self.simple_partner.self_invoice)
self.assertFalse(self.invoice.can_self_invoice)
self.invoice.partner_id = self.partner
self.invoice._onchange_partner_id()
self.assertTrue(self.invoice.can_self_invoice)
self.assertTrue(self.invoice.set_self_invoice)
self.invoice.invoice_date = None
self.invoice.with_user(self.user.id).action_post()
self.assertTrue(self.invoice.invoice_date)
self.assertTrue(self.invoice.self_invoice_number)
def test_self_invoice_child(self):
with Form(self.partner) as f:
f.self_invoice = True
self.assertFalse(self.simple_partner.self_invoice)
self.assertFalse(self.invoice.can_self_invoice)
self.invoice.partner_id = self.child_partner
self.invoice._onchange_partner_id()
self.assertTrue(self.invoice.can_self_invoice)
self.assertTrue(self.invoice.set_self_invoice)
self.invoice.invoice_date = None
self.invoice.with_user(self.user.id).action_post()
self.assertTrue(self.invoice.invoice_date)
self.assertTrue(self.invoice.self_invoice_number)
| 39.82963
| 5,377
|
3,294
|
py
|
PYTHON
|
15.0
|
# © 2017 Creu Blanca
# Copyright 2022 - Moduon
# License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html).
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
self_invoice_number = fields.Char(
string="Self-Bill Invoice Number",
readonly=True,
copy=False,
)
is_self_invoice_number_different = fields.Boolean(
string="Different Invoice Reference and Self-Bill Invoice Number",
compute="_compute_is_self_invoice_number_different",
help="Self-Bill Number is different than Invoice Reference",
)
set_self_invoice = fields.Boolean(
help="If enabled, create a Self-Bill Invoice when validating.",
compute="_compute_self_invoice",
readonly=False,
store=True,
)
can_self_invoice = fields.Boolean(
string="Approves Self Billing",
compute="_compute_self_invoice",
store=True,
readonly=True,
)
def _compute_is_self_invoice_number_different(self):
"""Compute if ref is different than self-invoice number"""
self.is_self_invoice_number_different = False
for move in self:
if move.is_purchase_document(False) or not (
move.ref and move.self_invoice_number
):
continue
if move.ref != move.self_invoice_number:
move.is_self_invoice_number_different = True
@api.depends("partner_id", "move_type")
def _compute_self_invoice(self):
"""Inherit default for self-invoice from partner."""
for move in self:
partner_self_invoice = (
move.is_purchase_document(False)
and move.with_company(
move.company_id or self.env.company,
).partner_id.commercial_partner_id.self_invoice
)
move.set_self_invoice = partner_self_invoice
move.can_self_invoice = partner_self_invoice
def _post(self, soft=True):
# Set today for invoice date in self invoices
self.filtered(
lambda inv: inv.is_purchase_document(False)
and inv.set_self_invoice
and not inv.invoice_date
).invoice_date = fields.Date.today()
res = super()._post(soft=soft)
for invoice in self:
partner = invoice.with_company(
invoice.company_id or self.env.company,
).partner_id.commercial_partner_id
if (
partner.self_invoice
and invoice.is_purchase_document(False)
and invoice.set_self_invoice
and not invoice.self_invoice_number
):
self_invoice_number = partner._get_self_invoice_number(invoice)
invoice.ref = self_invoice_number
invoice.self_invoice_number = self_invoice_number
return res
def _get_mail_template(self):
"""Get correct email template for self invoices"""
if all(
move.is_purchase_document(False) and move.self_invoice_number
for move in self
):
return "account_invoice_supplier_self_invoice.email_template_self_invoice"
return super()._get_mail_template()
| 37.420455
| 3,293
|
259
|
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
self_invoice_prefix = fields.Char(
string="Default Self Billing prefix",
help="Self Billing prefix for Bills generated by this company",
)
| 25.9
| 259
|
285
|
py
|
PYTHON
|
15.0
|
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
self_invoice_prefix = fields.Char(
string="Default Self Billing prefix",
related="company_id.self_invoice_prefix",
readonly=False,
)
| 25.909091
| 285
|
4,446
|
py
|
PYTHON
|
15.0
|
# © 2017 Creu Blanca
# Copyright 2022 - Moduon
# License AGPL-3.0 or later (https://www.gnuorg/licenses/agpl.html).
from odoo import _, api, exceptions, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
self_invoice = fields.Boolean(
string="Approves Self Billing",
default=False,
help="When checked, all vendor Bills will generate by default "
"a Self-Bill Invoice on confirmation.",
tracking=True,
copy=False,
company_dependent=True,
)
self_invoice_sequence_id = fields.Many2one(
comodel_name="ir.sequence",
string="Self Billing sequence",
ondelete="restrict",
copy=False,
company_dependent=True,
)
self_invoice_refund_sequence_id = fields.Many2one(
comodel_name="ir.sequence",
string="Self Billing Refund sequence",
ondelete="restrict",
copy=False,
company_dependent=True,
)
self_invoice_partner_prefix = fields.Char(
string="Self Billing partner prefix",
help="If set, Self Billing Partner Prefix will be added after the company "
"prefix when the sequence is created for the first time. Eg.:\n"
"With partner prefix: <COMP_PREFIX>/<PARTNER_PREFIX>/INV/<year>\n"
"Without partner prefix: <COMP_PREFIX>/INV/<year>",
copy=False,
tracking=True,
company_dependent=True,
)
self_invoice_report_footer = fields.Text(
string="Self Billing footer",
help="Footer text displayed at the bottom of the self invoice reports.",
copy=False,
tracking=True,
company_dependent=True,
)
@api.model
def _default_self_invoice_report_footer(self):
return _("Invoiced by the recipent")
def _get_self_invoice_number(self, invoice):
is_refund = invoice.move_type == "in_refund"
sequence = (
self.self_invoice_sequence_id
if not is_refund
else self.self_invoice_refund_sequence_id
)
if not sequence:
sequence = self._set_self_invoice(refund=is_refund)
return (
sequence.sudo()
.with_context(ir_sequence_date=invoice.invoice_date)
.next_by_id()
)
def _set_self_invoice(self, refund=False):
if not self.self_invoice:
return False
field = (
"self_invoice_refund_sequence_id" if refund else "self_invoice_sequence_id"
)
if not self[field]:
self.sudo()[field] = (
self.env["ir.sequence"]
.sudo()
.create(
{
"name": self.name
+ " Self invoice "
+ ("refund " if refund else "")
+ "sequence",
"implementation": "no_gap",
"number_increment": 1,
"padding": 4,
"prefix": self._self_invoice_sequence_prefix(refund=refund),
"use_date_range": True,
"number_next": 1,
}
)
)
return self[field]
def _self_invoice_sequence_prefix(self, refund=False):
self.ensure_one()
if not self.env.company.self_invoice_prefix:
raise exceptions.UserError(
_("You must set a Self Billing prefix in Account Settings.")
)
first_prefix = self.env.company.self_invoice_prefix
second_prefix = ""
if self.self_invoice_partner_prefix:
second_prefix = "/" + self.self_invoice_partner_prefix.strip().upper()
ref = "RINV" if refund else "INV"
return f"{first_prefix}{second_prefix}/{ref}/%(range_year)s/"
def action_set_self_invoice(self):
for partner in self:
if not partner.self_invoice_sequence_id:
partner._set_self_invoice()
if not partner.self_invoice_refund_sequence_id:
partner._set_self_invoice(refund=True)
@api.onchange("self_invoice")
def onchange_self_invoice(self):
if self.self_invoice and not self.self_invoice_report_footer:
self.self_invoice_report_footer = self.with_context(
lang=self.lang or self.env.user.lang
)._default_self_invoice_report_footer()
| 36.138211
| 4,445
|
501
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Acccount Invoice Section Sale Order",
"version": "15.0.1.0.2",
"summary": "For invoices targetting multiple sale order add"
"sections with sale order name.",
"author": "Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"category": "Accounting & Finance",
"depends": ["account", "sale"],
}
| 38.538462
| 501
|
3,981
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestInvoiceGroupBySaleOrder(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_1 = cls.env.ref("base.res_partner_1")
cls.product_1 = cls.env.ref("product.product_product_1")
cls.product_1.invoice_policy = "order"
cls.order1_p1 = cls.env["sale.order"].create(
{
"partner_id": cls.partner_1.id,
"partner_shipping_id": cls.partner_1.id,
"partner_invoice_id": cls.partner_1.id,
"client_order_ref": "ref123",
"order_line": [
(
0,
0,
{
"name": "order 1 line 1",
"product_id": cls.product_1.id,
"price_unit": 20,
"product_uom_qty": 1,
"product_uom": cls.product_1.uom_id.id,
},
),
(
0,
0,
{
"name": "order 1 line 2",
"product_id": cls.product_1.id,
"price_unit": 20,
"product_uom_qty": 1,
"product_uom": cls.product_1.uom_id.id,
},
),
],
}
)
cls.order1_p1.action_confirm()
cls.order2_p1 = cls.env["sale.order"].create(
{
"partner_id": cls.partner_1.id,
"partner_shipping_id": cls.partner_1.id,
"partner_invoice_id": cls.partner_1.id,
"order_line": [
(
0,
0,
{
"name": "order 2 line 1",
"product_id": cls.product_1.id,
"price_unit": 20,
"product_uom_qty": 1,
"product_uom": cls.product_1.uom_id.id,
},
),
(
0,
0,
{
"name": "order 2 line 2",
"product_id": cls.product_1.id,
"price_unit": 20,
"product_uom_qty": 1,
"product_uom": cls.product_1.uom_id.id,
},
),
],
}
)
cls.order2_p1.action_confirm()
def test_create_invoice(self):
"""Check invoice is generated with sale order sections."""
result = {
0: "".join([self.order1_p1.name, " - ", self.order1_p1.client_order_ref]),
1: "order 1 line 1",
2: "order 1 line 2",
3: self.order2_p1.name,
4: "order 2 line 1",
5: "order 2 line 2",
}
invoice_ids = (self.order1_p1 + self.order2_p1)._create_invoices()
lines = (
invoice_ids[0]
.line_ids.sorted("sequence")
.filtered(lambda r: not r.exclude_from_invoice_tab)
)
for idx, line in enumerate(lines):
self.assertEqual(line.name, result[idx])
def test_create_invoice_no_section(self):
"""Check invoice for only one sale order
No need to create sections
"""
invoice_id = (self.order1_p1)._create_invoices()
line_sections = invoice_id.line_ids.filtered(
lambda r: r.display_type == "line_section"
)
self.assertEqual(len(line_sections), 0)
| 36.522936
| 3,981
|
2,288
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def _create_invoices(self, grouped=False, final=False, date=None):
"""Add sections by sale order in the invoice line.
Order the invoicing lines by sale order and add lines section with
the sale order name.
Only do this for invoices targetting multiple sale order
"""
invoice_ids = super()._create_invoices(grouped=grouped, final=final)
for invoice in invoice_ids:
if len(invoice.line_ids.mapped("sale_line_ids.order_id.id")) == 1:
continue
so = None
sequence = 10
section_lines = []
lines = self._get_ordered_invoice_lines(invoice)
for line in lines:
if line.sale_line_ids.order_id and so != line.sale_line_ids.order_id:
so = line.sale_line_ids.order_id
section_lines.append(
(
0,
0,
{
"name": so._get_saleorder_section_name(),
"display_type": "line_section",
"sequence": sequence,
},
)
)
sequence += 10
if line.display_type == "line_section":
# add extra indent for existing SO Sections
line.name = f"- {line.name}"
line.sequence = sequence
sequence += 10
invoice.line_ids = section_lines
return invoice_ids
def _get_ordered_invoice_lines(self, invoice):
return invoice.line_ids.sorted(
key=lambda r: r.sale_line_ids.order_id.id
).filtered(lambda r: not r.exclude_from_invoice_tab)
def _get_saleorder_section_name(self):
"""Returns the text for the section name."""
self.ensure_one()
if self.client_order_ref:
return "{} - {}".format(self.name, self.client_order_ref or "")
else:
return self.name
| 38.133333
| 2,288
|
702
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Account Move Post Block",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"version": "15.0.1.0.1",
"category": "Accounting & Finance",
"website": "https://github.com/OCA/account-invoicing",
"depends": ["account_move_exception"],
"data": [
"data/account_exception_data.xml",
"security/ir.model.access.csv",
"security/account_move_post_block_security.xml",
"views/account_post_block_reason_view.xml",
"views/account_move_view.xml",
],
"license": "AGPL-3",
"installable": True,
}
| 35.1
| 702
|
3,259
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo.tests.common import TransactionCase
class TestAccountMovePostBlock(TransactionCase):
def setUp(self):
super(TestAccountMovePostBlock, self).setUp()
self.users_obj = self.env["res.users"]
self.am_obj = self.env["account.move"].with_context(check_move_validity=False)
self.am_block_obj = self.env["account.post.block.reason"]
# company
self.company1 = self.env.ref("base.main_company")
# groups
self.group_account_user = self.env.ref("account.group_account_invoice")
self.group_account_manager = self.env.ref("account.group_account_manager")
# Partner
self.partner1 = self.env.ref("base.res_partner_1")
# Products
self.product1 = self.env.ref("product.product_product_7")
self.product2 = self.env.ref("product.product_product_9")
self.product3 = self.env.ref("product.product_product_11")
# Accounts
self.account_receivable = self.env["account.account"].search(
[
(
"user_type_id",
"=",
self.env.ref("account.data_account_type_receivable").id,
)
],
limit=1,
)
# Create users
self.user1_id = self._create_user(
"user_1", [self.group_account_user], self.company1
)
self.user2_id = self._create_user(
"user_2", [self.group_account_manager], self.company1
)
# Create a AM Block Reason
self._create_block_reason()
def _create_block_reason(self):
self.am_post_block_reason = self.am_block_obj.create(
{"name": "Needs Permission", "description": "Permission to validate"}
)
def _create_user(self, login, groups, company):
"""Create a user."""
group_ids = [group.id for group in groups]
user = self.users_obj.with_context(no_reset_password=True).create(
{
"name": "Account User",
"login": login,
"password": "test",
"email": "test@yourcompany.com",
"company_id": company.id,
"company_ids": [(4, company.id)],
"groups_id": [(6, 0, group_ids)],
}
)
return user.id
def _create_account_move(self, line_products):
"""Create a account move.
``line_products`` is a list of tuple [(product, qty)]
"""
lines = []
for product, qty in line_products:
line_values = {
"name": product.name,
"product_id": product.id,
"quantity": qty,
"price_unit": 100,
"account_id": self.account_receivable.id,
}
lines.append((0, 0, line_values))
account_move = self.am_obj.create(
{
"move_type": "out_invoice",
"partner_id": self.partner1.id,
"line_ids": lines,
"company_id": self.company1.id,
}
)
return account_move
| 37.034091
| 3,259
|
1,954
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from .test_account_move_post_block import TestAccountMovePostBlock
class TestAmPostBlockReason(TestAccountMovePostBlock):
def test_am_post_block_manual_release(self):
"""Confirming the Blocked AM"""
# Create an AM
account_move = self._create_account_move(
[(self.product1, 1), (self.product2, 5), (self.product3, 8)]
)
account_move.post_block_id = self.am_post_block_reason.id
self.assertEqual(account_move.post_blocked, True)
# The account manager unblocks the journal entry with block
account_move.with_user(self.user2_id).button_release_post_block()
self.assertEqual(
account_move.post_block_id, self.env["account.post.block.reason"]
)
# The account user validates the journal entry without block
account_move.with_user(self.user1_id).action_post()
# The AM is posted
self.assertEqual(account_move.state, "posted")
def test_am_post_block_draft_release_01(self):
# Create an AM
account_move = self._create_account_move(
[(self.product1, 1), (self.product2, 5), (self.product3, 8)]
)
account_move.post_block_id = self.am_post_block_reason.id
self.assertEqual(account_move.state, "draft")
# Simulation the opening of the wizard account_exception_confirm and
# set ignore_exception to True
ctx = {
"active_id": account_move.id,
"active_ids": [account_move.id],
"active_model": account_move._name,
}
am_except_confirm = (
self.env["account.exception.confirm"]
.with_context(**ctx)
.create({"ignore": True})
)
am_except_confirm.action_confirm()
self.assertEqual(account_move.state, "posted")
| 38.313725
| 1,954
|
471
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import models
class AccountExceptionConfirm(models.TransientModel):
_inherit = "account.exception.confirm"
def action_confirm(self):
self.ensure_one()
if self.ignore and self.related_model_id.post_block_id:
self.related_model_id.button_release_post_block()
return super().action_confirm()
| 33.642857
| 471
|
1,581
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
post_block_id = fields.Many2one(
comodel_name="account.post.block.reason",
string="Post Block Reason",
)
post_blocked = fields.Boolean(
compute="_compute_post_blocked",
)
@api.depends("post_block_id")
def _compute_post_blocked(self):
for rec in self:
rec.post_blocked = rec.post_block_id
@api.model
def create(self, vals):
am = super().create(vals)
if "post_block_id" in vals and vals["post_block_id"]:
am.message_post(
body=_('Entry "{}" blocked with reason' "{}").format(
am.name, am.post_block_id.name
)
)
return am
def write(self, vals):
res = super().write(vals)
for am in self:
if "post_block_id" in vals and vals["post_block_id"]:
am.message_post(
body=_("Entry {} blocked with reason {}").format(
am.name, am.post_block_id.name
)
)
elif "post_block_id" in vals and not vals["post_block_id"]:
am.message_post(body=_('Entry "%s" post block released.') % am.name)
return res
def button_release_post_block(self):
for move in self:
move.post_block_id = False
return True
| 31.62
| 1,581
|
403
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import fields, models
class AccountPostBlockReason(models.Model):
_name = "account.post.block.reason"
_description = "Account Post Block Reason"
name = fields.Char(required=True)
description = fields.Text()
active = fields.Boolean(default=True)
| 31
| 403
|
585
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "Account Fixed Discount",
"summary": "Allows to apply fixed amount discounts in invoices.",
"version": "15.0.1.0.0",
"category": "Accounting & Finance",
"website": "https://github.com/OCA/account-invoicing",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["account"],
"data": ["views/account_move_view.xml", "reports/report_account_invoice.xml"],
}
| 36.5625
| 585
|
4,179
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Tecnativa - David Vidal
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.exceptions import ValidationError
from odoo.tests import TransactionCase
class TestInvoiceFixedDiscount(TransactionCase):
@classmethod
def setUpClass(cls):
super(TestInvoiceFixedDiscount, cls).setUpClass()
cls.partner = cls.env["res.partner"].create({"name": "Test"})
cls.product = cls.env.ref("product.product_product_3")
cls.account = cls.env["account.account"].search(
[
(
"user_type_id",
"=",
cls.env.ref("account.data_account_type_revenue").id,
)
],
limit=1,
)
type_current_liability = cls.env.ref(
"account.data_account_type_current_liabilities"
)
cls.output_vat_acct = cls.env["account.account"].create(
{"name": "10", "code": "10", "user_type_id": type_current_liability.id}
)
cls.tax_group_vat = cls.env["account.tax.group"].create({"name": "VAT"})
cls.vat = cls.env["account.tax"].create(
{
"name": "TEST 10%",
"type_tax_use": "sale",
"amount_type": "percent",
"amount": 10.00,
"tax_group_id": cls.tax_group_vat.id,
"tax_exigibility": "on_invoice",
"invoice_repartition_line_ids": [
(0, 0, {"factor_percent": 100.0, "repartition_type": "base"}),
(
0,
0,
{
"factor_percent": 100.0,
"repartition_type": "tax",
"account_id": cls.output_vat_acct.id,
},
),
],
}
)
def _create_invoice(self, discount=0.00, discount_fixed=0.00):
invoice_vals = [
(
0,
0,
{
"product_id": self.product.id,
"quantity": 1.0,
"account_id": self.account.id,
"name": "Line 1",
"price_unit": 200.00,
"discount_fixed": discount_fixed,
"discount": discount,
"tax_ids": [(6, 0, [self.vat.id])],
},
)
]
invoice = (
self.env["account.move"]
.with_context(check_move_validity=False)
.create(
{
"journal_id": self.env["account.journal"]
.search([("type", "=", "sale")], limit=1)
.id,
"partner_id": self.partner.id,
"move_type": "out_invoice",
"invoice_line_ids": invoice_vals,
}
)
)
return invoice
def test_01_discounts_fixed(self):
"""Tests multiple discounts in line with taxes."""
invoice = self._create_invoice(discount_fixed=57)
with self.assertRaises(ValidationError):
invoice.invoice_line_ids.discount = 50
invoice.invoice_line_ids._onchange_discount_fixed()
self.assertEqual(invoice.invoice_line_ids.discount, 0.00)
invoice.invoice_line_ids._onchange_price_subtotal()
invoice.line_ids.write({"recompute_tax_line": True})
invoice._onchange_invoice_line_ids()
# compute amount total (200 - 57) * 10%
self.assertEqual(invoice.amount_total, 157.3)
self.assertEqual(invoice.invoice_line_ids.price_unit, 200.00)
self.assertEqual(invoice.invoice_line_ids.price_subtotal, 143.00)
def test_02_discounts(self):
invoice = self._create_invoice(discount=50)
invoice.invoice_line_ids._onchange_discount()
self.assertEqual(invoice.invoice_line_ids.discount_fixed, 0.00)
self.assertEqual(invoice.invoice_line_ids.price_unit, 200.00)
self.assertEqual(invoice.invoice_line_ids.price_subtotal, 100.00)
| 39.056075
| 4,179
|
4,017
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class AccountMove(models.Model):
_inherit = "account.move"
def _recompute_tax_lines(
self, recompute_tax_base_amount=False, tax_rep_lines_to_recompute=None
):
vals = {}
for line in self.invoice_line_ids.filtered("discount_fixed"):
vals[line] = {"price_unit": line.price_unit}
price_unit = line.price_unit - line.discount_fixed
line.update({"price_unit": price_unit})
res = super(AccountMove, self)._recompute_tax_lines(
recompute_tax_base_amount=recompute_tax_base_amount,
tax_rep_lines_to_recompute=tax_rep_lines_to_recompute,
)
for line in vals.keys():
line.update(vals[line])
return res
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
discount_fixed = fields.Float(
string="Discount (Fixed)",
digits="Product Price",
default=0.00,
help="Fixed amount discount.",
)
@api.onchange("discount")
def _onchange_discount(self):
if self.discount:
self.discount_fixed = 0.0
@api.onchange("discount_fixed")
def _onchange_discount_fixed(self):
if self.discount_fixed:
self.discount = 0.0
@api.constrains("discount", "discount_fixed")
def _check_only_one_discount(self):
for rec in self:
for line in rec:
if line.discount and line.discount_fixed:
raise ValidationError(
_("You can only set one type of discount per line.")
)
@api.onchange("quantity", "discount", "price_unit", "tax_ids", "discount_fixed")
def _onchange_price_subtotal(self):
return super(AccountMoveLine, self)._onchange_price_subtotal()
@api.model
def _get_price_total_and_subtotal_model(
self,
price_unit,
quantity,
discount,
currency,
product,
partner,
taxes,
move_type,
):
if self.discount_fixed != 0:
discount = ((self.discount_fixed) / price_unit) * 100 or 0.00
return super(AccountMoveLine, self)._get_price_total_and_subtotal_model(
price_unit, quantity, discount, currency, product, partner, taxes, move_type
)
@api.model
def _get_fields_onchange_balance_model(
self,
quantity,
discount,
amount_currency,
move_type,
currency,
taxes,
price_subtotal,
force_computation=False,
):
if self.discount_fixed != 0:
discount = ((self.discount_fixed) / self.price_unit) * 100 or 0.00
return super(AccountMoveLine, self)._get_fields_onchange_balance_model(
quantity,
discount,
amount_currency,
move_type,
currency,
taxes,
price_subtotal,
force_computation=force_computation,
)
@api.model_create_multi
def create(self, vals_list):
prev_discount = []
for vals in vals_list:
if vals.get("discount_fixed"):
prev_discount.append(
{"discount_fixed": vals.get("discount_fixed"), "discount": 0.00}
)
fixed_discount = (
vals.get("discount_fixed") / vals.get("price_unit")
) * 100
vals.update({"discount": fixed_discount, "discount_fixed": 0.00})
elif vals.get("discount"):
prev_discount.append({"discount": vals.get("discount")})
res = super(AccountMoveLine, self).create(vals_list)
i = 0
for rec in res:
if rec.discount and prev_discount:
rec.write(prev_discount[i])
i += 1
return res
| 32.395161
| 4,017
|
771
|
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 Customer code for account invoice",
"summary": "Based on product_customer_code, this module loads in every "
"account invoice the customer code defined in the product",
"version": "15.0.1.0.0",
"author": "Agile Business Group, ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"category": "Account",
"license": "AGPL-3",
"depends": ["account", "product_supplierinfo_for_customer"],
"data": ["views/account_move_view.xml"],
"installable": True,
}
| 42.833333
| 771
|
3,022
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestProductSupplierinfoForCustomerInvoice(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.move_model = cls.env["account.move"]
cls.customerinfo_model = cls.env["product.customerinfo"]
cls.pricelist_model = cls.env["product.pricelist"]
cls.customer_1 = cls._create_customer("customer1")
cls.customer_2 = cls._create_customer("customer2")
cls.company = cls.env.ref("base.main_company")
cls.product = cls.env.ref("product.product_product_4")
cls.customerinfo_1 = cls.customerinfo_model.create(
{
"name": cls.customer_1.id,
"product_tmpl_id": cls.product.product_tmpl_id.id,
"product_id": cls.product.id,
"product_code": "CUST1234",
}
)
@classmethod
def _create_customer(cls, name):
return cls.env["res.partner"].create(
{"name": name, "email": "example@yourcompany.com", "phone": 123456}
)
@classmethod
def _create_invoice(cls, customer):
return cls.move_model.create(
{
"journal_id": cls.env["account.journal"]
.search([("type", "=", "sale")], limit=1)
.id,
"partner_id": customer.id,
"move_type": "out_invoice",
"invoice_line_ids": [
(
0,
0,
{
"product_id": cls.product.id,
"quantity": 1.0,
"name": cls.product.name,
"price_unit": 450.00,
},
),
(
0,
0,
{
"name": "Line without product",
"quantity": 1.0,
"price_unit": 50.00,
},
),
],
}
)
def test_01_invoice_line_customer_code(self):
invoice = self._create_invoice(self.customer_1)
line = invoice.invoice_line_ids.filtered(lambda l: l.product_id)
self.assertEqual(len(line), 1)
self.assertEqual(line.product_customer_code, "CUST1234")
def test_02_invoice_line_no_customer_code(self):
invoice = self._create_invoice(self.customer_2)
line = invoice.invoice_line_ids.filtered(lambda l: l.product_id)
self.assertEqual(len(line), 1)
self.assertFalse(line.product_customer_code)
line_no_product = invoice.invoice_line_ids.filtered(lambda l: not l.product_id)
self.assertEqual(len(line_no_product), 1)
self.assertFalse(line_no_product.product_customer_code)
| 37.775
| 3,022
|
1,125
|
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 AccountInvoiceLine(models.Model):
_inherit = "account.move.line"
@api.depends("product_id")
def _compute_product_customer_code(self):
for line in self:
if line.product_id and line.partner_show_customer_code:
product = line.product_id
code_id = product._select_customerinfo(partner=line.move_id.partner_id)
line.product_customer_code = code_id.product_code or ""
else:
line.product_customer_code = ""
product_customer_code = fields.Char(
compute="_compute_product_customer_code",
)
partner_show_customer_code = fields.Boolean(
compute="_compute_partner_show_customer_code"
)
def _compute_partner_show_customer_code(self):
for rec in self:
rec.partner_show_customer_code = rec.move_id.is_sale_document()
| 36.290323
| 1,125
|
545
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Account Invoice Tree Currency",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"summary": "Show currencies in the invoice tree view",
"version": "15.0.1.0.0",
"category": "Accounting & Finance",
"website": "https://github.com/OCA/account-invoicing",
"depends": ["account"],
"data": ["views/account_move_view.xml"],
"license": "LGPL-3",
"installable": True,
}
| 36.333333
| 545
|
804
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association (OCA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Stock Picking Invoicing",
"version": "15.0.1.0.0",
"category": "Warehouse Management",
"author": "Agile Business Group,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"depends": ["stock", "account", "stock_picking_invoice_link"],
"data": [
"security/ir.model.access.csv",
"wizards/stock_invoice_onshipping_view.xml",
"wizards/stock_return_picking_view.xml",
"views/stock_move.xml",
"views/stock_picking.xml",
"views/stock_picking_type.xml",
],
"demo": ["demo/stock_picking_demo.xml"],
"installable": True,
}
| 38.285714
| 804
|
41,115
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association (OCA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import exceptions
from odoo.tests import Form, TransactionCase
class TestPickingInvoicing(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.picking_model = cls.env["stock.picking"]
cls.move_model = cls.env["stock.move"]
cls.invoice_wizard = cls.env["stock.invoice.onshipping"]
cls.invoice_model = cls.env["account.move"]
cls.partner_model = cls.env["res.partner"]
cls.partner = cls.env.ref("base.res_partner_2")
cls.partner2 = cls.env.ref("base.res_partner_address_4")
cls.partner3 = cls.env.ref("base.res_partner_18")
cls.supplier = cls.env.ref("base.res_partner_12")
cls.pick_type_in = cls.env.ref("stock.picking_type_in")
cls.pick_type_out = cls.env.ref("stock.picking_type_out")
cls.stock_location = cls.env.ref("stock.stock_location_stock")
cls.customers_location = cls.env.ref("stock.stock_location_customers")
cls.suppliers_location = cls.env.ref("stock.stock_location_suppliers")
cls.stock_return_picking = cls.env["stock.return.picking"]
cls.journal = cls.env["account.journal"].create(
{
"name": "A super journal name",
"code": "ABC",
"type": "sale",
"refund_sequence": True,
}
)
cls.product_model = cls.env["product.product"]
cls.fiscal_position_model = cls.env["account.fiscal.position"]
cls.fiscal_position_tax_model = cls.env["account.fiscal.position.tax"]
cls.fiscal_position_account_model = cls.env["account.fiscal.position.account"]
cls.account_user_type = cls.env.ref("account.data_account_type_revenue")
cls.account_model = cls.env["account.account"]
cls.tax_model = cls.env["account.tax"]
cls.product_tmpl_model = cls.env["product.template"]
cls.account_receivable = cls.env["account.account"].search(
[
(
"user_type_id",
"=",
cls.env.ref("account.data_account_type_receivable").id,
)
],
limit=1,
)
cls.account_revenue = cls.env["account.account"].search(
[("user_type_id", "=", cls.account_user_type.id)], limit=1
)
cls.tax_sale_1 = cls.tax_model.create(
{"name": "Sale tax 20", "type_tax_use": "sale", "amount": "20.00"}
)
cls.tax_sale_2 = cls.tax_model.create(
{"name": "Sale tax 10", "type_tax_use": "sale", "amount": "10.00"}
)
cls.tax_purchase_1 = cls.tax_model.create(
{"name": "Purchase tax 10", "type_tax_use": "purchase", "amount": "10.00"}
)
cls.tax_purchase_2 = cls.tax_model.create(
{"name": "Purchase tax 20", "type_tax_use": "purchase", "amount": "20.00"}
)
cls.product_test_1 = cls.product_model.create(
{
"name": "Test 1",
"lst_price": "15000",
"taxes_id": [(6, 0, [cls.tax_sale_1.id, cls.tax_sale_2.id])],
"supplier_taxes_id": [
(6, 0, [cls.tax_purchase_1.id, cls.tax_purchase_2.id])
],
"property_account_income_id": cls.account_revenue.id,
"standard_price": "500",
}
)
cls.product_test_2 = cls.product_model.create(
{
"name": "Test 2",
"lst_price": "15000",
"taxes_id": [(6, 0, [cls.tax_sale_1.id, cls.tax_sale_2.id])],
"supplier_taxes_id": [
(6, 0, [cls.tax_purchase_1.id, cls.tax_purchase_2.id])
],
"property_account_income_id": cls.account_revenue.id,
"standard_price": "500",
}
)
def test_0_picking_out_invoicing(self):
# setting Agrolait type to default, because it's 'contact' in demo data
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner2.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 2,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
new_move._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.partner)
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoice))
assert invoice.invoice_user_id, "Error to map User in Invoice."
assert invoice.invoice_payment_term_id, "Error to map Payment Term in Invoice."
assert invoice.fiscal_position_id, "Error to map Fiscal Position in Invoice."
assert invoice.company_id, "Error to map Company in Invoice."
assert invoice.invoice_line_ids, "Error to create invoice line."
for inv_line in invoice.invoice_line_ids:
assert inv_line.account_id, "Error to map Account in Invoice Line."
assert inv_line.tax_ids, "Error to map Sale Tax in Invoice Line."
assert inv_line.product_uom_id, "Error to map Product UOM in Invoice Line."
for mv_line in inv_line.move_line_ids:
self.assertEqual(
mv_line.id,
new_move.id,
"Error to link stock.move with invoice.line.",
)
def test_1_picking_out_invoicing(self):
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner2.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 2,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
new_move._onchange_product_id()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
with self.assertRaises(exceptions.UserError) as e:
wizard.with_context(lang="en_US").action_generate()
msg = "No invoice created!"
self.assertIn(msg, e.exception.args[0])
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after)
def test_2_picking_out_invoicing(self):
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner2.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 2,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
new_move._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard_values.update({"group": "partner"})
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
# invoice = picking.invoice_ids[0]
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.partner)
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoice))
assert invoice.invoice_line_ids, "Error to create invoice line."
for inv_line in invoice.invoice_line_ids:
for mv_line in inv_line.move_line_ids:
self.assertEqual(
mv_line.id,
new_move.id,
"Error to link stock.move with invoice.line.",
)
self.assertTrue(inv_line.tax_ids, "Error to map Sale Tax in invoice.line.")
def test_3_picking_out_invoicing(self):
"""
Test invoicing picking in to check if get the taxes
from supplier_taxes_id.
"""
nb_invoice_before = self.invoice_model.search_count([])
picking = self.picking_model.create(
{
"partner_id": self.supplier.id,
"picking_type_id": self.pick_type_in.id,
"location_id": self.suppliers_location.id,
"location_dest_id": self.stock_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.stock_location.id,
"location_id": self.suppliers_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 2,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
new_move._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.supplier)
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoice))
assert invoice.invoice_line_ids, "Error to create invoice line."
for inv_line in invoice.invoice_line_ids:
for mv_line in inv_line.move_line_ids:
self.assertEqual(
mv_line.id,
new_move.id,
"Error to link stock.move with invoice.line.",
)
self.assertTrue(
inv_line.tax_ids,
"Error to map Purchase Tax in invoice.line.",
)
def test_4_picking_out_invoicing_backorder(self):
"""
Test invoicing picking out to check if backorder is create
with same invoice state.
"""
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner2.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 4,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
new_move._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty / 2.0
backorder_action = picking.button_validate()
Form(
self.env[(backorder_action.get("res_model"))].with_context(
**backorder_action["context"]
)
).save().process()
backorder = self.env["stock.picking"].search(
[("backorder_id", "=", picking.id)]
)
backorder.action_assign()
self.assertEqual(backorder.invoice_state, "2binvoiced")
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.partner)
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoice))
assert invoice.invoice_line_ids, "Error to create invoice line."
for inv_line in invoice.invoice_line_ids:
for mv_line in inv_line.move_line_ids:
self.assertEqual(
mv_line.id,
new_move.id,
"Error to link stock.move with invoice.line.",
)
self.assertTrue(inv_line.tax_ids, "Error to map Sale Tax in invoice.line.")
def test_picking_cancel(self):
"""
Ensure that the invoice_state of the picking is correctly
updated when an invoice is cancelled
:return:
"""
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner2.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 2,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
new_move._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard_values.update({"group": "partner"})
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.partner)
invoice.button_cancel()
self.assertEqual(picking.invoice_state, "2binvoiced")
invoice.button_draft()
self.assertEqual(picking.invoice_state, "invoiced")
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoice))
def test_picking_invoice_refund(self):
"""
Ensure that a refund keep the link to the picking
:return:
"""
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner2.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 2,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
new_move._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard_values.update({"group": "partner"})
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.partner)
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
invoice.action_post()
refund = invoice._reverse_moves(cancel=True)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertIn(picking, refund.picking_ids)
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoice | refund))
def test_picking_invoicing_by_product1(self):
"""
Test the invoice generation grouped by partner/product with 1
picking and 2 moves.
:return:
"""
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 1,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
move_vals2 = {
"product_id": self.product_test_2.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_2.name,
"product_uom_qty": 1,
"product_uom": self.product_test_2.uom_id.id,
}
new_move2 = self.move_model.create(move_vals2)
new_move._onchange_product_id()
new_move2._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
# One invoice per partner but group products
wizard_values.update({"group": "partner_product"})
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.partner)
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
products = invoice.invoice_line_ids.mapped("product_id")
self.assertEqual(len(invoice.invoice_line_ids), 2)
self.assertIn(self.product_test_1, products)
self.assertIn(self.product_test_2, products)
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoice))
def test_picking_invoicing_by_product2(self):
"""
Test the invoice generation grouped by partner/product with 2
picking and 2 moves per picking.
We use same partner for 2 picking so we should have 1 invoice with 2
lines (and qty 2)
:return:
"""
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 1,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
picking2 = picking.copy()
move_vals2 = {
"product_id": self.product_test_1.id,
"picking_id": picking2.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 1,
"product_uom": self.product_test_1.uom_id.id,
}
new_move2 = self.move_model.create(move_vals2)
new_move._onchange_product_id()
new_move2._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
picking2.set_to_be_invoiced()
picking2.action_confirm()
# Check product availability
picking2.action_assign()
# Force product availability
for move in picking2.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking2.button_validate()
self.assertEqual(picking.state, "done")
self.assertEqual(picking2.state, "done")
pickings = picking | picking2
wizard_obj = self.invoice_wizard.with_context(
active_ids=pickings.ids,
active_model=pickings._name,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
# One invoice per partner but group products
wizard_values.update({"group": "partner_product"})
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
self.assertEqual(len(invoice), 1)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(picking2.invoice_state, "invoiced")
self.assertEqual(invoice.partner_id, self.partner)
self.assertIn(invoice, picking.invoice_ids)
self.assertIn(invoice, picking2.invoice_ids)
self.assertIn(picking, invoice.picking_ids)
self.assertIn(picking2, invoice.picking_ids)
products = invoice.invoice_line_ids.mapped("product_id")
self.assertIn(self.product_test_1, products)
for inv_line in invoice.invoice_line_ids:
# qty = 3 because 1 move + duplicate one + 1 new
self.assertAlmostEqual(inv_line.quantity, 3)
self.assertTrue(inv_line.tax_ids, "Error to map Sale Tax in invoice.line.")
# Now test behaviour if the invoice is delete
invoice.unlink()
for picking in pickings:
self.assertEqual(picking.invoice_state, "2binvoiced")
nb_invoice_after = self.invoice_model.search_count([])
# Should be equals because we delete the invoice
self.assertEqual(nb_invoice_before, nb_invoice_after)
def test_picking_invoicing_by_product3(self):
"""
Test the invoice generation grouped by partner/product with 2
picking and 2 moves per picking.
We use different partner for 2 picking so we should have 2 invoice
with 2 lines (and qty 1)
:return:
"""
nb_invoice_before = self.invoice_model.search_count([])
self.partner.write({"type": "invoice"})
picking = self.picking_model.create(
{
"partner_id": self.partner.id,
"picking_type_id": self.pick_type_out.id,
"location_id": self.stock_location.id,
"location_dest_id": self.customers_location.id,
}
)
move_vals = {
"product_id": self.product_test_1.id,
"picking_id": picking.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_1.name,
"product_uom_qty": 1,
"product_uom": self.product_test_1.uom_id.id,
}
new_move = self.move_model.create(move_vals)
picking2 = picking.copy({"partner_id": self.partner3.id})
move_vals2 = {
"product_id": self.product_test_2.id,
"picking_id": picking2.id,
"location_dest_id": self.customers_location.id,
"location_id": self.stock_location.id,
"name": self.product_test_2.name,
"product_uom_qty": 1,
"product_uom": self.product_test_2.uom_id.id,
}
new_move2 = self.move_model.create(move_vals2)
new_move._onchange_product_id()
new_move2._onchange_product_id()
picking.set_to_be_invoiced()
picking.action_confirm()
# Check product availability
picking.action_assign()
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
picking2.set_to_be_invoiced()
picking2.action_confirm()
# Check product availability
picking2.action_assign()
# Force product availability
for move in picking2.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking2.button_validate()
self.assertEqual(picking.state, "done")
self.assertEqual(picking2.state, "done")
pickings = picking | picking2
wizard_obj = self.invoice_wizard.with_context(
active_ids=pickings.ids,
active_model=pickings._name,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
# One invoice per partner but group products
wizard_values.update({"group": "partner_product"})
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "in", [picking.id, picking2.id])]
invoices = self.invoice_model.search(domain)
self.assertEqual(len(invoices), 2)
self.assertEqual(picking.invoice_state, "invoiced")
self.assertEqual(picking2.invoice_state, "invoiced")
self.assertIn(self.partner, invoices.mapped("partner_id"))
self.assertIn(self.partner3, invoices.mapped("partner_id"))
for invoice in invoices:
self.assertEqual(len(invoice.picking_ids), 1)
picking = invoice.picking_ids
self.assertIn(invoice, picking.invoice_ids)
for inv_line in invoice.invoice_line_ids:
self.assertAlmostEqual(inv_line.quantity, 1)
self.assertTrue(
inv_line.tax_ids,
"Error to map Sale Tax in invoice.line.",
)
# Test the behaviour when the invoice is cancelled
# The picking invoice_status should be updated
invoice.button_cancel()
self.assertEqual(picking.invoice_state, "2binvoiced")
nb_invoice_after = self.invoice_model.search_count([])
self.assertEqual(nb_invoice_before, nb_invoice_after - len(invoices))
def test_0_counting_2binvoiced(self):
"""
Check method counting 2binvoice used in kanban view
"""
self.assertEqual(1, self.pick_type_in.count_picking_2binvoiced)
def test_return_customer_picking(self):
"""
Test Return Customer Picking and Invoice created.
"""
picking = self.env.ref("stock_picking_invoicing.stock_picking_invoicing_2")
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids,
active_model=picking._name,
active_id=picking.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
# Confirm Invoice
invoice.action_post()
self.assertEqual(invoice.state, "posted", "Invoice should be in state Posted")
# Check Invoice Type
self.assertEqual(
invoice.move_type, "out_invoice", "Invoice Type should be Out Invoice"
)
# Return Picking
return_wizard_form = Form(
self.stock_return_picking.with_context(
**dict(active_id=picking.id, active_model="stock.picking")
)
)
return_wizard_form.invoice_state = "2binvoiced"
self.return_wizard = return_wizard_form.save()
result_wizard = self.return_wizard.create_returns()
self.assertTrue(result_wizard, "Create returns wizard fail.")
picking_devolution = self.env["stock.picking"].browse(
result_wizard.get("res_id")
)
self.assertEqual(picking_devolution.invoice_state, "2binvoiced")
for line in picking_devolution.move_lines:
self.assertEqual(line.invoice_state, "2binvoiced")
picking_devolution.action_confirm()
picking_devolution.action_assign()
# Force product availability
for move in picking_devolution.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking_devolution.button_validate()
self.assertEqual(picking_devolution.state, "done", "Change state fail.")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking_devolution.ids,
active_model=picking_devolution._name,
active_id=picking_devolution.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking_devolution.id)]
invoice_devolution = self.invoice_model.search(domain)
# Confirm Return Invoice
invoice_devolution.action_post()
self.assertEqual(
invoice_devolution.state, "posted", "Invoice should be in state Posted"
)
# Check Invoice Type
self.assertEqual(
invoice_devolution.move_type,
"out_refund",
"Invoice Type should be Out Refund",
)
def test_return_supplier_picking(self):
"""
Test Return Supplier Picking and Invoice created.
"""
picking = self.env.ref("stock_picking_invoicing.stock_picking_invoicing_7")
# Force product availability
for move in picking.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking.button_validate()
self.assertEqual(picking.state, "done")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking.ids, active_model=picking._name, active_id=picking.id
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking.id)]
invoice = self.invoice_model.search(domain)
# Confirm Invoice
invoice.action_post()
self.assertEqual(invoice.state, "posted", "Invoice should be in state Posted")
# Check Invoice Type
self.assertEqual(
invoice.move_type, "in_invoice", "Invoice Type should be In Invoice"
)
# Return Picking
return_wizard_form = Form(
self.stock_return_picking.with_context(
**dict(active_id=picking.id, active_model="stock.picking")
)
)
return_wizard_form.invoice_state = "2binvoiced"
self.return_wizard = return_wizard_form.save()
result_wizard = self.return_wizard.create_returns()
self.assertTrue(result_wizard, "Create returns wizard fail.")
picking_devolution = self.env["stock.picking"].browse(
result_wizard.get("res_id")
)
self.assertEqual(picking_devolution.invoice_state, "2binvoiced")
for line in picking_devolution.move_lines:
self.assertEqual(line.invoice_state, "2binvoiced")
picking_devolution.action_confirm()
picking_devolution.action_assign()
# Force product availability
for move in picking_devolution.move_ids_without_package:
move.quantity_done = move.product_uom_qty
picking_devolution.button_validate()
self.assertEqual(picking_devolution.state, "done", "Change state fail.")
wizard_obj = self.invoice_wizard.with_context(
active_ids=picking_devolution.ids,
active_model=picking_devolution._name,
active_id=picking_devolution.id,
)
fields_list = wizard_obj.fields_get().keys()
wizard_values = wizard_obj.default_get(fields_list)
wizard = wizard_obj.create(wizard_values)
wizard.onchange_group()
wizard.action_generate()
domain = [("picking_ids", "=", picking_devolution.id)]
invoice_devolution = self.invoice_model.search(domain)
# Confirm Return Invoice
invoice_devolution.action_post()
self.assertEqual(
invoice_devolution.state, "posted", "Invoice should be in state Posted"
)
# Check Invoice Type
self.assertEqual(
invoice_devolution.move_type,
"in_refund",
"Invoice Type should be In Refund",
)
| 43.188025
| 41,115
|
1,945
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association (OCA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class StockInvoiceStateMixin(models.AbstractModel):
"""
Abstract model used to define invoice state with selection choices
"""
_name = "stock.invoice.state.mixin"
_description = "Stock Invoice State Mixin"
invoice_state = fields.Selection(
selection=[
("invoiced", "Invoiced"),
("2binvoiced", "To Be Invoiced"),
("none", "Not Applicable"),
],
string="Invoice Status",
default="none",
help="Invoiced: an invoice already exists\n"
"To Be Invoiced: need to be invoiced\n"
"Not Applicable: no invoice to create",
copy=False,
)
def _set_as_invoiced(self):
"""
Update invoice_state on current recordset to 'invoiced'
:return: self recordset (where the updated has been executed)
"""
return self._update_invoice_state("invoiced")
def _set_as_2binvoiced(self):
"""
Update invoice_state on current recordset to '2binvoiced'
:return: self recordset (where the updated has been executed)
"""
return self._update_invoice_state("2binvoiced")
def _set_as_not_billable(self):
"""
Update invoice_state on current recordset to 'invoiced'
:return: self recordset (where the updated has been executed)
"""
return self._update_invoice_state("none")
def _update_invoice_state(self, invoice_state):
"""
Execute the write
:param invoice_state: str
:return: self recordset (where the updated has been executed)
"""
records = self.filtered(lambda r: r.invoice_state != invoice_state)
if records:
records.write({"invoice_state": invoice_state})
return records
| 32.966102
| 1,945
|
1,576
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association (OCA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class AccountInvoice(models.Model):
_inherit = "account.move"
def button_cancel(self):
"""
Inherit to update related picking as '2binvoiced' when the invoice is
cancelled (only for invoices, not refunds)
:return: bool
"""
result = super().button_cancel()
pickings = self.filtered(
lambda i: i.picking_ids and i.move_type in ["out_invoice", "in_invoice"]
).mapped("picking_ids")
self.mapped("invoice_line_ids.move_line_ids")._set_as_2binvoiced()
pickings._set_as_2binvoiced()
return result
def button_draft(self):
result = super().button_draft()
pickings = self.filtered(
lambda i: i.picking_ids and i.move_type in ["out_invoice", "in_invoice"]
).mapped("picking_ids")
self.mapped("invoice_line_ids.move_line_ids")._set_as_invoiced()
pickings._set_as_invoiced()
return result
def unlink(self):
"""
Inherit the unlink to update related picking as "2binvoiced"
(only for invoices, not refunds)
:return:
"""
pickings = self.filtered(
lambda i: i.picking_ids and i.move_type in ["out_invoice", "in_invoice"]
).mapped("picking_ids")
self.mapped("invoice_line_ids.move_line_ids")._set_as_2binvoiced()
pickings._set_as_2binvoiced()
return super().unlink()
| 35.818182
| 1,576
|
1,232
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association
# @ 2019-Today: Akretion - www.akretion.com.br -
# Magno Costa <magno.costa@akretion.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class PickingType(models.Model):
_inherit = "stock.picking.type"
count_picking_2binvoiced = fields.Integer(compute="_compute_picking_2binvoiced")
def _compute_picking_2binvoiced(self):
domains = {
"count_picking_2binvoiced": [("invoice_state", "=", "2binvoiced")],
}
for field in domains:
data = self.env["stock.picking"].read_group(
domains[field]
+ [
("state", "!=", "cancel"),
("invoice_state", "=", "2binvoiced"),
("picking_type_id", "in", self.ids),
],
["picking_type_id"],
["picking_type_id"],
)
count = {
x["picking_type_id"][0]: x["picking_type_id_count"]
for x in data
if x["picking_type_id"]
}
for record in self:
record[field] = count.get(record.id, 0)
| 35.2
| 1,232
|
2,780
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association (OCA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class StockMove(models.Model):
_name = "stock.move"
_inherit = [
_name,
"stock.invoice.state.mixin",
]
def _get_taxes(self, fiscal_position, inv_type):
"""
Map product taxes based on given fiscal position
:param fiscal_position: account.fiscal.position recordset
:param inv_type: string
:return: account.tax recordset
"""
product = self.mapped("product_id")
product.ensure_one()
if inv_type in ("out_invoice", "out_refund"):
taxes = product.taxes_id
else:
taxes = product.supplier_taxes_id
company_id = self.env.context.get("force_company", self.env.company.id)
my_taxes = taxes.filtered(lambda r: r.company_id.id == company_id)
return fiscal_position.map_tax(my_taxes)
@api.model
def _get_account(self, fiscal_position, account):
"""
Map the given account with given fiscal position
:param fiscal_position: account.fiscal.position recordset
:param account: account.account recordset
:return: account.account recordset
"""
return fiscal_position.map_account(account)
def _get_price_unit_invoice(self, inv_type, partner, qty=1):
"""
Gets price unit for invoice
:param inv_type: str
:param partner: res.partner
:param qty: float
:return: float
"""
product = self.mapped("product_id")
product.ensure_one()
if inv_type in ("in_invoice", "in_refund"):
result = product.price
else:
# If partner given, search price in its sale pricelist
if partner and partner.property_product_pricelist:
product = product.with_context(
partner=partner.id,
quantity=qty,
pricelist=partner.property_product_pricelist.id,
uom=fields.first(self).product_uom.id,
)
result = product.price
else:
result = product.lst_price
return result
def _prepare_extra_move_vals(self, qty):
"""Copy invoice state for a new extra stock move"""
values = super()._prepare_extra_move_vals(qty)
values["invoice_state"] = self.invoice_state
return values
def _prepare_move_split_vals(self, uom_qty):
"""Copy invoice state for a new splitted stock move"""
values = super()._prepare_move_split_vals(uom_qty)
values["invoice_state"] = self.invoice_state
return values
| 36.103896
| 2,780
|
1,388
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association (OCA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class StockPicking(models.Model):
_name = "stock.picking"
_inherit = [
_name,
"stock.invoice.state.mixin",
]
def set_to_be_invoiced(self):
"""
Update invoice_state of current pickings to "2binvoiced".
:return: dict
"""
self._set_as_2binvoiced()
return {}
def _set_as_2binvoiced(self):
"""
Inherit to also update related moves.
:return: bool
"""
self.mapped("move_lines")._set_as_2binvoiced()
return super()._set_as_2binvoiced()
def _set_as_invoiced(self):
"""
Inherit to also update related moves.
:return: bool
"""
self.mapped("move_lines")._set_as_invoiced()
return super()._set_as_invoiced()
def _get_partner_to_invoice(self):
self.ensure_one()
partner = self.partner_id
return partner.address_get(["invoice"]).get("invoice")
def action_assign(self):
"""If any stock move is to be invoiced, picking status is updated"""
if any(m.invoice_state == "2binvoiced" for m in self.mapped("move_lines")):
self.write({"invoice_state": "2binvoiced"})
return super().action_assign()
| 29.531915
| 1,388
|
772
|
py
|
PYTHON
|
15.0
|
# @ 2021-Today: Akretion - www.akretion.com -
# Magno Costa <magno.costa@akretion.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class StockReturnPicking(models.TransientModel):
_inherit = "stock.return.picking"
invoice_state = fields.Selection(
selection=[("2binvoiced", "To be refunded/invoiced"), ("none", "No invoicing")],
string="Invoicing",
required=True,
default="none",
)
def _prepare_move_default_values(self, return_line, new_picking):
vals = super()._prepare_move_default_values(return_line, new_picking)
if self.invoice_state == "2binvoiced":
vals.update({"invoice_state": self.invoice_state})
return vals
| 33.565217
| 772
|
19,677
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019-Today: Odoo Community Association (OCA)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
JOURNAL_TYPE_MAP = {
("outgoing", "customer"): ["sale"],
("outgoing", "supplier"): ["purchase"],
("outgoing", "transit"): ["sale", "purchase"],
("incoming", "supplier"): ["purchase"],
("incoming", "customer"): ["sale"],
("incoming", "transit"): ["purchase", "sale"],
}
INVOICE_TYPE_MAP = {
# Picking Type Code | Local Origin Usage | Local Dest Usage
("outgoing", "internal", "customer"): "out_invoice",
("incoming", "customer", "internal"): "out_refund",
("incoming", "supplier", "internal"): "in_invoice",
("outgoing", "internal", "supplier"): "in_refund",
("incoming", "transit", "internal"): "in_invoice",
("outgoing", "transit", "supplier"): "in_refund",
("outgoing", "transit", "customer"): "out_invoice",
}
class StockInvoiceOnshipping(models.TransientModel):
_name = "stock.invoice.onshipping"
_description = "Stock Invoice Onshipping"
@api.model
def _get_journal_type(self):
active_ids = self.env.context.get("active_ids", [])
if active_ids:
active_ids = active_ids[0]
pick_obj = self.env["stock.picking"]
picking = pick_obj.browse(active_ids)
if not picking or not picking.move_lines:
return "sale"
pick_type_code = picking.picking_type_id.code
line = fields.first(picking.move_lines)
if pick_type_code == "incoming":
usage = line.location_id.usage
else:
usage = line.location_dest_id.usage
return JOURNAL_TYPE_MAP.get((pick_type_code, usage), ["sale"])[0]
journal_type = fields.Selection(
selection=[
("purchase", "Create Supplier Invoice"),
("sale", "Create Customer Invoice"),
],
default=_get_journal_type,
readonly=True,
)
group = fields.Selection(
selection=[
("picking", "Picking"),
("partner", "Partner"),
("partner_product", "Partner/Product"),
],
default="picking",
help="Group pickings/moves to create invoice(s):\n"
"Picking: One invoice per picking;\n"
"Partner: One invoice for each picking's partner;\n"
"Partner/Product: One invoice per picking's partner and group "
"product into a single invoice line.",
required=True,
)
invoice_date = fields.Date()
sale_journal = fields.Many2one(
comodel_name="account.journal",
domain="[('type', '=', 'sale')]",
default=lambda self: self._default_journal("sale"),
ondelete="cascade",
)
purchase_journal = fields.Many2one(
comodel_name="account.journal",
domain="[('type', '=', 'purchase')]",
default=lambda self: self._default_journal("purchase"),
ondelete="cascade",
)
show_sale_journal = fields.Boolean()
show_purchase_journal = fields.Boolean()
@api.model
def default_get(self, fields_list):
"""
Inherit to add default invoice_date
:param fields_list: list of str
:return: dict
"""
result = super().default_get(fields_list)
result.update({"invoice_date": fields.Date.today()})
return result
@api.onchange("group")
def onchange_group(self):
self.ensure_one()
(
sale_pickings,
sale_refund_pickings,
purchase_pickings,
purchase_refund_pickings,
) = self.get_split_pickings()
self.show_sale_journal = bool(sale_pickings)
self.show_purchase_journal = bool(purchase_pickings)
def get_partner_sum(self, pickings, partner, inv_type, picking_type, usage):
pickings = pickings.filtered(
lambda x: x.picking_type_id.code == picking_type and x.partner_id == partner
)
lines = pickings.mapped("move_lines")
if picking_type == "outgoing":
moves = lines.filtered(lambda x: x.location_dest_id.usage == usage)
else:
moves = lines.filtered(lambda x: x.location_id.usage == usage)
total = sum(
(
m._get_price_unit_invoice(inv_type, m.picking_id.partner_id)
* m.product_uom_qty
)
for m in moves
)
return total, moves.mapped("picking_id")
def get_split_pickings(self):
self.ensure_one()
picking_obj = self.env["stock.picking"]
pickings = picking_obj.browse(self.env.context.get("active_ids", []))
if self.group != "picking":
return self.get_split_pickings_grouped(pickings)
return self.get_split_pickings_nogrouped(pickings)
def get_split_pickings_grouped(self, pickings):
sale_pickings = self.env["stock.picking"].browse()
sale_refund_pickings = self.env["stock.picking"].browse()
purchase_pickings = self.env["stock.picking"].browse()
purchase_refund_pickings = self.env["stock.picking"].browse()
for partner in pickings.mapped("partner_id"):
so_sum, so_pickings = self.get_partner_sum(
pickings, partner, "out_invoice", "outgoing", "customer"
)
si_sum, si_pickings = self.get_partner_sum(
pickings, partner, "out_invoice", "incoming", "customer"
)
if (so_sum - si_sum) >= 0:
sale_pickings |= so_pickings | si_pickings
else:
sale_refund_pickings |= so_pickings | si_pickings
pi_sum, pi_pickings = self.get_partner_sum(
pickings, partner, "in_invoice", "incoming", "supplier"
)
po_sum, po_pickings = self.get_partner_sum(
pickings, partner, "in_invoice", "outgoing", "supplier"
)
if (pi_sum - po_sum) >= 0:
purchase_pickings |= pi_pickings | po_pickings
else:
purchase_refund_pickings |= pi_pickings | po_pickings
return (
sale_pickings,
sale_refund_pickings,
purchase_pickings,
purchase_refund_pickings,
)
def get_split_pickings_nogrouped(self, pickings):
first = fields.first
sale_pickings = pickings.filtered(
lambda x: x.picking_type_id.code == "outgoing"
and first(x.move_lines).location_dest_id.usage == "customer"
)
sale_refund_pickings = pickings.filtered(
lambda x: x.picking_type_id.code == "incoming"
and first(x.move_lines).location_id.usage == "customer"
)
purchase_pickings = pickings.filtered(
lambda x: x.picking_type_id.code == "incoming"
and first(x.move_lines).location_id.usage == "supplier"
)
purchase_refund_pickings = pickings.filtered(
lambda x: x.picking_type_id.code == "outgoing"
and first(x.move_lines).location_dest_id.usage == "supplier"
)
return (
sale_pickings,
sale_refund_pickings,
purchase_pickings,
purchase_refund_pickings,
)
@api.model
def _default_journal(self, journal_type):
"""
Get the default journal based on the given type
:param journal_type: str
:return: account.journal recordset
"""
default_journal = self.env["account.journal"].search(
[
("type", "=", journal_type),
("company_id", "=", self.env.company.id),
],
limit=1,
)
return default_journal
def action_generate(self):
"""
Launch the invoice generation
:return:
"""
self.ensure_one()
invoices = self._action_generate_invoices()
if not invoices:
raise UserError(_("No invoice created!"))
# Update the state on pickings related to new invoices only
self._update_picking_invoice_status(invoices.mapped("picking_ids"))
inv_type = self._get_invoice_type()
if inv_type in ["out_invoice", "out_refund"]:
xmlid = "account.action_move_out_invoice_type"
else:
xmlid = "account.action_move_in_invoice_type"
action_dict = self.env["ir.actions.act_window"]._for_xml_id(xmlid)
if len(invoices) > 1:
action_dict["domain"] = [("id", "in", invoices.ids)]
elif len(invoices) == 1:
if inv_type in ["out_invoice", "out_refund"]:
form_view = [(self.env.ref("account.view_move_form").id, "form")]
else:
form_view = [(self.env.ref("account.view_move_form").id, "form")]
if "views" in action_dict:
action_dict["views"] = form_view + [
(state, view)
for state, view in action_dict["views"]
if view != "form"
]
else:
action_dict["views"] = form_view
action_dict["res_id"] = invoices.ids[0]
return action_dict
def _load_pickings(self):
"""
Load pickings from context
:return: stock.picking recordset
"""
picking_obj = self.env["stock.picking"]
active_ids = self.env.context.get("active_ids", [])
pickings = picking_obj.browse(active_ids)
pickings = pickings.filtered(lambda p: p.invoice_state == "2binvoiced")
return pickings
def _get_journal(self):
"""
Get the journal depending on the journal_type
:return: account.journal recordset
"""
self.ensure_one()
journal_field = "%s_journal" % self.journal_type
journal = self[journal_field]
return journal
def _get_invoice_type(self):
"""
Get the invoice type
:return: str
"""
self.ensure_one()
active_ids = self.env.context.get("active_ids", [])
if active_ids:
active_ids = active_ids[0]
picking = self.env["stock.picking"].browse(active_ids)
inv_type = (
INVOICE_TYPE_MAP.get(
(
picking.picking_type_code,
picking.location_id.usage,
picking.location_dest_id.usage,
)
)
or "out_invoice"
)
return inv_type
@api.model
def _get_picking_key(self, picking):
"""
Get the key for the given picking.
By default, it's based on the invoice partner and the picking_type_id
of the picking
:param picking: stock.picking recordset
:return: key (tuple,...)
"""
key = (picking,)
if self.group in ["partner", "partner_product"]:
# Pickings with same Partner to create Invoice but the
# Partner to Shipping is different should not be grouping.
key = (
picking._get_partner_to_invoice(),
picking.picking_type_id,
picking.partner_id,
)
return key
def _group_pickings(self, pickings):
"""
Group given picking
:param pickings:
:return: list of stock.picking recordset
"""
grouped_picking = {}
pickings = pickings.filtered(lambda p: p.invoice_state == "2binvoiced")
for picking in pickings:
key = self._get_picking_key(picking)
picks_grouped = grouped_picking.get(key, self.env["stock.picking"].browse())
picks_grouped |= picking
grouped_picking.update({key: picks_grouped})
return grouped_picking.values()
def _simulate_invoice_onchange(self, values):
"""
Simulate onchange for invoice
:param values: dict
:return: dict
"""
invoice = self.env["account.move"].new(values.copy())
invoice._onchange_partner_id()
new_values = invoice._convert_to_write(invoice._cache)
# Ensure basic values are not updated
values.update(new_values)
return invoice, values
def _build_invoice_values_from_pickings(self, pickings):
"""
Build dict to create a new invoice from given pickings
:param pickings: stock.picking recordset
:return: dict
"""
picking = fields.first(pickings)
partner_id = picking._get_partner_to_invoice()
partner = self.env["res.partner"].browse(partner_id)
inv_type = self._get_invoice_type()
currency = self.env.company.currency_id
if partner:
code = picking.picking_type_id.code
if partner.property_product_pricelist and code == "outgoing":
currency = partner.property_product_pricelist.currency_id
journal = self._get_journal()
invoice_obj = self.env["account.move"]
values = invoice_obj.default_get(invoice_obj.fields_get().keys())
values.update(
{
"invoice_origin": ", ".join(pickings.mapped("name")),
"partner_id": partner_id,
"move_type": inv_type,
"currency_id": currency.id,
"journal_id": journal.id,
"picking_ids": [(4, p.id, False) for p in pickings],
}
)
invoice, values = self._simulate_invoice_onchange(values)
return invoice, values
def _get_move_key(self, move):
"""
Get the key based on the given move
:param move: stock.move recordset
:return: (key,)
"""
key = (move,)
if self.group == "partner_product":
key = (move.product_id,)
return key
def _group_moves(self, moves):
"""
Possibility to group moves (to create 1 invoice line with many moves)
:param moves: stock.move recordset
:return: list of stock.move recordset
"""
grouped_moves = {}
moves = moves.filtered(lambda m: m.invoice_state == "2binvoiced")
for move in moves:
key = self._get_move_key(move)
move_grouped = grouped_moves.get(key, self.env["stock.move"].browse())
move_grouped |= move
grouped_moves.update({key: move_grouped})
return grouped_moves.values()
def _simulate_invoice_line_onchange(self, values, price_unit=None):
"""
Simulate onchange for invoice line
:param values: dict
:return: dict
"""
line = self.env["account.move.line"].new(values.copy())
line._onchange_product_id()
new_values = line._convert_to_write(line._cache)
if price_unit:
new_values["price_unit"] = price_unit
# Ensure basic values are not updated
values.update(new_values)
return values
def _get_invoice_line_values(self, moves, invoice_values, invoice):
"""
Create invoice line values from given moves
:param moves: stock.move
:param invoice: account.move
:return: dict
"""
name = ", ".join(moves.mapped("name"))
move = fields.first(moves)
product = move.product_id
partner_id = self.env["res.partner"].browse(invoice_values["partner_id"])
inv_type = invoice_values["move_type"]
quantity = 0
move_line_ids = []
for move in moves:
qty = move.product_uom_qty
loc = move.location_id
loc_dst = move.location_dest_id
# Better to understand with IF/ELIF than many OR
if inv_type == "out_invoice" and loc.usage == "customer":
qty *= -1
elif inv_type == "out_refund" and loc_dst.usage == "customer":
qty *= -1
elif inv_type == "in_invoice" and loc_dst.usage == "supplier":
qty *= -1
elif inv_type == "in_refund" and loc.usage == "supplier":
qty *= -1
quantity += qty
move_line_ids.append((4, move.id, False))
price = moves._get_price_unit_invoice(inv_type, partner_id, quantity)
line_obj = self.env["account.move.line"]
values = line_obj.default_get(line_obj.fields_get().keys())
values.update(
{
"name": name,
"product_id": product.id,
"quantity": quantity,
"price_unit": price,
"move_line_ids": move_line_ids,
"move_id": invoice.id,
}
)
values = self._simulate_invoice_line_onchange(values, price_unit=price)
values.update({"name": name})
return values
def _update_picking_invoice_status(self, pickings):
"""
Update invoice_state on pickings
:param pickings: stock.picking recordset
:return: stock.picking recordset
"""
return pickings._set_as_invoiced()
def ungroup_moves(self, grouped_moves_list):
"""Ungroup your moves, split them again, grouping by
fiscal position, max itens per invoice and etc
:param grouped_moves_list:
:return: list of grouped moves list
"""
return [grouped_moves_list]
def _create_invoice(self, invoice_values):
"""Override this method if you need to change any values of the
invoice and the lines before the invoice creation
:param invoice_values: dict with the invoice and its lines
:return: invoice
"""
return self.env["account.move"].create(invoice_values)
def _action_generate_invoices(self):
"""
Action to generate invoices based on pickings
:return: account.move recordset
"""
pickings = self._load_pickings()
company = pickings.mapped("company_id")
if company and company != self.env.company:
raise UserError(_("All pickings are not related to your company!"))
pick_list = self._group_pickings(pickings)
invoices = self.env["account.move"].browse()
for pickings in pick_list:
moves = pickings.mapped("move_lines")
grouped_moves_list = self._group_moves(moves)
parts = self.ungroup_moves(grouped_moves_list)
for moves_list in parts:
invoice, invoice_values = self._build_invoice_values_from_pickings(
pickings
)
lines = [(5, 0, {})]
line_values = False
for moves in moves_list:
line_values = self._get_invoice_line_values(
moves, invoice_values, invoice
)
if line_values:
lines.append((0, 0, line_values))
if line_values: # Only create the invoice if it has lines
invoice_values["invoice_line_ids"] = lines
invoice_values["invoice_date"] = self.invoice_date
# this is needed otherwise invoice_line_ids are removed
# in _move_autocomplete_invoice_lines_create
# and no invoice line is created
invoice_values.pop("line_ids")
invoice = self._create_invoice(invoice_values)
invoice._onchange_invoice_line_ids()
invoice._compute_amount()
invoices |= invoice
return invoices
| 37.337761
| 19,677
|
1,181
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow S.L.
# (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import logging
from odoo.tools.sql import column_exists
logger = logging.getLogger(__name__)
def pre_init_hook(cr):
"""
The objective of this hook is to speed up the installation
of the module on an existing Odoo instance.
"""
store_exception_fields(cr)
def store_exception_fields(cr):
if not column_exists(cr, "account_move", "main_exception_id"):
logger.info("Creating field main_exception_id on account_move")
cr.execute(
"""
ALTER TABLE account_move
ADD COLUMN main_exception_id int;
COMMENT ON COLUMN account_move.main_exception_id IS 'Main Exception';
"""
)
if not column_exists(cr, "account_move", "ignore_exception"):
logger.info("Creating field ignore_exception on account_move")
cr.execute(
"""
ALTER TABLE account_move
ADD COLUMN ignore_exception boolean;
COMMENT ON COLUMN account_move.ignore_exception IS 'Ignore Exceptions';
"""
)
| 31.078947
| 1,181
|
736
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Account Move Exception",
"summary": "Custom exceptions on account move",
"version": "15.0.1.0.0",
"category": "Generic Modules/Account",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"depends": ["account", "base_exception"],
"license": "AGPL-3",
"data": [
"data/account_exception_data.xml",
"security/ir.model.access.csv",
"wizard/account_exception_confirm_view.xml",
"views/account_view.xml",
],
"pre_init_hook": "pre_init_hook",
"installable": True,
}
| 35.047619
| 736
|
4,415
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestAccountException(TransactionCase):
def setUp(self):
super(TestAccountException, self).setUp()
# Useful models
self.AccountMove = self.env["account.move"].with_context(
check_move_validity=False
)
self.AccountMoveLine = self.env["account.move.line"]
self.partner_id = self.env.ref("base.res_partner_1")
self.product_id_1 = self.env.ref("product.product_product_6")
self.product_id_2 = self.env.ref("product.product_product_7")
self.product_id_3 = self.env.ref("product.product_product_7")
self.account_receivable = self.env["account.account"].search(
[
(
"user_type_id",
"=",
self.env.ref("account.data_account_type_receivable").id,
)
],
limit=1,
)
self.account_exception_confirm = self.env["account.exception.confirm"]
self.exception_noemail = self.env.ref(
"account_move_exception.am_excep_no_email"
)
self.exception_qtycheck = self.env.ref(
"account_move_exception.aml_excep_qty_check"
)
self.am_vals = {
"move_type": "out_invoice",
"partner_id": self.partner_id.id,
"invoice_line_ids": [
(
0,
0,
{
"product_id": self.product_id_1.id,
"quantity": 5.0,
"price_unit": 500.0,
},
),
(
0,
0,
{
"product_id": self.product_id_2.id,
"quantity": 5.0,
"price_unit": 250.0,
},
),
],
}
def test_account_move_exception(self):
self.exception_noemail.active = True
self.exception_qtycheck.active = True
self.partner_id.email = False
self.am = self.AccountMove.create(self.am_vals.copy())
self.assertEqual(self.am.state, "draft")
# test all draft am
self.am2 = self.AccountMove.create(self.am_vals.copy())
self.AccountMove.test_all_draft_moves()
self.assertEqual(self.am2.state, "draft")
# Set ignore_exception flag (Done after ignore is selected at wizard)
self.am.ignore_exception = True
self.am.action_post()
self.assertEqual(self.am.state, "posted")
# Add an account move to test after AM is confirmed
# set ignore_exception = False (Done by onchange of line_ids)
field_onchange = self.AccountMove._onchange_spec()
self.assertEqual(field_onchange.get("line_ids"), "1")
self.env.cache.invalidate()
self.am3New = self.AccountMove.new(self.am_vals.copy())
self.am3New.ignore_exception = True
self.am3New.state = "posted"
self.am3New.onchange_ignore_exception()
self.assertFalse(self.am3New.ignore_exception)
self.am.line_ids.write(
{
"product_id": self.product_id_3.id,
"quantity": 2,
"price_unit": 30,
}
)
# Set ignore exception True (Done manually by user)
self.am.ignore_exception = True
self.am.button_cancel()
self.am.button_draft()
self.assertEqual(self.am.state, "draft")
self.assertTrue(not self.am.ignore_exception)
self.am.action_post()
self.assertTrue(self.am.state, "posted")
# Simulation the opening of the wizard account_exception_confirm and
# set ignore_exception to True
am_except_confirm = self.account_exception_confirm.with_context(
**{
"active_id": self.am.id,
"active_ids": [self.am.id],
"active_model": self.am._name,
}
).create({"ignore": True})
# avoid balance check:
for line in self.am.line_ids:
line.credit = 0.0
am_except_confirm.action_confirm()
self.assertTrue(self.am.ignore_exception)
| 36.791667
| 4,415
|
724
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class AccountExceptionConfirm(models.TransientModel):
_name = "account.exception.confirm"
_description = "Account exception wizard"
_inherit = ["exception.rule.confirm"]
related_model_id = fields.Many2one(
comodel_name="account.move", string="Journal Entry"
)
def action_confirm(self):
self.ensure_one()
if self.ignore:
self.related_model_id.button_draft()
self.related_model_id.ignore_exception = True
self.related_model_id.action_post()
return super().action_confirm()
| 32.909091
| 724
|
1,727
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class AccountMove(models.Model):
_inherit = ["account.move", "base.exception"]
_name = "account.move"
_order = "main_exception_id asc, date desc, name desc"
@api.model
def test_all_draft_moves(self):
move_set = self.search([("state", "=", "draft")])
move_set.detect_exceptions()
return True
@api.model
def _reverse_field(self):
return "account_move_ids"
def detect_exceptions(self):
all_exceptions = super().detect_exceptions()
lines = self.mapped("line_ids")
all_exceptions += lines.detect_exceptions()
return all_exceptions
@api.constrains("ignore_exception", "line_ids", "state")
def account_move_check_exception(self):
moves = self.filtered(lambda s: s.state == "posted")
if moves:
moves._check_exception()
@api.onchange("line_ids")
def onchange_ignore_exception(self):
if self.state == "posted":
self.ignore_exception = False
def action_post(self):
if self.detect_exceptions() and not self.ignore_exception:
return self._popup_exceptions()
return super().action_post()
def button_draft(self):
res = super().button_draft()
for order in self:
order.exception_ids = False
order.main_exception_id = False
order.ignore_exception = False
return res
@api.model
def _get_popup_action(self):
action = self.env.ref("account_move_exception.action_account_exception_confirm")
return action
| 31.4
| 1,727
|
709
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AccountMoveLine(models.Model):
_inherit = ["account.move.line", "base.exception.method"]
_name = "account.move.line"
ignore_exception = fields.Boolean(
related="move_id.ignore_exception", store=True, string="Ignore Exceptions"
)
def _get_main_records(self):
return self.mapped("move_id")
@api.model
def _reverse_field(self):
return "account_move_ids"
def _detect_exceptions(self, rule):
records = super()._detect_exceptions(rule)
return records.mapped("move_id")
| 29.541667
| 709
|
622
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class ExceptionRule(models.Model):
_inherit = "exception.rule"
account_move_ids = fields.Many2many(
comodel_name="account.move", string="Journal Entries"
)
model = fields.Selection(
selection_add=[
("account.move", "Account move"),
("account.move.line", "Account move line"),
],
ondelete={
"account.move": "cascade",
"account.move.line": "cascade",
},
)
| 28.272727
| 622
|
590
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Unique Supplier Invoice Number in Invoice",
"version": "15.0.1.0.0",
"summary": "Checks that supplier invoices are not entered twice",
"author": "Savoir-faire Linux, Acsone SA/NV, Odoo Community Association (OCA)",
"maintainer": "Savoir-faire Linux",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"category": "Accounting & Finance",
"depends": ["account"],
"data": ["views/account_move.xml"],
"installable": True,
}
| 36.875
| 590
|
3,593
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone
# Copyright 2020 Onestein (<https://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields
from odoo.exceptions import ValidationError
from odoo.tests import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
@tagged("post_install", "-at_install")
class TestAccountInvoiceSupplierRefUnique(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
# ENVIRONMENTS
cls.account_account = cls.env["account.account"]
cls.account_move = cls.env["account.move"].with_context(
**{"tracking_disable": True}
)
# INSTANCES
cls.partner = cls.env.ref("base.res_partner_2")
# Account for invoice
cls.account = cls.account_account.search(
[
(
"user_type_id",
"=",
cls.env.ref("account.data_account_type_receivable").id,
)
],
limit=1,
)
# Invoice with unique reference 'ABC123'
cls.invoice = cls.account_move.create(
{
"partner_id": cls.partner.id,
"invoice_date": fields.Date.today(),
"move_type": "in_invoice",
"supplier_invoice_number": "ABC123",
"invoice_line_ids": [(0, 0, {"partner_id": cls.partner.id})],
}
)
def test_check_unique_supplier_invoice_number_insensitive(self):
# A new invoice instance with an existing supplier_invoice_number
with self.assertRaises(ValidationError):
self.account_move.create(
{
"partner_id": self.partner.id,
"move_type": "in_invoice",
"supplier_invoice_number": "ABC123",
}
)
# A new invoice instance with a new supplier_invoice_number
self.account_move.create(
{
"partner_id": self.partner.id,
"move_type": "in_invoice",
"supplier_invoice_number": "ABC123bis",
}
)
def test_onchange_supplier_invoice_number(self):
self.invoice._onchange_supplier_invoice_number()
self.assertEqual(
self.invoice.ref,
self.invoice.supplier_invoice_number,
"_onchange_supplier_invoice_number",
)
def test_copy_invoice(self):
invoice2 = self.invoice.copy()
self.assertNotEqual(self.invoice.ref, "")
self.assertEqual(invoice2.ref, "")
def test_reverse_invoice(self):
self.invoice._post()
move_reversal = (
self.env["account.move.reversal"]
.with_context(active_model="account.move", active_ids=self.invoice.ids)
.create(
{
"date": fields.Date.today(),
"reason": "no reason",
"refund_method": "refund",
"journal_id": self.invoice.journal_id.id,
}
)
)
reversal = move_reversal.reverse_moves()
refund = self.env["account.move"].browse(reversal["res_id"])
self.assertNotEqual(self.invoice.ref, "")
self.assertEqual(refund.ref, "")
def test_reverse_moves_robustness(self):
res = self.invoice._reverse_moves()
self.assertTrue(res.is_purchase_document(include_receipts=True))
| 35.574257
| 3,593
|
3,018
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class AccountMove(models.Model):
_inherit = "account.move"
supplier_invoice_number = fields.Char(
string="Vendor invoice number",
readonly=True,
states={"draft": [("readonly", False)]},
copy=False,
)
@api.constrains("supplier_invoice_number")
def _check_unique_supplier_invoice_number_insensitive(self):
"""
Check if an other vendor bill has the same supplier_invoice_number
and the same commercial_partner_id than the current instance
"""
for rec in self:
if rec.supplier_invoice_number and rec.is_purchase_document(
include_receipts=True
):
same_supplier_inv_num = rec.search(
[
("commercial_partner_id", "=", rec.commercial_partner_id.id),
("move_type", "in", ("in_invoice", "in_refund")),
(
"supplier_invoice_number",
"=ilike",
rec.supplier_invoice_number,
),
("id", "!=", rec.id),
],
limit=1,
)
if same_supplier_inv_num:
raise ValidationError(
_(
"The invoice/refund with supplier invoice number {} "
"already exists in Odoo under the number {} "
"for supplier {}."
).format(
same_supplier_inv_num.supplier_invoice_number,
same_supplier_inv_num.name or "-",
same_supplier_inv_num.partner_id.display_name,
)
)
@api.onchange("supplier_invoice_number")
def _onchange_supplier_invoice_number(self):
if not self.ref:
self.ref = self.supplier_invoice_number
def _reverse_moves(self, default_values_list=None, cancel=False):
# OVERRIDE
if default_values_list:
for move, default_values in zip(self, default_values_list):
if (
move
and move.is_purchase_document(include_receipts=True)
and default_values.get("ref")
):
default_values.update({"ref": ""})
return super()._reverse_moves(
default_values_list=default_values_list, cancel=cancel
)
def copy(self, default=None):
"""
The unique vendor invoice number is not copied in vendor bills
"""
if self.is_purchase_document(include_receipts=True):
default = dict(default or {}, ref="")
return super().copy(default)
| 38.202532
| 3,018
|
563
|
py
|
PYTHON
|
15.0
|
# © 2017 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Account Invoice Pricelist - Sale",
"summary": "Module to fill pricelist from sales order in invoice.",
"author": "Therp BV,GRAP,Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/account-invoicing",
"category": "Sales",
"version": "15.0.1.0.0",
"depends": ["account_invoice_pricelist", "sale"],
"installable": True,
"auto_install": True,
"application": False,
}
| 37.466667
| 562
|
1,641
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 - Today: GRAP (http://www.grap.coop)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestModule(TransactionCase):
def setUp(self):
super(TestModule, self).setUp()
self.partner = self.env.ref("base.res_partner_12")
self.product = self.env.ref("product.consu_delivery_01")
self.product.invoice_policy = "order"
def test_main(self):
# Create Pricelist
pricelist = self.env["product.pricelist"].create({"name": "Demo Pricelist"})
# Create Product
order = self.env["sale.order"].create(
{
"partner_id": self.partner.id,
"pricelist_id": pricelist.id,
"order_line": [
(
0,
0,
{
"name": self.product.name,
"product_id": self.product.id,
"product_uom_qty": 5,
"product_uom": self.product.uom_id.id,
"price_unit": self.product.list_price,
"qty_delivered": 5,
},
),
],
}
)
order.action_confirm()
invoice = order._create_invoices()
self.assertEqual(
invoice.pricelist_id,
order.pricelist_id,
"Invoice Pricelist has not been recovered from sale order",
)
| 36.466667
| 1,641
|
464
|
py
|
PYTHON
|
15.0
|
# © 2017 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def _prepare_invoice(self):
"""Pricelist_id is set on invoice."""
self.ensure_one()
val = super(SaleOrder, self)._prepare_invoice()
if self.pricelist_id:
val.update({"pricelist_id": self.pricelist_id.id})
return val
| 30.866667
| 463
|
704
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Moduon Team S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0)
{
"name": "Account Invoice Clearing",
"summary": "Account invoice clearing wizard",
"version": "15.0.0.1.3",
"development_status": "Alpha",
"category": "Accounting/Accounting",
"website": "https://github.com/OCA/account-invoicing",
"author": "Moduon, Odoo Community Association (OCA)",
"maintainers": ["Shide"],
"license": "AGPL-3",
"application": False,
"depends": [
"account",
],
"data": [
"security/ir.model.access.csv",
"views/account_move_view.xml",
"wizards/account_invoice_clearing_wizard_views.xml",
],
}
| 30.608696
| 704
|
5,647
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Moduon Team S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0)
from datetime import timedelta
from odoo import fields
from odoo.tests.common import tagged
from odoo.tools import float_is_zero
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
@tagged("post_install", "-at_install")
class TestClearingWizard(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.cl_partner = cls.env["res.partner"].create(
{
"name": "Clearing Partner",
"is_company": True,
"child_ids": [
(0, 0, {"name": "Clearing Contact 1", "type": "invoice"}),
(0, 0, {"name": "Clearing Contact 2", "type": "invoice"}),
],
}
)
def test_clearing_wizard(self):
"""Test clearing wizard with different move types."""
def sorted_by_sequence(lines):
return sorted(lines, key=lambda l: l.sequence)
move_types = ["out_invoice", "in_invoice"]
for init_move_type, clearing_move_type in [move_types, move_types[::-1]]:
with self.subTest(
init_move_type=init_move_type, clearing_move_type=clearing_move_type
):
init_inv = self.init_invoice(
invoice_date=fields.Date.today(),
move_type=init_move_type,
partner=self.cl_partner,
amounts=[100, 200],
post=True,
)
cl_inv_1 = self.init_invoice(
invoice_date=fields.Date.today() + timedelta(days=5),
move_type=clearing_move_type,
partner=self.cl_partner.child_ids[0],
amounts=[100],
post=True,
)
cl_inv_2 = self.init_invoice(
invoice_date=fields.Date.today() + timedelta(days=10),
move_type=clearing_move_type,
partner=self.cl_partner.child_ids[1],
amounts=[200],
post=True,
)
# Create wizard
cw_action = init_inv.action_open_invoice_clearing_wizard()
wizard = self.env[cw_action["res_model"]].browse(cw_action["res_id"])
# Test Action: Unlink Lines
wizard.action_unlink_lines()
self.assertFalse(wizard.line_ids)
# Test Action: Add Lines
wizard.action_add_lines()
self.assertTrue(wizard.line_ids)
# Test Action: Sort Lines by Date Due
wizard.action_sort_by_date_due_asc()
slines = sorted_by_sequence(wizard.line_ids)
self.assertTrue(slines[0].date_maturity < slines[1].date_maturity)
wizard.action_sort_by_date_due_desc()
slines = sorted_by_sequence(wizard.line_ids)
self.assertTrue(slines[0].date_maturity > slines[1].date_maturity)
# Test Action: Sort Lines by Amount Residual
wizard.action_sort_by_residual_asc()
slines = sorted_by_sequence(wizard.line_ids)
self.assertTrue(slines[0].amount_residual < slines[1].amount_residual)
wizard.action_sort_by_residual_desc()
slines = sorted_by_sequence(wizard.line_ids)
self.assertTrue(slines[0].amount_residual > slines[1].amount_residual)
# Test Action: Fill Amount to Clear
wizard.action_fill_amount_to_clear()
wizard.refresh()
self.assertTrue(
float_is_zero(
wizard.amount_to_clear,
precision_rounding=wizard.company_currency_id.rounding,
)
)
# Test Action: Reset Lines
wizard.action_reset_lines()
wizard.refresh()
self.assertTrue(
not float_is_zero(
wizard.amount_to_clear,
precision_rounding=wizard.company_currency_id.rounding,
)
)
# Create moves
wizard.action_fill_amount_to_clear()
wizard.refresh()
wizard.button_confirm()
self.assertEqual(init_inv.payment_state, "paid")
self.assertEqual(cl_inv_1.payment_state, "paid")
self.assertEqual(cl_inv_2.payment_state, "paid")
def test_internal_types(self):
aicw_model = self.env["account.invoice.clearing.wizard"]
# For lines to clear
self.assertEqual(
"payable",
aicw_model._get_internal_type_from_move_type(
"in_invoice", is_counterpart=False
),
)
self.assertEqual(
"receivable",
aicw_model._get_internal_type_from_move_type(
"out_invoice", is_counterpart=False
),
)
# For counterpart lines
self.assertEqual(
"receivable",
aicw_model._get_internal_type_from_move_type(
"in_invoice", is_counterpart=True
),
)
self.assertEqual(
"payable",
aicw_model._get_internal_type_from_move_type(
"out_invoice", is_counterpart=True
),
)
| 41.218978
| 5,647
|
758
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Moduon Team S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0)
from odoo import models
class AccountMove(models.Model):
_inherit = "account.move"
def action_open_invoice_clearing_wizard(self):
wizard = (
self.env["account.invoice.clearing.wizard"]
.with_context(active_model=self._name, active_ids=self.ids)
.create({"invoice_ids": [(6, 0, self.ids)]})
)
wizard._compute_initial_data()
wizard._onchange_move_type()
action = (
self.sudo()
.env.ref("account_invoice_clearing.action_account_invoice_clearing_wizard")
.read()[0]
)
action["res_id"] = wizard.id
return action
| 30.32
| 758
|
24,650
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 Moduon Team S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0)
import json
from collections import OrderedDict
from itertools import groupby
from odoo import _, api, exceptions, fields, models
from odoo.tools import float_is_zero
class AccountInvoiceClearingWizard(models.TransientModel):
_name = "account.invoice.clearing.wizard"
_description = "Invoice Clearing Wizard"
_transient_max_hours = 6 # 6 hours to allow vacuuming
@api.model
def _get_default_journal(self):
return self.env["account.journal"].search(
[
("company_id", "=", self.env.company.id),
("type", "=", "general"),
],
limit=1,
)
move_name = fields.Char(
help="Name of the move generated by this wizard",
default="Clearing operation",
)
move_line_prefix = fields.Char(
string="Prefix for move lines",
help="Prefix to be used in the name of the move lines generated by this wizard",
default="Clearing operation",
)
invoice_ids = fields.Many2many(
comodel_name="account.move",
domain=[("move_type", "!=", "entry"), ("state", "=", "posted")],
string="Invoices/Bills",
required=True,
)
move_line_ids = fields.Many2many(
comodel_name="account.move.line",
compute="_compute_initial_data",
store=True,
)
company_id = fields.Many2one(
comodel_name="res.company",
compute="_compute_initial_data",
store=True,
)
company_currency_id = fields.Many2one(
comodel_name="res.currency",
compute="_compute_initial_data",
store=True,
)
move_type = fields.Char(
compute="_compute_initial_data",
store=True,
)
commercial_partner_id = fields.Many2one(
comodel_name="res.partner",
compute="_compute_initial_data",
store=True,
)
amount_to_clear = fields.Monetary(
compute="_compute_amount_to_clear",
currency_field="company_currency_id",
store=False,
)
line_ids = fields.One2many(
comodel_name="account.invoice.clearing.lines.wizard",
inverse_name="clearing_id",
string="Lines",
)
date = fields.Date(
default=fields.Date.context_today,
required=True,
)
journal_id = fields.Many2one(
comodel_name="account.journal",
domain="[('type', '=', 'general'), ('company_id', '=', company_id)]",
string="Journal",
check_company=True,
required=True,
default=_get_default_journal,
)
# Preview resulting move
move_data = fields.Text(
compute="_compute_move_data",
help="JSON value of the moves to be created",
)
preview_move_data = fields.Text(
compute="_compute_preview_move_data",
help="JSON value of the data to be displayed in the previewer",
)
def default_get(self, fields):
res = super().default_get(fields)
active_model = self.env.context.get("active_model")
active_ids = self.env.context.get("active_ids")
if active_model == "account.move" and active_ids:
res["invoice_ids"] = [(6, 0, active_ids)]
return res
@api.model
def _get_internal_type_from_move_type(self, move_type, is_counterpart=False):
move_types = ["payable", "receivable"]
if is_counterpart and "refund" not in move_type:
move_types.reverse()
if move_type.startswith("out_"):
move_types.reverse()
return move_types[0]
# Computes & Onchange
@api.depends("invoice_ids")
def _compute_initial_data(self):
"""Compute initial data for the wizard."""
self.update(
{
"move_type": False,
"commercial_partner_id": False,
"company_id": False,
"company_currency_id": False,
"move_line_ids": False,
}
)
for record in self:
if not record.invoice_ids:
continue
company = self._get_companies(record.invoice_ids)[0]
record.move_type = self._get_move_types(record.invoice_ids)[0]
record.commercial_partner_id = self._get_commercial_partners(
record.invoice_ids
)[0]
record.company_id = company
record.company_currency_id = company.currency_id
internal_type = self._get_internal_type_from_move_type(record.move_type)
record.move_line_ids = self.invoice_ids.mapped("line_ids").filtered(
lambda ml: not ml.full_reconcile_id
and ml.balance
and ml.account_id.reconcile
and ml.account_id.internal_type == internal_type
)
@api.depends("move_line_ids", "line_ids")
def _compute_move_data(self):
"""Compute the data to be used by the account.move form view."""
self.update({"move_data": "[]"})
for record in self:
if not record.move_line_ids or not record.line_ids:
continue
record.move_data = json.dumps(
record.with_context(preview=True)._get_move_dict_vals()
)
@api.depends("move_data")
def _compute_preview_move_data(self):
"""Compute the data to be displayed in the previewer."""
am_model = self.env["account.move"]
for record in self:
preview_columns = [
{"field": "account_id", "label": _("Account")},
{"field": "name", "label": _("Label")},
{"field": "partner_id", "label": _("Partner")},
{
"field": "debit",
"label": _("Debit"),
"class": "text-right text-nowrap",
},
{
"field": "credit",
"label": _("Credit"),
"class": "text-right text-nowrap",
},
]
move_vals = json.loads(record.move_data)
preview_data = []
for move in move_vals:
preview_vals = am_model._move_dict_to_preview_vals(
move,
record.company_currency_id,
)
preview_vals["group_name"] = _(
"Preview of the clearing move related to %s",
move["related_to_move"],
)
preview_data += [preview_vals]
record.preview_move_data = json.dumps(
{
"groups_vals": preview_data,
"options": {
"discarded_number": False,
"columns": preview_columns,
},
}
)
def _compute_amount_to_clear(self):
"""Compute the remaining amount to clear."""
for record in self:
residual_amount = sum(record.move_line_ids.mapped("amount_residual"))
amount_cleared = sum(record.line_ids.mapped("amount_to_clear"))
record.amount_to_clear = residual_amount + amount_cleared
@api.onchange("move_type")
def _onchange_move_type(self):
"""Create lines for all invoices of the counterpart types."""
data = [(5, 0, 0)]
if self.move_type and self.commercial_partner_id:
for idx, move_line in enumerate(
self._get_available_clearing_move_lines(
self.move_type, self.commercial_partner_id, self.move_line_ids
),
10,
):
data.append((0, 0, {"move_line_id": move_line.id, "sequence": idx}))
self.line_ids = data
# Actions
def action_reopen_wizard(self):
"""Reopen the wizard."""
self.ensure_one()
action = (
self.sudo()
.env.ref("account_invoice_clearing.action_account_invoice_clearing_wizard")
.read()[0]
)
action["res_id"] = self.id
return action
def action_reset_lines(self):
"""Reset all lines."""
self.ensure_one()
self.action_unlink_lines()
self.action_add_lines()
return self.action_reopen_wizard()
def action_fill_amount_to_clear(self):
"""Fill the amount to clear in all lines until amount to clear is zero."""
self.ensure_one()
# Always inverse sign because move lines has negative residual amounts
amount_to_clear = -self.amount_to_clear
for line in self.line_ids.filtered(lambda l: not l.amount_to_clear):
cmp_fnc = float.__le__ if line.amount_residual < 0.0 else float.__ge__
if float_is_zero(
amount_to_clear, precision_rounding=line.company_currency_id.rounding
):
line.amount_to_clear = 0.0
elif cmp_fnc(amount_to_clear, line.amount_residual):
line.amount_to_clear = line.amount_residual
amount_to_clear -= line.amount_residual
else:
line.amount_to_clear = amount_to_clear
amount_to_clear = 0.0
return self.action_reopen_wizard()
def action_unlink_lines(self):
"""Unlink all lines."""
self.ensure_one()
self.line_ids = [(5, 0, 0)]
return self.action_reopen_wizard()
def action_add_lines(self):
"""Add all possible lines."""
self.ensure_one()
existing_move_lines = self.line_ids.mapped("move_line_id")
last_sequence = self.line_ids[-1].sequence if self.line_ids else 0
new_lines = []
for move_line in self._get_available_clearing_move_lines(
self.move_type, self.commercial_partner_id, self.move_line_ids
):
if move_line in existing_move_lines:
continue
new_lines.append(
(0, 0, {"move_line_id": move_line.id, "sequence": last_sequence + 1})
)
last_sequence += 10
if new_lines:
self.line_ids = new_lines
return self.action_reopen_wizard()
def action_sort_by_date_due(self, reverse=False):
"""Sort lines by date due."""
self.ensure_one()
sorted_lines = self.line_ids.sorted(
key=lambda l: l.date_maturity, reverse=reverse
)
for seq, line in enumerate(sorted_lines, start=10):
line.sequence = seq
return self.action_reopen_wizard()
def action_sort_by_date_due_asc(self):
"""Sort lines by date due ascending."""
return self.action_sort_by_date_due(reverse=False)
def action_sort_by_date_due_desc(self):
"""Sort lines by date due descending."""
return self.action_sort_by_date_due(reverse=True)
def action_sort_by_residual(self, reverse=False):
"""Sort lines by residual amount."""
self.ensure_one()
sorted_lines = self.line_ids.sorted(
key=lambda l: l.amount_residual, reverse=reverse
)
for seq, line in enumerate(sorted_lines, start=10):
line.sequence = seq
return self.action_reopen_wizard()
def action_sort_by_residual_asc(self):
"""Sort lines by residual amount ascending."""
return self.action_sort_by_residual(reverse=False)
def action_sort_by_residual_desc(self):
"""Sort lines by residual amount descending."""
return self.action_sort_by_residual(reverse=True)
def button_confirm(self):
"""Create the clearing move."""
self.ensure_one()
am_model = self.env["account.move"]
aml_model = self.env["account.move.line"]
# Get the fresh resulting moves data
res_ids = []
moves_data = self._get_move_dict_vals()
for move_data in moves_data:
# Extract in order the move_line wich every line needs to be reconciled
to_concile_lines = []
for move_line in move_data["line_ids"]:
to_concile_lines.append(
aml_model.browse(move_line[2]["move_line_id_to_reconcile"])
)
del move_line[2]["move_line_id_to_reconcile"]
# Create move with cleaned data
del move_data["related_to_move"]
move = am_model.create(move_data)
move.action_post()
res_ids.append(move.id)
for idx, move_line in enumerate(move.line_ids):
(move_line | to_concile_lines[idx]).reconcile()
# Build resulting action
action = {
"name": _("Resulting Clearing Move"),
"type": "ir.actions.act_window",
"res_model": "account.move",
"view_mode": "form",
"target": "current",
}
if len(res_ids) > 1:
action.update(
{
"domain": [("id", "in", res_ids)],
"view_mode": "tree,form",
}
)
else:
action["res_id"] = res_ids[0]
return action
# Helpers
@api.model
def _get_commercial_partners(self, invoices):
"""Get the commercial partners of the invoices."""
partners = invoices.mapped("commercial_partner_id")
return partners.mapped("commercial_partner_id")
@api.model
def _get_companies(self, invoices):
"""Get the companies of the invoices."""
return invoices.mapped("company_id")
@api.model
def _get_move_types(self, invoices):
"""Get the move types of the invoices."""
return list(set(invoices.mapped("move_type")))
@api.model
def _get_available_clearing_move_lines(self, move_type, partner, move_lines):
"""Get the move lines that can be used for clearing."""
counterpart_internal_type = self._get_internal_type_from_move_type(
move_type, is_counterpart=True
)
debit_credit_field = (
"credit" if sum(move_lines.mapped("amount_residual")) > 0 else "debit"
)
return (
self.env["account.move.line"]
.sudo()
.search(
[
("id", "not in", move_lines.ids),
("account_id.internal_type", "=", counterpart_internal_type),
("reconciled", "=", False),
("partner_id", "child_of", partner.id),
("parent_state", "=", "posted"),
("account_id.reconcile", "=", True),
(debit_credit_field, ">", 0.0),
],
order="date_maturity asc, amount_residual asc",
)
)
def _get_remaining_amount_to_clear(self):
"""Get the remaining amount to clear."""
self.ensure_one()
return self.amount_to_clear + sum(self.line_ids.mapped("amount_to_clear"))
# flake8: noqa: C901
def _get_move_dict_vals(self):
self.ensure_one()
move_name, move_line_prefix = self.move_name, self.move_line_prefix
if self.env.context.get("preview"):
move_name, move_line_prefix = "<Move Name>", "<Move Line Prefix>"
def fiz(amount):
return float_is_zero(
amount, precision_rounding=self.company_currency_id.rounding
)
def get_debit_credit(amount):
if amount > 0.0:
return amount, 0.0
return 0.0, 0.0 if fiz(amount) else -amount
def get_amount_to_use(amount_to_fill, avaiable_amount):
amount = max(amount_to_fill, avaiable_amount)
if amount_to_fill > 0.0:
amount = min(amount_to_fill, avaiable_amount)
return self.company_currency_id.round(amount)
def build_line_name(move_line):
txts = [move_line_prefix, move_line.move_id.name, move_line.name]
if move_line.move_id.name == move_line.name:
txts[1:] = [move_line.move_id.name]
return " - ".join(list(map(str.strip, filter(lambda t: t, txts))))
def get_clear_sign_modifier(a, b):
different_sign = (a < 0.0 and b > 0.0) or (a > 0.0 and b < 0.0)
return -1.0 if different_sign else 1.0
clear_lines_availability = OrderedDict()
for cl in self.line_ids.filtered(lambda l: l.amount_to_clear):
clear_lines_availability[cl.move_line_id] = cl.amount_to_clear
move_vals = []
for move, move_lines in groupby(self.move_line_ids, key=lambda ml: ml.move_id):
line_vals = []
for move_line in move_lines:
related_move_line_vals = []
ml_amount_residual, cl_balance = move_line.amount_residual, 0.0
for cl_move_line in clear_lines_availability:
# Move line fully cleared
if fiz(ml_amount_residual):
break
# Clearing line fully used
if fiz(clear_lines_availability[cl_move_line]):
continue
# Choose correct sign to compute clearing amount
clear_sign = get_clear_sign_modifier(
ml_amount_residual, clear_lines_availability[cl_move_line]
)
# Used amount for clearing (sign aligned)
used_amount = get_amount_to_use(
ml_amount_residual,
clear_sign * clear_lines_availability[cl_move_line],
)
# Clearing balance for this move line
cl_balance += clear_sign * used_amount
# Remaining amount to clear on this move
ml_amount_residual -= used_amount
# Remaining amount on this clearing move line
clear_lines_availability[cl_move_line] += used_amount
cl_debit, cl_credit = get_debit_credit(used_amount)
related_move_line_vals.append(
{
"name": build_line_name(cl_move_line),
"debit": cl_debit,
"credit": cl_credit,
"account_id": cl_move_line.account_id.id,
"partner_id": self.commercial_partner_id.id,
"currency_id": self.company_currency_id.id,
"move_line_id_to_reconcile": cl_move_line.id,
}
)
ml_debit, ml_credit = get_debit_credit(cl_balance)
if fiz(ml_debit) and fiz(ml_credit):
continue
line_vals.append(
{
"name": build_line_name(move_line),
"debit": ml_debit,
"credit": ml_credit,
"account_id": move_line.account_id.id,
"partner_id": self.commercial_partner_id.id,
"currency_id": self.company_currency_id.id,
"move_line_id_to_reconcile": move_line.id,
}
)
line_vals.extend(related_move_line_vals)
if not line_vals:
continue
move_vals.append(
{
"currency_id": self.company_currency_id.id,
"move_type": "entry",
"journal_id": self.journal_id.id,
"date": fields.Date.to_string(self.date),
"ref": move_name,
"line_ids": [(0, 0, line) for line in line_vals],
"related_to_move": move.name,
}
)
return move_vals
# Constrains
@api.constrains("invoice_ids")
def _check_invoices_same_partner(self):
"""Check that all invoices are from the same
commercial partner, type and company."""
for record in self:
if len(set(self._get_commercial_partners(record.invoice_ids))) > 1:
raise exceptions.ValidationError(
_("Invoices must be from the same commercial partner.")
)
if len(self._get_move_types(record.invoice_ids)) > 1:
raise exceptions.ValidationError(
_("Invoices must be of the same type.")
)
if len(self._get_companies(record.invoice_ids)) > 1:
raise exceptions.ValidationError(
_("Invoices must belong to the same company.")
)
class AccountInvoiceClearingLinesWizard(models.TransientModel):
_name = "account.invoice.clearing.lines.wizard"
_description = "Account Invoice Clearing Lines Wizard"
_order = "sequence, id"
clearing_id = fields.Many2one(
comodel_name="account.invoice.clearing.wizard",
string="Clearing",
)
sequence = fields.Integer(
default=10,
)
move_line_id = fields.Many2one(
comodel_name="account.move.line",
string="Move Line",
required=True,
)
invoice_id = fields.Many2one(
related="move_line_id.move_id",
readonly=True,
)
date = fields.Date(
related="move_line_id.date",
readonly=True,
)
date_maturity = fields.Date(
related="move_line_id.date_maturity",
readonly=True,
)
company_currency_id = fields.Many2one(
related="move_line_id.company_currency_id",
readonly=True,
)
amount_residual = fields.Monetary(
related="move_line_id.amount_residual",
currency_field="company_currency_id",
readonly=True,
)
debit = fields.Monetary(
related="move_line_id.debit",
currency_field="company_currency_id",
readonly=True,
)
credit = fields.Monetary(
related="move_line_id.credit",
currency_field="company_currency_id",
readonly=True,
)
account_id = fields.Many2one(
related="move_line_id.account_id",
readonly=True,
)
name = fields.Char(
related="move_line_id.name",
readonly=True,
)
product_id = fields.Many2one(
related="move_line_id.product_id",
readonly=True,
)
analytic_account_id = fields.Many2one(
related="move_line_id.analytic_account_id",
readonly=True,
)
analytic_tag_ids = fields.Many2many(
related="move_line_id.analytic_tag_ids",
readonly=True,
)
amount_to_clear = fields.Monetary(
string="Clearing amount",
currency_field="company_currency_id",
default=0.0,
readonly=True,
)
can_use_line = fields.Boolean(
compute="_compute_can_use_line",
store=False,
)
# Compute
@api.depends("amount_residual")
def _compute_can_use_line(self):
"""Compute if the line can be used for clearing."""
self.update({"can_use_line": False})
for record in self:
if record.clearing_id.amount_to_clear == 0.0:
continue
record.can_use_line = record.amount_residual != record.amount_to_clear
# Actions
def action_use_all_amount_residual(self):
"""Fill the amount to clear with the residual amount."""
self.ensure_one()
clearing = self.clearing_id
if float_is_zero(
clearing.amount_to_clear,
precision_digits=clearing.company_currency_id.rounding,
):
return clearing.action_reopen_wizard()
# Always inverse sign because move lines has negative residual amounts
amount_to_clear = -clearing.amount_to_clear
cmp_fnc = float.__le__ if self.amount_residual < 0.0 else float.__ge__
if cmp_fnc(amount_to_clear, self.amount_residual):
amount_to_clear = self.amount_residual
self.amount_to_clear = amount_to_clear
return clearing.action_reopen_wizard()
# Constrains
@api.constrains("amount_to_clear")
def _check_amount_to_clear(self):
"""Check that the amount to clear is not greater than the residual amount."""
for record in self:
if abs(record.amount_to_clear) > abs(record.amount_residual):
raise exceptions.ValidationError(
_("Amount to clear cannot be greater than residual amount.")
)
| 37.57622
| 24,650
|
492
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2020 Agile Business Group sagl
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Stock Picking Invoicing Incoterm",
"version": "15.0.1.0.0",
"category": "Inventory/Inventory",
"author": "Agile Business Group, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"depends": ["sale_stock"],
"data": ["views/stock_picking_views.xml"],
"installable": True,
}
| 37.846154
| 492
|
334
|
py
|
PYTHON
|
15.0
|
# Copyright 2014-2020 Agile Business Group sagl
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models
class StockPicking(models.Model):
_inherit = "stock.picking"
incoterm = fields.Many2one(
related="sale_id.incoterm", string="Incoterm", store=True, readonly=False
)
| 27.833333
| 334
|
605
|
py
|
PYTHON
|
15.0
|
# Copyright <2020> PESOL <info@pesol.es>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
{
"name": "Account Move Tier Validation",
"summary": "Extends the functionality of Account Moves to "
"support a tier validation process.",
"version": "15.0.1.1.1",
"category": "Accounts",
"website": "https://github.com/OCA/account-invoicing",
"author": "PESOL, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["account", "base_tier_validation"],
"data": ["views/account_move_view.xml"],
}
| 37.8125
| 605
|
674
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class TierValidationTester(models.Model):
_name = "tier.validation.tester"
_description = "Tier Validation Tester"
_inherit = ["tier.validation"]
state = fields.Selection(
selection=[
("draft", "Draft"),
("confirmed", "Confirmed"),
("cancel", "Cancel"),
],
default="draft",
)
test_field = fields.Float()
user_id = fields.Many2one(string="Assigned to:", comodel_name="res.users")
def action_confirm(self):
self.write({"state": "confirmed"})
| 28.083333
| 674
|
2,212
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ForgeFlow S.L.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo.tests import common
from odoo.tests.common import tagged
from .common import setup_test_model, teardown_test_model
from .tier_validation_tester import TierValidationTester
@tagged("post_install", "-at_install")
class TestAccountTierValidation(common.TransactionCase):
@classmethod
def setUpClass(cls):
super(TestAccountTierValidation, cls).setUpClass()
setup_test_model(cls.env, [TierValidationTester])
cls.test_model = cls.env[TierValidationTester._name]
cls.tester_model = cls.env["ir.model"].search(
[("model", "=", "tier.validation.tester")]
)
# Access record:
cls.env["ir.model.access"].create(
{
"name": "access.tester",
"model_id": cls.tester_model.id,
"perm_read": 1,
"perm_write": 1,
"perm_create": 1,
"perm_unlink": 1,
}
)
# Create users:
group_ids = cls.env.ref("base.group_system").ids
cls.test_user_1 = cls.env["res.users"].create(
{"name": "John", "login": "test1", "groups_id": [(6, 0, group_ids)]}
)
# Create tier definitions:
cls.tier_def_obj = cls.env["tier.definition"]
cls.tier_def_obj.create(
{
"model_id": cls.tester_model.id,
"review_type": "individual",
"reviewer_id": cls.test_user_1.id,
"definition_domain": "[('test_field', '>', 1.0)]",
}
)
cls.test_record = cls.test_model.create({"test_field": 2.5})
@classmethod
def tearDownClass(cls):
teardown_test_model(cls.env, [TierValidationTester])
return super(TestAccountTierValidation, cls).tearDownClass()
def test_01_tier_definition_models(self):
"""When the user can validate all future reviews, it is not needed
to request a validation, the action can be done straight forward."""
res = self.tier_def_obj._get_tier_validation_model_names()
self.assertIn("account.move", res)
| 34.030769
| 2,212
|
598
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
def setup_test_model(env, model_clses):
for model_cls in model_clses:
model_cls._build_model(env.registry, env.cr)
env.registry.setup_models(env.cr)
env.registry.init_models(
env.cr,
[model_cls._name for model_cls in model_clses],
dict(env.context, update_custom_fields=True),
)
def teardown_test_model(env, model_clses):
for model_cls in model_clses:
del env.registry.models[model_cls._name]
env.registry.setup_models(env.cr)
| 29.9
| 598
|
745
|
py
|
PYTHON
|
15.0
|
# Copyright <2020> PESOL <info@pesol.es>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import _, models
class AccountMove(models.Model):
_name = "account.move"
_inherit = ["account.move", "tier.validation"]
_state_from = ["draft"]
_state_to = ["posted"]
def _get_to_validate_message_name(self):
name = super(AccountMove, self)._get_to_validate_message_name()
if self.move_type == "in_invoice":
name = _("Bill")
elif self.move_type == "in_refund":
name = _("Refund")
elif self.move_type == "out_invoice":
name = _("Invoice")
elif self.move_type == "out_refund":
name = _("Credit Note")
return name
| 32.391304
| 745
|
401
|
py
|
PYTHON
|
15.0
|
# Copyright <2020> PESOL <info@pesol.es>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import api, models
class TierDefinition(models.Model):
_inherit = "tier.definition"
@api.model
def _get_tier_validation_model_names(self):
res = super(TierDefinition, self)._get_tier_validation_model_names()
res.append("account.move")
return res
| 28.642857
| 401
|
565
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Partner Invoicing Mode At Shipping",
"version": "15.0.1.0.0",
"summary": "Create invoices automatically when goods are shipped.",
"author": "Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"category": "Accounting & Finance",
"data": [
"data/queue_job_data.xml",
],
"depends": ["account", "partner_invoicing_mode", "queue_job", "stock"],
}
| 37.666667
| 565
|
2,330
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import TransactionCase
class TestInvoiceModeAtShipping(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
cls.partner = cls.env.ref("base.res_partner_1")
cls.product = cls.env.ref("product.product_delivery_01")
cls.so1 = cls.env["sale.order"].create(
{
"partner_id": cls.partner.id,
"partner_invoice_id": cls.partner.id,
"partner_shipping_id": cls.partner.id,
"order_line": [
(
0,
0,
{
"name": "Line one",
"product_id": cls.product.id,
"product_uom_qty": 4,
"product_uom": cls.product.uom_id.id,
"price_unit": 123,
},
)
],
"pricelist_id": cls.env.ref("product.list0").id,
}
)
def test_invoice_created_at_shipping(self):
"""Check that an invoice is created when goods are shipped."""
self.partner.invoicing_mode = "at_shipping"
self.so1.action_confirm()
for picking in self.so1.picking_ids:
for line in picking.move_lines:
line.quantity_done = line.product_uom_qty
picking.action_assign()
picking.with_context(test_queue_job_no_delay=True).button_validate()
self.assertEqual(len(self.so1.invoice_ids), 1)
self.assertEqual(self.so1.invoice_ids.state, "posted")
def test_invoice_not_created_at_shipping(self):
"""Check that an invoice is not created when goods are shipped."""
self.partner.invoicing_mode = "standard"
self.so1.action_confirm()
for picking in self.so1.picking_ids:
for line in picking.move_lines:
line.quantity_done = line.product_uom_qty
picking.action_assign()
picking.button_validate()
self.assertEqual(len(self.so1.invoice_ids), 0)
| 40.877193
| 2,330
|
588
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import models
class StockMove(models.Model):
_inherit = "stock.move"
def _get_related_invoices(self):
"""Overridden from stock_account to return the customer invoices
related to this stock move.
"""
invoices = super()._get_related_invoices()
line_invoices = self.mapped("sale_line_id.order_id.invoice_ids").filtered(
lambda x: x.state == "posted"
)
invoices |= line_invoices
return invoices
| 30.947368
| 588
|
1,879
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import _, models
class StockPicking(models.Model):
_inherit = "stock.picking"
def _action_done(self):
res = super()._action_done()
for picking in self:
if picking._invoice_at_shipping():
picking.with_delay()._invoicing_at_shipping()
return res
def _invoice_at_shipping(self):
"""Check if picking must be invoiced at shipping."""
self.ensure_one()
return (
self.picking_type_code == "outgoing"
and self.sale_id.partner_invoice_id.invoicing_mode == "at_shipping"
)
def _invoicing_at_shipping(self):
self.ensure_one()
sales = self.env["sale.order"].browse()
# Filter out non invoicable sales order
for sale in self._get_sales_order_to_invoice():
if sale._get_invoiceable_lines():
sales |= sale
# Split invoice creation on partner sales grouping on invoice settings
sales_one_invoice_per_order = sales.filtered(
"partner_invoice_id.one_invoice_per_order"
)
invoices = self.env["account.move"].browse()
if sales_one_invoice_per_order:
invoices |= sales_one_invoice_per_order._create_invoices(grouped=True)
sales_many_invoice_per_order = sales - sales_one_invoice_per_order
if sales_many_invoice_per_order:
invoices |= sales_many_invoice_per_order._create_invoices(grouped=False)
for invoice in invoices:
invoice.with_delay()._validate_invoice()
return invoices or _("Nothing to invoice.")
def _get_sales_order_to_invoice(self):
return self.mapped("move_lines.sale_line_id.order_id").filtered(
lambda r: r._get_invoiceable_lines()
)
| 38.346939
| 1,879
|
346
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
invoicing_mode = fields.Selection(
selection_add=[("at_shipping", "At Shipping")],
ondelete={"at_shipping": "set default"},
)
| 26.615385
| 346
|
565
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Invoice Analytic Search",
"summary": "Search invoices by analytic account or by project manager",
"version": "15.0.1.0.0",
"author": "Project Expert Team, ForgeFlow, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"category": "Project Management",
"depends": ["analytic", "account"],
"data": ["views/account_move_view.xml"],
"installable": True,
}
| 37.666667
| 565
|
2,442
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
class TestAccountMove(TransactionCase):
def setUp(self):
super(TestAccountMove, self).setUp()
self.account_invoice = self.env["account.move"]
self.account_model = self.env["account.account"]
self.account_invoice_line = self.env["account.move.line"]
self.analytic_account = self.env["account.analytic.account"]
self.partner_2 = self.env.ref("base.res_partner_2").id
self.product_4 = self.env.ref("product.product_product_4").id
self.type_receivable = self.env.ref("account.data_account_type_receivable")
self.type_expenses = self.env.ref("account.data_account_type_expenses")
self.invoice_line_account = self.account_model.search(
[("user_type_id", "=", self.type_expenses.id)], limit=1
).id
self.analytic_account = self.analytic_account.create(
{"name": "Test Account", "code": "TA"}
)
self.invoice = self.account_invoice.create(
{
"partner_id": self.partner_2,
"move_type": "in_invoice",
}
)
self.account_invoice_line.create(
{
"product_id": self.product_4,
"quantity": 1.0,
"debit": 0.0,
"credit": 0.0,
"move_id": self.invoice.id,
"name": "product that cost 100",
"account_id": self.invoice_line_account,
"analytic_account_id": self.analytic_account.id,
}
)
self.account_invoice_line.create(
{
"product_id": self.product_4,
"quantity": 1.0,
"debit": 0.0,
"credit": 0.0,
"move_id": self.invoice.id,
"name": "product that cost 10",
"account_id": self.invoice_line_account,
"analytic_account_id": self.analytic_account.id,
}
)
def test_search_analytic_accounts(self):
self.invoice_search = self.account_invoice._search_analytic_accounts(
"ilike", "Test Account"
)
invoice_id = self.account_invoice.search(self.invoice_search)
self.assertEqual(invoice_id.invoice_line_ids, self.invoice.invoice_line_ids)
| 40.7
| 2,442
|
848
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = "account.move"
@api.depends("invoice_line_ids.analytic_account_id")
def _compute_analytic_accounts(self):
for invoice in self:
invoice.analytic_account_ids = invoice.mapped(
"invoice_line_ids.analytic_account_id.id"
)
def _search_analytic_accounts(self, operator, value):
return [("invoice_line_ids.analytic_account_id", operator, value)]
analytic_account_ids = fields.Many2many(
comodel_name="account.analytic.account",
compute="_compute_analytic_accounts",
search="_search_analytic_accounts",
string="Analytic Account",
readonly=True,
)
| 32.615385
| 848
|
587
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Invoice Check Total",
"summary": """
Check if the verification total is equal to the bill's total""",
"version": "15.0.1.0.0",
"website": "https://github.com/OCA/account-invoicing",
"author": "Acsone SA/NV, Odoo Community Association (OCA)",
"license": "AGPL-3",
"depends": ["account"],
"data": [
"security/account_invoice_security.xml",
"views/res_config_settings.xml",
"views/account_invoice.xml",
],
}
| 32.611111
| 587
|
1,365
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.exceptions import ValidationError
from odoo.tests import Form, TransactionCase
from ..models.account_move import GROUP_AICT
class TestAccountInvoice(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.account_move = cls.env["account.move"]
# Add current user to group: group_supplier_inv_check_total
cls.env.ref(GROUP_AICT).write({"users": [(4, cls.env.user.id)]})
# create a vendor bill
invoice_form = Form(
cls.account_move.with_context(default_move_type="in_invoice")
)
invoice_form.partner_id = cls.env["res.partner"].create(
{"name": "test partner"}
)
invoice_form.check_total = 1.19
with invoice_form.invoice_line_ids.new() as line_form:
line_form.name = "Test invoice line"
line_form.price_unit = 2.99
line_form.tax_ids.clear()
cls.invoice = invoice_form.save()
def test_post(self):
# wrong check_total rise a ValidationError
self.assertEqual(self.invoice.check_total, 1.19)
self.assertEqual(self.invoice.check_total_display_difference, -1.80)
with self.assertRaises(ValidationError):
self.invoice.action_post()
| 37.916667
| 1,365
|
2,363
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_compare, float_round
GROUP_AICT = "account_invoice_check_total.group_supplier_inv_check_total"
class AccountMove(models.Model):
_inherit = "account.move"
check_total = fields.Monetary(
string="Verification Total",
readonly=True,
states={"draft": [("readonly", False)]},
copy=False,
)
check_total_display_difference = fields.Monetary(
string="Total Difference", compute="_compute_total_display_difference"
)
@api.depends("check_total", "amount_total")
def _compute_total_display_difference(self):
for invoice in self:
invoice.check_total_display_difference = float_round(
invoice.check_total - invoice.amount_total,
precision_rounding=invoice.currency_id.rounding,
)
def action_post(self):
for inv in self:
if (
self.env.user.has_group(GROUP_AICT)
and inv.move_type in ("in_invoice", "in_refund")
and float_compare(
inv.check_total,
inv.amount_total,
precision_rounding=inv.currency_id.rounding,
)
!= 0
):
raise ValidationError(
_(
"Please verify the price of the invoice!\n"
"The total amount (%(amount_total)s) does not match "
"the Verification Total amount (%(check_total)s)!\n"
"There is a difference of %(diff)s"
)
% {
"amount_total": inv.amount_total,
"check_total": inv.check_total,
"diff": inv.check_total_display_difference,
}
)
return super().action_post()
@api.model
def _reverse_move_vals(self, default_values, cancel=True):
vals = super()._reverse_move_vals(default_values, cancel)
if self.move_type in ["in_invoice", "in_refund"]:
vals["check_total"] = self.check_total
return vals
| 36.921875
| 2,363
|
396
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
from ..models.account_move import GROUP_AICT
class AccountConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
group_supplier_inv_check_total = fields.Boolean(
string="Check Total on Vendor Bills", implied_group=GROUP_AICT
)
| 26.4
| 396
|
879
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Account Invoice Refund Reason",
"version": "15.0.1.0.3",
"summary": "Account Invoice Refund Reason.",
"category": "Accounting",
"author": "Open Source Integrators, "
"Serpent CS, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"data": [
"security/ir.model.access.csv",
"data/account.move.refund.reason.csv",
"views/account_move_view.xml",
"views/account_move_refund_reason_view.xml",
"wizard/account_move_reversal_view.xml",
],
"depends": ["account"],
"license": "AGPL-3",
"development_status": "Beta",
"maintainers": ["max3903"],
"installable": True,
}
| 33.807692
| 879
|
3,351
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import datetime
from odoo.tests.common import TransactionCase
class TestAccountInvoiceRefundReason(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.account_move_obj = cls.env["account.move"]
cls.account_obj = cls.env["account.account"]
cls.journal_obj = cls.env["account.journal"]
cls.invoice_refund_obj = cls.env["account.move.reversal"]
cls.reason_obj = cls.env["account.move.refund.reason"]
cls.payment_term = cls.env.ref("account.account_payment_term_advance")
cls.partner3 = cls.env.ref("base.res_partner_3")
cls.account_user_type = cls.env.ref("account.data_account_type_receivable")
cls.product_id = cls.env.ref("product.product_product_5")
cls.account_revenue = cls.env.ref("account.data_account_type_revenue")
cls.journal = cls.journal_obj.search([("type", "=", "sale")])
if cls.journal:
cls.journal = cls.journal[0]
cls.account_id = cls.account_obj.search(
[("user_type_id", "=", cls.account_revenue.id)], limit=1
)
cls.reason_id = cls.env["account.move.refund.reason"].create(
{"name": "Cancellation"}
)
cls.account_rec1_id = cls.account_obj.create(
dict(
code="cust_acc",
name="customer account",
user_type_id=cls.account_user_type.id,
reconcile=True,
)
)
invoice_line_data = [
(
0,
0,
{
"product_id": cls.product_id.id,
"quantity": 10.0,
"account_id": cls.account_id.id,
"name": "product test 5",
"price_unit": 100.00,
},
)
]
cls.account_invoice_customer0 = cls.account_move_obj.create(
dict(
name="Test Customer Invoice",
move_type="out_invoice",
invoice_payment_term_id=cls.payment_term.id,
journal_id=cls.journal.id,
partner_id=cls.partner3.id,
invoice_line_ids=invoice_line_data,
)
)
def test_onchange_reason_id(self):
self.account_invoice_customer0.action_post()
self.account_invoice_refund_0 = self.invoice_refund_obj.with_context(
active_model="account.move", active_ids=self.account_invoice_customer0.ids
).create(
dict(
refund_method="refund",
date=datetime.date.today(),
reason_id=self.reason_id.id,
journal_id=self.account_invoice_customer0.journal_id.id,
)
)
self.account_invoice_refund_0._onchange_reason_id()
self.assertEqual(
self.account_invoice_refund_0.reason,
self.account_invoice_refund_0.reason_id.name,
)
self.account_invoice_refund_0.reverse_moves()
reversal_move = self.account_invoice_customer0.reversal_move_id
self.assertEqual(reversal_move.reason_id.id, self.reason_id.id)
| 38.079545
| 3,351
|
696
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class AccountMoveReversal(models.TransientModel):
_inherit = "account.move.reversal"
reason_id = fields.Many2one("account.move.refund.reason", string="Refund Reason")
@api.onchange("reason_id")
def _onchange_reason_id(self):
if self.reason_id:
self.reason = self.reason_id.name
def reverse_moves(self):
res = super().reverse_moves()
self.move_ids.mapped("reversal_move_id").write({"reason_id": self.reason_id})
return res
| 34.8
| 696
|
381
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountMove(models.Model):
_inherit = "account.move"
reason_id = fields.Many2one(
"account.move.refund.reason", string="Refund Reason", readonly=True
)
| 31.75
| 381
|
465
|
py
|
PYTHON
|
15.0
|
# Copyright (C) 2019 Open Source Integrators
# Copyright (C) 2019 Serpent Consulting Services Pvt. Ltd.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class AccountMoveRefundReason(models.Model):
_name = "account.move.refund.reason"
_description = "Account Move Refund Reason"
name = fields.Char(required=True, translate=True)
active = fields.Boolean(default=True)
description = fields.Char()
| 35.769231
| 465
|
731
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sales order invoicing grouping criteria",
"version": "15.0.1.0.2",
"category": "Sales Management",
"license": "AGPL-3",
"author": "Tecnativa, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"depends": ["sale_management"],
"data": [
"security/ir.model.access.csv",
"views/res_config_settings_views.xml",
"views/res_partner_views.xml",
"views/sale_invoicing_grouping_criteria_views.xml",
],
"installable": True,
"development_status": "Production/Stable",
"maintainers": ["pedrobaeza"],
}
| 34.809524
| 731
|
4,697
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import TransactionCase
class TestSaleOrderInvoicingGroupingCriteria(TransactionCase):
def setUp(self):
super().setUp()
self.env = self.env(context=dict(self.env.context, tracking_disable=True))
self.partner = self.env["res.partner"].create({"name": "Test partner"})
self.partner2 = self.env["res.partner"].create({"name": "Other partner"})
self.product = self.env["product.product"].create(
{"name": "Test product", "type": "service", "invoice_policy": "order"}
)
self.GroupingCriteria = self.env["sale.invoicing.grouping.criteria"]
self.grouping_criteria = self.GroupingCriteria.create(
{
"name": "Delivery Address",
"field_ids": [
(4, self.env.ref("sale.field_sale_order__partner_shipping_id").id)
],
}
)
self.order = self.env["sale.order"].create(
{
"partner_id": self.partner.id,
"partner_shipping_id": self.partner.id,
"partner_invoice_id": self.partner.id,
"pricelist_id": self.partner.property_product_pricelist.id,
"order_line": [
(
0,
0,
{
"name": self.product.name,
"product_id": self.product.id,
"price_unit": 20,
"product_uom_qty": 1,
"product_uom": self.product.uom_id.id,
},
)
],
}
)
self.order.action_confirm()
self.order2 = self.order.copy()
self.order2.action_confirm()
def test_invoicing_same_data(self):
invoice_ids = (self.order + self.order2)._create_invoices()
self.assertEqual(len(invoice_ids), 1)
self.assertEqual(self.order.invoice_ids, self.order2.invoice_ids)
def test_invoicing_grouping_default(self):
self.order2.partner_invoice_id = self.partner2.id
invoice_ids = (self.order + self.order2)._create_invoices()
self.assertEqual(len(invoice_ids), 2)
self.assertNotEqual(self.order.invoice_ids, self.order2.invoice_ids)
def test_invoicing_grouping_company_criteria(self):
self.order2.partner_shipping_id = self.partner2.id
self.order.company_id.default_sale_invoicing_grouping_criteria_id = (
self.grouping_criteria.id
)
invoice_ids = (self.order + self.order2)._create_invoices()
self.assertEqual(len(invoice_ids), 2)
self.assertNotEqual(self.order.invoice_ids, self.order2.invoice_ids)
def test_invoicing_grouping_partner_criteria(self):
self.order2.partner_shipping_id = self.partner2.id
self.partner.sale_invoicing_grouping_criteria_id = self.grouping_criteria.id
invoice_ids = (self.order + self.order2)._create_invoices()
self.assertEqual(len(invoice_ids), 2)
self.assertNotEqual(self.order.invoice_ids, self.order2.invoice_ids)
def test_invoicing_grouping_partner_criteria_as_demo(self):
self.order2.partner_shipping_id = self.partner2.id
self.partner.sale_invoicing_grouping_criteria_id = self.grouping_criteria.id
user_demo = self.env.ref("base.user_demo")
user_demo.groups_id = [
(4, self.env.ref("sales_team.group_sale_salesman_all_leads").id)
]
invoice_ids = (self.order + self.order2).with_user(user_demo)._create_invoices()
self.assertEqual(len(invoice_ids), 2)
self.assertNotEqual(self.order.invoice_ids, self.order2.invoice_ids)
def test_invoicing_grouping_specific_order_field(self):
"""Regression test for checking values in order, not in invoices vals."""
self.partner.sale_invoicing_grouping_criteria_id = self.grouping_criteria.id
self.grouping_criteria["field_ids"] = [
(4, self.env.ref("sale.field_sale_order__id").id)
]
invoices = (self.order + self.order2)._create_invoices()
self.assertEqual(len(invoices), 2)
def test_commercial_field(self):
self.partner.sale_invoicing_grouping_criteria_id = self.grouping_criteria.id
children = self.env["res.partner"].create(
{"name": "Test children", "parent_id": self.partner.id}
)
self.assertEqual(
children.sale_invoicing_grouping_criteria_id, self.grouping_criteria
)
| 45.163462
| 4,697
|
630
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class SaleInvoicingGroupingCriteria(models.Model):
_name = "sale.invoicing.grouping.criteria"
_description = "Sales Invoicing Grouping Criteria"
name = fields.Char()
field_ids = fields.Many2many(
string="Grouping Fields",
comodel_name="ir.model.fields",
domain="[('model', '=', 'sale.order')]",
help="Fields used for grouping sales orders when invoicing. "
"Invoicing address, company and currency will always be applied.",
)
| 35
| 630
|
1,808
|
py
|
PYTHON
|
15.0
|
# Copyright 2019-2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def _get_grouping_partner(self):
"""
Get the partner who contains the grouping criteria.
On sale.order, the default should be the invoice address.
If not set, use the partner_id.
:return: res.partner recordset
"""
self.ensure_one()
return self.partner_invoice_id or self.partner_id
def _get_sale_invoicing_group_key(self):
"""Prepare extended grouping criteria for sales orders."""
self.ensure_one()
group_key = [
self.company_id.id,
self.partner_invoice_id.id,
self.currency_id.id,
]
partner = self._get_grouping_partner()
criteria = (
partner.sale_invoicing_grouping_criteria_id
or self.company_id.default_sale_invoicing_grouping_criteria_id
)
for field in criteria.field_ids.sudo():
group_key.append(self[field.name])
return tuple(group_key)
def _create_invoices(self, grouped=False, final=False, date=None):
"""Slice the batch according grouping criteria."""
order_groups = {}
for order in self:
group_key = order._get_sale_invoicing_group_key()
if group_key not in order_groups:
order_groups[group_key] = order
else:
order_groups[group_key] += order
moves = self.env["account.move"]
for group in order_groups.values():
moves += super(SaleOrder, group)._create_invoices(
grouped=grouped, final=final, date=date
)
return moves
| 35.45098
| 1,808
|
395
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
default_sale_invoicing_grouping_criteria_id = fields.Many2one(
string="Default Sales Invoicing Grouping Criteria",
comodel_name="sale.invoicing.grouping.criteria",
)
| 30.384615
| 395
|
395
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# 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"
res_default_sale_invoicing_grouping_criteria_id = fields.Many2one(
related="company_id.default_sale_invoicing_grouping_criteria_id", readonly=False
)
| 32.916667
| 395
|
707
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
sale_invoicing_grouping_criteria_id = fields.Many2one(
string="Sales Invoicing Grouping Criteria",
comodel_name="sale.invoicing.grouping.criteria",
help="If empty, company default (if any) or default will be applied.",
)
@api.model
def _commercial_fields(self):
"""Add this field to commercial fields, as it should be propagated
to children.
"""
return super()._commercial_fields() + ["sale_invoicing_grouping_criteria_id"]
| 33.666667
| 707
|
562
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Partner Invoicing Mode",
"version": "15.0.1.0.0",
"summary": "Base module for handling multiple partner invoicing mode",
"author": "Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/account-invoicing",
"license": "AGPL-3",
"category": "Accounting & Finance",
"depends": ["account", "queue_job", "sale"],
"data": [
"data/queue_job_data.xml",
"views/res_partner.xml",
],
}
| 35.125
| 562
|
277
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class SaleOrder(models.Model):
_inherit = "sale.order"
invoicing_mode = fields.Selection(related="partner_invoice_id.invoicing_mode")
| 27.7
| 277
|
1,102
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from odoo import _, models
class QueueJob(models.Model):
_inherit = "queue.job"
def related_action_open_invoice(self):
"""Open a form view with the invoice related to the job."""
self.ensure_one()
model_name = self.model_name
records = self.env[model_name].browse(self.record_ids).exists()
if not records:
return None
action = {
"name": _("Related Record"),
"type": "ir.actions.act_window",
"view_type": "form",
"view_mode": "form",
"res_model": records._name,
}
if len(records) == 1:
action["res_id"] = records.id
else:
action.update(
{
"name": _("Related Records"),
"view_mode": "tree,form",
"view_id": "account.view_invoice_tree",
"domain": [("id", "in", records.ids)],
}
)
return action
| 31.485714
| 1,102
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.