diff --git a/rma_account/README.rst b/rma_account/README.rst new file mode 100644 index 000000000..c464cd707 --- /dev/null +++ b/rma_account/README.rst @@ -0,0 +1,52 @@ +.. image:: https://img.shields.io/badge/licence-LGPL--3-blue.svg + :alt: License LGPL-3 + +=========== +RMA Account +=========== + +This module integrates Return Merchandise Authorizations (RMA) with invoices, +allowing to: + +#. Create complete RMA's using existing invoices as a reference. +#. Create refunds from a RMA. + +Usage +===== + +RMA are accessible though Inventory menu. There's four menus, divided by type. +Users can access to the list of RMA or RMA lines. + +Create an RMA: + +#. Select a partner. Fill the rma lines by selecting an invoice. +#. Request approval and approve. +#. Click on RMA Lines button. +#. Click on more and select an option: "Receive products", "Create Delivery + Order, Create Refund". +#. Go back to the RMA. Set the RMA to done if not further action is required. + +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 smashing it by providing a detailed and welcomed feedback. + +Credits +======= + +Contributors +------------ + +* Jordi Ballester Alomar +* Aaron Henriquez +* Lois Rilo +* Bhavesh Odedra +* Akim Juillerat + +Maintainer +---------- + +This module is maintained by ForgeFlow. diff --git a/rma_account/__init__.py b/rma_account/__init__.py new file mode 100644 index 000000000..d4a427805 --- /dev/null +++ b/rma_account/__init__.py @@ -0,0 +1,5 @@ +# Copyright 2017 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from . import models +from . import wizards diff --git a/rma_account/__manifest__.py b/rma_account/__manifest__.py new file mode 100644 index 000000000..796f2ec92 --- /dev/null +++ b/rma_account/__manifest__.py @@ -0,0 +1,25 @@ +# Copyright 2017 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +{ + "name": "RMA Account", + "version": "18.0.1.0.0", + "license": "LGPL-3", + "category": "RMA", + "summary": "Integrates RMA with Invoice Processing", + "author": "ForgeFlow", + "website": "https://github.com/ForgeFlow", + "depends": ["stock_account", "rma"], + "data": [ + "security/ir.model.access.csv", + "data/rma_operation.xml", + "views/rma_order_view.xml", + "views/rma_operation_view.xml", + "views/rma_order_line_view.xml", + "views/account_move_view.xml", + "views/rma_account_menu.xml", + "wizards/rma_add_account_move.xml", + "wizards/rma_refund.xml", + ], + "installable": True, +} diff --git a/rma_account/data/rma_operation.xml b/rma_account/data/rma_operation.xml new file mode 100644 index 000000000..2c320f3be --- /dev/null +++ b/rma_account/data/rma_operation.xml @@ -0,0 +1,42 @@ + + + + + no + + + + no + + + + Refund after receive + RF-C + received + ordered + no + customer + + + + + + Refund after deliver + RF-S + ordered + no + ordered + supplier + + + + + + no + + + + no + + + diff --git a/rma_account/models/__init__.py b/rma_account/models/__init__.py new file mode 100644 index 000000000..0d8b82553 --- /dev/null +++ b/rma_account/models/__init__.py @@ -0,0 +1,8 @@ +from . import rma_order +from . import rma_order_line +from . import rma_operation +from . import account_move +from . import account_move_line +from . import procurement +from . import stock_move +from . import stock_valuation_layer diff --git a/rma_account/models/account_move.py b/rma_account/models/account_move.py new file mode 100644 index 000000000..b39c73f6e --- /dev/null +++ b/rma_account/models/account_move.py @@ -0,0 +1,147 @@ +# Copyright 2017-22 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import api, fields, models +from odoo.tools.float_utils import float_compare + + +class AccountMove(models.Model): + _inherit = "account.move" + + @api.depends("line_ids.rma_line_ids") + def _compute_used_in_rma_count(self): + for inv in self: + rmas = inv.mapped("line_ids.rma_line_ids") + inv.used_in_rma_count = len(rmas) + + @api.depends("line_ids.rma_line_id") + def _compute_rma_count(self): + for inv in self: + rmas = inv.mapped("line_ids.rma_line_id") + inv.rma_count = len(rmas) + + def _prepare_invoice_line_from_rma_line(self, rma_line): + sequence = max(self.line_ids.mapped("sequence")) + 1 if self.line_ids else 10 + qty = rma_line.qty_to_refund + if float_compare(qty, 0.0, precision_rounding=rma_line.uom_id.rounding) <= 0: + qty = 0.0 + data = { + "move_id": self.id, + "product_uom_id": rma_line.uom_id.id, + "product_id": rma_line.product_id.id, + "price_unit": rma_line.company_id.currency_id._convert( + rma_line._get_price_unit(), + self.currency_id, + self.company_id, + self.date, + round=False, + ), + "quantity": qty, + "discount": 0.0, + "rma_line_id": rma_line.id, + "sequence": sequence + 1, + } + return data + + def _post_process_invoice_line_from_rma_line(self, new_line, rma_line): + new_line.rma_line_id = rma_line + new_line.name = f"{self.add_rma_line_id.name}: {new_line.name}" + new_line.account_id = new_line.account_id + return True + + @api.onchange("add_rma_line_id") + def onchange_add_rma_line_id(self): + if not self.add_rma_line_id: + return {} + if not self.partner_id: + self.partner_id = self.add_rma_line_id.partner_id.id + + new_line = self.env["account.move.line"] + if self.add_rma_line_id not in (self.line_ids.mapped("rma_line_id")): + data = self._prepare_invoice_line_from_rma_line(self.add_rma_line_id) + new_line = new_line.new(data) + self._post_process_invoice_line_from_rma_line( + new_line, self.add_rma_line_id + ) + # Compute invoice_origin. + origins = set(self.line_ids.mapped("rma_line_id.name")) + self.invoice_origin = ",".join(list(origins)) + self.add_rma_line_id = False + + rma_count = fields.Integer(compute="_compute_rma_count", string="# of RMA") + used_in_rma_count = fields.Integer( + compute="_compute_used_in_rma_count", string="# of Used in RMA" + ) + + add_rma_line_id = fields.Many2one( + comodel_name="rma.order.line", + string="Add from RMA line", + ondelete="set null", + help="Create a refund in based on an existing rma_line", + ) + + def action_view_used_in_rma(self): + rmas = self.mapped("line_ids.rma_line_ids") + return self._prepare_action_view_rma(rmas) + + def action_view_rma(self): + rmas = self.mapped("line_ids.rma_line_id") + return self._prepare_action_view_rma(rmas) + + def _prepare_action_view_rma(self, rmas): + if self.move_type in ["in_invoice", "in_refund"]: + action = self.env.ref("rma.action_rma_supplier_lines") + form_view = self.env.ref("rma.view_rma_line_supplier_form", False) + else: + action = self.env.ref("rma.action_rma_customer_lines") + form_view = self.env.ref("rma.view_rma_line_form", False) + result = action.sudo().read()[0] + rma_ids = rmas.ids + # choose the view_mode accordingly + if not rma_ids: + result["domain"] = [("id", "in", [])] + elif len(rma_ids) > 1: + result["domain"] = [("id", "in", rma_ids)] + else: + res = form_view + result["views"] = [(res and res.id or False, "form")] + result["res_id"] = rma_ids and rma_ids[0] or False + return result + + def _stock_account_prepare_anglo_saxon_out_lines_vals(self): + product_model = self.env["product.product"] + res = super()._stock_account_prepare_anglo_saxon_out_lines_vals() + for line in res: + if line.get("product_id", False): + product = product_model.browse(line.get("product_id", False)) + if ( + line.get("account_id") + != product.categ_id.property_stock_valuation_account_id.id + ): + current_move = self.browse(line.get("move_id", False)) + current_rma = current_move.invoice_line_ids.filtered( + lambda x, product=product: x.rma_line_id + and x.product_id.id == product.id + ).mapped("rma_line_id") + if len(current_rma) == 1: + line.update({"rma_line_id": current_rma.id}) + elif len(current_rma) > 1: + find_with_label_rma = current_rma.filtered( + lambda x, line=line: x.name == line.get("name") + ) + if len(find_with_label_rma) == 1: + line.update({"rma_line_id": find_with_label_rma.id}) + return res + + def _stock_account_get_last_step_stock_moves(self): + rslt = super()._stock_account_get_last_step_stock_moves() + for invoice in self.filtered(lambda x: x.move_type == "out_invoice"): + rslt += invoice.mapped("line_ids.rma_line_id.move_ids").filtered( + lambda x: x.state == "done" and x.location_dest_id.usage == "customer" + ) + for invoice in self.filtered(lambda x: x.move_type == "out_refund"): + # Add refunds generated from the RMA + rslt += invoice.mapped("line_ids.rma_line_id.move_ids").filtered( + lambda x: x.state == "done" and x.location_id.usage == "customer" + ) + return rslt diff --git a/rma_account/models/account_move_line.py b/rma_account/models/account_move_line.py new file mode 100644 index 000000000..70a6b918c --- /dev/null +++ b/rma_account/models/account_move_line.py @@ -0,0 +1,116 @@ +# Copyright 2017-22 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import api, fields, models +from odoo.osv import expression + + +class AccountMoveLine(models.Model): + _inherit = "account.move.line" + + @api.model + def _name_search(self, name, domain=None, operator="ilike", limit=None, order=None): + """Allows to search by Invoice number. This has to be done this way, + as Odoo adds extra args to name_search on _name_search method that + will make impossible to get the desired result.""" + domain = domain or [] + if self.env.context.get("rma"): + domain = expression.AND( + [ + domain, + [("display_type", "in", ("product", "line_section", "line_note"))], + ] + ) + lines = self.search([("move_id.name", operator, name)] + domain, limit=limit) + if limit: + limit_rest = limit - len(lines) + else: + # limit can be 0 or None representing infinite + limit_rest = limit + if limit_rest or not limit: + domain += [("id", "in", lines.ids)] + return super()._name_search( + name, domain=domain, operator=operator, limit=limit_rest, order=order + ) + return self._search(domain, limit=limit, order=order) + + def _compute_display_name(self): + if not self.env.context.get("rma"): + return super()._compute_display_name() + for inv in self: + if inv.move_id.ref: + name = "INV:{} | REF:{} | ORIG:{} | PART:{} | QTY:{}".format( + inv.move_id.name or "", + inv.move_id.invoice_origin or "", + inv.move_id.ref or "", + inv.product_id.name, + inv.quantity, + ) + inv.display_name = name + elif inv.move_id.name: + name = "INV:{} | ORIG:{} | PART:{} | QTY:{}".format( + inv.move_id.name or "", + inv.move_id.invoice_origin or "", + inv.product_id.name, + inv.quantity, + ) + inv.display_name = name + + def _compute_used_in_rma_count(self): + for invl in self: + rma_lines = invl.mapped("rma_line_ids") + invl.used_in_rma_line_count = len(rma_lines) + + def _compute_rma_count(self): + for invl in self: + rma_lines = invl.mapped("rma_line_id") + invl.rma_line_count = len(rma_lines) + + used_in_rma_line_count = fields.Integer( + compute="_compute_used_in_rma_count", string="# of used RMA" + ) + rma_line_count = fields.Integer(compute="_compute_rma_count", string="# of RMA") + rma_line_ids = fields.One2many( + comodel_name="rma.order.line", + inverse_name="account_move_line_id", + string="RMA", + readonly=True, + help="This will contain the RMA lines for the invoice line", + ) + rma_line_id = fields.Many2one( + comodel_name="rma.order.line", + string="RMA line", + ondelete="set null", + index=True, + help="This will contain the rma line that originated this line", + ) + + def _stock_account_get_anglo_saxon_price_unit(self): + self.ensure_one() + price_unit = super()._stock_account_get_anglo_saxon_price_unit() + rma_line = self.rma_line_id or self.env["rma.order.line"] + if rma_line: + is_line_reversing = bool(self.move_id.reversed_entry_id) + qty_to_refund = self.product_uom_id._compute_quantity( + self.quantity, self.product_id.uom_id + ) + posted_invoice_lines = rma_line.move_line_ids.filtered( + lambda line: line.move_id.move_type == "out_refund" + and line.move_id.state == "posted" + and bool(line.move_id.reversed_entry_id) == is_line_reversing + ) + qty_refunded = sum( + x.product_uom_id._compute_quantity(x.quantity, x.product_id.uom_id) + for x in posted_invoice_lines + ) + product = self.product_id.with_company(self.company_id).with_context( + is_returned=is_line_reversing + ) + average_price_unit = product._compute_average_price( + qty_refunded, qty_to_refund, rma_line._get_in_moves() + ) + if average_price_unit: + price_unit = self.product_id.uom_id.with_company( + self.company_id + )._compute_price(average_price_unit, self.product_uom_id) + return price_unit diff --git a/rma_account/models/procurement.py b/rma_account/models/procurement.py new file mode 100644 index 000000000..e065cfe9f --- /dev/null +++ b/rma_account/models/procurement.py @@ -0,0 +1,15 @@ +# Copyright 2017-2022 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import fields, models + + +class ProcurementGroup(models.Model): + _inherit = "procurement.group" + + rma_id = fields.Many2one( + comodel_name="rma.order", string="RMA", ondelete="set null" + ) + rma_line_id = fields.Many2one( + comodel_name="rma.order.line", string="RMA line", ondelete="set null" + ) diff --git a/rma_account/models/rma_operation.py b/rma_account/models/rma_operation.py new file mode 100644 index 000000000..96736c711 --- /dev/null +++ b/rma_account/models/rma_operation.py @@ -0,0 +1,56 @@ +# Copyright 2017-22 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import api, fields, models + + +class RmaOperation(models.Model): + _inherit = "rma.operation" + + refund_policy = fields.Selection( + [ + ("no", "No refund"), + ("ordered", "Based on Ordered Quantities"), + ("delivered", "Based on Delivered Quantities"), + ("received", "Based on Received Quantities"), + ], + default="no", + ) + + refund_journal_id = fields.Many2one( + comodel_name="account.journal", + string="Refund Account Journal", + domain="[('id', 'in', valid_refund_journal_ids)]", + ) + + valid_refund_journal_ids = fields.Many2many( + comodel_name="account.journal", + compute="_compute_domain_valid_journal", + ) + automated_refund = fields.Boolean( + help="In the scenario where a company uses anglo-saxon accounting, if " + "you receive products from a customer and don't expect to refund the customer " + "but send a replacement unit, mark this flag to be accounting consistent" + ) + refund_free_of_charge = fields.Boolean( + help="In case of automated refund you should mark this option as long automated" + "refunds mean to compensate Stock Interim accounts only without hitting" + "Accounts receivable" + ) + + @api.onchange("type") + def _compute_domain_valid_journal(self): + for rec in self: + if rec.type == "customer": + rec.valid_refund_journal_ids = self.env["account.journal"].search( + [("type", "=", "sale")] + ) + else: + rec.valid_refund_journal_ids = self.env["account.journal"].search( + [("type", "=", "purchase")] + ) + + @api.onchange("automated_refund") + def _onchange_automated_refund(self): + for rec in self: + rec.refund_free_of_charge = rec.automated_refund diff --git a/rma_account/models/rma_order.py b/rma_account/models/rma_order.py new file mode 100644 index 000000000..6c66a012a --- /dev/null +++ b/rma_account/models/rma_order.py @@ -0,0 +1,119 @@ +# Copyright 2017-22 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import api, fields, models + + +class RmaOrder(models.Model): + _inherit = "rma.order" + + def _compute_invoice_refund_count(self): + for rec in self: + invoices = rec.mapped("rma_line_ids.refund_line_ids.move_id") + rec.invoice_refund_count = len(invoices) + + def _compute_invoice_count(self): + for rec in self: + invoices = rec.mapped("rma_line_ids.move_id") + rec.invoice_count = len(invoices) + + add_move_id = fields.Many2one( + comodel_name="account.move", + string="Add Invoice", + ondelete="set null", + readonly=True, + ) + invoice_refund_count = fields.Integer( + compute="_compute_invoice_refund_count", string="# of Refunds" + ) + invoice_count = fields.Integer( + compute="_compute_invoice_count", string="# of Invoices" + ) + + def _prepare_rma_line_from_inv_line(self, line): + if self.type == "customer": + operation = ( + self.rma_line_ids.product_id.rma_customer_operation_id + or self.rma_line_ids.product_id.categ_id.rma_customer_operation_id + ) + else: + operation = ( + self.rma_line_ids.product_id.rma_supplier_operation_id + or self.rma_line_ids.product_id.categ_id.rma_supplier_operation_id + ) + data = { + "account_move_line_id": line.id, + "product_id": line.product_id.id, + "name": line.name, + "origin": line.move_id.name, + "uom_id": line.product_uom_id.id, + "operation_id": operation, + "product_qty": line.quantity, + "price_unit": line.move_id.currency_id._convert( + line.price_unit, + line.currency_id, + line.company_id, + line.date, + round=False, + ), + "rma_id": self.id, + } + return data + + @api.onchange("add_move_id") + def onchange_invoice(self): + if not self.add_move_id: + return {} + if not self.partner_id: + self.partner_id = self.add_move_id.partner_id.id + new_lines = self.env["rma.order.line"] + for line in self.add_move_id.line_ids: + # Load a PO line only once + if line in self.rma_line_ids.mapped("account_move_line_id"): + continue + data = self._prepare_rma_line_from_inv_line(line) + new_line = new_lines.new(data) + new_lines += new_line + + self.rma_line_ids += new_lines + self.date_rma = fields.Datetime.now() + self.delivery_address_id = self.add_move_id.partner_id.id + self.invoice_address_id = self.add_move_id.partner_id.id + self.add_move_id = False + return {} + + @api.model + def prepare_rma_line(self, origin_rma, rma_id, line): + line_values = super().prepare_rma_line(origin_rma, rma_id, line) + line_values["invoice_address_id"] = line.invoice_address_id.id + return line_values + + @api.model + def _prepare_rma_data(self, partner, origin_rma): + res = super()._prepare_rma_data(partner, origin_rma) + res["invoice_address_id"] = partner.id + return res + + def action_view_invoice_refund(self): + move_ids = self.mapped("rma_line_ids.move_id").ids + form_view_ref = self.env.ref("account.view_move_form", False) + list_view_ref = self.env.ref("account.view_move_tree", False) + + return { + "domain": [("id", "in", move_ids)], + "name": "Refunds", + "res_model": "account.move", + "views": [(list_view_ref.id, "list"), (form_view_ref.id, "form")], + } + + def action_view_invoice(self): + move_ids = self.mapped("rma_line_ids.move_id").ids + form_view_ref = self.env.ref("account.view_move_form", False) + list_view_ref = self.env.ref("account.view_move_tree", False) + + return { + "domain": [("id", "in", move_ids)], + "name": "Originating Invoice", + "res_model": "account.move", + "views": [(list_view_ref.id, "list"), (form_view_ref.id, "form")], + } diff --git a/rma_account/models/rma_order_line.py b/rma_account/models/rma_order_line.py new file mode 100644 index 000000000..89d9a891a --- /dev/null +++ b/rma_account/models/rma_order_line.py @@ -0,0 +1,401 @@ +# Copyright 2017-22 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import _, api, fields, models +from odoo.exceptions import UserError, ValidationError + + +class RmaOrderLine(models.Model): + _inherit = "rma.order.line" + + @api.model + def _default_invoice_address(self): + partner_id = self.env.context.get("partner_id") + if partner_id: + return self.env["res.partner"].browse(partner_id) + return self.env["res.partner"] + + @api.depends( + "move_line_ids", "move_line_ids.move_id.state", "refund_policy", "type" + ) + def _compute_qty_refunded(self): + for rec in self: + rec.qty_refunded = sum( + rec.refund_line_ids.filtered( + lambda i: i.move_id.state in ("posted") + ).mapped("quantity") + ) + + @api.depends( + "move_line_ids", + "move_line_ids.move_id.state", + "refund_policy", + "move_ids", + "move_ids.state", + "type", + ) + def _compute_qty_to_refund(self): + qty = 0.0 + for res in self: + if res.refund_policy == "ordered": + qty = res.product_qty - res.qty_refunded + elif res.refund_policy == "received": + qty = res.qty_received - res.qty_refunded + elif res.refund_policy == "delivered": + qty = res.qty_delivered - res.qty_refunded + res.qty_to_refund = qty + + def _compute_refund_count(self): + for rec in self: + rec.refund_count = len(rec.refund_line_ids.mapped("move_id")) + + invoice_address_id = fields.Many2one( + "res.partner", + string="Partner invoice address", + default=lambda self: self._default_invoice_address(), + help="Invoice address for current rma order.", + ) + refund_count = fields.Integer( + compute="_compute_refund_count", string="# of Refunds", default=0 + ) + account_move_line_id = fields.Many2one( + comodel_name="account.move.line", + string="Originating Invoice Line", + ondelete="restrict", + index=True, + ) + move_line_ids = fields.One2many( + comodel_name="account.move.line", + inverse_name="rma_line_id", + string="Journal Items", + copy=False, + index=True, + readonly=True, + ) + refund_line_ids = fields.One2many( + comodel_name="account.move.line", + inverse_name="rma_line_id", + string="Refund Lines", + domain=[ + ("move_id.move_type", "in", ["in_refund", "out_refund"]), + ("display_type", "=", "product"), + ], + copy=False, + index=True, + readonly=True, + ) + move_id = fields.Many2one( + "account.move", + string="Source", + related="account_move_line_id.move_id", + index=True, + readonly=True, + ) + refund_policy = fields.Selection( + [ + ("no", "No refund"), + ("ordered", "Based on Ordered Quantities"), + ("delivered", "Based on Delivered Quantities"), + ("received", "Based on Received Quantities"), + ], + required=True, + default="no", + readonly=False, + ) + qty_to_refund = fields.Float( + copy=False, + digits="Product Unit of Measure", + readonly=True, + compute="_compute_qty_to_refund", + store=True, + ) + qty_refunded = fields.Float( + copy=False, + digits="Product Unit of Measure", + readonly=True, + compute="_compute_qty_refunded", + store=True, + ) + + commercial_partner_id = fields.Many2one( + "res.partner", + string="Commercial Entity", + store=True, + readonly=True, + compute="_compute_commercial_partner_id", + ondelete="restrict", + ) + + @api.depends("partner_id") + def _compute_commercial_partner_id(self): + for rma_line in self: + rma_line.commercial_partner_id = rma_line.partner_id.commercial_partner_id + + @api.onchange("product_id", "partner_id") + def _onchange_product_id(self): + """Domain for sale_line_id is computed here to make it dynamic.""" + res = super()._onchange_product_id() + if not res.get("domain"): + res["domain"] = {} + if not self.product_id: + domain = [ + "|", + ("move_id.partner_id", "=", self.partner_id.id), + ("move_id.partner_id", "child_of", self.partner_id.id), + ("display_type", "=", "product"), + ] + res["domain"]["account_move_line_id"] = domain + else: + domain = [ + "&", + "|", + ("move_id.partner_id", "=", self.partner_id.id), + ("move_id.partner_id", "child_of", self.partner_id.id), + ("display_type", "=", "product"), + ("product_id", "=", self.product_id.id), + ] + res["domain"]["account_move_line_id"] = domain + return res + + def _prepare_rma_line_from_inv_line(self, line): + self.ensure_one() + if not self.type: + self.type = self._get_default_type() + if self.type == "customer": + operation = ( + line.product_id.rma_customer_operation_id + or line.product_id.categ_id.rma_customer_operation_id + ) + else: + operation = ( + line.product_id.rma_supplier_operation_id + or line.product_id.categ_id.rma_supplier_operation_id + ) + if not operation: + operation = self.env["rma.operation"].search( + [("type", "=", self.type)], limit=1 + ) + if not operation: + raise ValidationError(_("Please define an operation first")) + + if not operation.in_route_id or not operation.out_route_id: + route = self.env["stock.location.route"].search( + [("rma_selectable", "=", True)], limit=1 + ) + if not route: + raise ValidationError(_("Please define an rma route")) + + if not operation.in_warehouse_id or not operation.out_warehouse_id: + warehouse = self.env["stock.warehouse"].search( + [("company_id", "=", self.company_id.id), ("lot_rma_id", "!=", False)], + limit=1, + ) + if not warehouse: + raise ValidationError( + _("Please define a warehouse with a" " default rma location") + ) + data = { + "product_id": line.product_id.id, + "origin": line.move_id.name, + "uom_id": line.product_uom_id.id, + "operation_id": operation.id, + "product_qty": line.quantity, + "price_unit": line.move_id.currency_id._convert( + line.price_unit, + line.currency_id, + line.company_id, + line.date, + round=False, + ), + "delivery_address_id": line.move_id.partner_shipping_id.id + if line.move_id.partner_shipping_id + else line.move_id.partner_id.id, + "invoice_address_id": line.move_id.partner_id.id, + "receipt_policy": operation.receipt_policy, + "refund_policy": operation.refund_policy, + "delivery_policy": operation.delivery_policy, + "currency_id": line.currency_id.id, + "in_warehouse_id": operation.in_warehouse_id.id or warehouse.id, + "out_warehouse_id": operation.out_warehouse_id.id or warehouse.id, + "in_route_id": operation.in_route_id.id or route.id, + "out_route_id": operation.out_route_id.id or route.id, + "location_id": ( + operation.location_id.id + or operation.in_warehouse_id.lot_rma_id.id + or warehouse.lot_rma_id.id + ), + } + return data + + @api.onchange("account_move_line_id") + def _onchange_account_move_line_id(self): + if not self.account_move_line_id: + return + data = self._prepare_rma_line_from_inv_line(self.account_move_line_id) + self.update(data) + self._remove_other_data_origin("account_move_line_id") + + @api.constrains("account_move_line_id", "partner_id") + def _check_invoice_partner(self): + for rec in self: + if ( + rec.account_move_line_id + and rec.account_move_line_id.move_id.partner_id != rec.partner_id + ): + raise ValidationError( + _( + "RMA customer and originating invoice line customer " + "doesn't match." + ) + ) + + def _remove_other_data_origin(self, exception): + res = super()._remove_other_data_origin(exception) + if not exception == "account_move_line_id": + self.account_move_line_id = False + return res + + @api.onchange("operation_id") + def _onchange_operation_id(self): + result = super()._onchange_operation_id() + if self.operation_id: + self.refund_policy = self.operation_id.refund_policy or "no" + return result + + @api.constrains("account_move_line_id") + def _check_duplicated_lines(self): + for line in self: + matching_inv_lines = self.env["account.move.line"].search( + [("id", "=", line.account_move_line_id.id)] + ) + if len(matching_inv_lines) > 1: + raise UserError( + _( + "There's an rma for the " + "invoice line %(arg1)s and invoice %(arg2)s", + arg1=line.account_move_line_id, + arg2=line.account_move_line_id.move_id, + ) + ) + return {} + + def action_view_invoice(self): + form_view_ref = self.env.ref("account.view_move_form", False) + list_view_ref = self.env.ref("account.view_move_tree", False) + + return { + "domain": [("id", "in", [self.account_move_line_id.move_id.id])], + "name": "Originating Invoice", + "res_model": "account.move", + "type": "ir.actions.act_window", + "views": [(list_view_ref.id, "list"), (form_view_ref.id, "form")], + } + + def action_view_refunds(self): + moves = self.mapped("refund_line_ids.move_id") + form_view_ref = self.env.ref("account.view_move_form", False) + list_view_ref = self.env.ref("account.view_move_tree", False) + + return { + "domain": [("id", "in", moves.ids)], + "name": "Refunds", + "res_model": "account.move", + "type": "ir.actions.act_window", + "views": [(list_view_ref.id, "list"), (form_view_ref.id, "form")], + } + + def _compute_display_name(self): + if not self.env.context.get("rma"): + return super()._compute_display_name() + for rma in self: + rma.display_name = f"{rma.name} {rma.product_id.name} qty:{rma.product_qty}" + + def _stock_account_anglo_saxon_reconcile_valuation(self): + for rma in self: + prod = rma.product_id + if rma.product_id.valuation != "real_time": + continue + if not rma.company_id.anglo_saxon_accounting: + continue + product_accounts = prod.product_tmpl_id._get_product_accounts() + if rma.type == "customer": + product_interim_account = product_accounts["stock_output"] + else: + product_interim_account = product_accounts["stock_input"] + if product_interim_account.reconcile: + # Get the in and out moves + amls = self.env["account.move.line"].search( + [ + ("rma_line_id", "=", rma.id), + ("account_id", "=", product_interim_account.id), + ("parent_state", "=", "posted"), + ("reconciled", "=", False), + ] + ) + amls |= rma.move_ids.mapped( + "stock_valuation_layer_ids.account_move_id.line_ids" + ) + # Search for anglo-saxon lines linked to the product in the journal + # entry. + amls = amls.filtered( + lambda line, + prod=prod, + product_interim_account=product_interim_account: line.product_id + == prod + and line.account_id == product_interim_account + and not line.reconciled + ) + # Reconcile. + amls.reconcile() + + def _get_price_unit(self): + self.ensure_one() + price_unit = super()._get_price_unit() + if self.reference_move_id: + move = self.reference_move_id + layers = move.sudo().stock_valuation_layer_ids + if layers: + price_unit = sum(layers.mapped("value")) / sum( + layers.mapped("quantity") + ) + price_unit = price_unit + elif self.account_move_line_id and self.type == "supplier": + # We get the cost from the original invoice line + price_unit = self.account_move_line_id.price_unit + return price_unit + + def _refund_at_zero_cost(self): + make_refund = ( + self.env["rma.refund"] + .with_context( + **{ + "customer": True, + "active_ids": self.ids, + "active_model": "rma.order.line", + } + ) + .create({"description": "RMA Anglosaxon Regularisation"}) + ) + for item in make_refund.item_ids: + item.qty_to_refund = item.line_id.qty_received - item.line_id.qty_refunded + action_refund = make_refund.invoice_refund() + refund_id = action_refund.get("res_id", False) + if refund_id: + refund = self.env["account.move"].browse(refund_id) + refund._post() + + def _check_refund_zero_cost(self): + """ + In the scenario where a company uses anglo-saxon accounting, if you receive + products from a customer and don't expect to refund the customer but send a + replacement unit you still need to create a debit entry on the + Stock Interim (Delivered) account. In order to do this the best approach is + to create a customer refund from the RMA, but set as free of charge + (price unit = 0). The refund will be 0, but the Stock Interim (Delivered) + account will be posted anyways. + """ + # For some reason api.depends on qty_received is not working. Using the + # _account_entry_move method in stock move as trigger then + for rec in self.filtered(lambda line: line.operation_id.automated_refund): + if rec.qty_received > rec.qty_refunded: + rec._refund_at_zero_cost() diff --git a/rma_account/models/stock_move.py b/rma_account/models/stock_move.py new file mode 100644 index 000000000..042d40c5b --- /dev/null +++ b/rma_account/models/stock_move.py @@ -0,0 +1,32 @@ +# Copyright 2017-22 ForgeFlow S.L. (www.forgeflow.com) +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). + +from odoo import api, models + + +class StockMove(models.Model): + _inherit = "stock.move" + + @api.model + def _prepare_account_move_line( + self, qty, cost, credit_account_id, debit_account_id, svl_id, description + ): + res = super()._prepare_account_move_line( + qty, cost, credit_account_id, debit_account_id, svl_id, description + ) + for line in res: + if ( + line[2]["account_id"] + != self.product_id.categ_id.property_stock_valuation_account_id.id + ): + line[2]["rma_line_id"] = self.rma_line_id.id + return res + + def _account_entry_move(self, qty, description, svl_id, cost): + res = super()._account_entry_move(qty, description, svl_id, cost) + if self.company_id.anglo_saxon_accounting: + # Eventually reconcile together the invoice and valuation accounting + # entries on the stock interim accounts + self.rma_line_id._stock_account_anglo_saxon_reconcile_valuation() + self.rma_line_id._check_refund_zero_cost() + return res diff --git a/rma_account/models/stock_valuation_layer.py b/rma_account/models/stock_valuation_layer.py new file mode 100644 index 000000000..f7b751886 --- /dev/null +++ b/rma_account/models/stock_valuation_layer.py @@ -0,0 +1,16 @@ +# Copyright 2017-22 ForgeFlow S.L. (www.forgeflow.com) +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). + +from odoo import models + + +class StockValuationLayer(models.Model): + _inherit = "stock.valuation.layer" + + def _validate_accounting_entries(self): + res = super()._validate_accounting_entries() + for svl in self: + # Eventually reconcile together the stock interim accounts + if svl.company_id.anglo_saxon_accounting: + svl.stock_move_id.rma_line_id._stock_account_anglo_saxon_reconcile_valuation() + return res diff --git a/rma_account/pyproject.toml b/rma_account/pyproject.toml new file mode 100644 index 000000000..4231d0ccc --- /dev/null +++ b/rma_account/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/rma_account/security/ir.model.access.csv b/rma_account/security/ir.model.access.csv new file mode 100644 index 000000000..75b11edf6 --- /dev/null +++ b/rma_account/security/ir.model.access.csv @@ -0,0 +1,11 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_account_move_customer_user,access_account_move,account.model_account_move,rma.group_rma_customer_user,1,0,0,0 +access_account_move_supplier_user,access_account_move,account.model_account_move,rma.group_rma_supplier_user,1,0,0,0 +access_account_move_line_customer_user,access_account_move_line,account.model_account_move_line,rma.group_rma_customer_user,1,0,0,0 +access_account_move_line_supplier_user,access_account_move_line,account.model_account_move_line,rma.group_rma_supplier_user,1,0,0,0 +access_rma_refund_customer_user_item,rma.refund.customer.user,model_rma_refund,rma.group_rma_customer_user,1,1,1,1 +access_rma_refund_supplier_user_item,rma.refund.supplier.user,model_rma_refund,rma.group_rma_supplier_user,1,1,1,1 +access_rma_refund_item_customer_user_item,rma.refund.item.customer.user,model_rma_refund_item,rma.group_rma_customer_user,1,1,1,1 +access_rma_refund_item_supplier_user_item,rma.refund.item.supplier.user,model_rma_refund_item,rma.group_rma_supplier_user,1,1,1,1 +access_rma_add_account_move_customer_user_item,rma.add.account.move.customer.user,model_rma_add_account_move,rma.group_rma_customer_user,1,1,1,1 +access_rma_add_account_move_supplier_user_item,rma.add.account.move.supplier.user,model_rma_add_account_move,rma.group_rma_supplier_user,1,1,1,1 diff --git a/rma_account/tests/__init__.py b/rma_account/tests/__init__.py new file mode 100644 index 000000000..4a2091dee --- /dev/null +++ b/rma_account/tests/__init__.py @@ -0,0 +1,7 @@ +# Copyright 2018 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from . import test_rma_account + +# from . import test_rma_stock_account +from . import test_account_move_line_rma_order_line diff --git a/rma_account/tests/test_account_move_line_rma_order_line.py b/rma_account/tests/test_account_move_line_rma_order_line.py new file mode 100644 index 000000000..21a621afa --- /dev/null +++ b/rma_account/tests/test_account_move_line_rma_order_line.py @@ -0,0 +1,283 @@ +# Copyright 2017-22 ForgeFlow S.L. (www.forgeflow.com) +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). + +from odoo.tests import common + + +class TestAccountMoveLineRmaOrderLine(common.TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.rma_model = cls.env["rma.order"] + cls.rma_line_model = cls.env["rma.order.line"] + cls.rma_refund_wiz = cls.env["rma.refund"] + cls.rma_add_stock_move = cls.env["rma_add_stock_move"] + cls.rma_make_picking = cls.env["rma_make_picking.wizard"] + cls.invoice_model = cls.env["account.move"] + cls.stock_picking_model = cls.env["stock.picking"] + cls.invoice_line_model = cls.env["account.move.line"] + cls.product_model = cls.env["product.product"] + cls.product_ctg_model = cls.env["product.category"] + cls.account_model = cls.env["account.account"] + cls.aml_model = cls.env["account.move.line"] + cls.res_users_model = cls.env["res.users"] + + cls.partner1 = cls.env.ref("base.res_partner_1") + cls.location_stock = cls.env.ref("stock.stock_location_stock") + cls.company = cls.env.ref("base.main_company") + cls.group_rma_user = cls.env.ref("rma.group_rma_customer_user") + cls.group_account_invoice = cls.env.ref("account.group_account_invoice") + cls.group_account_manager = cls.env.ref("account.group_account_manager") + cls.stock_location = cls.env.ref("stock.stock_location_stock") + wh = cls.env.ref("stock.warehouse0") + cls.stock_rma_location = wh.lot_rma_id + cls.customer_location = cls.env.ref("stock.stock_location_customers") + cls.supplier_location = cls.env.ref("stock.stock_location_suppliers") + # Create account for Goods Received Not Invoiced + name = "Goods Received Not Invoiced" + code = "grni" + cls.account_grni = cls._create_account("equity", name, code, cls.company) + + # Create account for Cost of Goods Sold + name = "Goods Delivered Not Invoiced" + code = "gdni" + cls.account_cogs = cls._create_account("expense", name, code, cls.company) + # Create account for Inventory + name = "Inventory" + code = "inventory" + cls.account_inventory = cls._create_account( + "asset_current", name, code, cls.company + ) # TODO: poner asset de inventario + # Create Product + cls.product = cls._create_product() + cls.product_uom_id = cls.env.ref("uom.product_uom_unit") + # Create users + cls.rma_user = cls._create_user( + "rma_user", [cls.group_rma_user, cls.group_account_invoice], cls.company + ) + cls.account_invoice = cls._create_user( + "account_invoice", [cls.group_account_invoice], cls.company + ) + cls.account_manager = cls._create_user( + "account_manager", [cls.group_account_manager], cls.company + ) + + @classmethod + def _create_user(cls, login, groups, company): + """Create a user.""" + group_ids = [group.id for group in groups] + user = cls.res_users_model.with_context(**{"no_reset_password": True}).create( + { + "name": "Test User", + "login": login, + "password": "demo", + "email": "test@yourcompany.com", + "company_id": company.id, + "company_ids": [(4, company.id)], + "groups_id": [(6, 0, group_ids)], + } + ) + return user.id + + @classmethod + def _create_account(cls, acc_type, name, code, company, reconcile=False): + """Create an account.""" + account = cls.account_model.create( + { + "name": name, + "code": code, + "account_type": acc_type, + "company_ids": [(4, company.id)], + "reconcile": reconcile, + } + ) + return account + + @classmethod + def _create_product(cls): + """Create a Product.""" + # group_ids = [group.id for group in groups] + product_ctg = cls.product_ctg_model.create( + { + "name": "test_product_ctg", + "property_stock_valuation_account_id": cls.account_inventory.id, + "property_valuation": "real_time", + "property_stock_account_input_categ_id": cls.account_grni.id, + "property_stock_account_output_categ_id": cls.account_cogs.id, + } + ) + product = cls.product_model.create( + { + "name": "test_product", + "categ_id": product_ctg.id, + "is_storable": True, + "standard_price": 1.0, + "list_price": 1.0, + } + ) + return product + + @classmethod + def _create_picking(cls, partner): + return cls.stock_picking_model.create( + { + "partner_id": partner.id, + "picking_type_id": cls.env.ref("stock.picking_type_in").id, + "location_id": cls.stock_location.id, + "location_dest_id": cls.supplier_location.id, + } + ) + + @classmethod + def _prepare_move(cls, product, qty, src, dest, picking_in): + res = { + "partner_id": cls.partner1.id, + "product_id": product.id, + "name": product.partner_ref, + "state": "confirmed", + "product_uom": cls.product_uom_id.id or product.uom_id.id, + "product_uom_qty": qty, + "origin": "Test RMA", + "location_id": src.id, + "location_dest_id": dest.id, + "picking_id": picking_in.id, + } + return res + + @classmethod + def _create_rma(cls, products2move, partner): + picking_in = cls._create_picking(partner) + moves = [] + for item in products2move: + move_values = cls._prepare_move( + item[0], item[1], cls.stock_location, cls.customer_location, picking_in + ) + moves.append(cls.env["stock.move"].create(move_values)) + + rma_id = cls.rma_model.create( + { + "reference": "0001", + "type": "customer", + "partner_id": partner.id, + "company_id": cls.env.ref("base.main_company").id, + } + ) + for move in moves: + wizard = cls.rma_add_stock_move.new( + { + "move_ids": [(6, 0, move.ids)], + "rma_id": rma_id.id, + "partner_id": move.partner_id.id, + } + ) + # data = wizard._prepare_rma_line_from_stock_move(move) + wizard.add_lines() + + # CHECK ME: this code duplicate rma lines, what is the porpourse? + # if move.product_id.rma_customer_operation_id: + # move.product_id.rma_customer_operation_id.in_route_id = False + # move.product_id.categ_id.rma_customer_operation_id = False + # move.product_id.rma_customer_operation_id = False + # wizard._prepare_rma_line_from_stock_move(move) + # cls.line = cls.rma_line_model.create(data) + return rma_id + + def _get_balance(self, domain): + """ + Call read_group method and return the balance of particular account. + """ + aml_rec = self.aml_model.read_group( + domain, ["debit", "credit", "account_id"], ["account_id"] + ) + if aml_rec: + return aml_rec[0].get("debit", 0) - aml_rec[0].get("credit", 0) + else: + return 0.0 + + def _check_account_balance(self, account_id, rma_line=None, expected_balance=0.0): + """ + Check the balance of the account + """ + domain = [("account_id", "=", account_id)] + if rma_line: + domain.extend([("rma_line_id", "=", rma_line.id)]) + + balance = self._get_balance(domain) + if rma_line: + self.assertEqual( + balance, + expected_balance, + f"Balance is not {str(expected_balance)} for rma Line {rma_line.name}.", + ) + + def test_rma_invoice(self): + """Test that the rma line moves from the rma order to the + account move line and to the invoice line. + """ + products2move = [ + (self.product, 1), + ] + rma = self._create_rma(products2move, self.partner1) + rma_line = rma.rma_line_ids + for rma in rma_line: + if rma.price_unit == 0: + rma.price_unit = 1.0 + rma_line.action_rma_approve() + wizard = self.rma_make_picking.with_context( + **{ + "active_id": 1, + "active_ids": rma_line.ids, + "active_model": "rma.order.line", + "picking_type": "incoming", + } + ).create({}) + operation = self.env["rma.operation"].search( + [("type", "=", "customer"), ("refund_policy", "=", "received")], limit=1 + ) + rma_line.write({"operation_id": operation.id}) + rma_line.write({"refund_policy": "received"}) + + wizard._create_picking() + res = rma_line.action_view_in_shipments() + if "res_id" in res: + picking = self.env["stock.picking"].browse(res["res_id"]) + else: + picking_ids = self.env["stock.picking"].search(res["domain"]) + picking = self.env["stock.picking"].browse(picking_ids) + # picking.move_line_ids.write({"qty_done": 1.0}) + picking.button_validate() + # decreasing cogs + expected_balance = -1.0 + for record in rma_line: + self._check_account_balance( + self.account_cogs.id, rma_line=record, expected_balance=expected_balance + ) + make_refund = self.rma_refund_wiz.with_context( + **{ + "customer": True, + "active_ids": rma_line.ids, + "active_model": "rma.order.line", + } + ).create( + { + "description": "Test refund", + } + ) + for item in make_refund.item_ids: + item.write( + { + "qty_to_refund": 1.0, + } + ) + make_refund.invoice_refund() + rma_line.refund_line_ids.move_id.filtered( + lambda x: x.state != "posted" + ).action_post() + for aml in rma_line.refund_line_ids.move_id.invoice_line_ids: + if aml.product_id == rma_line.product_id and aml.move_id: + self.assertEqual( + aml.rma_line_id, + rma_line, + "Rma Order line has not been copied from the invoice to " + "the account move line.", + ) diff --git a/rma_account/tests/test_rma_account.py b/rma_account/tests/test_rma_account.py new file mode 100644 index 000000000..57bb23ff2 --- /dev/null +++ b/rma_account/tests/test_rma_account.py @@ -0,0 +1,304 @@ +# Copyright 2017-22 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import fields +from odoo.fields import Date +from odoo.tests import Form, common + + +class TestRmaAccount(common.SingleTransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + + cls.rma_obj = cls.env["rma.order"] + cls.rma_line_obj = cls.env["rma.order.line"] + cls.rma_op_obj = cls.env["rma.operation"] + cls.rma_add_invoice_wiz = cls.env["rma_add_account_move"] + cls.rma_refund_wiz = cls.env["rma.refund"] + cls.acc_obj = cls.env["account.account"] + cls.inv_obj = cls.env["account.move"] + cls.invl_obj = cls.env["account.move.line"] + cls.product_obj = cls.env["product.product"] + customer1_obj = cls.env["res.partner"] + + cls.rma_route_cust = cls.env.ref("rma.route_rma_customer") + cls.cust_refund_op = cls.env.ref("rma_account.rma_operation_customer_refund") + cls.sup_refund_op = cls.env.ref("rma_account.rma_operation_supplier_refund") + cls.company_id = cls.env.user.company_id + + # Create partners + customer1 = customer1_obj.create({"name": "Customer 1"}) + supplier1 = customer1_obj.create({"name": "Supplier 1"}) + + # Create Journal + cls.journal_sale = cls.env["account.journal"].create( + { + "name": "Test Sales Journal", + "code": "tSAL", + "type": "sale", + "company_id": cls.company_id.id, + } + ) + + # Create RMA group and operation: + cls.rma_group_customer = cls.rma_obj.create( + {"partner_id": customer1.id, "type": "customer"} + ) + cls.rma_group_customer_2 = cls.rma_obj.create( + {"partner_id": customer1.id, "type": "customer"} + ) + cls.rma_group_supplier = cls.rma_obj.create( + {"partner_id": supplier1.id, "type": "supplier"} + ) + cls.operation_1 = cls.rma_op_obj.create( + { + "code": "TEST", + "name": "Refund and receive", + "type": "customer", + "receipt_policy": "ordered", + "refund_policy": "ordered", + "in_route_id": cls.rma_route_cust.id, + "out_route_id": cls.rma_route_cust.id, + } + ) + + # Create products + cls.product_1 = cls.product_obj.create( + { + "name": "Test Product 1", + "is_storable": True, + "list_price": 100.0, + "rma_customer_operation_id": cls.cust_refund_op.id, + "rma_supplier_operation_id": cls.sup_refund_op.id, + } + ) + cls.product_2 = cls.product_obj.create( + { + "name": "Test Product 2", + "is_storable": True, + "list_price": 150.0, + "rma_customer_operation_id": cls.operation_1.id, + "rma_supplier_operation_id": cls.sup_refund_op.id, + } + ) + cls.currency_id = cls.company_id.currency_id + + # Create Invoices: + cls.customer_account = cls.acc_obj.search( + [("account_type", "=", "asset_receivable")], limit=1 + ).id + + cls.invoices = cls.env["account.move"].create( + [ + { + "move_type": "out_invoice", + "partner_id": customer1.id, + "invoice_date": fields.Date.from_string("2016-01-01"), + "currency_id": cls.currency_id.id, + "invoice_line_ids": [ + ( + 0, + None, + { + "product_id": cls.product_1.id, + "product_uom_id": cls.product_1.uom_id.id, + "quantity": 3, + "price_unit": 1000, + }, + ), + ( + 0, + None, + { + "product_id": cls.product_2.id, + "product_uom_id": cls.product_2.uom_id.id, + "quantity": 2, + "price_unit": 3000, + }, + ), + ], + }, + { + "move_type": "in_invoice", + "partner_id": supplier1.id, + "invoice_date": fields.Date.from_string("2016-01-01"), + "currency_id": cls.currency_id.id, + "invoice_line_ids": [ + ( + 0, + None, + { + "product_id": cls.product_1.id, + "product_uom_id": cls.product_1.uom_id.id, + "quantity": 3, + "price_unit": 1000, + }, + ), + ( + 0, + None, + { + "product_id": cls.product_2.id, + "product_uom_id": cls.product_2.uom_id.id, + "quantity": 2, + "price_unit": 3000, + }, + ), + ], + }, + ] + ) + cls.inv_customer = cls.invoices[0] + cls.inv_supplier = cls.invoices[1] + + def test_01_add_from_invoice_customer(self): + """Test wizard to create RMA from a customer invoice.""" + add_inv = self.rma_add_invoice_wiz.with_context( + **{ + "customer": True, + "active_ids": self.rma_group_customer.id, + "active_model": "rma.order", + } + ).create({"line_ids": [(6, 0, self.inv_customer.invoice_line_ids.ids)]}) + add_inv.add_lines() + + self.assertEqual(len(self.rma_group_customer.rma_line_ids), 2) + for t in self.rma_group_supplier.rma_line_ids.mapped("type"): + self.assertEqual(t, "customer") + rma_1 = self.rma_group_customer.rma_line_ids.filtered( + lambda r: r.product_id == self.product_1 + ) + self.assertEqual(rma_1.operation_id, self.cust_refund_op) + rma_2 = self.rma_group_customer.rma_line_ids.filtered( + lambda r: r.product_id == self.product_2 + ) + self.assertEqual(rma_2.operation_id, self.operation_1) + + def test_02_add_from_invoice_supplier(self): + """Test wizard to create RMA from a vendor bill.""" + add_inv = self.rma_add_invoice_wiz.with_context( + **{ + "supplier": True, + "active_ids": self.rma_group_supplier.id, + "active_model": "rma.order", + } + ).create({"line_ids": [(6, 0, self.inv_supplier.line_ids.ids)]}) + add_inv.add_lines() + self.assertEqual(len(self.rma_group_supplier.rma_line_ids), 2) + for t in self.rma_group_supplier.rma_line_ids.mapped("type"): + self.assertEqual(t, "supplier") + + def test_03_rma_refund_operation(self): + """Test RMA quantities using refund operations.""" + # Received refund_policy: + rma_1 = self.rma_group_customer.rma_line_ids.filtered( + lambda r: r.product_id == self.product_1 + ) + self.assertEqual(rma_1.refund_policy, "received") + self.assertEqual(rma_1.qty_to_refund, 0.0) + # TODO: receive and check qty_to_refund is 12.0 + # Ordered refund_policy: + rma_2 = self.rma_group_customer.rma_line_ids.filtered( + lambda r: r.product_id == self.product_2 + ) + rma_2._onchange_operation_id() + self.assertEqual(rma_2.refund_policy, "ordered") + self.assertEqual(rma_2.qty_to_refund, 2.0) + + def test_04_rma_create_refund(self): + """Generate a Refund from a customer RMA.""" + rma = self.rma_group_customer.rma_line_ids.filtered( + lambda r: r.product_id == self.product_2 + ) + rma.action_rma_to_approve() + rma.action_rma_approve() + self.assertEqual(rma.refund_count, 0) + self.assertEqual(rma.qty_to_refund, 2.0) + self.assertEqual(rma.qty_refunded, 0.0) + make_refund = self.rma_refund_wiz.with_context( + **{ + "customer": True, + "active_ids": rma.ids, + "active_model": "rma.order.line", + } + ).create({"description": "Test refund"}) + make_refund.invoice_refund() + rma.refund_line_ids.move_id.action_post() + rma._compute_refund_count() + self.assertEqual(rma.refund_count, 1) + self.assertEqual(rma.qty_to_refund, 0.0) + self.assertEqual(rma.qty_refunded, 2.0) + + def test_05_fill_rma_from_supplier_inv_line(self): + """Test filling a RMA (line) from a invoice line.""" + with Form( + self.rma_line_obj.with_context(default_type="supplier"), + view="rma_account.view_rma_line_supplier_form", + ) as rma_line_form: + rma_line_form.partner_id = self.inv_supplier.partner_id + rma_line_form.account_move_line_id = self.inv_supplier.line_ids[0] + rma = rma_line_form.save() + self.assertEqual(rma.product_id, self.product_1) + self.assertEqual(rma.product_qty, 3.0) + # Remember that the test is SingleTransactionCase. + # This supplier invoice has been referenced in 3 RMA lines. + self.assertEqual(self.inv_supplier.used_in_rma_count, 3) + self.assertEqual(self.inv_supplier.rma_count, 0) + + def test_06_default_journal(self): + self.operation_1.write({"refund_journal_id": self.journal_sale.id}) + add_inv = self.rma_add_invoice_wiz.with_context( + **{ + "customer": True, + "active_ids": self.rma_group_customer_2.id, + "active_model": "rma.order", + } + ).create({"line_ids": [(6, 0, self.inv_customer.invoice_line_ids.ids)]}) + add_inv.add_lines() + rma = self.rma_group_customer_2.rma_line_ids.filtered( + lambda r: r.product_id == self.product_2 + ) + rma.action_rma_to_approve() + rma.action_rma_approve() + make_refund = self.rma_refund_wiz.with_context( + **{ + "customer": True, + "active_ids": rma.ids, + "active_model": "rma.order.line", + } + ).create({"description": "Test refund"}) + make_refund.invoice_refund() + rma.refund_line_ids.move_id.action_post() + rma._compute_refund_count() + self.assertEqual( + self.operation_1.refund_journal_id, rma.refund_line_ids.journal_id + ) + + def test_07_add_lines_from_rma(self): + """Test adding line from rma to supplier refund""" + add_inv = self.rma_add_invoice_wiz.with_context( + **{ + "supplier": True, + "active_ids": self.rma_group_supplier.id, + "active_model": "rma.order", + } + ).create({"line_ids": [(6, 0, self.inv_supplier.line_ids.ids)]}) + add_inv.add_lines() + rma_1 = self.rma_group_supplier.rma_line_ids.filtered( + lambda r: r.product_id == self.product_1 + ) + with Form( + self.env["account.move"].with_context(default_move_type="in_refund") + ) as bill_form: + bill_form.partner_id = rma_1.partner_id + bill_form.invoice_date = Date.today() + bill_form.add_rma_line_id = rma_1 + bill = bill_form.save() + bill.action_post() + bill_product = bill.invoice_line_ids.filtered( + lambda x: x.product_id == self.product_1 + ).mapped("product_id") + self.assertEqual(rma_1.product_id.id, bill_product.id) + self.assertEqual(bill.rma_count, 1) + self.assertEqual(bill.used_in_rma_count, 0) diff --git a/rma_account/tests/test_rma_stock_account.py b/rma_account/tests/test_rma_stock_account.py new file mode 100644 index 000000000..039ad5fb3 --- /dev/null +++ b/rma_account/tests/test_rma_stock_account.py @@ -0,0 +1,355 @@ +# Copyright 2017-22 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo.tests import Form + +# pylint: disable=odoo-addons-relative-import +from odoo.addons.rma.tests.test_rma import TestRma + + +class TestRmaStockAccount(TestRma): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.account_model = cls.env["account.account"] + cls.g_account_user = cls.env.ref("account.group_account_user") + cls.rma_refund_wiz = cls.env["rma.refund"] + # we create new products to ensure previous layers do not affect when + # running FIFO + cls.product_fifo_1 = cls._create_product("product_fifo1") + cls.product_fifo_2 = cls._create_product("product_fifo2") + cls.product_fifo_3 = cls._create_product("product_fifo3") + # Refs + cls.rma_operation_customer_refund_id = cls.env.ref( + "rma_account.rma_operation_customer_refund" + ) + cls.rma_basic_user.write({"groups_id": [(4, cls.g_account_user.id)]}) + cls.customer_route = cls.env.ref("rma.route_rma_customer") + cls.input_location = cls.env.ref("stock.stock_location_company") + cls.output_location = cls.env.ref("stock.stock_location_output") + # The product category created in the base module is not automated valuation + # we have to create a new category here + # Create account for Goods Received Not Invoiced + name = "Goods Received Not Invoiced" + code = "grni" + cls.account_grni = cls._create_account("equity", name, code, cls.company, True) + # Create account for Goods Delievered + name = "Goods Delivered Not Invoiced" + code = "gdni" + cls.account_gdni = cls._create_account( + "asset_current", name, code, cls.company, True + ) + # Create account for Inventory + name = "Inventory" + code = "inventory" + cls.account_inventory = cls._create_account( + "asset_current", name, code, cls.company, False + ) + product_ctg = cls.product_ctg_model.create( + { + "name": "test_product_ctg", + "property_stock_valuation_account_id": cls.account_inventory.id, + "property_valuation": "real_time", + "property_stock_account_input_categ_id": cls.account_grni.id, + "property_stock_account_output_categ_id": cls.account_gdni.id, + "rma_approval_policy": "one_step", + "rma_customer_operation_id": cls.rma_operation_customer_refund_id.id, + "rma_supplier_operation_id": cls.rma_sup_replace_op_id.id, + "property_cost_method": "fifo", + } + ) + # We use FIFO to test the cost is taken from the original layers + cls.product_fifo_1.categ_id = product_ctg + cls.product_fifo_2.categ_id = product_ctg + cls.product_fifo_3.categ_id = product_ctg + + @classmethod + def _create_account(cls, acc_type, name, code, company, reconcile): + """Create an account.""" + account = cls.account_model.create( + { + "name": name, + "code": code, + "account_type": acc_type, + "company_ids": [(4, company.id)], + "reconcile": reconcile, + } + ) + return account + + def check_accounts_used( + self, account_move, debit_account=False, credit_account=False + ): + debit_line = account_move.mapped("line_ids").filtered(lambda line: line.debit) + credit_line = account_move.mapped("line_ids").filtered(lambda line: line.credit) + if debit_account: + self.assertEqual(debit_line.account_id[0].code, debit_account) + if credit_account: + self.assertEqual(credit_line.account_id[0].code, credit_account) + + def test_01_cost_from_standard(self): + """ + Test the price unit is taken from the standard cost when there is no reference + """ + self.product_fifo_1.standard_price = 15 + rma_line = Form(self.rma_line.with_user(self.rma_basic_user)) + rma_line.partner_id = self.partner_id + rma_line.product_id = self.product_fifo_1 + rma_line.price_unit = 1234 + rma_line = rma_line.save() + rma_line.action_rma_to_approve() + picking = self._receive_rma(rma_line) + self.assertEqual( + picking.move_line_ids.move_id.stock_valuation_layer_ids.value, 15.0 + ) + account_move = ( + picking.move_line_ids.move_id.stock_valuation_layer_ids.account_move_id + ) + self.check_accounts_used( + account_move, debit_account="inventory", credit_account="gdni" + ) + + def test_02_cost_from_move(self): + """ + Test the price unit is taken from the cost of the stock move when the + reference is the stock move + """ + # Set a standard price on the products + self.product_fifo_1.standard_price = 10 + self.product_fifo_2.standard_price = 20 + self.product_fifo_3.standard_price = 30 + self._create_inventory( + self.product_fifo_1, 20.0, self.env.ref("stock.stock_location_customers") + ) + products2move = [ + (self.product_fifo_1, 3), + (self.product_fifo_2, 5), + (self.product_fifo_3, 2), + ] + rma_customer_id = self._create_rma_from_move( + products2move, + "customer", + self.env.ref("base.res_partner_2"), + dropship=False, + ) + # Set an incorrect price in the RMA (this should not affect cost) + rma_lines = rma_customer_id.rma_line_ids + rma_lines.price_unit = 999 + rma_lines.action_rma_to_approve() + picking = self._receive_rma(rma_customer_id.rma_line_ids) + # Test the value in the layers of the incoming stock move is used + for rma_line in rma_customer_id.rma_line_ids: + value_origin = rma_line.reference_move_id.stock_valuation_layer_ids.value + move_product = picking.move_line_ids.filtered( + lambda line, rma_line=rma_line: line.product_id == rma_line.product_id + ) + value_used = move_product.move_id.stock_valuation_layer_ids.value + self.assertEqual(value_used, -value_origin) + # Create a refund for the first line + rma = rma_lines[0] + make_refund = self.rma_refund_wiz.with_context( + **{ + "customer": True, + "active_ids": rma.ids, + "active_model": "rma.order.line", + } + ).create({"description": "Test refund"}) + make_refund.item_ids.qty_to_refund = 1 + make_refund.invoice_refund() + rma.refund_line_ids.move_id.action_post() + rma._compute_refund_count() + gdni_amls = rma.refund_line_ids.move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + gdni_amls |= ( + rma.move_ids.stock_valuation_layer_ids.account_move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + ) + gdni_balance = sum(gdni_amls.mapped("balance")) + # When we received we Credited to GDNI 30 + # When we refund we Debit to GDNI 10 + self.assertEqual(gdni_balance, -20.0) + make_refund = self.rma_refund_wiz.with_context( + **{ + "customer": True, + "active_ids": rma.ids, + "active_model": "rma.order.line", + } + ).create({"description": "Test refund"}) + make_refund.item_ids.qty_to_refund = 2 + make_refund.invoice_refund() + rma.refund_line_ids.move_id.filtered( + lambda m: m.state != "posted" + ).action_post() + rma._compute_refund_count() + gdni_amls = rma.refund_line_ids.move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + gdni_amls |= ( + rma.move_ids.stock_valuation_layer_ids.account_move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + ) + gdni_balance = sum(gdni_amls.mapped("balance")) + # When we received we Credited to GDNI 30 + # When we refund we Debit to GDNI 30 + self.assertEqual(gdni_balance, 0.0) + # Ensure that the GDNI move lines are all reconciled + self.assertEqual(all(gdni_amls.mapped("reconciled")), True) + + def test_03_cost_from_move(self): + """ + Receive a product and then return it. The Goods Delivered Not Invoiced + should result in 0 + """ + # Set a standard price on the products + self.product_fifo_1.standard_price = 10 + self._create_inventory( + self.product_fifo_1, 20.0, self.env.ref("stock.stock_location_customers") + ) + products2move = [ + (self.product_fifo_1, 3), + ] + self.product_fifo_1.categ_id.rma_customer_operation_id = ( + self.rma_cust_replace_op_id + ) + rma_customer_id = self._create_rma_from_move( + products2move, + "customer", + self.env.ref("base.res_partner_2"), + dropship=False, + ) + # Set an incorrect price in the RMA (this should not affect cost) + rma = rma_customer_id.rma_line_ids + rma.price_unit = 999 + rma.action_rma_to_approve() + self._receive_rma(rma_customer_id.rma_line_ids) + gdni_amls = ( + rma.move_ids.stock_valuation_layer_ids.account_move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + ) + gdni_balance = sum(gdni_amls.mapped("balance")) + self.assertEqual(len(gdni_amls), 1) + # Balance should be -30, as we have only received + self.assertEqual(gdni_balance, -30.0) + self._deliver_rma(rma_customer_id.rma_line_ids) + gdni_amls = ( + rma.move_ids.stock_valuation_layer_ids.account_move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + ) + gdni_balance = sum(gdni_amls.mapped("balance")) + self.assertEqual(len(gdni_amls), 2) + # Balance should be 0, as we have received and shipped + self.assertEqual(gdni_balance, 0.0) + # The GDNI entries should be now reconciled + self.assertEqual(all(gdni_amls.mapped("reconciled")), True) + + def test_08_cost_from_move_multi_step(self): + """ + Receive a product and then return it using a multi-step route. + The Goods Delivered Not Invoiced should result in 0 + """ + # Alter the customer RMA route to make it multi-step + # Get rid of the duplicated rule + self.env.ref("rma.rule_rma_customer_out_pull").active = False + self.env.ref("rma.rule_rma_customer_in_pull").active = False + cust_in_pull_rule = self.customer_route.rule_ids.filtered( + lambda r: r.location_dest_id == self.stock_rma_location + ) + cust_in_pull_rule.location_dest_id = self.input_location + cust_out_pull_rule = self.customer_route.rule_ids.filtered( + lambda r: r.location_src_id == self.env.ref("rma.location_rma") + ) + cust_out_pull_rule.location_src_id = self.output_location + cust_out_pull_rule.procure_method = "make_to_order" + self.env["stock.rule"].create( + { + "name": "RMA->Output", + "action": "pull", + "warehouse_id": self.wh.id, + "location_src_id": self.env.ref("rma.location_rma").id, + "location_dest_id": self.output_location.id, + "procure_method": "make_to_stock", + "route_id": self.customer_route.id, + "picking_type_id": self.env.ref("stock.picking_type_internal").id, + } + ) + self.env["stock.rule"].create( + { + "name": "Customers->RMA", + "action": "pull", + "warehouse_id": self.wh.id, + "location_src_id": self.customer_location.id, + "location_dest_id": self.env.ref("rma.location_rma").id, + "procure_method": "make_to_order", + "route_id": self.customer_route.id, + "picking_type_id": self.env.ref("stock.picking_type_in").id, + } + ) + # Set a standard price on the products + self.product_fifo_1.standard_price = 10 + self._create_inventory( + self.product_fifo_1, 20.0, self.env.ref("stock.stock_location_customers") + ) + products2move = [ + (self.product_fifo_1, 3), + ] + self.product_fifo_1.categ_id.rma_customer_operation_id = ( + self.rma_cust_replace_op_id + ) + rma_customer_id = self._create_rma_from_move( + products2move, + "customer", + self.env.ref("base.res_partner_2"), + dropship=False, + ) + # Set an incorrect price in the RMA (this should not affect cost) + rma = rma_customer_id.rma_line_ids + rma.price_unit = 999 + rma.action_rma_to_approve() + self._receive_rma(rma) + layers = rma.move_ids.sudo().stock_valuation_layer_ids + gdni_amls = layers.account_move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + gdni_balance = sum(gdni_amls.mapped("balance")) + self.assertEqual(len(gdni_amls), 1) + # Balance should be -30, as we have only received + self.assertEqual(gdni_balance, -30.0) + self._deliver_rma(rma) + layers = rma.move_ids.sudo().stock_valuation_layer_ids + gdni_amls = layers.account_move_id.line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + gdni_balance = sum(gdni_amls.mapped("balance")) + self.assertEqual(len(gdni_amls), 2) + # Balance should be 0, as we have received and shipped + self.assertEqual(gdni_balance, 0.0) + # The GDNI entries should be now reconciled + self.assertEqual(all(gdni_amls.mapped("reconciled")), True) + + def test_05_reconcile_grni_when_no_refund(self): + """ + Test that receive and send a replacement order leaves GDNI reconciled + """ + self.product_fifo_1.standard_price = 15 + rma_line = Form(self.rma_line) + rma_line.partner_id = self.partner_id + rma_line.product_id = self.product_fifo_1 + rma_line.operation_id.automated_refund = True + rma_line = rma_line.save() + rma_line.action_rma_to_approve() + # receiving should trigger the refund at zero cost + self._receive_rma(rma_line) + gdni_amls = self.env["account.move.line"].search( + [ + ("rma_line_id", "in", rma_line.ids), + ("account_id", "=", self.account_gdni.id), + ] + ) + rma_line.refund_line_ids.filtered( + lambda line: line.account_id == self.account_gdni + ) + self.assertEqual(all(gdni_amls.mapped("reconciled")), True) diff --git a/rma_account/views/account_move_view.xml b/rma_account/views/account_move_view.xml new file mode 100644 index 000000000..1c538794f --- /dev/null +++ b/rma_account/views/account_move_view.xml @@ -0,0 +1,96 @@ + + + + account.move.form + account.move + + +
+ + +
+ + + + + + + +
+
+ + + rma.invoice.line.form + account.move.line + + + + + + + + + + + + + + + + + + + + + + + + account.move.supplier.rma + account.move + + + + + + + + + + Invoice Line + account.move.line + form + + +
diff --git a/rma_account/views/rma_account_menu.xml b/rma_account/views/rma_account_menu.xml new file mode 100644 index 000000000..0af37f2a6 --- /dev/null +++ b/rma_account/views/rma_account_menu.xml @@ -0,0 +1,69 @@ + + + + + + Customer RMA + rma.order.line + [('type','=', 'customer')] + {"search_default_to_refund":1} + list,form + + + + Supplier RMA + rma.order.line + [('type','=', 'supplier')] + {"search_default_to_refund":1, "supplier":1} + list,form + + + + + + + + + + + + + + + + diff --git a/rma_account/views/rma_operation_view.xml b/rma_account/views/rma_operation_view.xml new file mode 100644 index 000000000..70f3bb06f --- /dev/null +++ b/rma_account/views/rma_operation_view.xml @@ -0,0 +1,30 @@ + + + + rma.operation.list + rma.operation + + + + + + + + + + rma.operation.form + rma.operation + + + + + + + + + + + + + + diff --git a/rma_account/views/rma_order_line_view.xml b/rma_account/views/rma_order_line_view.xml new file mode 100644 index 000000000..e1d8b1935 --- /dev/null +++ b/rma_account/views/rma_order_line_view.xml @@ -0,0 +1,100 @@ + + + + rma.order.line.supplier.form + rma.order.line + + + + + + + + + + + rma.order.line.form + rma.order.line + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + rma.order.line.select + rma.order.line + + + + + + + + + + diff --git a/rma_account/views/rma_order_view.xml b/rma_account/views/rma_order_view.xml new file mode 100644 index 000000000..669785189 --- /dev/null +++ b/rma_account/views/rma_order_view.xml @@ -0,0 +1,38 @@ + + + + rma.order.form - rma_account + rma.order + + + + + + + + + + + + diff --git a/rma_account/wizards/__init__.py b/rma_account/wizards/__init__.py new file mode 100644 index 000000000..52d1defb8 --- /dev/null +++ b/rma_account/wizards/__init__.py @@ -0,0 +1,6 @@ +# Copyright 2017 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from . import rma_refund +from . import rma_add_account_move +from . import rma_order_line_make_supplier_rma diff --git a/rma_account/wizards/rma_add_account_move.py b/rma_account/wizards/rma_add_account_move.py new file mode 100644 index 000000000..8ab574a4f --- /dev/null +++ b/rma_account/wizards/rma_add_account_move.py @@ -0,0 +1,141 @@ +# Copyright 2017 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import _, api, fields, models +from odoo.exceptions import ValidationError + + +class RmaAddAccountMove(models.TransientModel): + _name = "rma_add_account_move" + _description = "Wizard to add rma lines" + + @api.model + def default_get(self, fields_list): + res = super().default_get(fields_list) + rma_obj = self.env["rma.order"] + rma_id = self.env.context["active_ids"] or [] + active_model = self.env.context["active_model"] + if not rma_id: + return res + assert active_model == "rma.order", "Bad context propagation" + rma = rma_obj.browse(rma_id) + res["rma_id"] = rma.id + res["partner_id"] = rma.partner_id.id + res["line_ids"] = False + return res + + rma_id = fields.Many2one( + "rma.order", string="RMA Order", readonly=True, ondelete="cascade" + ) + partner_id = fields.Many2one( + comodel_name="res.partner", string="Partner", readonly=True + ) + line_ids = fields.Many2many( + "account.move.line", + "rma_add_account_move_add_line_rel", + "account_move_line_id", + "rma_add_move_id", + string="Invoice Lines", + ) + + def _prepare_rma_line_from_inv_line(self, line): + if self.env.context.get("customer"): + operation = ( + line.product_id.rma_customer_operation_id + or line.product_id.categ_id.rma_customer_operation_id + ) + else: + operation = ( + line.product_id.rma_supplier_operation_id + or line.product_id.categ_id.rma_supplier_operation_id + ) + if not operation: + operation = self.env["rma.operation"].search( + [("type", "=", self.rma_id.type)], limit=1 + ) + if not operation: + raise ValidationError(_("Please define an operation first")) + if not operation.in_route_id or not operation.out_route_id: + route = self.env["stock.location.route"].search( + [("rma_selectable", "=", True)], limit=1 + ) + if not route: + raise ValidationError(_("Please define an rma route")) + + if not operation.in_warehouse_id or not operation.out_warehouse_id: + warehouse = self.env["stock.warehouse"].search( + [ + ("company_id", "=", self.rma_id.company_id.id), + ("lot_rma_id", "!=", False), + ], + limit=1, + ) + if not warehouse: + raise ValidationError( + _("Please define a warehouse with a" " default rma location") + ) + data = { + "partner_id": self.partner_id.id, + "account_move_line_id": line.id, + "product_id": line.product_id.id, + "origin": line.move_id.name, + "uom_id": line.product_uom_id.id, + "operation_id": operation.id, + "product_qty": line.quantity, + "price_unit": line.move_id.currency_id._convert( + line.price_unit, + line.currency_id, + line.company_id, + line.date, + round=False, + ), + "delivery_address_id": line.move_id.partner_shipping_id.id + if line.move_id.partner_shipping_id + else line.move_id.partner_id.id, + "invoice_address_id": line.move_id.partner_id.id, + "rma_id": self.rma_id.id, + "receipt_policy": operation.receipt_policy, + "refund_policy": operation.refund_policy, + "delivery_policy": operation.delivery_policy, + "in_warehouse_id": operation.in_warehouse_id.id or warehouse.id, + "out_warehouse_id": operation.out_warehouse_id.id or warehouse.id, + "in_route_id": operation.in_route_id.id or route.id, + "out_route_id": operation.out_route_id.id or route.id, + "location_id": ( + operation.location_id.id + or operation.in_warehouse_id.lot_rma_id.id + or warehouse.lot_rma_id.id + ), + } + return data + + @api.model + def _get_rma_data(self): + data = {"date_rma": fields.Datetime.now()} + return data + + @api.model + def _get_existing_invoice_lines(self): + existing_invoice_lines = [] + for rma_line in self.rma_id.rma_line_ids: + existing_invoice_lines.append(rma_line.account_move_line_id) + return existing_invoice_lines + + def add_lines(self): + rma_line_obj = self.env["rma.order.line"] + existing_invoice_lines = self._get_existing_invoice_lines() + for line in self.line_ids.filtered(lambda aml: aml.display_type == "product"): + # Load a PO line only once + if line not in existing_invoice_lines: + data = self._prepare_rma_line_from_inv_line(line) + rec = rma_line_obj.create(data) + # Ensure that configuration on the operation is applied (like + # policies). + # TODO MIG: in v16 the usage of such onchange can be removed in + # favor of (pre)computed stored editable fields for all policies + # and configuration in the RMA operation. + rec._onchange_operation_id() + rma = self.rma_id + data_rma = self._get_rma_data() + rma.write(data_rma) + return {"type": "ir.actions.act_window_close"} diff --git a/rma_account/wizards/rma_add_account_move.xml b/rma_account/wizards/rma_add_account_move.xml new file mode 100644 index 000000000..a949d56da --- /dev/null +++ b/rma_account/wizards/rma_add_account_move.xml @@ -0,0 +1,96 @@ + + + + + rma.add.invoice + rma_add_account_move + +
+ + + + + + + + + + + + + + + + + + +
+
+ +
+
+ + + rma.add.invoice.supplier + rma_add_account_move + +
+ + + + + + + + + + + + + + + + + + +
+
+ +
+
+ +
diff --git a/rma_account/wizards/rma_order_line_make_supplier_rma.py b/rma_account/wizards/rma_order_line_make_supplier_rma.py new file mode 100644 index 000000000..19e9fbb0d --- /dev/null +++ b/rma_account/wizards/rma_order_line_make_supplier_rma.py @@ -0,0 +1,16 @@ +# Copyright 2016 ForgeFlow S.L. +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). + +from odoo import api, models + + +class RmaLineMakeSupplierRma(models.TransientModel): + _inherit = "rma.order.line.make.supplier.rma" + + @api.model + def _prepare_supplier_rma_line(self, rma, item): + res = super()._prepare_supplier_rma_line(rma, item) + if res["operation_id"]: + operation = self.env["rma.operation"].browse(res["operation_id"]) + res["refund_policy"] = operation.refund_policy + return res diff --git a/rma_account/wizards/rma_refund.py b/rma_account/wizards/rma_refund.py new file mode 100644 index 000000000..fb4407db5 --- /dev/null +++ b/rma_account/wizards/rma_refund.py @@ -0,0 +1,232 @@ +# Copyright 2017 ForgeFlow S.L. +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) + +from odoo import _, api, fields, models +from odoo.exceptions import ValidationError + + +class RmaRefund(models.TransientModel): + _name = "rma.refund" + _description = "Wizard for RMA Refund" + + @api.model + def _get_reason(self): + active_ids = self.env.context.get("active_ids", False) + return self.env["rma.order.line"].browse(active_ids[0]).rma_id.name or "" + + @api.returns("rma.order.line") + def _prepare_item(self, line): + values = { + "product_id": line.product_id.id, + "product": line.product_id.id, + "name": line.name, + "product_qty": line.product_qty, + "uom_id": line.uom_id.id, + "qty_to_refund": line.qty_to_refund, + "refund_policy": line.refund_policy, + "invoice_address_id": line.invoice_address_id.id, + "line_id": line.id, + "rma_id": line.rma_id.id, + } + return values + + @api.model + def default_get(self, fields_list): + """Default values for wizard, if there is more than one supplier on + lines the supplier field is empty otherwise is the unique line + supplier. + """ + context = self._context.copy() + res = super().default_get(fields_list) + rma_line_obj = self.env["rma.order.line"] + rma_line_ids = self.env.context["active_ids"] or [] + active_model = self.env.context["active_model"] + if not rma_line_ids: + return res + assert active_model == "rma.order.line", "Bad context propagation" + + items = [] + lines = rma_line_obj.browse(rma_line_ids) + if len(lines.mapped("partner_id")) > 1: + raise ValidationError( + _( + "Only RMAs from the same partner can be processed at " + "the same time." + ) + ) + for line in lines: + items.append([0, 0, self._prepare_item(line)]) + res["item_ids"] = items + context.update({"items_ids": items}) + return res + + date_invoice = fields.Date( + string="Refund Date", default=fields.Date.context_today, required=True + ) + date = fields.Date( + string="Accounting Date", default=fields.Date.context_today, required=True + ) + description = fields.Char( + string="Reason", required=True, default=lambda self: self._get_reason() + ) + item_ids = fields.One2many( + comodel_name="rma.refund.item", + inverse_name="wiz_id", + string="Items", + required=True, + ) + + def compute_refund(self): + for wizard in self: + first = self.item_ids[0] + values = self._prepare_refund(wizard, first.line_id) + default_move_type = ( + "in_refund" if first.line_id.type == "supplier" else "out_refund", + ) + account_move_model = self.env["account.move"].with_context( + default_move_type=default_move_type + ) + new_refund = account_move_model.create(values) + return new_refund + + def invoice_refund(self): + rma_line_ids = self.env["rma.order.line"].browse(self.env.context["active_ids"]) + for line in rma_line_ids: + if line.state != "approved": + raise ValidationError(_("RMA %s is not approved") % line.name) + new_invoice = self.compute_refund() + action = ( + "action_move_out_refund_type" + if (new_invoice.move_type in ["out_refund", "out_invoice"]) + else "action_move_in_refund_type" + ) + result = self.env.ref(f"account.{action}").sudo().read()[0] + form_view = self.env.ref("account.move_supplier_form", False) + result["views"] = [(form_view and form_view.id or False, "form")] + result["res_id"] = new_invoice.id + return result + + def _get_refund_price_unit(self, rma): + if rma.operation_id.refund_free_of_charge: + return 0.0 + price_unit = rma.price_unit + # If this references a previous invoice/bill, use the same unit price + if rma.account_move_line_id: + price_unit = rma.account_move_line_id.price_unit + return price_unit + + def _get_refund_currency(self, rma): + currency = rma.currency_id + if rma.account_move_line_id: + currency = rma.account_move_line_id.currency_id + return currency + + @api.model + def prepare_refund_line(self, item): + values = { + "name": item.line_id.name or item.rma_id.name, + "price_unit": self._get_refund_price_unit(item.line_id), + "product_uom_id": item.line_id.uom_id.id, + "product_id": item.product.id, + "rma_line_id": item.line_id.id, + "quantity": item.qty_to_refund, + } + return values + + @api.model + def _prepare_refund(self, wizard, rma_line): + # origin_invoices = self._get_invoice(rma_line) + if rma_line.operation_id.refund_journal_id: + journal = rma_line.operation_id.refund_journal_id + elif rma_line.type == "customer": + journal = self.env["account.journal"].search( + [("type", "=", "sale"), ("company_id", "=", rma_line.company_id.id)], + limit=1, + ) + else: + journal = self.env["account.journal"].search( + [ + ("type", "=", "purchase"), + ("company_id", "=", rma_line.company_id.id), + ], + limit=1, + ) + values = { + "payment_reference": rma_line.rma_id.name or rma_line.name, + "invoice_origin": rma_line.rma_id.name or rma_line.name, + "ref": False, + "move_type": "in_refund" if rma_line.type == "supplier" else "out_refund", + "journal_id": journal.id, + "state": "draft", + "currency_id": self._get_refund_currency(rma_line).id, + "date": wizard.date, + "invoice_date": wizard.date_invoice, + "partner_id": rma_line.invoice_address_id.id or rma_line.partner_id.id, + "partner_shipping_id": rma_line.delivery_address_id.id + or rma_line.partner_id.id, + "invoice_line_ids": [ + (0, None, self.prepare_refund_line(item)) for item in self.item_ids + ], + } + if self.env.registry.models.get("crm.team", False): + team_ids = self.env["crm.team"].search( + [ + "|", + ("user_id", "=", self.env.uid), + ("member_ids", "=", self.env.uid), + ], + limit=1, + ) + team_id = team_ids[0] if team_ids else False + if team_id: + values["team_id"] = team_id.id + if rma_line.type == "customer": + values["move_type"] = "out_refund" + else: + values["move_type"] = "in_refund" + return values + + @api.constrains("item_ids") + def check_unique_invoice_address_id(self): + addresses = self.item_ids.mapped("invoice_address_id") + if len(addresses) > 1: + raise ValidationError( + _("The invoice address must be the same for all the lines.") + ) + return True + + +class RmaRefundItem(models.TransientModel): + _name = "rma.refund.item" + _description = "RMA Lines to refund" + + wiz_id = fields.Many2one(comodel_name="rma.refund", string="Wizard", required=True) + line_id = fields.Many2one( + "rma.order.line", + string="RMA order Line", + required=True, + ondelete="cascade", + ) + rma_id = fields.Many2one("rma.order", related="line_id.rma_id", string="RMA") + product_id = fields.Many2one("product.product", string="Product (Technical)") + product = fields.Many2one("product.product", required=True) + name = fields.Char(string="Description", required=True) + product_qty = fields.Float( + string="Quantity Ordered", + copy=False, + digits="Product Unit of Measure", + ) + invoice_address_id = fields.Many2one( + comodel_name="res.partner", string="Invoice Address" + ) + qty_to_refund = fields.Float( + string="Quantity To Refund", digits="Product Unit of Measure" + ) + uom_id = fields.Many2one("uom.uom", string="Unit of Measure") + refund_policy = fields.Selection( + selection=[ + ("no", "Not required"), + ("ordered", "Based on Ordered Quantities"), + ("received", "Based on Received Quantities"), + ], + ) diff --git a/rma_account/wizards/rma_refund.xml b/rma_account/wizards/rma_refund.xml new file mode 100644 index 000000000..b60be88b7 --- /dev/null +++ b/rma_account/wizards/rma_refund.xml @@ -0,0 +1,75 @@ + + + + rma.refund.form + rma.refund + +
+ + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+ + + Create Refund + rma.refund + list,form + + + + new + + + + rma.order.line.form + rma.order.line + + + +