diff --git a/sale_certification/README.rst b/sale_certification/README.rst new file mode 100644 index 0000000..f155ea5 --- /dev/null +++ b/sale_certification/README.rst @@ -0,0 +1,152 @@ +================== +Sale Certification +================== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:1f049980e201d8e8c96e1b79387c1549f0ac6b3063da07f282d020d5c6fd6702 + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png + :target: https://odoo-community.org/page/development-status + :alt: Beta +.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fvertical--construction-lightgray.png?logo=github + :target: https://github.com/OCA/vertical-construction/tree/17.0/sale_certification + :alt: OCA/vertical-construction +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/vertical-construction-17-0/vertical-construction-17-0-sale_certification + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/vertical-construction&target_branch=17.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module introduces a certification workflow between sales orders and +invoicing, commonly used in construction and large-scale contracting +industries. + +Instead of invoicing directly from sales orders, this module allows the +creation of **certifications** that represent approved progress or +partial completion. These certifications can then generate invoices, +optionally applying **retention amounts** (withholding a percentage of +the payment until final project acceptance). + +Key Features: + +- Add a certification step between sales and invoicing. +- Generate invoices based on certified quantities. +- Support for configurable retention percentages per certification. +- Tracks invoiced vs. certified amounts for better financial oversight + at sale level. + +**Table of contents** + +.. contents:: + :local: + +Usage +===== + +1. **Create a Sales Order** as usual with your products or services. + +2. Enable the **Certifiable?** checkbox on the Sales Order. + +3. Confirm the Sales Order. + +4. Once confirmed: + + - A **Certified Percentage** will be displayed at the Sales Order + level. + - A **Quantity Certified** field will appear at the line level. + +5. Based on the invoice policy of your products, the same logic will + apply to the certification process. A new **Certification** button + will appear in the header. + +6. Creating a new Certification offers three options: + + - **Regular** – Automatically includes all available lines based on + the invoice policy. + - **Percentage** – Applies a percentage to the amounts from the + regular option (not the total sale). + - **Chapter** – Allows selection of specific sections (sale order + lines within sections) to include in the certification. + +7. After creating a certification, you can freely adjust quantities or + remove lines. These changes will be reflected in the Sales Order, + following the same logic as invoices. + +8. When you confirm the certification, the confirmation date will be + set. + +9. Click **Create Invoice**. If you select **Apply Retention Monies**, + you will have two retention options: + + - **Percentage** of the certified base amount. + - **Fixed Value** over the certified base amount. + + This will: + + - Create a negative line in the invoice subtracting the retention + amount. + - Generate a separate invoice to hold the retention amount (if no + draft retention invoice already exists), accessible from the Sales + Order view. + +10. You can set a payment method or reminders on the retention invoice + to charge the client later or cancel the invoice if necessary. + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* Binhex + +Contributors +------------ + +- Christian Ramos + +Maintainers +----------- + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +.. |maintainer-Christian-RB| image:: https://github.com/Christian-RB.png?size=40px + :target: https://github.com/Christian-RB + :alt: Christian-RB + +Current `maintainer `__: + +|maintainer-Christian-RB| + +This module is part of the `OCA/vertical-construction `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/sale_certification/__init__.py b/sale_certification/__init__.py new file mode 100644 index 0000000..6e88ee1 --- /dev/null +++ b/sale_certification/__init__.py @@ -0,0 +1,4 @@ +from . import models +from . import security +from . import views +from . import wizard diff --git a/sale_certification/__manifest__.py b/sale_certification/__manifest__.py new file mode 100644 index 0000000..b374033 --- /dev/null +++ b/sale_certification/__manifest__.py @@ -0,0 +1,35 @@ +{ + "name": "Sale Certification", + "summary": ( + "This module allows to certificate sales orders " "in a construction context" + ), + "version": "17.0.1.0.0", + "license": "AGPL-3", + "author": "Binhex,Odoo Community Association (OCA)", + "website": "https://github.com/OCA/vertical-construction", + "category": "Sales", + "depends": [ + "sale", + ], + "maintainers": ["Christian-RB"], + "data": [ + "security/ir.model.access.csv", + "security/ir_rules.xml", + "wizard/certification_invoice_wizard_view.xml", + "wizard/certification_wizard_view.xml", + "views/view_order_certifications.xml", + "views/view_order_form_certify.xml", + "views/order_certifications_menu.xml", + "views/account_views.xml", + "report/certification_reports.xml", + "report/certification_templates.xml", + ], + "assets": { + "web.report_assets_common": [ + "sale_certification/static/src/css/report_certification.css", + ], + "web.report_assets_pdf": [ + "sale_certification/static/src/css/report_certification.css", + ], + }, +} diff --git a/sale_certification/models/__init__.py b/sale_certification/models/__init__.py new file mode 100644 index 0000000..b7885e9 --- /dev/null +++ b/sale_certification/models/__init__.py @@ -0,0 +1,6 @@ +from . import account_move +from . import account_move_line +from . import order_certification +from . import certification_line +from . import sale_order +from . import sale_order_line diff --git a/sale_certification/models/account_move.py b/sale_certification/models/account_move.py new file mode 100644 index 0000000..8ef727e --- /dev/null +++ b/sale_certification/models/account_move.py @@ -0,0 +1,41 @@ +from odoo import fields, models + + +class AccountMove(models.Model): + _inherit = "account.move" + + certification_count = fields.Integer( + compute="_compute_origin_certification_count", + ) + retention_invoice = fields.Boolean( + help="Indicates if this invoice is a retention invoice.", + ) + + def _compute_origin_certification_count(self): + for move in self: + move.certification_count = len( + move.line_ids.certification_line_ids.certification_id + ) + + def action_view_source_certifications(self): + self.ensure_one() + certification_lines = self.line_ids.certification_line_ids + source_certifications = certification_lines.certification_id + result = self.env["ir.actions.act_window"]._for_xml_id( + "sale_certification.order_certification_action" + ) + if len(source_certifications) > 1: + result["domain"] = [("id", "in", source_certifications.ids)] + elif len(source_certifications) == 1: + result["views"] = [ + ( + self.env.ref( + "sale_certification.view_order_certifications_form", False + ).id, + "form", + ) + ] + result["res_id"] = source_certifications.id + else: + result = {"type": "ir.actions.act_window_close"} + return result diff --git a/sale_certification/models/account_move_line.py b/sale_certification/models/account_move_line.py new file mode 100644 index 0000000..c5eb5d1 --- /dev/null +++ b/sale_certification/models/account_move_line.py @@ -0,0 +1,56 @@ +from odoo import fields, models + + +class AccountMoveLine(models.Model): + _inherit = "account.move.line" + + certification_line_ids = fields.Many2many( + "certification.line", + "certification_line_invoice_rel", + "invoice_line_id", + "certification_line_id", + string="Certification Lines", + readonly=True, + copy=False, + ) + retention_invoice_line = fields.Many2one( + comodel_name="account.move.line", + help="The retention invoice line related to this line.", + copy=False, + ondelete="restrict", + ) + + def find_retention_invoice(self, certification): + retention_invoice = certification.mapped( + "order_id.invoice_ids.invoice_line_ids.retention_invoice_line.move_id" + ).filtered(lambda move: move.state == "draft" and move.retention_invoice) + if retention_invoice: + return retention_invoice[0] + return False + + def create_retention_invoice_line(self, certification): + self.ensure_one() + move_id = self.find_retention_invoice(certification) + if not move_id: + move_id = self.env["account.move"].create( + { + "move_type": "out_invoice", + "partner_id": self.move_id.partner_id.id, + "date": fields.Date.context_today(self), + "retention_invoice": True, + } + ) + retention_vals = { + "display_type": "product", + "name": self.name, + "quantity": 1.0, + "move_id": move_id.id, + "price_unit": -1 * self.price_subtotal, + "balance": -1 * self.price_subtotal, + "retention_invoice_line": self.id, + "currency_id": move_id.currency_id.id, + } + self.retention_invoice_line = self.env["account.move.line"].create( + retention_vals + ) + return move_id diff --git a/sale_certification/models/certification_line.py b/sale_certification/models/certification_line.py new file mode 100644 index 0000000..c04efb4 --- /dev/null +++ b/sale_certification/models/certification_line.py @@ -0,0 +1,157 @@ +from odoo import api, fields, models +from odoo.tools import float_compare, float_is_zero + + +class CertificationLine(models.Model): + _name = "certification.line" + _description = "Certification Line" + _order = "sequence, id" + + certification_id = fields.Many2one( + "order.certification", + string="Certification", + required=True, + ondelete="cascade", + ) + sale_line_ids = fields.Many2many( + "sale.order.line", + "sale_order_line_certif_line_rel", + "certification_line_id", + "order_line_id", + string="Sales Order Lines", + readonly=True, + copy=False, + ) + invoice_lines = fields.Many2many( + comodel_name="account.move.line", + relation="certification_line_invoice_rel", + column1="certification_line_id", + column2="invoice_line_id", + copy=False, + ) + invoice_status = fields.Selection( + selection=[ + ("invoiced", "Fully Invoiced"), + ("to invoice", "To Invoice"), + ("no", "Nothing to Invoice"), + ], + compute="_compute_invoice_status", + store=True, + ) + sequence = fields.Integer() + product_id = fields.Many2one( + comodel_name="product.product", + string="Product", + ondelete="restrict", + check_company=True, + ) + name = fields.Text( + string="Description", + ) + quantity = fields.Float( + digits="Product Unit of Measure", + ) + qty_to_invoice = fields.Float( + string="Quantity To Invoice", + compute="_compute_qty_to_invoice", + digits="Product Unit of Measure", + store=True, + ) + qty_invoiced = fields.Float( + string="Invoiced Quantity", + compute="_compute_qty_invoiced", + digits="Product Unit of Measure", + store=True, + ) + product_uom_id = fields.Many2one( + comodel_name="uom.uom", + string="Unit of Measure", + compute="_compute_product_uom_id", + store=True, + readonly=False, + precompute=True, + ondelete="restrict", + ) + display_type = fields.Selection( + selection=[ + ("line_section", "Section"), + ("line_note", "Note"), + ], + default=False, + ) + company_id = fields.Many2one( + related="certification_id.company_id", + store=True, + readonly=True, + precompute=True, + index=True, + ) + state = fields.Selection( + related="certification_id.state", + string="Certification Status", + copy=False, + store=True, + precompute=True, + ) + + @api.depends("product_id") + def _compute_product_uom_id(self): + for line in self: + line.product_uom_id = line.product_id.uom_id + + @api.depends("quantity", "sale_line_ids.product_uom_qty") + def _compute_relative_percentage(self): + for rec in self: + total_qty = sum(rec.sale_line_ids.mapped("product_uom_qty")) + + if total_qty: + rec.relative_percentage = (self.quantity / total_qty) * 100 + else: + rec.relative_percentage = 0.0 + + @api.depends("invoice_lines.move_id.state", "invoice_lines.quantity") + def _compute_qty_invoiced(self): + for line in self: + qty_invoiced = 0.0 + for invoice_line in line.invoice_lines: + if ( + invoice_line.move_id.state != "cancel" + or invoice_line.move_id.payment_state == "invoicing_legacy" + ): + if invoice_line.move_id.move_type == "out_invoice": + qty_invoiced += invoice_line.product_uom_id._compute_quantity( + invoice_line.quantity, line.product_uom_id + ) + elif invoice_line.move_id.move_type == "out_refund": + qty_invoiced -= invoice_line.product_uom_id._compute_quantity( + invoice_line.quantity, line.product_uom_id + ) + line.qty_invoiced = qty_invoiced + + @api.depends("state", "quantity", "qty_to_invoice", "qty_invoiced") + def _compute_invoice_status(self): + precision = self.env["decimal.precision"].precision_get( + "Product Unit of Measure" + ) + for line in self: + if line.state != "confirmed": + line.invoice_status = "no" + elif not float_is_zero(line.qty_to_invoice, precision_digits=precision): + line.invoice_status = "to invoice" + elif ( + float_compare( + line.qty_invoiced, line.quantity, precision_digits=precision + ) + >= 0 + ): + line.invoice_status = "invoiced" + else: + line.invoice_status = "no" + + @api.depends("qty_invoiced", "quantity", "state") + def _compute_qty_to_invoice(self): + for line in self: + if line.state == "confirmed" and not line.display_type: + line.qty_to_invoice = line.quantity - line.qty_invoiced + else: + line.qty_to_invoice = 0 diff --git a/sale_certification/models/order_certification.py b/sale_certification/models/order_certification.py new file mode 100644 index 0000000..6f894a7 --- /dev/null +++ b/sale_certification/models/order_certification.py @@ -0,0 +1,151 @@ +from odoo import api, fields, models + +INVOICE_STATUS = [ + ("invoiced", "Fully Invoiced"), + ("to invoice", "To Invoice"), + ("no", "Nothing to Invoice"), +] + + +class OrderCertification(models.Model): + _name = "order.certification" + _inherit = ["mail.thread", "mail.activity.mixin"] + _description = "Base model to define a certification" + _order = "id desc" + + order_id = fields.Many2one( + "sale.order", string="Sale Order", required=True, ondelete="cascade" + ) + name = fields.Char( + string="Certification", + required=True, + copy=False, + default=lambda self: self.env["ir.sequence"].next_by_code("order.certification") + or "New", + ) + certification_line_ids = fields.One2many( + "certification.line", "certification_id", string="Lines" + ) + chapter_cert_ids = fields.Many2many("sale.order.line", string="Certified Chapters") + certification_date = fields.Datetime(string="Date", default=fields.Datetime.now) + state = fields.Selection( + selection=[ + ("draft", "Draft"), + ("confirmed", "Confirmed"), + ("cancel", "Cancelled"), + ], + default="draft", + required=True, + ) + company_id = fields.Many2one( + comodel_name="res.company", + required=True, + index=True, + default=lambda self: self.env.company, + ) + invoice_status = fields.Selection( + selection=INVOICE_STATUS, + compute="_compute_invoice_status", + store=True, + ) + invoice_count = fields.Integer(compute="_compute_get_invoiced") + invoice_ids = fields.Many2many( + comodel_name="account.move", + string="Invoices", + compute="_compute_get_invoiced", + copy=False, + ) + + @api.depends("certification_line_ids.invoice_lines") + def _compute_get_invoiced(self): + for cert in self: + invoice_lines = cert.certification_line_ids.invoice_lines + invoices = invoice_lines.move_id.filtered( + lambda r: r.move_type in ("out_invoice", "out_refund") + ) + cert.invoice_ids = invoices + cert.invoice_count = len(invoices) + + def button_confirm(self): + self.state = "confirmed" + self.certification_date = fields.Datetime.now(self) + + def button_cancel(self): + self.state = "cancel" + + def button_back2draft(self): + self.state = "draft" + + @api.depends("state", "certification_line_ids.invoice_status") + def _compute_invoice_status(self): + confirmed_certifications = self.filtered(lambda cert: cert.state == "confirmed") + (self - confirmed_certifications).invoice_status = "no" + if not confirmed_certifications: + return + lines_domain = [("display_type", "=", False)] + line_invoice_status_all = [ + (certification.id, invoice_status) + for certification, invoice_status in self.env[ + "certification.line" + ]._read_group( + lines_domain + + [("certification_id", "in", confirmed_certifications.ids)], + ["certification_id", "invoice_status"], + ) + ] + for certification in confirmed_certifications: + line_invoice_status = [ + d[1] for d in line_invoice_status_all if d[0] == certification.id + ] + if certification.state != "confirmed": + certification.invoice_status = "no" + elif any( + invoice_status == "to invoice" for invoice_status in line_invoice_status + ): + certification.invoice_status = "to invoice" + elif line_invoice_status and all( + invoice_status == "invoiced" for invoice_status in line_invoice_status + ): + certification.invoice_status = "invoiced" + else: + certification.invoice_status = "no" + + def create_invoice(self, retention=False, retention_value=0.0): + invoices = self.env["account.move"] + for certification in self.filtered( + lambda cert: cert.state == "confirmed" + and cert.invoice_status == "to invoice" + ): + for order in certification.certification_line_ids.mapped( + "sale_line_ids.order_id" + ): + invoices |= order.with_context( + certification=certification, + retention=retention, + retention_value=retention_value, + )._create_invoices() + return self.env["sale.order"].action_view_invoice(invoices=invoices) + + def action_view_invoice(self, invoices=False): + if not invoices: + invoices = self.mapped("invoice_ids") + action = self.env["ir.actions.actions"]._for_xml_id( + "account.action_move_out_invoice_type" + ) + if len(invoices) > 1: + action["domain"] = [("id", "in", invoices.ids)] + elif len(invoices) == 1: + form_view = [(self.env.ref("account.view_move_form").id, "form")] + if "views" in action: + action["views"] = form_view + [ + (state, view) for state, view in action["views"] if view != "form" + ] + else: + action["views"] = form_view + action["res_id"] = invoices.id + else: + action = {"type": "ir.actions.act_window_close"} + action["context"] = { + "default_move_type": "out_invoice", + } + return action diff --git a/sale_certification/models/sale_order.py b/sale_certification/models/sale_order.py new file mode 100644 index 0000000..6ef6446 --- /dev/null +++ b/sale_certification/models/sale_order.py @@ -0,0 +1,218 @@ +from odoo import _, fields, models +from odoo.exceptions import UserError +from odoo.fields import Command +from odoo.tools import float_is_zero + + +class SaleOrder(models.Model): + _inherit = "sale.order" + + certification_ids = fields.One2many( + "order.certification", "order_id", string="Certifications" + ) + is_certifiable = fields.Boolean( + string="Certifiable?", + default=False, + help="Check if the order is in a state that allows to create certifications", + ) + certification_count = fields.Integer( + compute="_compute_certification_count", + ) + certified_percentage = fields.Float( + string="Certified Quantities", + compute="_compute_certified_percentage", + digits=(16, 2), + ) + retention_invoice_count = fields.Integer( + string="Invoice Count", compute="_compute_retention_invoices_count" + ) + + def _compute_certification_count(self): + for order in self: + order.certification_count = len( + order.certification_ids.filtered(lambda cert: cert.state != "cancel") + ) + + def _compute_certified_percentage(self): + for order in self: + total_qty = sum(order.order_line.mapped("product_uom_qty")) + certified_qty = sum(order.order_line.mapped("qty_certified")) + if total_qty: + order.certified_percentage = max( + (certified_qty / total_qty) * 100.0, 0.0 + ) + else: + order.certified_percentage = 0.0 + + def open_certify_wizard(self): + self.ensure_one() + return { + "name": "Certify Order", + "type": "ir.actions.act_window", + "res_model": "certification.wizard", + "view_mode": "form", + "target": "new", + "context": {"default_order_id": self.id}, + } + + def action_view_certifications(self, certifications=False): + if not certifications: + certifications = self.mapped("certification_ids") + + action = self.env["ir.actions.actions"]._for_xml_id( + "sale_certification.order_certification_action" + ) + if len(certifications) > 1: + action["domain"] = [("id", "in", certifications.ids)] + elif len(certifications) == 1: + form_view = [ + ( + self.env.ref( + "sale_certification.view_order_certifications_form" + ).id, + "form", + ) + ] + if "views" in action: + action["views"] = form_view + [ + (state, view) for state, view in action["views"] if view != "form" + ] + else: + action["views"] = form_view + action["res_id"] = certifications.id + else: + action = {"type": "ir.actions.act_window_close"} + + return action + + def create_certifications(self, mode="regular", options=None): + certification_vals_list = [] + certification_item_sequence = 1 + for order in self: + order = order.with_company(order.company_id) + + certification_vals = order._prepare_certification(mode, options) + certificable_lines = order._get_certificable_lines(mode, options) + + if not any(not line.display_type for line in certificable_lines): + continue + + certification_line_vals = [] + for line in certificable_lines: + certification_line_vals.append( + Command.create( + line._prepare_certification_line( + mode, options, certification_item_sequence + ) + ), + ) + certification_item_sequence += 1 + + certification_vals["certification_line_ids"] += certification_line_vals + certification_vals_list.append(certification_vals) + if not certification_vals_list: + raise UserError( + _( + "Cannot create a certification." + " No items are available to certify.\n\n" + ) + ) + + return self._create_certifications(certification_vals_list) + + def _create_certifications(self, certification_vals_list): + return self.env["order.certification"].sudo().create(certification_vals_list) + + def _prepare_certification(self, mode, options): + self.ensure_one() + + values = { + "order_id": self.id, + "company_id": self.company_id.id, + "certification_line_ids": [], + } + return values + + def _get_certificable_lines(self, mode, options): + """Return the certificable lines for order `self`.""" + certificable_line_ids = [] + pending_section = None + current_section = None + precision = self.env["decimal.precision"].precision_get( + "Product Unit of Measure" + ) + + for line in self.order_line: + if line.display_type == "line_section": + pending_section = current_section = line + continue + if line.display_type != "line_note" and float_is_zero( + line.qty_to_certify, precision_digits=precision + ): + continue + if line.qty_to_certify > 0 or line.display_type == "line_note": + if mode == "chapters" and ( + not current_section + or current_section.id not in options.get("chapter_ids", []) + ): + continue + if pending_section: + certificable_line_ids.append(pending_section.id) + pending_section = None + certificable_line_ids.append(line.id) + + return self.env["sale.order.line"].browse(certificable_line_ids) + + def _create_invoices(self, grouped=False, final=False, date=None): + moves = super()._create_invoices(grouped=grouped, final=final, date=date) + certification = self._context.get("certification", False) + retention = self._context.get("retention", False) + retention_value = self._context.get("retention_value", 0.0) + if certification and retention and retention_value: + for move in moves: + retention_line_vals = { + "name": _("Retention for Certification %s") % certification.name, + "quantity": 1.0, + "move_id": move.id, + "display_type": "product", + } + if retention == "percentage": + retention_line_vals["name"] += f" ({retention_value * 100:.2f}%)" + retention_line_vals["price_unit"] = ( + -1 * move.amount_untaxed_signed * retention_value + ) + elif retention == "value": + retention_line_vals["price_unit"] = -1 * retention_value + retention_move_line = self.env["account.move.line"].create( + retention_line_vals + ) + moves |= retention_move_line.create_retention_invoice_line( + certification + ) + return moves + + def _get_invoiceable_lines(self, final=False): + certification = self._context.get("certification", False) + if certification: + sale_order_lines = certification.certification_line_ids.filtered( + lambda cert_line: cert_line.invoice_status == "to invoice" + ).mapped("sale_line_ids") + else: + sale_order_lines = super()._get_invoiceable_lines(final) + return sale_order_lines.with_context(certification=certification) + + def _get_retention_invoices(self): + return self.mapped( + "invoice_ids.invoice_line_ids.retention_invoice_line.move_id" + ).filtered(lambda move: move.state != "cancel" and move.retention_invoice) + + def _compute_retention_invoices_count(self): + for order in self: + retention_invoices = order._get_retention_invoices() + order.retention_invoice_count = len(retention_invoices) + + def action_view_retention_invoices(self): + retention_invoices = self._get_retention_invoices() + if not retention_invoices: + raise UserError(_("No retention invoices found for this order.")) + return self.action_view_invoice(retention_invoices) diff --git a/sale_certification/models/sale_order_line.py b/sale_certification/models/sale_order_line.py new file mode 100644 index 0000000..0d393e5 --- /dev/null +++ b/sale_certification/models/sale_order_line.py @@ -0,0 +1,178 @@ +from odoo import api, fields, models +from odoo.fields import Command +from odoo.tools import float_compare, float_is_zero + + +class SaleOrderLine(models.Model): + _inherit = "sale.order.line" + + is_certified = fields.Boolean( + string="Is Certified?", + compute="_compute_is_certified", + store=True, + ) + section_id = fields.Many2one( + "sale.order.line", + string="Section", + domain=[("display_type", "=", "line_section")], + compute="_compute_section", + store=True, + help="Section or Chapter to which this line belongs.", + ) + certified_lines = fields.Many2many( + comodel_name="certification.line", + relation="sale_order_line_certif_line_rel", + column1="order_line_id", + column2="certification_line_id", + copy=False, + ) + qty_certified = fields.Float( + string="Certified Quantity", + compute="_compute_qty_certified", + digits="Product Unit of Measure", + store=True, + ) + qty_to_certify = fields.Float( + string="Quantity To Certify", + compute="_compute_qty_to_certify", + digits="Product Unit of Measure", + store=True, + ) + certifiable_quantity = fields.Float(compute="_compute_certifiable_quantity") + certified_status = fields.Selection( + selection=[ + ("certified", "Fully Certified"), + ("to certify", "To Certify"), + ("no", "Nothing to Certify"), + ], + string="Certify Status", + compute="_compute_certified_status", + store=True, + ) + + @api.depends("qty_certified", "qty_delivered", "product_uom_qty", "state") + def _compute_qty_to_certify(self): + for line in self: + if line.state == "sale" and not line.display_type: + if line.product_id.invoice_policy == "order": + line.qty_to_certify = line.product_uom_qty - line.qty_certified + else: + line.qty_to_certify = line.qty_delivered - line.qty_certified + else: + line.qty_to_certify = 0 + + @api.depends( + "state", "product_uom_qty", "qty_delivered", "qty_to_certify", "qty_certified" + ) + def _compute_certified_status(self): + precision = self.env["decimal.precision"].precision_get( + "Product Unit of Measure" + ) + for line in self: + if line.state != "sale": + line.certified_status = "no" + elif not float_is_zero(line.qty_to_certify, precision_digits=precision): + line.certified_status = "to certify" + elif ( + float_compare( + line.qty_invoiced, line.product_uom_qty, precision_digits=precision + ) + >= 0 + ): + line.certified_status = "certified" + else: + line.certified_status = "no" + + @api.depends("certified_lines.certification_id.state", "certified_lines.quantity") + def _compute_qty_certified(self): + for line in self: + qty_certified = 0.0 + + for certified_line in line.certified_lines: + if certified_line.certification_id.state != "cancel": + qty_certified += certified_line.product_uom_id._compute_quantity( + certified_line.quantity, line.product_uom + ) + + line.qty_certified = qty_certified + + @api.depends( + "order_id.order_line", + "order_id.order_line.sequence", + "order_id.order_line.display_type", + ) + def _compute_section(self): + for line in self: + if not line.order_id: + line.section_id = False + continue + + last_section = None + + for line2 in line.order_id.order_line.sorted(key=lambda r: r.sequence): + if line2.display_type == "line_section": + last_section = line2 + if line2.id == line.id: + break + + line.section_id = last_section.id if last_section else False + + @api.depends( + "product_uom_qty", "qty_delivered", "qty_certified", "product_id.invoice_policy" + ) + def _compute_certifiable_quantity(self): + for line in self: + if line.product_id.invoice_policy == "delivery": + line.certifiable_quantity = max( + line.qty_delivered - line.qty_certified, 0 + ) + else: + line.certifiable_quantity = max( + line.product_uom_qty - line.qty_certified, 0 + ) + + def _compute_is_certified(self): + CertificationLine = self.env["certification.line"] + for line in self: + line.is_certified = bool( + CertificationLine.search([("sale_line_ids", "in", [line.id])], limit=1) + ) + + def _prepare_certification_line(self, mode, options, sequence): + """Prepare the values to create the new certification line + for a sales order line. + + :param optional_values: any parameter that should be added to + the returned certification line + :rtype: dict + """ + self.ensure_one() + if mode in ["percentage", "chapters"]: + quantity = self.qty_to_certify * options.get("percentage", 1) + else: + quantity = self.qty_to_certify + res = { + "display_type": self.display_type or False, + "sequence": sequence or self.sequence, + "name": self.name, + "product_id": self.product_id.id, + "product_uom_id": self.product_uom.id, + "quantity": quantity, + "sale_line_ids": [Command.link(self.id)], + } + return res + + def _prepare_invoice_line(self, **optional_values): + res = super()._prepare_invoice_line(**optional_values) + certification = self._context.get("certification", False) + if certification: + certification_line_ids = certification.certification_line_ids.filtered( + lambda line, self=self: self.id in line.sale_line_ids.ids + ) + res["quantity"] = sum(certification_line_ids.mapped("qty_to_invoice")) + res["certification_line_ids"] = [ + Command.link(certification_line_id.id) + for certification_line_id in certification_line_ids + ] + + return res diff --git a/sale_certification/pyproject.toml b/sale_certification/pyproject.toml new file mode 100644 index 0000000..4231d0c --- /dev/null +++ b/sale_certification/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/sale_certification/readme/CONTRIBUTORS.md b/sale_certification/readme/CONTRIBUTORS.md new file mode 100644 index 0000000..93d124c --- /dev/null +++ b/sale_certification/readme/CONTRIBUTORS.md @@ -0,0 +1 @@ +- Christian Ramos \<\> diff --git a/sale_certification/readme/DESCRIPTION.md b/sale_certification/readme/DESCRIPTION.md new file mode 100644 index 0000000..b8a9750 --- /dev/null +++ b/sale_certification/readme/DESCRIPTION.md @@ -0,0 +1,9 @@ +This module introduces a certification workflow between sales orders and invoicing, commonly used in construction and large-scale contracting industries. + +Instead of invoicing directly from sales orders, this module allows the creation of **certifications** that represent approved progress or partial completion. These certifications can then generate invoices, optionally applying **retention amounts** (withholding a percentage of the payment until final project acceptance). + +Key Features: +- Add a certification step between sales and invoicing. +- Generate invoices based on certified quantities. +- Support for configurable retention percentages per certification. +- Tracks invoiced vs. certified amounts for better financial oversight at sale level. diff --git a/sale_certification/readme/USAGE.md b/sale_certification/readme/USAGE.md new file mode 100644 index 0000000..c6c6f3d --- /dev/null +++ b/sale_certification/readme/USAGE.md @@ -0,0 +1,21 @@ +1. **Create a Sales Order** as usual with your products or services. +2. Enable the **Certifiable?** checkbox on the Sales Order. +3. Confirm the Sales Order. +4. Once confirmed: + - A **Certified Percentage** will be displayed at the Sales Order level. + - A **Quantity Certified** field will appear at the line level. +5. Based on the invoice policy of your products, the same logic will apply to the certification process. A new **Certification** button will appear in the header. +6. Creating a new Certification offers three options: + - **Regular** – Automatically includes all available lines based on the invoice policy. + - **Percentage** – Applies a percentage to the amounts from the regular option (not the total sale). + - **Chapter** – Allows selection of specific sections (sale order lines within sections) to include in the certification. +7. After creating a certification, you can freely adjust quantities or remove lines. These changes will be reflected in the Sales Order, following the same logic as invoices. +8. When you confirm the certification, the confirmation date will be set. +9. Click **Create Invoice**. If you select **Apply Retention Monies**, you will have two retention options: + - **Percentage** of the certified base amount. + - **Fixed Value** over the certified base amount. + + This will: + - Create a negative line in the invoice subtracting the retention amount. + - Generate a separate invoice to hold the retention amount (if no draft retention invoice already exists), accessible from the Sales Order view. +10. You can set a payment method or reminders on the retention invoice to charge the client later or cancel the invoice if necessary. diff --git a/sale_certification/report/certification_reports.xml b/sale_certification/report/certification_reports.xml new file mode 100644 index 0000000..be6f852 --- /dev/null +++ b/sale_certification/report/certification_reports.xml @@ -0,0 +1,12 @@ + + + + Certification Report + order.certification + qweb-pdf + sale_certification.report_certification + sale_certification.report_certification + + report + + diff --git a/sale_certification/report/certification_templates.xml b/sale_certification/report/certification_templates.xml new file mode 100644 index 0000000..ab154c2 --- /dev/null +++ b/sale_certification/report/certification_templates.xml @@ -0,0 +1,588 @@ + + + + diff --git a/sale_certification/security/ir.model.access.csv b/sale_certification/security/ir.model.access.csv new file mode 100644 index 0000000..1ae602b --- /dev/null +++ b/sale_certification/security/ir.model.access.csv @@ -0,0 +1,5 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_certification_wizard,Certification Wizard,model_certification_wizard,base.group_user,1,1,1,1 +access_certification_invoice_wizard,Certification Invoice Wizard,model_certification_invoice_wizard,base.group_user,1,1,1,1 +access_order_certification,Order Certification,model_order_certification,base.group_user,1,1,1,1 +access_certification_line,Certification Line,model_certification_line,base.group_user,1,1,1,1 diff --git a/sale_certification/security/ir_rules.xml b/sale_certification/security/ir_rules.xml new file mode 100644 index 0000000..6625e37 --- /dev/null +++ b/sale_certification/security/ir_rules.xml @@ -0,0 +1,17 @@ + + + + + + Certification multi-company + + [('company_id', 'in', company_ids)] + + + + Certification Line multi-company + + [('company_id', 'in', company_ids)] + + + diff --git a/sale_certification/static/description/icon.png b/sale_certification/static/description/icon.png new file mode 100644 index 0000000..3a0328b Binary files /dev/null and b/sale_certification/static/description/icon.png differ diff --git a/sale_certification/static/description/index.html b/sale_certification/static/description/index.html new file mode 100644 index 0000000..a2e6381 --- /dev/null +++ b/sale_certification/static/description/index.html @@ -0,0 +1,498 @@ + + + + + +Sale Certification + + + +
+

Sale Certification

+ + +

Beta License: AGPL-3 OCA/vertical-construction Translate me on Weblate Try me on Runboat

+

This module introduces a certification workflow between sales orders and +invoicing, commonly used in construction and large-scale contracting +industries.

+

Instead of invoicing directly from sales orders, this module allows the +creation of certifications that represent approved progress or +partial completion. These certifications can then generate invoices, +optionally applying retention amounts (withholding a percentage of +the payment until final project acceptance).

+

Key Features:

+
    +
  • Add a certification step between sales and invoicing.
  • +
  • Generate invoices based on certified quantities.
  • +
  • Support for configurable retention percentages per certification.
  • +
  • Tracks invoiced vs. certified amounts for better financial oversight +at sale level.
  • +
+

Table of contents

+ +
+

Usage

+
    +
  1. Create a Sales Order as usual with your products or services.

    +
  2. +
  3. Enable the Certifiable? checkbox on the Sales Order.

    +
  4. +
  5. Confirm the Sales Order.

    +
  6. +
  7. Once confirmed:

    +
      +
    • A Certified Percentage will be displayed at the Sales Order +level.
    • +
    • A Quantity Certified field will appear at the line level.
    • +
    +
  8. +
  9. Based on the invoice policy of your products, the same logic will +apply to the certification process. A new Certification button +will appear in the header.

    +
  10. +
  11. Creating a new Certification offers three options:

    +
      +
    • Regular – Automatically includes all available lines based on +the invoice policy.
    • +
    • Percentage – Applies a percentage to the amounts from the +regular option (not the total sale).
    • +
    • Chapter – Allows selection of specific sections (sale order +lines within sections) to include in the certification.
    • +
    +
  12. +
  13. After creating a certification, you can freely adjust quantities or +remove lines. These changes will be reflected in the Sales Order, +following the same logic as invoices.

    +
  14. +
  15. When you confirm the certification, the confirmation date will be +set.

    +
  16. +
  17. Click Create Invoice. If you select Apply Retention Monies, +you will have two retention options:

    +
      +
    • Percentage of the certified base amount.
    • +
    • Fixed Value over the certified base amount.
    • +
    +

    This will:

    +
      +
    • Create a negative line in the invoice subtracting the retention +amount.
    • +
    • Generate a separate invoice to hold the retention amount (if no +draft retention invoice already exists), accessible from the Sales +Order view.
    • +
    +
  18. +
  19. You can set a payment method or reminders on the retention invoice +to charge the client later or cancel the invoice if necessary.

    +
  20. +
+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • Binhex
  • +
+
+
+

Contributors

+ +
+
+

Maintainers

+

This module is maintained by the OCA.

+ +Odoo Community Association + +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

Current maintainer:

+

Christian-RB

+

This module is part of the OCA/vertical-construction project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+ + diff --git a/sale_certification/static/src/css/report_certification.css b/sale_certification/static/src/css/report_certification.css new file mode 100644 index 0000000..90cab4c --- /dev/null +++ b/sale_certification/static/src/css/report_certification.css @@ -0,0 +1,10 @@ +.table-borderless-cert, +.table-borderless-cert tbody, +.table-borderless-cert thead, +.table-borderless-cert tfoot, +.table-borderless-cert tr, +.table-borderless-cert td, +.table-borderless-cert th { + border: 0 none !important; + padding: 5px 5px !important; +} diff --git a/sale_certification/tests/__init__.py b/sale_certification/tests/__init__.py new file mode 100644 index 0000000..9a7a60f --- /dev/null +++ b/sale_certification/tests/__init__.py @@ -0,0 +1,4 @@ +# Copyright 2025 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from . import test_sale_certification diff --git a/sale_certification/tests/test_sale_certification.py b/sale_certification/tests/test_sale_certification.py new file mode 100644 index 0000000..64a1f63 --- /dev/null +++ b/sale_certification/tests/test_sale_certification.py @@ -0,0 +1,138 @@ +# Copyright 2025 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.exceptions import UserError +from odoo.fields import Command +from odoo.tests import tagged + +from odoo.addons.sale.tests.common import SaleCommon + + +@tagged("post_install", "-at_install") +class TestSaleCertification(SaleCommon): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.ResCompany = cls.env["res.company"] + cls.sale_order.write( + { + "order_line": [ + Command.create( + { + "display_type": "line_section", + "name": "Section 1", + } + ), + Command.create( + { + "product_id": cls.consumable_product.id, + "product_uom_qty": 12.5, + } + ), + ], + "is_certifiable": True, + } + ) + cls.sale_order.action_confirm() + + def test_certification_generation(self): + with self.assertRaises(UserError): + self.env["certification.wizard"].create( + { + "sale_order_ids": [(6, 0, [self.sale_order.id])], + "certification_type": "percentage", + "percentage": -1, + } + ) + with self.assertRaises(UserError): + self.env["certification.wizard"].create( + { + "sale_order_ids": [(6, 0, [self.sale_order.id])], + "certification_type": "percentage", + "percentage": 2, + } + ) + with self.assertRaises(UserError): + self.env["certification.wizard"].create( + { + "sale_order_ids": [(6, 0, [self.sale_order.id])], + "certification_type": "chapters", + } + ) + # Chapter certification + self.env["certification.wizard"].create( + { + "sale_order_ids": [(6, 0, [self.sale_order.id])], + "certification_type": "chapters", + "chapter_ids": [ + Command.link( + self.sale_order.order_line.filtered( + lambda line: line.display_type == "line_section" + ).id + ) + ], + } + ).create_certifications() + self.assertEqual(self.sale_order.certification_count, 1) + self.assertEqual(len(self.sale_order.certification_ids), 1) + + # Invoicing + certification = self.sale_order.certification_ids[0] + certification.button_confirm() + self.env["certification.invoice.wizard"].create( + { + "order_certification_ids": [(6, 0, [certification.id])], + "retention_monies": True, + "retention_type": "percentage", + "retention_percentage": 0.1, + } + ).create_invoices() + self.assertEqual(len(self.sale_order.invoice_ids), 1) + self.assertEqual(self.sale_order.retention_invoice_count, 1) + + # Percentage certification + self.assertEqual(self.sale_order.certified_percentage, 41.67) + self.env["certification.wizard"].create( + { + "sale_order_ids": [(6, 0, [self.sale_order.id])], + "certification_type": "percentage", + "percentage": 0.5, + } + ).create_certifications() + self.assertEqual(len(self.sale_order.certification_ids), 2) + + # Invoicing + certification = self.sale_order.certification_ids[1] + certification.button_confirm() + self.env["certification.invoice.wizard"].create( + { + "order_certification_ids": [(6, 0, [certification.id])], + "retention_monies": False, + } + ).create_invoices() + self.assertEqual(len(self.sale_order.invoice_ids), 2) + self.assertEqual(self.sale_order.retention_invoice_count, 1) + self.sale_order._get_retention_invoices().action_post() + + # Regular certification + self.env["certification.wizard"].create( + { + "sale_order_ids": [(6, 0, [self.sale_order.id])], + "certification_type": "regular", + } + ).create_certifications() + self.assertEqual(len(self.sale_order.certification_ids), 3) + + # Invoicing + certification = self.sale_order.certification_ids[2] + certification.button_confirm() + self.env["certification.invoice.wizard"].create( + { + "order_certification_ids": [(6, 0, [certification.id])], + "retention_monies": True, + "retention_type": "value", + "retention_value": 10, + } + ).create_invoices() + self.assertEqual(len(self.sale_order.invoice_ids), 3) + self.assertEqual(len(self.sale_order._get_retention_invoices()), 2) diff --git a/sale_certification/views/account_views.xml b/sale_certification/views/account_views.xml new file mode 100644 index 0000000..1a83d1f --- /dev/null +++ b/sale_certification/views/account_views.xml @@ -0,0 +1,27 @@ + + + + + Account Invoice + account.move + + + + + + + + + diff --git a/sale_certification/views/order_certifications_menu.xml b/sale_certification/views/order_certifications_menu.xml new file mode 100644 index 0000000..3c8a50d --- /dev/null +++ b/sale_certification/views/order_certifications_menu.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/sale_certification/views/view_order_certifications.xml b/sale_certification/views/view_order_certifications.xml new file mode 100644 index 0000000..4ad8d9d --- /dev/null +++ b/sale_certification/views/view_order_certifications.xml @@ -0,0 +1,186 @@ + + + + Certification + order.certification + tree,form + + + + + order.certification.tree + order.certification + + + + + + + + + + + + + + order.certification.form + order.certification + +
+
+ + +
+ +
+ +
+
+

+ +

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + + + certification.line.tree + certification.line + + + + + + + + + + + Order Certification + order.certification + CERT/ + 5 + + + + + + + +
diff --git a/sale_certification/views/view_order_form_certify.xml b/sale_certification/views/view_order_form_certify.xml new file mode 100644 index 0000000..71a3912 --- /dev/null +++ b/sale_certification/views/view_order_form_certify.xml @@ -0,0 +1,94 @@ + + + sale.order.form.certify + sale.order + + + + + + + + + +