size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
1,171
py
PYTHON
15.0
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class MgmtsystemNonconformityOrigin(models.Model): _name = "mgmtsystem.nonconformity.origin" _description = "Origin of nonconformity of the management system" _order = "parent_id, sequence" _parent_store = True name = fields.Char("Origin", required=True, translate=True) description = fields.Text() sequence = fields.Integer(help="Defines the order to present items") parent_path = fields.Char(index=True) parent_id = fields.Many2one( "mgmtsystem.nonconformity.origin", "Group", ondelete="restrict" ) child_ids = fields.One2many( "mgmtsystem.nonconformity.origin", "parent_id", "Childs" ) ref_code = fields.Char("Reference Code") active = fields.Boolean(default=True) def name_get(self): res = [] for obj in self: name = obj.name if obj.parent_id: name = obj.parent_id.name_get()[0][1] + " / " + name res.append((obj.id, name)) return res
33.457143
1,171
7,745
py
PYTHON
15.0
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class MgmtsystemNonconformity(models.Model): _name = "mgmtsystem.nonconformity" _description = "Nonconformity" _inherit = ["mail.thread", "mail.activity.mixin"] _order = "create_date desc" @api.model def _default_stage(self): """Return the default stage.""" return self.env.ref("mgmtsystem_nonconformity.stage_draft", False) or self.env[ "mgmtsystem.nonconformity.stage" ].search([("is_starting", "=", True)], limit=1) @api.model def _stage_groups(self, stages, domain, order): stage_ids = self.env["mgmtsystem.nonconformity.stage"].search([]) return stage_ids # 1. Description name = fields.Char() ref = fields.Char("Reference", required=True, readonly=True, default="NEW") # Compute data number_of_nonconformities = fields.Integer( "# of nonconformities", readonly=True, default=1 ) days_since_updated = fields.Integer( readonly=True, compute="_compute_days_since_updated", store=True ) number_of_days_to_close = fields.Integer( "# of days to close", compute="_compute_number_of_days_to_close", store=True, readonly=True, ) closing_date = fields.Datetime(readonly=True) partner_id = fields.Many2one("res.partner", "Partner", required=True) reference = fields.Char("Related to") responsible_user_id = fields.Many2one( "res.users", "Responsible", required=True, tracking=True ) manager_user_id = fields.Many2one( "res.users", "Manager", required=True, tracking=True ) user_id = fields.Many2one( "res.users", "Filled in by", required=True, default=lambda self: self.env.user, tracking=True, ) origin_ids = fields.Many2many( "mgmtsystem.nonconformity.origin", "mgmtsystem_nonconformity_origin_rel", "nonconformity_id", "origin_id", "Origin", required=True, ) procedure_ids = fields.Many2many( "document.page", "mgmtsystem_nonconformity_procedure_rel", "nonconformity_id", "procedure_id", "Procedure", ) description = fields.Text(required=True) system_id = fields.Many2one("mgmtsystem.system", "System") stage_id = fields.Many2one( "mgmtsystem.nonconformity.stage", "Stage", tracking=True, copy=False, default=_default_stage, group_expand="_stage_groups", ) state = fields.Selection(related="stage_id.state", store=True) kanban_state = fields.Selection( [ ("normal", "In Progress"), ("done", "Ready for next stage"), ("blocked", "Blocked"), ], default="normal", tracking=True, help="A kanban state indicates special situations affecting it:\n" " * Normal is the default situation\n" " * Blocked indicates something is preventing" " the progress of this task\n" " * Ready for next stage indicates the" " task is ready to be pulled to the next stage", required=True, copy=False, ) # 2. Root Cause Analysis cause_ids = fields.Many2many( "mgmtsystem.nonconformity.cause", "mgmtsystem_nonconformity_cause_rel", "nonconformity_id", "cause_id", "Cause", ) severity_id = fields.Many2one("mgmtsystem.nonconformity.severity", "Severity") analysis = fields.Text() immediate_action_id = fields.Many2one( "mgmtsystem.action", domain="[('nonconformity_ids', '=', id)]", ) # 3. Action Plan action_ids = fields.Many2many( "mgmtsystem.action", "mgmtsystem_nonconformity_action_rel", "nonconformity_id", "action_id", "Actions", ) action_comments = fields.Text( "Action Plan Comments", help="Comments on the action plan." ) # 4. Effectiveness Evaluation evaluation_comments = fields.Text( help="Conclusions from the last effectiveness evaluation.", ) # Multi-company company_id = fields.Many2one( "res.company", "Company", default=lambda self: self.env.company ) res_model = fields.Char() res_id = fields.Integer(index=True) def _get_all_actions(self): self.ensure_one() return self.action_ids + self.immediate_action_id @api.constrains("stage_id") def _check_open_with_action_comments(self): for nc in self: if nc.state == "open" and not nc.action_comments: raise models.ValidationError( _( "Action plan comments are required " "in order to put a nonconformity In Progress." ) ) @api.constrains("stage_id") def _check_close_with_evaluation(self): for nc in self: if nc.state == "done": if not nc.evaluation_comments: raise models.ValidationError( _( "Evaluation Comments are required " "in order to close a Nonconformity." ) ) actions_are_closed = nc._get_all_actions().mapped("stage_id.is_ending") if not all(actions_are_closed): raise models.ValidationError( _("All actions must be done " "before closing a Nonconformity.") ) @api.model def _elapsed_days(self, dt1, dt2): return (dt2 - dt1).days if dt1 and dt2 else 0 @api.depends("closing_date", "create_date") def _compute_number_of_days_to_close(self): for nc in self: nc.number_of_days_to_close = self._elapsed_days( nc.create_date, nc.closing_date ) @api.depends("write_date") def _compute_days_since_updated(self): for nc in self: nc.days_since_updated = self._elapsed_days(nc.create_date, nc.write_date) @api.model def create(self, vals): vals.update( {"ref": self.env["ir.sequence"].next_by_code("mgmtsystem.nonconformity")} ) return super().create(vals) def write(self, vals): is_writing = self.env.context.get("is_writing", False) is_state_change = "stage_id" in vals or "state" in vals # Reset Kanban State on Stage change if is_state_change: was_not_open = { x.id: x.state in ("draft", "analysis", "pending") for x in self } if any(self.filtered(lambda x: x.kanban_state != "normal")): vals["kanban_state"] = "normal" result = super().write(vals) # Set/reset the closing date if not is_writing and is_state_change: for nc in self.with_context(is_writing=True): # On Close set Closing Date if nc.state == "done" and not nc.closing_date: nc.closing_date = fields.Datetime.now() # On reopen resete Closing Date elif nc.state != "done" and nc.closing_date: nc.closing_date = None # On action plan approval, Open the Actions if nc.state == "open" and was_not_open[nc.id]: for action in nc._get_all_actions(): if action.stage_id.is_starting: action.case_open() return result
34.422222
7,745
1,230
py
PYTHON
15.0
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models _STATES = [ ("draft", _("Draft")), ("analysis", _("Analysis")), ("pending", _("Action Plan")), ("open", _("In Progress")), ("done", _("Closed")), ("cancel", _("Cancelled")), ] class MgmtsystemNonconformityStage(models.Model): """This object is used to defined different state for non conformity.""" _name = "mgmtsystem.nonconformity.stage" _description = "Nonconformity Stages" _order = "sequence" name = fields.Char("Stage Name", required=True, translate=True) sequence = fields.Integer( help="Used to order states. Lower is better.", default=100 ) state = fields.Selection(_STATES, readonly=True, default="draft") is_starting = fields.Boolean( string="Is starting Stage", help="select stis checkbox if this is the default stage \n" "for new nonconformities", ) fold = fields.Boolean( string="Folded in Kanban", help="This stage is folded in the kanban view when there are \n" "no records in that stage to display.", )
33.243243
1,230
610
py
PYTHON
15.0
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class MgmtsystemNonconformitySeverity(models.Model): """Nonconformity Severity - Critical, Major, Minor, Invalid, ...""" _name = "mgmtsystem.nonconformity.severity" _description = "Severity of Complaints and Nonconformities" name = fields.Char("Title", required=True, translate=True) sequence = fields.Integer() description = fields.Text(translate=True) active = fields.Boolean("Active?", default=True)
35.882353
610
1,320
py
PYTHON
15.0
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class MgmtsystemNonconformityAbstract(models.AbstractModel): _name = "mgmtsystem.nonconformity.abstract" _description = "Nonconformity Abstract" non_conformity_ids = fields.One2many( "mgmtsystem.nonconformity", inverse_name="res_id", domain=lambda r: [("res_model", "=", r._name)], readonly=True, ) non_conformity_count = fields.Integer(compute="_compute_non_conformity_count") @api.depends("non_conformity_ids") def _compute_non_conformity_count(self): self.ensure_one() self.non_conformity_count = len(self.non_conformity_ids) def _get_non_conformities_domain(self): return [("res_model", "=", self._name), ("res_id", "=", self.id)] def _get_non_conformities_context(self): return {} def action_view_non_conformities(self): self.ensure_one() action = self.env.ref( "mgmtsystem_nonconformity.open_mgmtsystem_nonconformity_list" ).read()[0] action["domain"] = self._get_non_conformities_domain() action["context"] = self._get_non_conformities_context() return action
33
1,320
609
py
PYTHON
15.0
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class MgmtsystemAction(models.Model): _inherit = "mgmtsystem.action" nonconformity_immediate_id = fields.One2many( "mgmtsystem.nonconformity", "immediate_action_id", readonly=True ) nonconformity_ids = fields.Many2many( "mgmtsystem.nonconformity", "mgmtsystem_nonconformity_action_rel", "action_id", "nonconformity_id", "Nonconformities", readonly=True, )
30.45
609
1,222
py
PYTHON
15.0
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class MgmtsystemNonconformityCause(models.Model): """Cause of the nonconformity of the management system.""" _name = "mgmtsystem.nonconformity.cause" _description = "Cause of the nonconformity of the management system" _order = "parent_id, sequence" _parent_store = True name = fields.Char("Cause", required=True, translate=True) description = fields.Text() sequence = fields.Integer(help="Defines the order to present items") parent_path = fields.Char(index=True) parent_id = fields.Many2one( "mgmtsystem.nonconformity.cause", "Group", ondelete="restrict" ) child_ids = fields.One2many( "mgmtsystem.nonconformity.cause", "parent_id", "Child Causes" ) ref_code = fields.Char("Reference Code") def name_get(self): res = [] for obj in self: if obj.parent_id: name = obj.parent_id.name_get()[0][1] + " / " + obj.name else: name = obj.name res.append((obj.id, name)) return res
33.944444
1,222
634
py
PYTHON
15.0
# Copyright 2022 - TODAY, Escodoo # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Mgmtsystem Nonconformity Quality Control Oca", "summary": """ Bridge module between Quality Control and Non Conformities""", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "Escodoo,Odoo Community Association (OCA)", "website": "https://github.com/OCA/management-system", "depends": [ "mgmtsystem_nonconformity", "quality_control_oca", ], "data": [ "views/qc_inspection.xml", "views/mgmtsystem_nonconformity.xml", ], "demo": [], }
30.190476
634
2,195
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common class TestQualityControl(common.TransactionCase): @classmethod def setUpClass(cls): """ Sets some enviroment """ super().setUpClass() cls.test = cls.env.ref("quality_control_oca.qc_test_1") cls.inspection_model = cls.env["qc.inspection"] inspection_lines = cls.inspection_model._prepare_inspection_lines(cls.test) cls.inspection1 = cls.inspection_model.create( {"name": "Test Inspection", "inspection_lines": inspection_lines} ) cls.nc_model = cls.env["mgmtsystem.nonconformity"] cls.partner = cls.env["res.partner"].search([])[0] cls.nc_test = cls.nc_model.create( { "partner_id": cls.partner.id, "manager_user_id": cls.env.user.id, "description": "description", "responsible_user_id": cls.env.user.id, } ) cls.nc_test2 = cls.nc_model.create( { "partner_id": cls.partner.id, "manager_user_id": cls.env.user.id, "description": "description2", "responsible_user_id": cls.env.user.id, } ) cls.inspection1.mgmtsystem_nonconformity_ids = [cls.nc_test.id] def test_compute_mgmtsystem_nonconformity_count(self): nc_count = len(self.inspection1.mgmtsystem_nonconformity_ids) self.inspection1._compute_mgmtsystem_nonconformity_count() self.assertEqual(nc_count, self.inspection1.mgmtsystem_nonconformity_count) def test_action_view_nonconformities(self): action = self.inspection1.action_view_nonconformities() self.assertEqual(self.nc_test.id, action["res_id"]) self.inspection1.mgmtsystem_nonconformity_ids = [ self.nc_test.id, self.nc_test2.id, ] action = self.inspection1.action_view_nonconformities() nc_ids = [] for nc in self.inspection1.mgmtsystem_nonconformity_ids: nc_ids.append(nc.id) self.assertEqual(nc_ids, action["domain"][0][2])
37.844828
2,195
352
py
PYTHON
15.0
# Copyright 2022 - TODAY, Marcel Savegnago <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class MgmtsystemNonconformity(models.Model): _inherit = "mgmtsystem.nonconformity" qc_inspection_id = fields.Many2one("qc.inspection", "Quality Control Inspection")
32
352
1,796
py
PYTHON
15.0
# Copyright 2022 - TODAY, Marcel Savegnago <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class QcInspection(models.Model): _inherit = "qc.inspection" mgmtsystem_nonconformity_ids = fields.One2many( "mgmtsystem.nonconformity", "qc_inspection_id", string="Non-Conformities" ) mgmtsystem_nonconformity_count = fields.Integer( compute="_compute_mgmtsystem_nonconformity_count", string="# Non-Conformities" ) @api.depends("mgmtsystem_nonconformity_ids") def _compute_mgmtsystem_nonconformity_count(self): for rec in self: rec.mgmtsystem_nonconformity_count = len(rec.mgmtsystem_nonconformity_ids) def action_view_nonconformities(self): action = self.env.ref( "mgmtsystem_nonconformity.open_mgmtsystem_nonconformity_list" ).read()[0] if self.mgmtsystem_nonconformity_count > 1: action["domain"] = [("id", "in", self.mgmtsystem_nonconformity_ids.ids)] else: action["views"] = [ ( self.env.ref( "mgmtsystem_nonconformity.view_mgmtsystem_nonconformity_form" ).id, "form", ) ] action["res_id"] = ( self.mgmtsystem_nonconformity_ids and self.mgmtsystem_nonconformity_ids.ids[0] or False ) action["context"] = { "search_default_qc_inspection_id": self.id, "default_qc_inspection_id": self.id, "default_name": self.name, "default_company_id": self.company_id.id, } return action
35.92
1,796
1,326
py
PYTHON
15.0
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Health and Safety Manual", "version": "15.0.1.0.0", "author": "Savoir-faire Linux, Odoo Community Association (OCA)", "website": "https://github.com/OCA/management-system", "license": "AGPL-3", "category": "Generic Modules/Others", "depends": ["mgmtsystem_manual"], "data": ["data/document_page.xml"], "installable": True, }
44.2
1,326
728
py
PYTHON
15.0
# Copyright 2019 Marcelo Frare (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) # Copyright 2019 Stefano Consolaro (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) { "name": "Management System - Action Template", "summary": "Add Template management for Actions.", "version": "15.0.1.1.0", "author": "Associazione PNLUG - Gruppo Odoo, Odoo Community Association (OCA)", "website": "https://github.com/OCA/management-system", "license": "AGPL-3", "category": "Management System", "depends": ["mgmtsystem_action"], "data": [ "security/ir.model.access.csv", "views/mgmtsystem_action_template.xml", "views/mgmtsystem_action_views.xml", ], "installable": True, }
38.315789
728
1,013
py
PYTHON
15.0
from odoo import _ from odoo.tests.common import TransactionCase class TestModelNonConformity(TransactionCase): def setUp(self): """ Sets some enviroment """ super(TestModelNonConformity, self).setUp() self.action_model = self.env["mgmtsystem.action"] self.action_template_model = self.env["mgmtsystem.action.template"] # create a template action self.action_template = self.action_template_model.create( { "name": "Test Template", "type_action": self.action_model.search([])[0]["type_action"], } ) def test_get_template(self): """ Test set Action template """ self.action = self.action_model.search([])[0] self.action["template_id"] = self.action_template["id"] self.action._onchange_template_id() self.assertEqual( self.action["name"] == _("NEW") + " " + self.action_template["name"], True )
29.794118
1,013
1,128
py
PYTHON
15.0
# Copyright 2020 Creu Blanca # Copyright 2019 Marcelo Frare (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) # Copyright 2019 Stefano Consolaro (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) from odoo import fields, models class MgmtsystemActionTemplate(models.Model): """ Define a support structure to set action template values """ _name = "mgmtsystem.action.template" _description = "Define fields to save action template values" def _selection_type_action(self): # link to action type values return self.env["mgmtsystem.action"]._fields["type_action"].selection # fields # template identification name = fields.Char(required=True) # action preset description = fields.Html() type_action = fields.Selection( selection=lambda self: self._selection_type_action(), string="Response Type" ) user_id = fields.Many2one( "res.users", "Responsible", default=lambda self: self.env["mgmtsystem.action"]._default_owner(), required=True, ) tag_ids = fields.Many2many("mgmtsystem.action.tag", string="Tags")
33.176471
1,128
1,024
py
PYTHON
15.0
# Copyright 2019 Marcelo Frare (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) # Copyright 2019 Stefano Consolaro (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) # Copyright 2020 Creu Blanca from odoo import _, api, fields, models class MgmtsystemAction(models.Model): """ Extend actions adding template reference """ _inherit = "mgmtsystem.action" # template reference template_id = fields.Many2one( "mgmtsystem.action.template", "Reference Template", help="Fill Action's fields with Template's values", ) @api.onchange("template_id") def _onchange_template_id(self): """ Fill some fields with template ones """ if self.template_id: self.name = _("NEW") + " " + self.template_id.name self.type_action = self.template_id.type_action self.description = self.template_id.description self.user_id = self.template_id.user_id self.tag_ids = self.template_id.tag_ids
31.030303
1,024
1,449
py
PYTHON
15.0
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Environmental Aspects", "version": "15.0.1.0.0", "author": "Savoir-faire Linux, Odoo Community Association (OCA)", "website": "https://github.com/OCA/management-system", "license": "AGPL-3", "category": "Generic Modules/Others", "depends": ["document_page", "mgmtsystem"], "data": ["data/document_page.xml", "views/document_page.xml"], "installable": True, }
46.741935
1,449
719
py
PYTHON
15.0
# Copyright 2019 Stefano Consolaro (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) { "name": "Management System - Nonconformity Type", "summary": "Add Nonconformity classification for the root context.", "version": "15.0.1.0.0", "development_status": "Beta", "author": "Associazione PNLUG - Gruppo Odoo, Odoo Community Association (OCA)", "website": "https://github.com/OCA/management-system", "license": "AGPL-3", "category": "Management System", "depends": ["mgmtsystem", "mgmtsystem_nonconformity", "mgmtsystem_partner"], "data": [ "views/mgmtsystem_nonconformity_views.xml", "data/mgmtsystem_nonconformity_mail_data.xml", ], "installable": True, }
39.944444
719
2,394
py
PYTHON
15.0
from odoo import _ from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestModelNonConformity(TransactionCase): def setUp(self): """ Sets some enviroment """ super(TestModelNonConformity, self).setUp() self.nc_model = self.env["mgmtsystem.nonconformity"] self.nc = self.nc_model.search([])[0] self.nc["qty_checked"] = 100 self.nc["qty_noncompliant"] = 50 def test_nc(self): """ Test NC changes """ self.nc["qty_noncompliant"] = 150 self.nc._onchange_qty_noncompliant() self.assertEqual(self.nc["qty_noncompliant"] == self.nc["qty_checked"], True) self.nc["qty_noncompliant"] = 50 self.nc._onchange_qty_noncompliant() self.assertEqual(self.nc["qty_checked"] == 150, True) self.nc["qty_noncompliant"] = 150 self.nc["qty_checked"] = 50 self.nc._onchange_qty_checked() self.assertEqual(self.nc["qty_noncompliant"] == self.nc["qty_checked"], True) self.nc["qty_checked"] = 200 self.nc._onchange_qty_checked() self.assertEqual(self.nc["qty_noncompliant"] == 50, True) def test_nc_email(self): """ Test NC partner email """ partner = self.nc.partner_id["child_ids"].search([])[0] partner_child = partner["child_ids"][0] partner_child.type = "quality" partner_child.email = "[email protected]" self.nc.partner_id = partner.id self.assertEqual(True, self.nc.action_nc_sent()) test_module = True with self.assertRaises(ValidationError) as e: self.assertEqual(True, self.nc.action_nc_sent(test_module)) self.assertIn( _( "The partner's contacts quality type isn't available.\n " "Check if module mgmtsystem_nonconformity_partner is installed." ), str(e.exception), ) partner_child.type = "quality" partner_child.email = "" with self.assertRaises(ValidationError) as e: self.assertEqual(True, self.nc.action_nc_sent()) self.assertIn( _( "The partner's quality contact email " "is required in order to send the message." ), str(e.exception), )
34.2
2,394
3,426
py
PYTHON
15.0
# Copyright 2019 Stefano Consolaro (Ass. PNLUG - Gruppo Odoo <http://odoo.pnlug.it>) from odoo import _, api, fields, models class MgmtsystemNonconformity(models.Model): """ Extend nonconformity adding fields for type, quantity checked and quantity non compliant, adding method to send email """ _inherit = ["mgmtsystem.nonconformity"] # new fields # nonconformity type nc_type = fields.Selection( [ ("internal", "Internal"), ("supplier", "Supplier"), ("customer", "Customer"), ("external", "External"), ], "Type", default="internal", ) # quantity checked to reveal the nonconformity [qty-ck] qty_checked = fields.Float("Quantity checked") # quantity found to be non-compliant with the inspection [qty-nc] qty_noncompliant = fields.Float("Quantity non-compliant") # utility name of quality contact quality_contact_name = fields.Char("Contact Name") # utility e-mail of quality contact quality_contact_email = fields.Char("Email") # define constraints for quantities @api.onchange("qty_noncompliant") def _onchange_qty_noncompliant(self): """ set qty checked equal to qty non compliant if it is lower (qty-ck can not be lower to qty-nc) """ if self.qty_noncompliant > self.qty_checked: self.qty_checked = self.qty_noncompliant @api.onchange("qty_checked") def _onchange_qty_checked(self): """ set qty non compliant equal to qty checked if it is higher qty-nc can not be greater to qty-ck """ if self.qty_checked < self.qty_noncompliant: self.qty_noncompliant = self.qty_checked # new method def action_nc_sent(self, test_module=False): """ send document to partner email if address not exists raises an error message todo: use a better way to test module availability """ if ( "quality" not in self.env["res.partner"]._fields["type"].get_values([]) or test_module ): # raise an error for module not installed message = _( "The partner's contacts quality type isn't available.\n " "Check if module mgmtsystem_nonconformity_partner is installed." ) raise models.ValidationError(message) # get first contact of type quality contact_quality = self.partner_id["child_ids"].search( [("parent_id", "=", self.partner_id.id), ("type", "=", "quality")], limit=1 ) if contact_quality["email"]: self.quality_contact_name = contact_quality["name"] self.quality_contact_email = contact_quality["email"] # find the e-mail template report_tmplt = self.env.ref( "mgmtsystem_nonconformity_type.email_template_nonconformity" ) # send out the e-mail template to the partner self.env["mail.template"].browse(report_tmplt.id).send_mail(self.id) else: # raise an error for field not compiled raise models.ValidationError( _( "The partner's quality contact email " "is required in order to send the message." ) ) return True
34.606061
3,426
647
py
PYTHON
15.0
# Copyright 2016-2022 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Banking Mandate Sale", "version": "15.0.1.0.0", "category": "Banking addons", "license": "AGPL-3", "summary": "Adds mandates on sale orders", "author": "Odoo Community Association (OCA), Akretion", "maintainers": ["alexis-via"], "website": "https://github.com/OCA/bank-payment", "depends": [ "account_payment_sale", "account_banking_mandate", ], "data": [ "views/sale_order.xml", ], "installable": True, }
30.809524
647
569
py
PYTHON
15.0
# Copyright 2016-2022 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" def _prepare_invoice_values(self, order, name, amount, so_line): """Copy mandate from sale order to invoice""" vals = super()._prepare_invoice_values(order, name, amount, so_line) if order.mandate_id: vals["mandate_id"] = order.mandate_id.id return vals
37.933333
569
2,071
py
PYTHON
15.0
# Copyright 2014-2022 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" commercial_invoice_partner_id = fields.Many2one( related="partner_invoice_id.commercial_partner_id", string="Invoicing Commercial Entity", store=True, ) mandate_id = fields.Many2one( "account.banking.mandate", string="Direct Debit Mandate", ondelete="restrict", check_company=True, readonly=False, domain="[('partner_id', '=', commercial_invoice_partner_id), " "('state', 'in', ('draft', 'valid')), " "('company_id', '=', company_id)]", ) mandate_required = fields.Boolean( related="payment_mode_id.payment_method_id.mandate_required", ) def _prepare_invoice(self): """Copy mandate from sale order to invoice""" vals = super()._prepare_invoice() if self.mandate_id: vals["mandate_id"] = self.mandate_id.id return vals @api.depends("partner_invoice_id") def _compute_payment_mode(self): """Select by default the first valid mandate of the invoicing partner""" res = super()._compute_payment_mode() abm_obj = self.env["account.banking.mandate"] for order in self: if order.mandate_required and order.partner_invoice_id: mandate = abm_obj.search( [ ("state", "=", "valid"), ( "partner_id", "=", order.partner_invoice_id.commercial_partner_id.id, ), ("company_id", "=", order.company_id.id), ], limit=1, ) order.mandate_id = mandate or False else: order.mandate_id = False return res
35.706897
2,071
795
py
PYTHON
15.0
# Copyright 2016-2020 Akretion France (<https://www.akretion.com>) # @author: Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Payment Mode", "version": "15.0.1.0.2", "development_status": "Mature", "license": "AGPL-3", "author": "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "category": "Banking addons", "depends": ["account"], "data": [ "security/account_payment_mode.xml", "security/ir.model.access.csv", "views/account_payment_method.xml", "views/account_payment_mode.xml", "views/account_journal.xml", ], "demo": ["demo/payment_demo.xml"], "installable": True, }
34.565217
795
5,279
py
PYTHON
15.0
# Copyright 2016-2020 ForgeFlow S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo.exceptions import UserError, ValidationError from odoo.tests.common import TransactionCase class TestAccountPaymentMode(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.res_users_model = cls.env["res.users"] cls.journal_model = cls.env["account.journal"] cls.payment_mode_model = cls.env["account.payment.mode"] # refs cls.manual_out = cls.env.ref("account.account_payment_method_manual_out") # Company cls.company = cls.env.ref("base.main_company") # Company 2 cls.company_2 = cls.env["res.company"].create({"name": "Company 2"}) cls.journal_c1 = cls._create_journal("J1", cls.company) cls.journal_c2 = cls._create_journal("J2", cls.company_2) cls.journal_c3 = cls._create_journal("J3", cls.company) cls.payment_mode_c1 = cls.payment_mode_model.create( { "name": "Direct Debit of suppliers from Bank 1", "bank_account_link": "variable", "payment_method_id": cls.manual_out.id, "company_id": cls.company.id, "fixed_journal_id": cls.journal_c1.id, "variable_journal_ids": [ (6, 0, [cls.journal_c1.id, cls.journal_c3.id]) ], } ) @classmethod def _create_journal(cls, name, company): # Create a cash account # Create a journal for cash account journal = cls.journal_model.create( {"name": name, "code": name, "type": "bank", "company_id": company.id} ) return journal def test_payment_mode_company_consistency_change(self): # Assertion on the constraints to ensure the consistency # for company dependent fields with self.assertRaises(UserError): self.payment_mode_c1.write({"fixed_journal_id": self.journal_c2.id}) with self.assertRaises(UserError): self.payment_mode_c1.write( { "variable_journal_ids": [ ( 6, 0, [ self.journal_c1.id, self.journal_c2.id, self.journal_c3.id, ], ) ] } ) with self.assertRaises(ValidationError): self.journal_c1.write({"company_id": self.company_2.id}) def test_payment_mode_company_consistency_create(self): # Assertion on the constraints to ensure the consistency # for company dependent fields with self.assertRaises(UserError): self.payment_mode_model.create( { "name": "Direct Debit of suppliers from Bank 2", "bank_account_link": "variable", "payment_method_id": self.manual_out.id, "company_id": self.company.id, "fixed_journal_id": self.journal_c2.id, } ) with self.assertRaises(UserError): self.payment_mode_model.create( { "name": "Direct Debit of suppliers from Bank 3", "bank_account_link": "variable", "payment_method_id": self.manual_out.id, "company_id": self.company.id, "variable_journal_ids": [(6, 0, [self.journal_c2.id])], } ) with self.assertRaises(UserError): self.payment_mode_model.create( { "name": "Direct Debit of suppliers from Bank 4", "bank_account_link": "fixed", "payment_method_id": self.manual_out.id, "company_id": self.company.id, } ) self.journal_c1.outbound_payment_method_line_ids = False with self.assertRaises(ValidationError): self.payment_mode_model.create( { "name": "Direct Debit of suppliers from Bank 5", "bank_account_link": "fixed", "payment_method_id": self.manual_out.id, "company_id": self.company.id, "fixed_journal_id": self.journal_c1.id, } ) self.journal_c1.inbound_payment_method_line_ids = False with self.assertRaises(ValidationError): self.payment_mode_model.create( { "name": "Direct Debit of suppliers from Bank 5", "bank_account_link": "fixed", "payment_method_id": self.env.ref( "account.account_payment_method_manual_in" ).id, "company_id": self.company.id, "fixed_journal_id": self.journal_c1.id, } )
39.691729
5,279
2,612
py
PYTHON
15.0
# Copyright 2016-2020 Akretion France (http://www.akretion.com/) # @author: Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError class AccountJournal(models.Model): _inherit = "account.journal" def _default_outbound_payment_methods(self): all_out = self.env["account.payment.method"].search( [("payment_type", "=", "outbound")] ) return all_out def _default_inbound_payment_methods(self): method_info = self.env[ "account.payment.method" ]._get_payment_method_information() unique_codes = tuple( code for code, info in method_info.items() if info.get("mode") == "unique" ) all_in = self.env["account.payment.method"].search( [ ("payment_type", "=", "inbound"), ("code", "not in", unique_codes), # filter out unique codes ] ) return all_in @api.constrains("company_id") def company_id_account_payment_mode_constrains(self): for journal in self: mode = self.env["account.payment.mode"].search( [ ("fixed_journal_id", "=", journal.id), ("company_id", "!=", journal.company_id.id), ], limit=1, ) if mode: raise ValidationError( _( "The company of the journal %(journal)s does not match " "with the company of the payment mode %(paymode)s where it is " "being used as Fixed Bank Journal.", journal=journal.name, paymode=mode.name, ) ) mode = self.env["account.payment.mode"].search( [ ("variable_journal_ids", "in", [journal.id]), ("company_id", "!=", journal.company_id.id), ], limit=1, ) if mode: raise ValidationError( _( "The company of the journal %(journal)s does not match " "with the company of the payment mode %(paymode)s where it is " "being used in the Allowed Bank Journals.", journal=journal.name, paymode=mode.name, ) )
37.855072
2,612
1,371
py
PYTHON
15.0
# Copyright 2016-2020 Akretion France (http://www.akretion.com/) # @author: Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountPaymentMethod(models.Model): _inherit = "account.payment.method" code = fields.Char( string="Code (Do Not Modify)", help="This code is used in the code of the Odoo module that handles " "this payment method. Therefore, if you change it, " "the generation of the payment file may fail.", ) active = fields.Boolean(default=True) bank_account_required = fields.Boolean( help="Activate this option if this payment method requires you to " "know the bank account number of your customer or supplier." ) payment_mode_ids = fields.One2many( comodel_name="account.payment.mode", inverse_name="payment_method_id", string="Payment modes", ) @api.depends("code", "name", "payment_type") def name_get(self): result = [] for method in self: result.append( ( method.id, "[{}] {} ({})".format( method.code, method.name, method.payment_type ), ) ) return result
34.275
1,371
5,956
py
PYTHON
15.0
# Copyright 2016-2020 Akretion France (http://www.akretion.com/) # @author: Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class AccountPaymentMode(models.Model): """This corresponds to the object payment.mode of v8 with some important changes. It also replaces the object payment.method of the module sale_payment_method of OCA/e-commerce""" _name = "account.payment.mode" _description = "Payment Modes" _order = "name" _check_company_auto = True name = fields.Char(required=True, translate=True) company_id = fields.Many2one( "res.company", string="Company", required=True, ondelete="restrict", default=lambda self: self.env.company, ) bank_account_link = fields.Selection( [("fixed", "Fixed"), ("variable", "Variable")], string="Link to Bank Account", required=True, help="For payment modes that are always attached to the same bank " "account of your company (such as wire transfer from customers or " "SEPA direct debit from suppliers), select " "'Fixed'. For payment modes that are not always attached to the same " "bank account (such as SEPA Direct debit for customers, wire transfer " "to suppliers), you should select 'Variable', which means that you " "will select the bank account on the payment order. If your company " "only has one bank account, you should always select 'Fixed'.", ) fixed_journal_id = fields.Many2one( "account.journal", string="Fixed Bank Journal", domain="[('company_id', '=', company_id), ('type', 'in', ('bank', 'cash'))]", ondelete="restrict", check_company=True, ) # I need to explicitly define the table name # because I have 2 M2M fields pointing to account.journal variable_journal_ids = fields.Many2many( comodel_name="account.journal", relation="account_payment_mode_variable_journal_rel", column1="payment_mode_id", column2="journal_id", string="Allowed Bank Journals", domain="[('company_id', '=', company_id), ('type', 'in', ('bank', 'cash'))]", ) payment_method_id = fields.Many2one( "account.payment.method", string="Payment Method", required=True, ondelete="restrict", ) payment_type = fields.Selection( related="payment_method_id.payment_type", readonly=True, store=True ) payment_method_code = fields.Char( related="payment_method_id.code", readonly=True, store=True ) active = fields.Boolean(default=True) note = fields.Text(translate=True) @api.onchange("company_id") def _onchange_company_id(self): self.variable_journal_ids = False self.fixed_journal_id = False @api.constrains("bank_account_link", "fixed_journal_id", "payment_method_id") def bank_account_link_constrains(self): for mode in self.filtered(lambda x: x.bank_account_link == "fixed"): if not mode.fixed_journal_id: raise ValidationError( _( "On the payment mode %(name)s, the bank account link is " "'Fixed' but the fixed bank journal is not set", name=mode.name, ) ) else: f_journal = mode.fixed_journal_id if mode.payment_method_id.payment_type == "outbound": p_modes = f_journal.outbound_payment_method_line_ids.mapped( "payment_method_id.id" ) if mode.payment_method_id.id not in p_modes: raise ValidationError( _( "On the payment mode %(paymode)s, the payment method " "is %(paymethod)s, but this payment method is not part " "of the payment methods of the fixed bank " "journal %(journal)s", paymode=mode.name, paymethod=mode.payment_method_id.name, journal=mode.fixed_journal_id.name, ) ) else: p_modes = f_journal.inbound_payment_method_line_ids.mapped( "payment_method_id.id" ) if mode.payment_method_id.id not in p_modes: raise ValidationError( _( "On the payment mode %(paymode)s, the payment method " "is %(paymethod)s (it is in fact a debit method), " "but this debit method is not part " "of the debit methods of the fixed bank " "journal %(journal)s", paymode=mode.name, paymethod=mode.payment_method_id.name, journal=mode.fixed_journal_id.name, ) ) @api.constrains("company_id", "variable_journal_ids") def company_id_variable_journal_ids_constrains(self): for mode in self: if any(mode.company_id != j.company_id for j in mode.variable_journal_ids): raise ValidationError( _( "The company of the payment mode %(paymode)s, does not match " "with one of the Allowed Bank Journals.", paymode=mode.name, ) )
44.447761
5,956
1,348
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-bank-payment", description="Meta package for oca-bank-payment Odoo addons", version=version, install_requires=[ 'odoo-addon-account_banking_mandate>=15.0dev,<15.1dev', 'odoo-addon-account_banking_mandate_contact>=15.0dev,<15.1dev', 'odoo-addon-account_banking_mandate_sale>=15.0dev,<15.1dev', 'odoo-addon-account_banking_pain_base>=15.0dev,<15.1dev', 'odoo-addon-account_banking_sepa_credit_transfer>=15.0dev,<15.1dev', 'odoo-addon-account_banking_sepa_direct_debit>=15.0dev,<15.1dev', 'odoo-addon-account_payment_mode>=15.0dev,<15.1dev', 'odoo-addon-account_payment_order>=15.0dev,<15.1dev', 'odoo-addon-account_payment_order_grouped_output>=15.0dev,<15.1dev', 'odoo-addon-account_payment_order_return>=15.0dev,<15.1dev', 'odoo-addon-account_payment_partner>=15.0dev,<15.1dev', 'odoo-addon-account_payment_purchase>=15.0dev,<15.1dev', 'odoo-addon-account_payment_purchase_stock>=15.0dev,<15.1dev', 'odoo-addon-account_payment_sale>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
43.483871
1,348
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
634
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Account Banking Mandate Contact", "summary": "Assign specific banking mandates in contact level", "version": "15.0.1.0.0", "development_status": "Production/Stable", "category": "Banking addons", "website": "https://github.com/OCA/bank-payment", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["account_banking_mandate", "sale"], "data": [ "views/res_partner.xml", ], }
35.222222
634
6,063
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl from unittest.mock import patch from odoo import fields from odoo.tests.common import Form, TransactionCase from odoo.addons.account.models.account_payment_method import AccountPaymentMethod class TestAccountPaymentOrder(TransactionCase): def setUp(self): super().setUp() self.partner = self.env["res.partner"].create({"name": "Test Partner"}) self.product = self.env["product.product"].create({"name": "Test product"}) self.partner_bank_core = self._create_res_partner_bank("N-CORE") self.mandate_core = self._create_mandate(self.partner_bank_core, "CORE") self.partner_bank_b2b = self._create_res_partner_bank("N-B2B") self.mandate_b2b = self._create_mandate(self.partner_bank_b2b, "B2B") payment_method_vals = { "name": "SEPA", "code": "sepa_direct_debit", "payment_type": "inbound", "bank_account_required": True, } self.method_sepa = self._create_multi_bank_payment_method(payment_method_vals) self.journal_bank = self.env["account.journal"].create( {"name": "BANK", "type": "bank", "code": "bank"} ) payment_form = Form(self.env["account.payment.mode"]) payment_form.name = "SEPA (CORE)" payment_form.payment_method_id = self.method_sepa payment_form.bank_account_link = "fixed" payment_form.fixed_journal_id = self.journal_bank payment_form.payment_order_ok = True self.payment_core = payment_form.save() self.payment_b2b = self.payment_core.copy({"name": "SEPA B2B"}) self.partner.customer_payment_mode_id = self.payment_core.id self.env["account.journal"].create( {"name": "SALE", "type": "sale", "code": "sale"} ) self.invoice = self._create_invoice() payment_order_form = Form( self.env["account.payment.order"].with_context( default_payment_type="inbound" ) ) payment_order_form.payment_mode_id = self.payment_core self.payment_order = payment_order_form.save() def _create_multi_bank_payment_method(self, payment_method_vals): method_get_payment_method_information = ( AccountPaymentMethod._get_payment_method_information ) def _get_payment_method_information(self): res = method_get_payment_method_information(self) res[payment_method_vals["code"]] = { "mode": "multi", "domain": [("type", "=", "bank")], } return res with patch.object( AccountPaymentMethod, "_get_payment_method_information", _get_payment_method_information, ): return self.env["account.payment.method"].create(payment_method_vals) def _create_res_partner_bank(self, acc_number): res_partner_bank_form = Form(self.env["res.partner.bank"]) res_partner_bank_form.partner_id = self.partner res_partner_bank_form.acc_number = acc_number return res_partner_bank_form.save() def _create_mandate(self, partner_bank, scheme): mandate_form = Form(self.env["account.banking.mandate"]) mandate_form.partner_bank_id = partner_bank mandate_form.signature_date = fields.Date.from_string("2021-01-01") mandate = mandate_form.save() mandate.validate() return mandate def _create_invoice(self): invoice_form = Form( self.env["account.move"].with_context(default_move_type="out_invoice") ) invoice_form.partner_id = self.partner invoice_form.invoice_date = fields.Date.from_string("2021-01-01") with invoice_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product line_form.quantity = 1 line_form.price_unit = 30 line_form.tax_ids.clear() invoice = invoice_form.save() invoice.action_post() return invoice def test_invoice_payment_mode(self): self.assertEqual(self.invoice.state, "posted") self.assertEqual(self.invoice.payment_mode_id, self.payment_core) self.assertEqual( self.invoice.invoice_date_due, fields.Date.from_string("2021-01-01") ) def test_account_payment_order_core(self): line_create_form = Form( self.env["account.payment.line.create"].with_context( active_model="account.payment.order", active_id=self.payment_order.id ) ) line_create_form.date_type = "due" line_create_form.due_date = fields.Date.from_string("2021-01-01") line_create = line_create_form.save() line_create.populate() line_create.create_payment_lines() self.assertAlmostEqual(len(self.payment_order.payment_line_ids), 1) payment_line = self.payment_order.payment_line_ids.filtered( lambda x: x.partner_id == self.partner ) self.assertEqual(payment_line.partner_bank_id, self.partner_bank_core) def test_account_payment_order_core_extra(self): self.partner.contact_mandate_id = self.mandate_b2b line_create_form = Form( self.env["account.payment.line.create"].with_context( active_model="account.payment.order", active_id=self.payment_order.id ) ) line_create_form.date_type = "due" line_create_form.due_date = fields.Date.from_string("2021-01-01") line_create = line_create_form.save() line_create.populate() line_create.create_payment_lines() self.assertAlmostEqual(len(self.payment_order.payment_line_ids), 1) payment_line = self.payment_order.payment_line_ids.filtered( lambda x: x.partner_id == self.partner ) self.assertEqual(payment_line.partner_bank_id, self.partner_bank_b2b)
42.985816
6,061
901
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class AccountMoveLine(models.Model): _inherit = "account.move.line" # Extended to use partner_shipping_id mandate if it have set def _prepare_payment_line_vals(self, payment_order): vals = super(AccountMoveLine, self)._prepare_payment_line_vals(payment_order) if payment_order.payment_type != "inbound" or self.move_id.mandate_id: return vals mandate = ( self.move_id.partner_shipping_id.valid_mandate_id or self.move_id.partner_id.valid_mandate_id ) if mandate: vals.update( { "mandate_id": mandate.id, "partner_bank_id": mandate.partner_bank_id.id, } ) return vals
33.37037
901
715
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" contact_mandate_id = fields.Many2one( comodel_name="account.banking.mandate", string="Contact Mandate", ) def _compute_valid_mandate_id(self): procesed_partners = self.browse() for partner in self: if partner.contact_mandate_id.state == "valid": partner.valid_mandate_id = partner.contact_mandate_id procesed_partners |= partner return super(ResPartner, self - procesed_partners)._compute_valid_mandate_id()
34.047619
715
646
py
PYTHON
15.0
# Copyright 2014-2016 Akretion (http://www.akretion.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). # @author Alexis de Lattre <[email protected]> { "name": "Account Payment Sale", "version": "15.0.1.0.0", "category": "Banking addons", "license": "AGPL-3", "summary": "Adds payment mode on sale orders", "author": "Akretion, " "Tecnativa, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "depends": ["sale", "account_payment_partner"], "data": ["views/sale_order_view.xml", "views/sale_report_templates.xml"], "auto_install": True, }
40.375
646
2,542
py
PYTHON
15.0
# Copyright 2018 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class CommonTestCase(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.bank = cls.env["res.partner.bank"].create( {"acc_number": "test", "partner_id": cls.env.user.company_id.partner_id.id} ) cls.journal = cls.env["account.journal"].create( { "name": "test journal", "code": "123", "type": "bank", "company_id": cls.env.ref("base.main_company").id, "bank_account_id": cls.bank.id, } ) cls.payment_mode = cls.env["account.payment.mode"].create( { "name": "test_mode", "active": True, "payment_method_id": cls.env.ref( "account.account_payment_method_manual_in" ).id, "bank_account_link": "fixed", "fixed_journal_id": cls.journal.id, } ) cls.payment_mode_2 = cls.env["account.payment.mode"].create( { "name": "test_mode_2", "active": True, "payment_method_id": cls.env.ref( "account.account_payment_method_manual_in" ).id, "bank_account_link": "fixed", "fixed_journal_id": cls.journal.id, } ) cls.base_partner = cls.env["res.partner"].create( { "name": "Dummy", "email": "[email protected]", "customer_payment_mode_id": cls.payment_mode.id, } ) cls.products = { "prod_order": cls.env.ref("product.product_order_01"), "prod_del": cls.env.ref("product.product_delivery_01"), "serv_order": cls.env["product.product"].create( { "name": "Test service product order", "type": "service", "invoice_policy": "order", } ), "serv_del": cls.env["product.product"].create( { "name": "Test service product delivery", "type": "service", "invoice_policy": "delivery", } ), }
35.802817
2,542
3,794
py
PYTHON
15.0
# Copyright 2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import Form from .common import CommonTestCase class TestSaleOrder(CommonTestCase): def create_sale_order(self, payment_mode=None): with Form(self.env["sale.order"]) as sale_form: sale_form.partner_id = self.base_partner sale_form.partner_invoice_id = self.base_partner sale_form.partner_shipping_id = self.base_partner sale_form.pricelist_id = self.env.ref("product.list0") for (_, p) in self.products.items(): with sale_form.order_line.new() as order_line: order_line.product_id = p order_line.name = p.name order_line.product_uom_qty = 2 order_line.product_uom = p.uom_id order_line.price_unit = p.list_price sale = sale_form.save() self.assertEqual( sale.payment_mode_id, self.base_partner.customer_payment_mode_id ) sale_form = Form(sale) # force payment mode if payment_mode: sale_form.payment_mode_id = payment_mode return sale_form.save() def create_invoice_and_check( self, order, expected_payment_mode, expected_partner_bank ): order.action_confirm() order._create_invoices() invoice = order.invoice_ids self.assertEqual(len(invoice), 1) self.assertEqual(invoice.payment_mode_id, expected_payment_mode) self.assertEqual(invoice.partner_bank_id, expected_partner_bank) def test_sale_to_invoice_payment_mode(self): """ Data: A partner with a specific payment_mode A sale order created with the payment_mode of the partner Test case: Create the invoice from the sale order Expected result: The invoice must be created with the payment_mode of the partner """ order = self.create_sale_order() self.create_invoice_and_check(order, self.payment_mode, self.bank) def test_sale_to_invoice_payment_mode_2(self): """ Data: A partner with a specific payment_mode A sale order created with an other payment_mode Test case: Create the invoice from the sale order Expected result: The invoice must be created with the specific payment_mode """ order = self.create_sale_order(payment_mode=self.payment_mode_2) self.create_invoice_and_check(order, self.payment_mode_2, self.bank) def test_sale_to_invoice_payment_mode_via_payment(self): """ Data: A partner with a specific payment_mode A sale order created with an other payment_mode Test case: Create the invoice from sale.advance.payment.inv Expected result: The invoice must be created with the specific payment_mode """ order = self.create_sale_order(payment_mode=self.payment_mode_2) context = { "active_model": "sale.order", "active_ids": [order.id], "active_id": order.id, } order.action_confirm() payment = self.env["sale.advance.payment.inv"].create( { "advance_payment_method": "fixed", "fixed_amount": 5, "product_id": self.env.ref("sale.advance_product_0").id, } ) payment.with_context(**context).create_invoices() invoice = order.invoice_ids self.assertEqual(len(invoice), 1) self.assertEqual(invoice.payment_mode_id, self.payment_mode_2) self.assertFalse(invoice.partner_bank_id)
38.714286
3,794
504
py
PYTHON
15.0
# Copyright 2016-2020 Akretion - Alexis de Lattre # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" def _prepare_invoice_values(self, order, name, amount, so_line): """Copy payment mode from sale order to invoice""" vals = super()._prepare_invoice_values(order, name, amount, so_line) order._get_payment_mode_vals(vals) return vals
36
504
1,425
py
PYTHON
15.0
# Copyright 2014-2020 Akretion - Alexis de Lattre # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", compute="_compute_payment_mode", store=True, readonly=False, check_company=True, domain="[('payment_type', '=', 'inbound'), ('company_id', '=', company_id)]", ) @api.depends("partner_id") def _compute_payment_mode(self): for order in self: if order.partner_id: order.payment_mode_id = order.partner_id.customer_payment_mode_id else: order.payment_mode_id = False def _get_payment_mode_vals(self, vals): if self.payment_mode_id: vals["payment_mode_id"] = self.payment_mode_id.id if ( self.payment_mode_id.bank_account_link == "fixed" and self.payment_mode_id.payment_method_id.code == "manual" ): vals[ "partner_bank_id" ] = self.payment_mode_id.fixed_journal_id.bank_account_id.id def _prepare_invoice(self): """Copy bank partner from sale order to invoice""" vals = super()._prepare_invoice() self._get_payment_mode_vals(vals) return vals
33.928571
1,425
1,299
py
PYTHON
15.0
# Copyright 2013-2020 Akretion (www.akretion.com) # Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2014-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Banking SEPA Direct Debit", "summary": "Create SEPA files for Direct Debit", "version": "15.0.2.1.0", "license": "AGPL-3", "author": "Akretion, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "category": "Banking addons", "depends": ["account_banking_pain_base", "account_banking_mandate"], "external_dependencies": { "python": [ "stdnum", ], }, "assets": { "web.report_assets_common": [ "/account_banking_sepa_direct_debit/static/src/css/report.css" ], }, "data": [ "views/account_banking_mandate_view.xml", "views/res_config_settings.xml", "views/account_payment_mode.xml", "data/mandate_expire_cron.xml", "data/account_payment_method.xml", "data/report_paperformat.xml", "reports/sepa_direct_debit_mandate.xml", "views/report_sepa_direct_debit_mandate.xml", ], "demo": ["demo/sepa_direct_debit_demo.xml"], "installable": True, }
35.108108
1,299
14,244
py
PYTHON
15.0
# Copyright 2016 Akretion (Alexis de Lattre <[email protected]>) # Copyright 2018-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import base64 from lxml import etree from odoo import fields from odoo.tests.common import TransactionCase from odoo.tools import float_compare class TestSDDBase(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.company_B = cls.env["res.company"].create({"name": "Company B"}) user_type_payable = cls.env.ref("account.data_account_type_payable") cls.account_payable_company_B = cls.env["account.account"].create( { "code": "NC1110", "name": "Test Payable Account Company B", "user_type_id": user_type_payable.id, "reconcile": True, "company_id": cls.company_B.id, } ) user_type_receivable = cls.env.ref("account.data_account_type_receivable") cls.account_receivable_company_B = cls.env["account.account"].create( { "code": "NC1111", "name": "Test Receivable Account Company B", "user_type_id": user_type_receivable.id, "reconcile": True, "company_id": cls.company_B.id, } ) cls.company = cls.env["res.company"] cls.account_model = cls.env["account.account"] cls.journal_model = cls.env["account.journal"] cls.payment_order_model = cls.env["account.payment.order"] cls.payment_line_model = cls.env["account.payment.line"] cls.mandate_model = cls.env["account.banking.mandate"] cls.partner_bank_model = cls.env["res.partner.bank"] cls.attachment_model = cls.env["ir.attachment"] cls.invoice_model = cls.env["account.move"] cls.partner_agrolait = cls.env.ref("base.res_partner_2") cls.partner_c2c = cls.env.ref("base.res_partner_12") cls.eur_currency = cls.env.ref("base.EUR") cls.setUpAdditionalAccounts() cls.setUpAccountJournal() cls.main_company = cls.company_B cls.company_B.write( { "name": "Test EUR company", "currency_id": cls.eur_currency.id, "sepa_creditor_identifier": "FR78ZZZ424242", } ) cls.env.user.write( { "company_ids": [(6, 0, cls.main_company.ids)], "company_id": cls.main_company.id, } ) (cls.partner_agrolait + cls.partner_c2c).write( { "company_id": cls.main_company.id, "property_account_payable_id": cls.account_payable_company_B.id, "property_account_receivable_id": cls.account_receivable_company_B.id, } ) cls.company_bank = cls.env.ref("account_payment_mode.main_company_iban").copy( { "company_id": cls.main_company.id, "partner_id": cls.main_company.partner_id.id, "bank_id": ( cls.env.ref("account_payment_mode.bank_la_banque_postale").id ), } ) # create journal cls.bank_journal = cls.journal_model.create( { "name": "Company Bank journal", "type": "bank", "code": "BNKFC", "bank_account_id": cls.company_bank.id, "bank_id": cls.company_bank.bank_id.id, "inbound_payment_method_line_ids": [ ( 0, 0, { "payment_method_id": cls.env.ref( "account_banking_sepa_direct_debit.sepa_direct_debit" ).id, "payment_account_id": cls.account_expense_company_B.id, }, ) ], } ) # update payment mode cls.payment_mode = cls.env.ref( "account_banking_sepa_direct_debit.payment_mode_inbound_sepa_dd1" ).copy({"company_id": cls.main_company.id}) cls.payment_mode.write( {"bank_account_link": "fixed", "fixed_journal_id": cls.bank_journal.id} ) # Copy partner bank accounts bank1 = cls.env.ref("account_payment_mode.res_partner_12_iban").copy( {"company_id": cls.main_company.id} ) cls.mandate12 = cls.env.ref( "account_banking_sepa_direct_debit.res_partner_12_mandate" ).copy( { "partner_bank_id": bank1.id, "company_id": cls.main_company.id, "state": "valid", "unique_mandate_reference": "BMTEST12", } ) bank2 = cls.env.ref("account_payment_mode.res_partner_2_iban").copy( {"company_id": cls.main_company.id} ) cls.mandate2 = cls.env.ref( "account_banking_sepa_direct_debit.res_partner_2_mandate" ).copy( { "partner_bank_id": bank2.id, "company_id": cls.main_company.id, "state": "valid", "unique_mandate_reference": "BMTEST2", } ) # Trigger the recompute of account type on res.partner.bank cls.partner_bank_model.search([])._compute_acc_type() @classmethod def setUpAdditionalAccounts(cls): """Set up some addionnal accounts: expenses, revenue, ...""" user_type_income = cls.env.ref("account.data_account_type_direct_costs") cls.account_income = cls.env["account.account"].create( { "code": "NC1112", "name": "Sale - Test Account", "user_type_id": user_type_income.id, } ) user_type_expense = cls.env.ref("account.data_account_type_expenses") cls.account_expense = cls.env["account.account"].create( { "code": "NC1113", "name": "HR Expense - Test Purchase Account", "user_type_id": user_type_expense.id, } ) user_type_revenue = cls.env.ref("account.data_account_type_revenue") cls.account_revenue = cls.env["account.account"].create( { "code": "NC1114", "name": "Sales - Test Sales Account", "user_type_id": user_type_revenue.id, "reconcile": True, } ) user_type_income = cls.env.ref("account.data_account_type_direct_costs") cls.account_income_company_B = cls.env["account.account"].create( { "code": "NC1112", "name": "Sale - Test Account Company B", "user_type_id": user_type_income.id, "company_id": cls.company_B.id, } ) user_type_expense = cls.env.ref("account.data_account_type_expenses") cls.account_expense_company_B = cls.env["account.account"].create( { "code": "NC1113", "name": "HR Expense - Test Purchase Account Company B", "user_type_id": user_type_expense.id, "company_id": cls.company_B.id, } ) user_type_revenue = cls.env.ref("account.data_account_type_revenue") cls.account_revenue_company_B = cls.env["account.account"].create( { "code": "NC1114", "name": "Sales - Test Sales Account Company B", "user_type_id": user_type_revenue.id, "reconcile": True, "company_id": cls.company_B.id, } ) @classmethod def setUpAccountJournal(cls): # Set up some journals cls.journal_purchase_company_B = cls.env["account.journal"].create( { "name": "Purchase Journal Company B - Test", "code": "AJ-PURC", "type": "purchase", "company_id": cls.company_B.id, "default_account_id": cls.account_expense_company_B.id, } ) cls.journal_sale_company_B = cls.env["account.journal"].create( { "name": "Sale Journal Company B - Test", "code": "AJ-SALE", "type": "sale", "company_id": cls.company_B.id, "default_account_id": cls.account_income_company_B.id, } ) cls.journal_general_company_B = cls.env["account.journal"].create( { "name": "General Journal Company B - Test", "code": "AJ-GENERAL", "type": "general", "company_id": cls.company_B.id, } ) def check_sdd(self): self.mandate2.recurrent_sequence_type = "first" invoice1 = self.create_invoice(self.partner_agrolait.id, self.mandate2, 42.0) self.mandate12.type = "oneoff" invoice2 = self.create_invoice(self.partner_c2c.id, self.mandate12, 11.0) for inv in [invoice1, invoice2]: action = inv.create_account_payment_line() self.assertEqual(action["res_model"], "account.payment.order") payment_order = self.payment_order_model.browse(action["res_id"]) self.assertEqual(payment_order.payment_type, "inbound") self.assertEqual(payment_order.payment_mode_id, self.payment_mode) self.assertEqual(payment_order.journal_id, self.bank_journal) # Check payment line pay_lines = self.payment_line_model.search( [ ("partner_id", "=", self.partner_agrolait.id), ("order_id", "=", payment_order.id), ] ) self.assertEqual(len(pay_lines), 1) agrolait_pay_line1 = pay_lines[0] accpre = self.env["decimal.precision"].precision_get("Account") self.assertEqual(agrolait_pay_line1.currency_id, self.eur_currency) self.assertEqual(agrolait_pay_line1.mandate_id, invoice1.mandate_id) self.assertEqual( agrolait_pay_line1.partner_bank_id, invoice1.mandate_id.partner_bank_id ) self.assertEqual( float_compare( agrolait_pay_line1.amount_currency, 42, precision_digits=accpre ), 0, ) self.assertEqual(agrolait_pay_line1.communication_type, "normal") self.assertEqual(agrolait_pay_line1.communication, invoice1.name) payment_order.draft2open() self.assertEqual(payment_order.state, "open") self.assertEqual(payment_order.sepa, True) # Check account payment agrolait_bank_line = payment_order.payment_ids[0] self.assertEqual(agrolait_bank_line.currency_id, self.eur_currency) self.assertEqual( float_compare(agrolait_bank_line.amount, 42.0, precision_digits=accpre), 0, ) self.assertEqual(agrolait_bank_line.payment_reference, invoice1.name) self.assertEqual( agrolait_bank_line.partner_bank_id, invoice1.mandate_id.partner_bank_id ) action = payment_order.open2generated() self.assertEqual(payment_order.state, "generated") self.assertEqual(action["res_model"], "ir.attachment") attachment = self.attachment_model.browse(action["res_id"]) self.assertEqual(attachment.name[-4:], ".xml") xml_file = base64.b64decode(attachment.datas) xml_root = etree.fromstring(xml_file) namespaces = xml_root.nsmap namespaces["p"] = xml_root.nsmap[None] namespaces.pop(None) pay_method_xpath = xml_root.xpath("//p:PmtInf/p:PmtMtd", namespaces=namespaces) self.assertEqual(pay_method_xpath[0].text, "DD") sepa_xpath = xml_root.xpath( "//p:PmtInf/p:PmtTpInf/p:SvcLvl/p:Cd", namespaces=namespaces ) self.assertEqual(sepa_xpath[0].text, "SEPA") debtor_acc_xpath = xml_root.xpath( "//p:PmtInf/p:CdtrAcct/p:Id/p:IBAN", namespaces=namespaces ) self.assertEqual( debtor_acc_xpath[0].text, payment_order.company_partner_bank_id.sanitized_acc_number, ) payment_order.generated2uploaded() self.assertEqual(payment_order.state, "uploaded") for inv in [invoice1, invoice2]: self.assertEqual(inv.payment_state, "paid") self.assertEqual(self.mandate2.recurrent_sequence_type, "recurring") return def create_invoice(self, partner_id, mandate, price_unit, inv_type="out_invoice"): invoice_vals = [ ( 0, 0, { "name": "Great service", "quantity": 1, "account_id": self.account_revenue_company_B.id, "price_unit": price_unit, }, ) ] invoice = self.invoice_model.create( { "partner_id": partner_id, "reference_type": "none", "currency_id": self.env.ref("base.EUR").id, "move_type": inv_type, "date": fields.Date.today(), "payment_mode_id": self.payment_mode.id, "mandate_id": mandate.id, "invoice_line_ids": invoice_vals, } ) invoice.action_post() return invoice class TestSDD(TestSDDBase): def test_pain_001_02(self): self.payment_mode.payment_method_id.pain_version = "pain.008.001.02" self.check_sdd() def test_pain_003_02(self): self.payment_mode.payment_method_id.pain_version = "pain.008.003.02" self.check_sdd() def test_pain_001_03(self): self.payment_mode.payment_method_id.pain_version = "pain.008.001.03" self.check_sdd() def test_pain_001_04(self): self.payment_mode.payment_method_id.pain_version = "pain.008.001.04" self.check_sdd()
40.465909
14,244
1,804
py
PYTHON
15.0
# Copyright 2016-2020 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from dateutil.relativedelta import relativedelta from odoo import fields from odoo.exceptions import UserError from odoo.tests.common import TransactionCase class TestMandate(TransactionCase): def test_contrains(self): with self.assertRaises(UserError): self.mandate.recurrent_sequence_type = False self.mandate.type = "recurrent" self.mandate._check_recurring_type() def test_onchange_bank(self): self.mandate.write( {"type": "recurrent", "recurrent_sequence_type": "recurring"} ) self.mandate.validate() self.mandate.partner_bank_id = self.env.ref( "account_payment_mode.res_partner_2_iban" ) self.mandate.mandate_partner_bank_change() self.assertEqual(self.mandate.recurrent_sequence_type, "first") def test_expire(self): self.mandate.signature_date = fields.Date.today() + relativedelta(months=-50) self.mandate.validate() self.assertEqual(self.mandate.state, "valid") self.env["account.banking.mandate"]._sdd_mandate_set_state_to_expired() self.assertEqual(self.mandate.state, "expired") def setUp(self): res = super().setUp() self.partner = self.env.ref("base.res_partner_12") bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") self.mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "format": "sepa", "type": "oneoff", "signature_date": "2015-01-01", } ) return res
37.583333
1,804
2,383
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import UserError class AccountPaymentLine(models.Model): _inherit = "account.payment.line" def draft2open_payment_line_check(self): res = super().draft2open_payment_line_check() sepa_dd_lines = self.filtered( lambda l: l.order_id.payment_method_id.code == "sepa_direct_debit" ) sepa_dd_lines._check_sepa_direct_debit_ready() return res def _check_sepa_direct_debit_ready(self): """ This method checks whether the payment line(s) are ready to be used in the SEPA Direct Debit file generation. :raise: UserError if a line does not fulfils all requirements """ for rec in self: if not rec.mandate_id: raise UserError( _( "Missing SEPA Direct Debit mandate on the line with " "partner {partner_name} (reference {reference})." ).format(partner_name=rec.partner_id.name, reference=rec.name) ) if rec.mandate_id.state != "valid": raise UserError( _( "The SEPA Direct Debit mandate with reference " "{mandate_ref} for partner {partner_name} has " "expired." ).format( mandate_ref=rec.mandate_id.unique_mandate_reference, partner_name=rec.partner_id.name, ) ) if rec.mandate_id.type == "oneoff" and rec.mandate_id.last_debit_date: raise UserError( _( "The SEPA Direct Debit mandate with reference " "{mandate_ref} for partner {partner_name} has type set " "to 'One-Off' but has a last debit date set to " "{last_debit_date}. Therefore, it cannot be used." ).format( mandate_ref=rec.mandate_id.unique_mandate_reference, partner_name=rec.partner_id.name, last_debit_date=rec.mandate_id.last_debit_date, ) )
42.553571
2,383
13,403
py
PYTHON
15.0
# Copyright 2020 Akretion (Alexis de Lattre <[email protected]>) # Copyright 2018-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from lxml import etree from odoo import _, exceptions, fields, models from odoo.exceptions import UserError class AccountPaymentOrder(models.Model): _inherit = "account.payment.order" def generate_payment_file(self): """Creates the SEPA Direct Debit file. That's the important code !""" self.ensure_one() if self.payment_method_id.code != "sepa_direct_debit": return super().generate_payment_file() pain_flavor = self.payment_method_id.pain_version # We use pain_flavor.startswith('pain.008.001.xx') # to support country-specific extensions such as # pain.008.001.02.ch.01 (cf l10n_ch_sepa) if pain_flavor.startswith("pain.008.001.02"): bic_xml_tag = "BIC" name_maxsize = 70 root_xml_tag = "CstmrDrctDbtInitn" elif pain_flavor.startswith("pain.008.003.02"): bic_xml_tag = "BIC" name_maxsize = 70 root_xml_tag = "CstmrDrctDbtInitn" elif pain_flavor.startswith("pain.008.001.03"): bic_xml_tag = "BICFI" name_maxsize = 140 root_xml_tag = "CstmrDrctDbtInitn" elif pain_flavor.startswith("pain.008.001.04"): bic_xml_tag = "BICFI" name_maxsize = 140 root_xml_tag = "CstmrDrctDbtInitn" else: raise UserError( _( "Payment Type Code '%s' is not supported. The only " "Payment Type Code supported for SEPA Direct Debit are " "'pain.008.001.02', 'pain.008.001.03' and " "'pain.008.001.04'." ) % pain_flavor ) pay_method = self.payment_mode_id.payment_method_id xsd_file = pay_method.get_xsd_file_path() gen_args = { "bic_xml_tag": bic_xml_tag, "name_maxsize": name_maxsize, "convert_to_ascii": pay_method.convert_to_ascii, "payment_method": "DD", "file_prefix": "sdd_", "pain_flavor": pain_flavor, "pain_xsd_file": xsd_file, } nsmap = self.generate_pain_nsmap() attrib = self.generate_pain_attrib() xml_root = etree.Element("Document", nsmap=nsmap, attrib=attrib) pain_root = etree.SubElement(xml_root, root_xml_tag) # A. Group header ( group_header, nb_of_transactions_a, control_sum_a, ) = self.generate_group_header_block(pain_root, gen_args) transactions_count_a = 0 amount_control_sum_a = 0.0 lines_per_group = {} # key = (requested_date, priority, sequence type) # value = list of lines as objects for line in self.payment_ids: transactions_count_a += 1 payment_line = line.payment_line_ids[:1] priority = payment_line.priority categ_purpose = payment_line.category_purpose scheme = payment_line.mandate_id.scheme if payment_line.mandate_id.type == "oneoff": seq_type = "OOFF" elif payment_line.mandate_id.type == "recurrent": seq_type_map = {"recurring": "RCUR", "first": "FRST", "final": "FNAL"} seq_type_label = payment_line.mandate_id.recurrent_sequence_type assert seq_type_label is not False seq_type = seq_type_map[seq_type_label] else: raise exceptions.UserError( _( "Invalid mandate type in '%s'. Valid ones are 'Recurrent' " "or 'One-Off'" ) % payment_line.mandate_id.unique_mandate_reference ) # The field line.date is the requested payment date # taking into account the 'date_preferred' setting # cf account_banking_payment_export/models/account_payment.py # in the inherit of action_open() key = (line.date, priority, categ_purpose, seq_type, scheme) if key in lines_per_group: lines_per_group[key].append(line) else: lines_per_group[key] = [line] for ( (requested_date, priority, categ_purpose, sequence_type, scheme), lines, ) in list(lines_per_group.items()): requested_date = fields.Date.to_string(requested_date) # B. Payment info ( payment_info, nb_of_transactions_b, control_sum_b, ) = self.generate_start_payment_info_block( pain_root, "self.name + '-' + " "sequence_type + '-' + requested_date.replace('-', '') " "+ '-' + priority + '-' + category_purpose", priority, scheme, categ_purpose, sequence_type, requested_date, { "self": self, "sequence_type": sequence_type, "priority": priority, "category_purpose": categ_purpose or "NOcateg", "requested_date": requested_date, }, gen_args, ) self.generate_party_block( payment_info, "Cdtr", "B", self.company_partner_bank_id, gen_args ) charge_bearer = etree.SubElement(payment_info, "ChrgBr") if self.sepa: charge_bearer_text = "SLEV" else: charge_bearer_text = self.charge_bearer charge_bearer.text = charge_bearer_text creditor_scheme_identification = etree.SubElement( payment_info, "CdtrSchmeId" ) self.generate_creditor_scheme_identification( creditor_scheme_identification, "self.payment_mode_id.sepa_creditor_identifier or " "self.company_id.sepa_creditor_identifier", "SEPA Creditor Identifier", {"self": self}, "SEPA", gen_args, ) transactions_count_b = 0 amount_control_sum_b = 0.0 for line in lines: transactions_count_b += 1 # C. Direct Debit Transaction Info dd_transaction_info = etree.SubElement(payment_info, "DrctDbtTxInf") payment_identification = etree.SubElement(dd_transaction_info, "PmtId") instruction_identification = etree.SubElement( payment_identification, "InstrId" ) instruction_identification.text = self._prepare_field( "Instruction Identification", "str(line.move_id.id)", {"line": line}, 35, gen_args=gen_args, ) end2end_identification = etree.SubElement( payment_identification, "EndToEndId" ) end2end_identification.text = self._prepare_field( "End to End Identification", "str(line.move_id.id)", {"line": line}, 35, gen_args=gen_args, ) currency_name = self._prepare_field( "Currency Code", "line.currency_id.name", {"line": line}, 3, gen_args=gen_args, ) instructed_amount = etree.SubElement( dd_transaction_info, "InstdAmt", Ccy=currency_name ) instructed_amount.text = "%.2f" % line.amount amount_control_sum_a += line.amount amount_control_sum_b += line.amount dd_transaction = etree.SubElement(dd_transaction_info, "DrctDbtTx") mandate_related_info = etree.SubElement(dd_transaction, "MndtRltdInf") mandate_identification = etree.SubElement( mandate_related_info, "MndtId" ) mandate = line.payment_line_ids[:1].mandate_id mandate_identification.text = self._prepare_field( "Unique Mandate Reference", "mandate.unique_mandate_reference", {"mandate": mandate}, 35, gen_args=gen_args, ) mandate_signature_date = etree.SubElement( mandate_related_info, "DtOfSgntr" ) mandate_signature_date.text = self._prepare_field( "Mandate Signature Date", "signature_date", {"signature_date": fields.Date.to_string(mandate.signature_date)}, 10, gen_args=gen_args, ) if sequence_type == "FRST" and mandate.last_debit_date: amendment_indicator = etree.SubElement( mandate_related_info, "AmdmntInd" ) amendment_indicator.text = "true" amendment_info_details = etree.SubElement( mandate_related_info, "AmdmntInfDtls" ) ori_debtor_account = etree.SubElement( amendment_info_details, "OrgnlDbtrAcct" ) ori_debtor_account_id = etree.SubElement(ori_debtor_account, "Id") ori_debtor_agent_other = etree.SubElement( ori_debtor_account_id, "Othr" ) ori_debtor_agent_other_id = etree.SubElement( ori_debtor_agent_other, "Id" ) ori_debtor_agent_other_id.text = "SMNDA" # Until 20/11/2016, SMNDA meant # "Same Mandate New Debtor Agent" # After 20/11/2016, SMNDA means # "Same Mandate New Debtor Account" self.generate_party_block( dd_transaction_info, "Dbtr", "C", line.partner_bank_id, gen_args, line, ) line_purpose = line.payment_line_ids[:1].purpose if line_purpose: purpose = etree.SubElement(dd_transaction_info, "Purp") etree.SubElement(purpose, "Cd").text = line_purpose self.generate_remittance_info_block(dd_transaction_info, line, gen_args) nb_of_transactions_b.text = str(transactions_count_b) control_sum_b.text = "%.2f" % amount_control_sum_b nb_of_transactions_a.text = str(transactions_count_a) control_sum_a.text = "%.2f" % amount_control_sum_a return self.finalize_sepa_file_creation(xml_root, gen_args) def generated2uploaded(self): """Write 'last debit date' on mandates Set mandates from first to recurring Set oneoff mandates to expired """ # I call super() BEFORE updating the sequence_type # from first to recurring, so that the account move # is generated BEFORE, which will allow the split # of the account move per sequence_type res = super().generated2uploaded() abmo = self.env["account.banking.mandate"] for order in self: to_expire_mandates = abmo.browse([]) first_mandates = abmo.browse([]) all_mandates = abmo.browse([]) for payment in order.payment_ids: mandate = payment.payment_line_ids.mandate_id if mandate in all_mandates: continue all_mandates += mandate if mandate.type == "oneoff": to_expire_mandates += mandate elif mandate.type == "recurrent": seq_type = mandate.recurrent_sequence_type if seq_type == "final": to_expire_mandates += mandate elif seq_type == "first": first_mandates += mandate all_mandates.write({"last_debit_date": order.date_generated}) to_expire_mandates.write({"state": "expired"}) first_mandates.write({"recurrent_sequence_type": "recurring"}) for first_mandate in first_mandates: first_mandate.message_post( body=_( "Automatically switched from <b>First</b> to " "<b>Recurring</b> when the debit order " "<a href=# data-oe-model=account.payment.order " "data-oe-id=%d>{}</a> has been marked as uploaded." ).format(order.id, order.name) ) return res
43.800654
13,403
4,449
py
PYTHON
15.0
# Copyright 2020 Akretion - Alexis de Lattre # Copyright 2014 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from datetime import datetime from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError NUMBER_OF_UNUSED_MONTHS_BEFORE_EXPIRY = 36 logger = logging.getLogger(__name__) class AccountBankingMandate(models.Model): """SEPA Direct Debit Mandate""" _inherit = "account.banking.mandate" _rec_name = "display_name" format = fields.Selection( selection_add=[("sepa", "Sepa Mandate")], default="sepa", ondelete={"sepa": "set default"}, ) type = fields.Selection( selection_add=[("recurrent", "Recurrent"), ("oneoff", "One-Off")], default="recurrent", ondelete={"recurrent": "set null", "oneoff": "set null"}, ) recurrent_sequence_type = fields.Selection( [("first", "First"), ("recurring", "Recurring"), ("final", "Final")], string="Sequence Type for Next Debit", tracking=70, help="This field is only used for Recurrent mandates, not for " "One-Off mandates.", default="first", ) scheme = fields.Selection( [("CORE", "Basic (CORE)"), ("B2B", "Enterprise (B2B)")], default="CORE", tracking=80, ) unique_mandate_reference = fields.Char(size=35) # cf ISO 20022 display_name = fields.Char(compute="_compute_display_name2", store=True) @api.constrains("type", "recurrent_sequence_type") def _check_recurring_type(self): for mandate in self: if mandate.type == "recurrent" and not mandate.recurrent_sequence_type: raise UserError( _("The recurrent mandate '%s' must have a sequence type.") % mandate.unique_mandate_reference ) @api.depends("unique_mandate_reference", "recurrent_sequence_type") def _compute_display_name2(self): for mandate in self: if mandate.format == "sepa": mandate.display_name = "{} ({})".format( mandate.unique_mandate_reference, mandate.recurrent_sequence_type ) else: mandate.display_name = mandate.unique_mandate_reference @api.onchange("partner_bank_id") def mandate_partner_bank_change(self): super().mandate_partner_bank_change() res = {} if ( self.state == "valid" and self.partner_bank_id and self.type == "recurrent" and self.recurrent_sequence_type != "first" ): self.recurrent_sequence_type = "first" res["warning"] = { "title": _("Mandate update"), "message": _( "As you changed the bank account attached " "to this mandate, the 'Sequence Type' has " "been set back to 'First'." ), } return res def _sdd_mandate_set_state_to_expired(self): logger.info("Searching for SDD Mandates that must be set to Expired") expire_limit_date = datetime.today() + relativedelta( months=-NUMBER_OF_UNUSED_MONTHS_BEFORE_EXPIRY ) expired_mandates = self.search( [ "|", ("last_debit_date", "=", False), ("last_debit_date", "<=", expire_limit_date), ("state", "=", "valid"), ("signature_date", "<=", expire_limit_date), ] ) if expired_mandates: expired_mandates.write({"state": "expired"}) expired_mandates.message_post( body=_( "Mandate automatically set to expired after %d months without use." ) % NUMBER_OF_UNUSED_MONTHS_BEFORE_EXPIRY ) logger.info( "%d SDD Mandate set to expired: IDs %s" % (len(expired_mandates), expired_mandates.ids) ) else: logger.info("0 SDD Mandates had to be set to Expired") def print_report(self): self.ensure_one() xmlid = "account_banking_sepa_direct_debit.report_sepa_direct_debit_mandate" action = self.env.ref(xmlid).report_action(self) return action
36.467213
4,449
1,423
py
PYTHON
15.0
# Copyright 2020 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountPaymentMethod(models.Model): _inherit = "account.payment.method" pain_version = fields.Selection( selection_add=[ ("pain.008.001.02", "pain.008.001.02 (recommended for direct debit)"), ("pain.008.001.03", "pain.008.001.03"), ("pain.008.001.04", "pain.008.001.04"), ("pain.008.003.02", "pain.008.003.02 (direct debit in Germany)"), ], ondelete={ "pain.008.001.02": "set null", "pain.008.001.03": "set null", "pain.008.001.04": "set null", "pain.008.003.02": "set null", }, ) def get_xsd_file_path(self): self.ensure_one() if self.pain_version in [ "pain.008.001.02", "pain.008.001.03", "pain.008.001.04", "pain.008.003.02", ]: path = "account_banking_sepa_direct_debit/data/%s.xsd" % self.pain_version return path return super().get_xsd_file_path() @api.model def _get_payment_method_information(self): res = super()._get_payment_method_information() res["sepa_direct_debit"] = {"mode": "multi", "domain": [("type", "=", "bank")]} return res
34.707317
1,423
1,172
py
PYTHON
15.0
# Copyright 2013-2016 Akretion - Alexis de Lattre # Copyright 2014 Tecnativa - Pedro M. Baeza # Copyright 2016 Tecnativa - Antonio Espinosa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from stdnum.eu.at_02 import is_valid from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ResCompany(models.Model): _inherit = "res.company" sepa_creditor_identifier = fields.Char( string="SEPA Creditor Identifier", size=35, help="Enter the Creditor Identifier that has been attributed to your " "company to make SEPA Direct Debits. This identifier is composed " "of :\n- your country ISO code (2 letters)\n- a 2-digits " "checkum\n- a 3-letters business code\n- a country-specific " "identifier", ) @api.constrains("sepa_creditor_identifier") def _check_sepa_creditor_identifier(self): for company in self: ics = company.sepa_creditor_identifier if ics and not is_valid(ics): raise ValidationError( _("The SEPA Creditor Identifier '%s' is invalid.") % ics )
36.625
1,172
1,207
py
PYTHON
15.0
# Copyright 2016 Tecnativa - Antonio Espinosa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from stdnum.eu.at_02 import is_valid from odoo import _, api, fields, models from odoo.exceptions import ValidationError class AccountPaymentMode(models.Model): _inherit = "account.payment.mode" sepa_creditor_identifier = fields.Char( string="SEPA Creditor Identifier", size=35, help="Enter the Creditor Identifier that has been attributed to your " "company to make SEPA Direct Debits. If not defined, " "SEPA Creditor Identifier from company will be used.\n" "This identifier is composed of :\n" "- your country ISO code (2 letters)\n" "- a 2-digits checkum\n" "- a 3-letters business code\n" "- a country-specific identifier", ) @api.constrains("sepa_creditor_identifier") def _check_sepa_creditor_identifier(self): for payment_mode in self: ics = payment_mode.sepa_creditor_identifier if ics and not is_valid(ics): raise ValidationError( _("The SEPA Creditor Identifier '%s' is invalid.") % ics )
36.575758
1,207
356
py
PYTHON
15.0
# Copyright 2016 Akretion - Alexis de Lattre # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" sepa_creditor_identifier = fields.Char( related="company_id.sepa_creditor_identifier", readonly=False )
29.666667
356
1,028
py
PYTHON
15.0
# Copyright 2013-2016 Akretion - Alexis de Lattre # Copyright 2016 Tecnativa - Antonio Espinosa # Copyright 2021 Tecnativa - Carlos Roca # Copyright 2014-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Banking PAIN Base Module", "summary": "Base module for PAIN file generation", "version": "15.0.2.0.2", "license": "AGPL-3", "author": "Akretion, Noviat, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "category": "Hidden", "depends": ["account_payment_order"], "external_dependencies": {"python": ["unidecode", "lxml"]}, "data": [ "security/security.xml", "views/account_payment_line.xml", "views/account_payment_order.xml", "views/account_payment_mode.xml", "views/res_config_settings.xml", "views/account_payment_method.xml", ], "post_init_hook": "set_default_initiating_party", "installable": True, }
38.074074
1,028
384
py
PYTHON
15.0
# © 2015-2016 Akretion - Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID, api def set_default_initiating_party(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) for company in env["res.company"].search([]): company._default_initiating_party() return
31.916667
383
7,518
py
PYTHON
15.0
# Copyright 2013-2016 Akretion - Alexis de Lattre <[email protected]> # Copyright 2021 Tecnativa - Carlos Roca # Copyright 2014-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountPaymentLine(models.Model): _inherit = "account.payment.line" priority = fields.Selection( [("NORM", "Normal"), ("HIGH", "High")], default="NORM", help="This field will be used as 'Instruction Priority' in " "the generated PAIN file.", ) # local_instrument is used for instant credit transfers which # will begin on November 2017, cf account_banking_sepa_credit_transfer # It is also used in some countries such as switzerland, # cf l10n_ch_pain_base that adds some entries in the selection field local_instrument = fields.Selection([]) category_purpose = fields.Selection( [ # Full category purpose list found on: # https://www.iso20022.org/external_code_list.page # Document "External Code Sets spreadsheet" version Feb 8th 2017 ("BONU", "Bonus Payment"), ("CASH", "Cash Management Transfer"), ("CBLK", "Card Bulk Clearing"), ("CCRD", "Credit Card Payment"), ("CORT", "Trade Settlement Payment"), ("DCRD", "Debit Card Payment"), ("DIVI", "Dividend"), ("DVPM", "Deliver Against Payment"), ("EPAY", "ePayment"), ("FCOL", "Fee Collection"), ("GOVT", "Government Payment"), ("HEDG", "Hedging"), ("ICCP", "Irrevocable Credit Card Payment"), ("IDCP", "Irrevocable Debit Card Payment"), ("INTC", "Intra-Company Payment"), ("INTE", "Interest"), ("LOAN", "Loan"), ("OTHR", "Other Payment"), ("PENS", "Pension Payment"), ("RVPM", "Receive Against Payment"), ("SALA", "Salary Payment"), ("SECU", "Securities"), ("SSBE", "Social Security Benefit"), ("SUPP", "Supplier Payment"), ("TAXS", "Tax Payment"), ("TRAD", "Trade"), ("TREA", "Treasury Payment"), ("VATX", "VAT Payment"), ("WHLD", "WithHolding"), ], help="If neither your bank nor your local regulations oblige you to " "set the category purpose, leave the field empty.", ) purpose = fields.Selection( # Full category purpose list found on: # https://www.iso20022.org/external_code_list.page # Document "External Code Sets spreadsheet" version 31 August, 2018 selection=[ ("ACCT", "Account Management"), ("CASH", "Cash Management Transfer"), ("COLL", "Collection Payment"), ("INTC", "Intra Company Payment"), ("LIMA", "Liquidity Management"), ("NETT", "Netting"), ("AGRT", "Agricultural Transfer"), ("BEXP", "Business Expenses"), ("COMC", "Commercial Payment"), ("CPYR", "Copyright"), ("GDDS", "Purchase Sale Of Goods"), ("LICF", "License Fee"), ("ROYA", "Royalties"), ("SCVE", "Purchase Sale Of Services"), ("SUBS", "Subscription"), ("SUPP", "Supplier Payment"), ("TRAD", "Trade Services"), ("CHAR", "Charity Payment"), ("COMT", "Consumer Third Party Consolidated Payment"), ("CLPR", "Car Loan Principal Repayment"), ("GOVI", "Government Insurance"), ("HLRP", "Housing Loan Repayment"), ("INSU", "Insurance Premium"), ("INTE", "Interest"), ("LBRI", "Labor Insurance"), ("LIFI", "Life Insurance"), ("LOAN", "Loan"), ("LOAR", "Loan Repayment"), ("PPTI", "Property Insurance"), ("RINP", "Recurring Installment Payment"), ("TRFD", "Trust Fund"), ("ADVA", "Advance Payment"), ("CCRD", "Credit Card Payment "), ("CFEE", "Cancellation Fee"), ("COST", "Costs"), ("DCRD", "Debit Card Payment"), ("GOVT", "Government Payment"), ("IHRP", "Instalment Hire Purchase Agreement"), ("INSM", "Installment"), ("MSVC", "Multiple Service Types"), ("NOWS", "Not Otherwise Specified"), ("OFEE", "Opening Fee"), ("OTHR", "Other"), ("PADD", "Preauthorized debit"), ("PTSP", "Payment Terms"), ("RCPT", "Receipt Payment"), ("RENT", "Rent"), ("STDY", "Study"), ("ANNI", "Annuity"), ("CMDT", "Commodity Transfer"), ("DERI", "Derivatives"), ("DIVD", "Dividend"), ("FREX", "Foreign Exchange"), ("HEDG", "Hedging"), ("PRME", "Precious Metal"), ("SAVG", "Savings"), ("SECU", "Securities"), ("TREA", "Treasury Payment"), ("ANTS", "Anesthesia Services"), ("CVCF", "Convalescent Care Facility"), ("DMEQ", "Durable Medicale Equipment"), ("DNTS", "Dental Services"), ("HLTC", "Home Health Care"), ("HLTI", "Health Insurance"), ("HSPC", "Hospital Care"), ("ICRF", "Intermediate Care Facility"), ("LTCF", "Long Term Care Facility"), ("MDCS", "Medical Services"), ("VIEW", "Vision Care"), ("ALMY", "Alimony Payment"), ("BECH", "Child Benefit"), ("BENE", "Unemployment Disability Benefit"), ("BONU", "Bonus Payment."), ("COMM", "Commission"), ("PENS", "Pension Payment"), ("PRCP", "Price Payment"), ("SALA", "Salary Payment"), ("SSBE", "Social Security Benefit"), ("ESTX", "Estate Tax"), ("HSTX", "Housing Tax"), ("INTX", "Income Tax"), ("TAXS", "Tax Payment"), ("VATX", "Value Added Tax Payment"), ("AIRB", "Air"), ("BUSB", "Bus"), ("FERB", "Ferry"), ("RLWY", "Railway"), ("CBTV", "Cable TV Bill"), ("ELEC", "Electricity Bill"), ("ENRG", "Energies"), ("GASB", "Gas Bill"), ("NWCH", "Network Charge"), ("NWCM", "Network Communication"), ("OTLC", "Other Telecom Related Bill"), ("PHON", "Telephone Bill"), ("WTER", "Water Bill"), ], help="If neither your bank nor your local regulations oblige you to " "set the category purpose, leave the field empty.", ) # PAIN allows 140 characters communication = fields.Char(size=140) # The field struct_communication_type has been dropped in v9 # We now use communication_type ; you should add an option # in communication_type with selection_add=[] communication_type = fields.Selection( selection_add=[("ISO", "ISO")], ondelete={"ISO": "cascade"} ) @api.model def _get_payment_line_grouping_fields(self): """Add specific PAIN fields to the grouping criteria.""" res = super()._get_payment_line_grouping_fields() res += ["priority", "local_instrument", "category_purpose", "purpose"] return res
41.766667
7,518
27,828
py
PYTHON
15.0
# Copyright 2013-2016 Akretion - Alexis de Lattre <[email protected]> # Copyright 2016 Antiun Ingenieria S.L. - Antonio Espinosa # Copyright 2021 Tecnativa - Carlos Roca # Copyright 2014-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from datetime import datetime from lxml import etree from odoo import _, api, fields, models, tools from odoo.exceptions import UserError from odoo.tools.safe_eval import safe_eval try: from unidecode import unidecode except ImportError: unidecode = None logger = logging.getLogger(__name__) class AccountPaymentOrder(models.Model): _inherit = "account.payment.order" sepa = fields.Boolean(compute="_compute_sepa", readonly=True, string="SEPA Payment") charge_bearer = fields.Selection( [ ("SLEV", "Following Service Level"), ("SHAR", "Shared"), ("CRED", "Borne by Creditor"), ("DEBT", "Borne by Debtor"), ], default="SLEV", readonly=True, states={"draft": [("readonly", False)], "open": [("readonly", False)]}, tracking=True, help="Following service level : transaction charges are to be " "applied following the rules agreed in the service level " "and/or scheme (SEPA Core messages must use this). Shared : " "transaction charges on the debtor side are to be borne by " "the debtor, transaction charges on the creditor side are to " "be borne by the creditor. Borne by creditor : all " "transaction charges are to be borne by the creditor. Borne " "by debtor : all transaction charges are to be borne by the " "debtor.", ) batch_booking = fields.Boolean( readonly=True, states={"draft": [("readonly", False)], "open": [("readonly", False)]}, tracking=True, help="If true, the bank statement will display only one debit " "line for all the wire transfers of the SEPA XML file ; if " "false, the bank statement will display one debit line per wire " "transfer of the SEPA XML file.", ) @api.model def _sepa_iban_prefix_list(self): # List of IBAN prefixes (not country codes !) # Source: https://www.europeanpaymentscouncil.eu/sites/default/files/kb/file/2023-01/EPC409-09%20EPC%20List%20of%20SEPA%20Scheme%20Countries%20v4.0_0.pdf # noqa: B950 # Some countries use IBAN but are not part of the SEPA zone # example: Turkey, Madagascar, Tunisia, etc. return [ "AD", "AT", "BE", "BG", "ES", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GI", "GR", "GB", "HU", "IS", "IE", "IT", "LV", "LI", "LT", "LU", "PT", "MT", "MC", "NL", "NO", "PL", "RO", "SM", "SK", "SI", "SE", "CH", "VA", ] @api.depends( "company_partner_bank_id.acc_type", "company_partner_bank_id.sanitized_acc_number", "payment_line_ids.currency_id", "payment_line_ids.partner_bank_id.acc_type", "payment_line_ids.partner_bank_id.sanitized_acc_number", ) def _compute_sepa(self): eur = self.env.ref("base.EUR") sepa_list = self._sepa_iban_prefix_list() for order in self: sepa = True if order.company_partner_bank_id.acc_type != "iban": sepa = False if ( order.company_partner_bank_id and order.company_partner_bank_id.sanitized_acc_number[:2] not in sepa_list ): sepa = False for pline in order.payment_line_ids: if pline.currency_id != eur: sepa = False break if pline.partner_bank_id.acc_type != "iban": sepa = False break if ( pline.partner_bank_id and pline.partner_bank_id.sanitized_acc_number[:2] not in sepa_list ): sepa = False break sepa = order.compute_sepa_final_hook(sepa) self.sepa = sepa def compute_sepa_final_hook(self, sepa): self.ensure_one() return sepa @api.model def _prepare_field( self, field_name, field_value, eval_ctx, max_size=0, gen_args=None ): """This function is designed to be inherited !""" if gen_args is None: gen_args = {} assert isinstance(eval_ctx, dict), "eval_ctx must contain a dict" try: value = safe_eval(field_value, eval_ctx) # SEPA uses XML ; XML = UTF-8 ; UTF-8 = support for all characters # But we are dealing with banks... # and many banks don't want non-ASCCI characters ! # cf section 1.4 "Character set" of the SEPA Credit Transfer # Scheme Customer-to-bank guidelines if gen_args.get("convert_to_ascii"): value = unidecode(value) unallowed_ascii_chars = [ '"', "#", "$", "%", "&", "*", ";", "<", ">", "=", "@", "[", "]", "^", "_", "`", "{", "}", "|", "~", "\\", "!", ] for unallowed_ascii_char in unallowed_ascii_chars: value = value.replace(unallowed_ascii_char, "-") except Exception: error_msg_prefix = _("Cannot compute the field '{field_name}'.").format( field_name=field_name ) error_msg_details_list = self.except_messages_prepare_field( eval_ctx, field_name ) error_msg_data = _( "Data for evaluation:\n" "\tcontext: {eval_ctx}\n" "\tfield path: {field_value}" ).format(eval_ctx=eval_ctx, field_value=field_value) raise UserError( "\n".join( [error_msg_prefix] + error_msg_details_list + [error_msg_data] ) ) from None if not isinstance(value, str): raise UserError( _( "The type of the field '%(field)s' is %(value)s. It should be a string " "or unicode.", field=field_name, value=type(value), ) ) if not value: raise UserError( _("The '%s' is empty or 0. It should have a non-null value.") % field_name ) if max_size and len(value) > max_size: value = value[0:max_size] return value @api.model def except_messages_prepare_field(self, eval_ctx, field_name): """ Inherit this method to provide more detailed error messages for exceptions to be raised while evaluating `field_name` using `eval_ctx`. :return: List containing the error messages. """ error_messages = list() line = eval_ctx.get("line") if line: error_messages.append(_("Payment Line has reference '%s'.") % line.name) partner_bank = eval_ctx.get("partner_bank") if partner_bank: error_messages.append( _("Partner's bank account is '%s'.") % partner_bank.display_name ) return error_messages @api.model def _validate_xml(self, xml_string, gen_args): xsd_etree_obj = etree.parse(tools.file_open(gen_args["pain_xsd_file"])) official_pain_schema = etree.XMLSchema(xsd_etree_obj) try: root_to_validate = etree.fromstring(xml_string) official_pain_schema.assertValid(root_to_validate) except Exception as e: logger.warning("The XML file is invalid against the XML Schema Definition") logger.warning(xml_string) logger.warning(e) raise UserError( _( "The generated XML file is not valid against the official " "XML Schema Definition. The generated XML file and the " "full error have been written in the server logs. Here " "is the error, which may give you an idea on the cause " "of the problem : %s" ) % str(e) ) from None return True def finalize_sepa_file_creation(self, xml_root, gen_args): xml_string = etree.tostring( xml_root, pretty_print=True, encoding="UTF-8", xml_declaration=True ) logger.debug( "Generated SEPA XML file in format %s below" % gen_args["pain_flavor"] ) logger.debug(xml_string) self._validate_xml(xml_string, gen_args) filename = "{}{}.xml".format(gen_args["file_prefix"], self.name) return (xml_string, filename) def generate_pain_nsmap(self): self.ensure_one() pain_flavor = self.payment_mode_id.payment_method_id.pain_version nsmap = { "xsi": "http://www.w3.org/2001/XMLSchema-instance", None: "urn:iso:std:iso:20022:tech:xsd:%s" % pain_flavor, } return nsmap def generate_pain_attrib(self): self.ensure_one() return {} @api.model def generate_group_header_block(self, parent_node, gen_args): group_header = etree.SubElement(parent_node, "GrpHdr") message_identification = etree.SubElement(group_header, "MsgId") message_identification.text = self._prepare_field( "Message Identification", "self.name", {"self": self}, 35, gen_args=gen_args ) creation_date_time = etree.SubElement(group_header, "CreDtTm") creation_date_time.text = datetime.strftime( datetime.today(), "%Y-%m-%dT%H:%M:%S" ) if gen_args.get("pain_flavor") == "pain.001.001.02": # batch_booking is in "Group header" with pain.001.001.02 # and in "Payment info" in pain.001.001.03/04 batch_booking = etree.SubElement(group_header, "BtchBookg") batch_booking.text = str(self.batch_booking).lower() nb_of_transactions = etree.SubElement(group_header, "NbOfTxs") control_sum = etree.SubElement(group_header, "CtrlSum") # Grpg removed in pain.001.001.03 if gen_args.get("pain_flavor") == "pain.001.001.02": grouping = etree.SubElement(group_header, "Grpg") grouping.text = "GRPD" self.generate_initiating_party_block(group_header, gen_args) return group_header, nb_of_transactions, control_sum @api.model def generate_start_payment_info_block( self, parent_node, payment_info_ident, priority, local_instrument, category_purpose, sequence_type, requested_date, eval_ctx, gen_args, ): payment_info = etree.SubElement(parent_node, "PmtInf") payment_info_identification = etree.SubElement(payment_info, "PmtInfId") payment_info_identification.text = self._prepare_field( "Payment Information Identification", payment_info_ident, eval_ctx, 35, gen_args=gen_args, ) payment_method = etree.SubElement(payment_info, "PmtMtd") payment_method.text = gen_args["payment_method"] nb_of_transactions = False control_sum = False if gen_args.get("pain_flavor") != "pain.001.001.02": batch_booking = etree.SubElement(payment_info, "BtchBookg") batch_booking.text = str(self.batch_booking).lower() # The "SEPA Customer-to-bank # Implementation guidelines" for SCT and SDD says that control sum # and nb_of_transactions should be present # at both "group header" level and "payment info" level nb_of_transactions = etree.SubElement(payment_info, "NbOfTxs") control_sum = etree.SubElement(payment_info, "CtrlSum") payment_type_info = etree.SubElement(payment_info, "PmtTpInf") if priority and gen_args["payment_method"] != "DD": instruction_priority = etree.SubElement(payment_type_info, "InstrPrty") instruction_priority.text = priority if self.sepa: service_level = etree.SubElement(payment_type_info, "SvcLvl") service_level_code = etree.SubElement(service_level, "Cd") service_level_code.text = "SEPA" if local_instrument: local_instrument_root = etree.SubElement(payment_type_info, "LclInstrm") if gen_args.get("local_instrument_type") == "proprietary": local_instr_value = etree.SubElement(local_instrument_root, "Prtry") else: local_instr_value = etree.SubElement(local_instrument_root, "Cd") local_instr_value.text = local_instrument if sequence_type: sequence_type_node = etree.SubElement(payment_type_info, "SeqTp") sequence_type_node.text = sequence_type if category_purpose: category_purpose_node = etree.SubElement(payment_type_info, "CtgyPurp") category_purpose_code = etree.SubElement(category_purpose_node, "Cd") category_purpose_code.text = category_purpose if gen_args["payment_method"] == "DD": request_date_tag = "ReqdColltnDt" else: request_date_tag = "ReqdExctnDt" requested_date_node = etree.SubElement(payment_info, request_date_tag) requested_date_node.text = requested_date return payment_info, nb_of_transactions, control_sum @api.model def _must_have_initiating_party(self, gen_args): """This method is designed to be inherited in localization modules for countries in which the initiating party is required""" return False @api.model def generate_initiating_party_block(self, parent_node, gen_args): my_company_name = self._prepare_field( "Company Name", "self.company_partner_bank_id.partner_id.name", {"self": self}, gen_args.get("name_maxsize"), gen_args=gen_args, ) initiating_party = etree.SubElement(parent_node, "InitgPty") initiating_party_name = etree.SubElement(initiating_party, "Nm") initiating_party_name.text = my_company_name initiating_party_identifier = ( self.payment_mode_id.initiating_party_identifier or self.payment_mode_id.company_id.initiating_party_identifier ) initiating_party_issuer = ( self.payment_mode_id.initiating_party_issuer or self.payment_mode_id.company_id.initiating_party_issuer ) initiating_party_scheme = ( self.payment_mode_id.initiating_party_scheme or self.payment_mode_id.company_id.initiating_party_scheme ) # in pain.008.001.02.ch.01.xsd files they use # initiating_party_identifier but not initiating_party_issuer if initiating_party_identifier: iniparty_id = etree.SubElement(initiating_party, "Id") iniparty_org_id = etree.SubElement(iniparty_id, "OrgId") iniparty_org_other = etree.SubElement(iniparty_org_id, "Othr") iniparty_org_other_id = etree.SubElement(iniparty_org_other, "Id") iniparty_org_other_id.text = initiating_party_identifier if initiating_party_scheme: iniparty_org_other_scheme = etree.SubElement( iniparty_org_other, "SchmeNm" ) iniparty_org_other_scheme_name = etree.SubElement( iniparty_org_other_scheme, "Prtry" ) iniparty_org_other_scheme_name.text = initiating_party_scheme if initiating_party_issuer: iniparty_org_other_issuer = etree.SubElement(iniparty_org_other, "Issr") iniparty_org_other_issuer.text = initiating_party_issuer elif self._must_have_initiating_party(gen_args): raise UserError( _( "Missing 'Initiating Party Issuer' and/or " "'Initiating Party Identifier' for the company '%s'. " "Both fields must have a value." ) % self.company_id.name ) return True @api.model def generate_party_agent( self, parent_node, party_type, order, partner_bank, gen_args, bank_line=None ): """Generate the piece of the XML file corresponding to BIC This code is mutualized between TRF and DD Starting from Feb 1st 2016, we should be able to do cross-border SEPA transfers without BIC, cf http://www.europeanpaymentscouncil.eu/index.cfm/ sepa-credit-transfer/iban-and-bic/ In some localization (l10n_ch_sepa for example), they need the bank_line argument""" assert order in ("B", "C"), "Order can be 'B' or 'C'" if partner_bank.bank_bic: party_agent = etree.SubElement(parent_node, "%sAgt" % party_type) party_agent_institution = etree.SubElement(party_agent, "FinInstnId") party_agent_bic = etree.SubElement( party_agent_institution, gen_args.get("bic_xml_tag") ) party_agent_bic.text = partner_bank.bank_bic else: if order == "B" or (order == "C" and gen_args["payment_method"] == "DD"): party_agent = etree.SubElement(parent_node, "%sAgt" % party_type) party_agent_institution = etree.SubElement(party_agent, "FinInstnId") party_agent_other = etree.SubElement(party_agent_institution, "Othr") party_agent_other_identification = etree.SubElement( party_agent_other, "Id" ) party_agent_other_identification.text = "NOTPROVIDED" # for Credit Transfers, in the 'C' block, if BIC is not provided, # we should not put the 'Creditor Agent' block at all, # as per the guidelines of the EPC return True @api.model def generate_party_id(self, parent_node, party_type, partner): """Generate an Id element for partner inside the parent node. party_type can currently be Cdtr or Dbtr. Notably, the initiating party orgid is generated with another mechanism and configured at the company or payment mode level. """ return @api.model def generate_party_acc_number( self, parent_node, party_type, order, partner_bank, gen_args, bank_line=None ): party_account = etree.SubElement(parent_node, "%sAcct" % party_type) party_account_id = etree.SubElement(party_account, "Id") if partner_bank.acc_type == "iban": party_account_iban = etree.SubElement(party_account_id, "IBAN") party_account_iban.text = partner_bank.sanitized_acc_number else: party_account_other = etree.SubElement(party_account_id, "Othr") party_account_other_id = etree.SubElement(party_account_other, "Id") party_account_other_id.text = partner_bank.sanitized_acc_number return True @api.model def generate_address_block(self, parent_node, partner, gen_args): """Generate the piece of the XML corresponding to PstlAdr""" if partner.country_id: postal_address = etree.SubElement(parent_node, "PstlAdr") country = etree.SubElement(postal_address, "Ctry") country.text = self._prepare_field( "Country", "partner.country_id.code", {"partner": partner}, 2, gen_args=gen_args, ) if partner.street: adrline1 = etree.SubElement(postal_address, "AdrLine") adrline1.text = self._prepare_field( "Adress Line1", "partner.street", {"partner": partner}, 70, gen_args=gen_args, ) if ( gen_args.get("pain_flavor").startswith("pain.001.001.") or gen_args.get("pain_flavor").startswith("pain.008.001.") ) and (partner.zip or partner.city): adrline2 = etree.SubElement(postal_address, "AdrLine") if partner.zip: val = self._prepare_field( "zip", "partner.zip", {"partner": partner}, 70, gen_args=gen_args, ) else: val = "" if partner.city: val += " " + self._prepare_field( "city", "partner.city", {"partner": partner}, 70, gen_args=gen_args, ) adrline2.text = val return True @api.model def generate_party_block( self, parent_node, party_type, order, partner_bank, gen_args, bank_line=None ): """Generate the piece of the XML file corresponding to Name+IBAN+BIC This code is mutualized between TRF and DD In some localization (l10n_ch_sepa for example), they need the bank_line argument""" assert order in ("B", "C"), "Order can be 'B' or 'C'" party_type_label = _("Partner name") if party_type == "Cdtr": party_type_label = _("Creditor name") elif party_type == "Dbtr": party_type_label = _("Debtor name") name = "partner_bank.acc_holder_name or partner_bank.partner_id.name" eval_ctx = {"partner_bank": partner_bank} party_name = self._prepare_field( party_type_label, name, eval_ctx, gen_args.get("name_maxsize"), gen_args=gen_args, ) # At C level, the order is : BIC, Name, IBAN # At B level, the order is : Name, IBAN, BIC if order == "C": self.generate_party_agent( parent_node, party_type, order, partner_bank, gen_args, bank_line=bank_line, ) party = etree.SubElement(parent_node, party_type) party_nm = etree.SubElement(party, "Nm") party_nm.text = party_name partner = partner_bank.partner_id self.generate_address_block(party, partner, gen_args) self.generate_party_id(party, party_type, partner) self.generate_party_acc_number( parent_node, party_type, order, partner_bank, gen_args, bank_line=bank_line ) if order == "B": self.generate_party_agent( parent_node, party_type, order, partner_bank, gen_args, bank_line=bank_line, ) return True @api.model def generate_remittance_info_block(self, parent_node, line, gen_args): remittance_info = etree.SubElement(parent_node, "RmtInf") communication_type = line.payment_line_ids[:1].communication_type if communication_type == "normal": remittance_info_unstructured = etree.SubElement(remittance_info, "Ustrd") remittance_info_unstructured.text = self._prepare_field( "Remittance Unstructured Information", "line.payment_reference", {"line": line}, 140, gen_args=gen_args, ) else: remittance_info_structured = etree.SubElement(remittance_info, "Strd") creditor_ref_information = etree.SubElement( remittance_info_structured, "CdtrRefInf" ) if gen_args.get("pain_flavor") == "pain.001.001.02": creditor_ref_info_type = etree.SubElement( creditor_ref_information, "CdtrRefTp" ) creditor_ref_info_type_code = etree.SubElement( creditor_ref_info_type, "Cd" ) creditor_ref_info_type_code.text = "SCOR" # SCOR means "Structured Communication Reference" creditor_ref_info_type_issuer = etree.SubElement( creditor_ref_info_type, "Issr" ) creditor_ref_info_type_issuer.text = communication_type creditor_reference = etree.SubElement( creditor_ref_information, "CdtrRef" ) else: if gen_args.get("structured_remittance_issuer", True): creditor_ref_info_type = etree.SubElement( creditor_ref_information, "Tp" ) creditor_ref_info_type_or = etree.SubElement( creditor_ref_info_type, "CdOrPrtry" ) creditor_ref_info_type_code = etree.SubElement( creditor_ref_info_type_or, "Cd" ) creditor_ref_info_type_code.text = "SCOR" creditor_ref_info_type_issuer = etree.SubElement( creditor_ref_info_type, "Issr" ) creditor_ref_info_type_issuer.text = communication_type creditor_reference = etree.SubElement(creditor_ref_information, "Ref") creditor_reference.text = self._prepare_field( "Creditor Structured Reference", "line.payment_reference", {"line": line}, 35, gen_args=gen_args, ) return True @api.model def generate_creditor_scheme_identification( self, parent_node, identification, identification_label, eval_ctx, scheme_name_proprietary, gen_args, ): csi_id = etree.SubElement(parent_node, "Id") csi_privateid = etree.SubElement(csi_id, "PrvtId") csi_other = etree.SubElement(csi_privateid, "Othr") csi_other_id = etree.SubElement(csi_other, "Id") csi_other_id.text = self._prepare_field( identification_label, identification, eval_ctx, gen_args=gen_args ) csi_scheme_name = etree.SubElement(csi_other, "SchmeNm") csi_scheme_name_proprietary = etree.SubElement(csi_scheme_name, "Prtry") csi_scheme_name_proprietary.text = scheme_name_proprietary return True
40.38897
27,828
1,219
py
PYTHON
15.0
# Copyright 2016 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, fields, models from odoo.exceptions import UserError class AccountPaymentMethod(models.Model): _inherit = "account.payment.method" pain_version = fields.Selection([], string="PAIN Version") convert_to_ascii = fields.Boolean( string="Convert to ASCII", default=True, help="If active, Odoo will convert each accented character to " "the corresponding unaccented character, so that only ASCII " "characters are used in the generated PAIN file.", ) def get_xsd_file_path(self): """This method is designed to be inherited in the SEPA modules""" self.ensure_one() raise UserError(_("No XSD file path found for payment method '%s'") % self.name) _sql_constraints = [ ( # Extending this constraint from account_payment_mode "code_payment_type_unique", "unique(code, payment_type, pain_version)", "A payment method of the same type already exists with this code" " and PAIN version", ) ]
36.939394
1,219
1,211
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import re from odoo import _, api, models from odoo.exceptions import ValidationError BIC_REGEX = re.compile(r"[A-Z]{6}[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3})?$") class ResBank(models.Model): _inherit = "res.bank" @api.constrains("bic") def _check_bic(self): """ This method strengthens the constraint on the BIC of the bank account (The account_payment_order module already checks the length in the check_bic_length method). :raise: ValidationError if the BIC doesn't respect the regex of the SEPA pain schemas. """ invalid_banks = self.filtered(lambda r: r.bic and not BIC_REGEX.match(r.bic)) if invalid_banks: raise ValidationError( _( "The following Bank Identifier Codes (BIC) do not respect " "the SEPA pattern:\n{bic_list}\n\nSEPA pattern: " "{sepa_pattern}" ).format( sepa_pattern=BIC_REGEX.pattern, bic_list="\n".join(invalid_banks.mapped("bic")), ) )
34.6
1,211
2,172
py
PYTHON
15.0
# Copyright 2013-2016 Akretion - Alexis de Lattre <[email protected]> # Copyright 2013 Noviat (http://www.noviat.com) - Luc de Meyer # Copyright 2014 Serv. Tecnol. Avanzados - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import logging from odoo import fields, models logger = logging.getLogger(__name__) class ResCompany(models.Model): _inherit = "res.company" initiating_party_issuer = fields.Char( size=35, help="This will be used as the 'Initiating Party Issuer' in the " "PAIN files generated by Odoo.", ) initiating_party_identifier = fields.Char( size=35, help="This will be used as the 'Initiating Party Identifier' in " "the PAIN files generated by Odoo.", ) initiating_party_scheme = fields.Char( size=35, help="This will be used as the 'Initiating Party Scheme Name' in " "the PAIN files generated by Odoo.", ) def _default_initiating_party(self): """This method is called from post_install.py""" self.ensure_one() party_issuer_per_country = { "BE": "KBO-BCE" # KBO-BCE = the registry of companies in Belgium } logger.debug("Calling _default_initiating_party on company %s", self.name) country_code = self.country_id.code if not self.initiating_party_issuer: if country_code and country_code in party_issuer_per_country: self.write( {"initiating_party_issuer": party_issuer_per_country[country_code]} ) logger.info("Updated initiating_party_issuer on company %s", self.name) party_identifier = False if not self.initiating_party_identifier: if self.vat and country_code: if country_code == "BE": party_identifier = self.vat[2:].replace(" ", "") if party_identifier: self.write({"initiating_party_identifier": party_identifier}) logger.info( "Updated initiating_party_identifier on company %s", self.name )
39.490909
2,172
972
py
PYTHON
15.0
# Copyright 2016 Akretion - Alexis de Lattre <[email protected]> # Copyright 2017 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" initiating_party_issuer = fields.Char( related="company_id.initiating_party_issuer", readonly=False ) initiating_party_identifier = fields.Char( related="company_id.initiating_party_identifier", readonly=False ) initiating_party_scheme = fields.Char( related="company_id.initiating_party_scheme", readonly=False ) group_pain_multiple_identifier = fields.Boolean( string="Multiple identifiers", implied_group="account_banking_pain_base." "group_pain_multiple_identifier", help="Enable this option if your country requires several SEPA/PAIN " "identifiers like in Spain.", )
38.88
972
1,570
py
PYTHON
15.0
# Copyright 2013-2016 Akretion - Alexis de Lattre <[email protected]> # Copyright 2014 Serv. Tecnol. Avanzados - Pedro M. Baeza # Copyright 2016 Antiun Ingenieria S.L. - Antonio Espinosa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountPaymentMode(models.Model): _inherit = "account.payment.mode" initiating_party_issuer = fields.Char( size=35, help="This will be used as the 'Initiating Party Issuer' in the " "PAIN files generated by Odoo. If not defined, Initiating Party " "Issuer from company will be used.\n" "Common format (13): \n" "- Country code (2, optional)\n" "- Company idenfier (N, VAT)\n" "- Service suffix (N, issued by bank)", ) initiating_party_identifier = fields.Char( size=35, help="This will be used as the 'Initiating Party Identifier' in " "the PAIN files generated by Odoo. If not defined, Initiating Party " "Identifier from company will be used.\n" "Common format (13): \n" "- Country code (2, optional)\n" "- Company idenfier (N, VAT)\n" "- Service suffix (N, issued by bank)", ) initiating_party_scheme = fields.Char( size=35, help="This will be used as the 'Initiating Party Scheme Name' in " "the PAIN files generated by Odoo. This value is determined by the " "financial institution that will process the file. If not defined, " "no scheme will be used.\n", )
41.315789
1,570
1,155
py
PYTHON
15.0
# Copyright 2014 Compassion CH - Cyril Sester <[email protected]> # Copyright 2015-2020 Akretion - Alexis de Lattre <[email protected]> # Copyright 2017 Tecnativa - Carlos Dauden # Copyright 2014-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Banking Mandate", "summary": "Banking mandates", "version": "15.0.2.0.0", "development_status": "Production/Stable", "license": "AGPL-3", "author": "Compassion CH, " "Tecnativa, " "Akretion, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "category": "Banking addons", "depends": ["account_payment_order"], "data": [ "views/account_banking_mandate_view.xml", "views/account_payment_method.xml", "views/account_move_view.xml", "views/account_payment_line.xml", "views/res_partner_bank_view.xml", "views/res_partner.xml", "data/mandate_reference_sequence.xml", "security/mandate_security.xml", "security/ir.model.access.csv", ], "installable": True, }
36.09375
1,155
10,693
py
PYTHON
15.0
# Copyright 2017 Creu Blanca # Copyright 2017-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from unittest.mock import patch from odoo import fields from odoo.exceptions import UserError from odoo.tests.common import TransactionCase from odoo.addons.account.models.account_payment_method import AccountPaymentMethod class TestInvoiceMandate(TransactionCase): def test_post_invoice_01(self): self.invoice._onchange_partner_id() prev_orders = self.env["account.payment.order"].search([]) self.assertEqual(self.invoice.mandate_id, self.mandate) self.invoice.action_post() self.env["account.invoice.payment.line.multi"].with_context( active_model="account.move", active_ids=self.invoice.ids ).create({}).run() payment_order = self.env["account.payment.order"].search([]) - prev_orders self.assertEqual(len(payment_order.ids), 1) payment_order.payment_mode_id_change() payment_order.draft2open() self.assertEqual(self.mandate.payment_line_ids_count, 1) def test_post_invoice_02(self): partner_2 = self._create_res_partner("Jane with ACME Bank") partner_2.customer_payment_mode_id = self.mode_inbound_acme bank_account = self.env["res.partner.bank"].create( { "acc_number": "0023032234211", "partner_id": partner_2.id, "bank_id": self.acme_bank.id, "company_id": self.company_2.id, } ) mandate_2 = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company_2.id, } ) mandate_2.validate() self.invoice._onchange_partner_id() self.assertEqual(self.invoice.mandate_id, self.mandate) self.invoice.action_post() payable_move_lines = self.invoice.line_ids.filtered( lambda s: s.account_id == self.invoice_account ) if payable_move_lines: with self.assertRaises(UserError): payable_move_lines[0].move_id.mandate_id = mandate_2 def test_post_invoice_and_refund_02(self): self.invoice._onchange_partner_id() self.invoice.action_post() self.assertEqual(self.invoice.mandate_id, self.mandate) move_reversal = ( self.env["account.move.reversal"] .with_context(active_model="account.move", active_ids=self.invoice.ids) .create( { "date": fields.Date.today(), "reason": "no reason", "refund_method": "refund", "journal_id": self.invoice.journal_id.id, } ) ) reversal = move_reversal.reverse_moves() ref = self.env["account.move"].browse(reversal["res_id"]) self.assertEqual(self.invoice.mandate_id, ref.mandate_id) def test_onchange_partner(self): partner_2 = self._create_res_partner("Jane with ACME Bank") partner_2.customer_payment_mode_id = self.mode_inbound_acme bank_account = self.env["res.partner.bank"].create( { "acc_number": "0023032234211", "partner_id": partner_2.id, "bank_id": self.acme_bank.id, "company_id": self.company.id, } ) mandate_2 = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) mandate_2.validate() invoice = self.env["account.move"].new( { "partner_id": self.partner.id, "move_type": "out_invoice", "company_id": self.company.id, } ) invoice.partner_id = partner_2 invoice._onchange_partner_id() self.assertEqual(invoice.mandate_id, mandate_2) def test_onchange_payment_mode(self): Method_get_payment_method_information = ( AccountPaymentMethod._get_payment_method_information ) def _get_payment_method_information(self): res = Method_get_payment_method_information(self) res["test"] = {"mode": "multi", "domain": [("type", "=", "bank")]} return res invoice = self.env["account.move"].new( { "partner_id": self.partner.id, "move_type": "out_invoice", "company_id": self.company.id, } ) invoice._onchange_partner_id() with patch.object( AccountPaymentMethod, "_get_payment_method_information", _get_payment_method_information, ): pay_method_test = self.env["account.payment.method"].create( { "name": "Test", "code": "test", "payment_type": "inbound", "mandate_required": False, } ) mode_inbound_acme_2 = self.env["account.payment.mode"].create( { "name": "Inbound Credit ACME Bank 2", "company_id": self.company.id, "bank_account_link": "variable", "payment_method_id": pay_method_test.id, } ) invoice.payment_mode_id = mode_inbound_acme_2 invoice._onchange_payment_mode_id() self.assertEqual(invoice.mandate_id, self.env["account.banking.mandate"]) def test_invoice_constrains(self): partner_2 = self._create_res_partner("Jane with ACME Bank") partner_2.customer_payment_mode_id = self.mode_inbound_acme bank_account = self.env["res.partner.bank"].create( { "acc_number": "0023032234211", "partner_id": partner_2.id, "bank_id": self.acme_bank.id, "company_id": self.company_2.id, } ) mandate_2 = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company_2.id, } ) mandate_2.validate() invoice = self.env["account.move"].create( { "partner_id": self.partner.id, "move_type": "out_invoice", "company_id": self.company.id, } ) with self.assertRaises(UserError): invoice.mandate_id = mandate_2 def _create_res_partner(self, name): return self.env["res.partner"].create({"name": name}) def _create_res_bank(self, name, bic, city, country): return self.env["res.bank"].create( {"name": name, "bic": bic, "city": city, "country": country.id} ) def setUp(self): res = super(TestInvoiceMandate, self).setUp() self.company = self.env.ref("base.main_company") self.partner = self._create_res_partner("Peter with ACME Bank") self.acme_bank = self._create_res_bank( "ACME Bank", "GEBABEBB03B", "Charleroi", self.env.ref("base.be") ) bank_account = self.env["res.partner.bank"].create( { "acc_number": "0023032234211123", "partner_id": self.partner.id, "bank_id": self.acme_bank.id, "company_id": self.company.id, } ) self.company_2 = self.env["res.company"].create({"name": "Company 2"}) self.mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) self.mandate.validate() self.mode_inbound_acme = self.env["account.payment.mode"].create( { "name": "Inbound Credit ACME Bank", "company_id": self.company.id, "bank_account_link": "variable", "payment_method_id": self.env.ref( "account.account_payment_method_manual_in" ).id, } ) bank_journal = self.env["account.journal"].search( [ ("type", "=", "bank"), ("company_id", "=", self.company.id), ], limit=1, ) self.mode_inbound_acme.variable_journal_ids = bank_journal self.mode_inbound_acme.payment_method_id.mandate_required = True self.mode_inbound_acme.payment_order_ok = True self.partner.customer_payment_mode_id = self.mode_inbound_acme self.invoice_account = self.env["account.account"].search( [ ( "user_type_id", "=", self.env.ref("account.data_account_type_receivable").id, ), ("company_id", "=", self.company.id), ], limit=1, ) invoice_line_account = ( self.env["account.account"] .search( [ ( "user_type_id", "=", self.env.ref("account.data_account_type_expenses").id, ), ("company_id", "=", self.company.id), ], limit=1, ) .id ) invoice_vals = [ ( 0, 0, { "product_id": self.env.ref("product.product_product_4").id, "quantity": 1.0, "account_id": invoice_line_account, "price_unit": 200.00, }, ) ] self.invoice = self.env["account.move"].create( { "partner_id": self.partner.id, "move_type": "out_invoice", "company_id": self.company.id, "journal_id": self.env["account.journal"] .search( [("type", "=", "sale"), ("company_id", "=", self.company.id)], limit=1, ) .id, "invoice_line_ids": invoice_vals, } ) return res
34.717532
10,693
8,765
py
PYTHON
15.0
# © 2016 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from datetime import timedelta from odoo import fields from odoo.exceptions import UserError, ValidationError from odoo.tests.common import TransactionCase class TestMandate(TransactionCase): def test_mandate_01(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) self.assertEqual(mandate.state, "draft") mandate.validate() self.assertEqual(mandate.state, "valid") mandate.cancel() self.assertEqual(mandate.state, "cancel") mandate.back2draft() self.assertEqual(mandate.state, "draft") def test_mandate_02(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) with self.assertRaises(UserError): mandate.back2draft() def test_mandate_03(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) mandate.validate() with self.assertRaises(UserError): mandate.validate() def test_mandate_04(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) mandate.validate() mandate.cancel() with self.assertRaises(UserError): mandate.cancel() def test_onchange_methods(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].new( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) bank_account_2 = self.env.ref("account_payment_mode.res_partner_2_iban") mandate.partner_bank_id = bank_account_2 mandate.mandate_partner_bank_change() self.assertEqual(mandate.partner_id, bank_account_2.partner_id) def test_constrains_01(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) mandate.validate() with self.assertRaises(ValidationError): mandate.signature_date = fields.Date.to_string( fields.Date.from_string(fields.Date.context_today(mandate)) + timedelta(days=1) ) def test_constrains_02(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) with self.assertRaises(UserError): mandate.company_id = self.company_2 def test_constrains_03(self): bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) bank_account_2 = self.env["res.partner.bank"].create( { "acc_number": "1234", "company_id": self.company_2.id, "partner_id": self.company_2.partner_id.id, } ) with self.assertRaises(UserError): mandate.partner_bank_id = bank_account_2 def test_constrains_04(self): mandate = self.env["account.banking.mandate"].create( {"signature_date": "2015-01-01", "company_id": self.company.id} ) bank_account = self.env["res.partner.bank"].create( { "acc_number": "1234", "company_id": self.company_2.id, "partner_id": self.company_2.partner_id.id, } ) with self.assertRaises(UserError): bank_account.mandate_ids += mandate def test_mandate_reference_01(self): """ Test case: create a mandate with no reference Expected result: the reference of the created mandate is not empty """ bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, } ) self.assertTrue(mandate.unique_mandate_reference) def test_mandate_reference_02(self): """ Test case: create a mandate with "ref01" as reference Expected result: the reference of the created mandate is "ref01" """ bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, "unique_mandate_reference": "ref01", } ) self.assertEqual(mandate.unique_mandate_reference, "ref01") def test_mandate_reference_03(self): """ Test case: create a mandate with "New" as reference Expected result: the reference of the created mandate is not empty and is not "New" """ bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, "unique_mandate_reference": "New", } ) self.assertTrue(mandate.unique_mandate_reference) self.assertNotEqual(mandate.unique_mandate_reference, "New") def test_mandate_reference_05(self): """ Test case: create a mandate with False as reference Expected result: the reference of the created mandate is not empty """ bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, "unique_mandate_reference": False, } ) self.assertTrue(mandate.unique_mandate_reference) def test_mandate_reference_06(self): """ Test case: create a mandate with a empty string as reference Expected result: the reference of the created mandate is not empty """ bank_account = self.env.ref("account_payment_mode.res_partner_12_iban") mandate = self.env["account.banking.mandate"].create( { "partner_bank_id": bank_account.id, "signature_date": "2015-01-01", "company_id": self.company.id, "unique_mandate_reference": "", } ) self.assertTrue(mandate.unique_mandate_reference) def setUp(self): res = super(TestMandate, self).setUp() # Company self.company = self.env.ref("base.main_company") # Company 2 self.company_2 = self.env["res.company"].create({"name": "Company 2"}) return res
37.613734
8,764
2,724
py
PYTHON
15.0
# Copyright 2014 Compassion CH - Cyril Sester <[email protected]> # Copyright 2014 Tecnativa - Pedro M. Baeza # Copyright 2015-16 Akretion - Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class AccountPaymentLine(models.Model): _inherit = "account.payment.line" mandate_id = fields.Many2one( comodel_name="account.banking.mandate", string="Direct Debit Mandate", domain=[("state", "=", "valid")], check_company=True, ) mandate_required = fields.Boolean( related="order_id.payment_method_id.mandate_required", readonly=True ) @api.constrains("mandate_id", "partner_bank_id") def _check_mandate_bank_link(self): for pline in self: if ( pline.mandate_id and pline.partner_bank_id and pline.mandate_id.partner_bank_id != pline.partner_bank_id ): raise ValidationError( _( "The payment line number {line_number} has " "the bank account '{line_bank_account}' which " "is not attached to the mandate '{mandate_ref}' " "(this mandate is attached to the bank account " "'{mandate_bank_account}')." ).format( line_number=pline.name, line_bank_account=pline.partner_bank_id.acc_number, mandate_ref=pline.mandate_id.unique_mandate_reference, mandate_bank_account=pline.mandate_id.partner_bank_id.acc_number, ) ) @api.constrains("mandate_id", "company_id") def _check_company_constrains(self): for pline in self: if ( pline.mandate_id.company_id and pline.mandate_id.company_id != pline.company_id ): raise ValidationError( _( "The payment line number {line_number} a different " "company than that of the linked mandate {mandate})." ).format( line_number=pline.name, mandate=pline.mandate_id.display_name ) ) def draft2open_payment_line_check(self): res = super().draft2open_payment_line_check() if self.mandate_required and not self.mandate_id: raise UserError(_("Missing Mandate on payment line %s") % self.name) return res
41.272727
2,724
2,036
py
PYTHON
15.0
# Copyright 2020 Marçal Isern <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountMove(models.Model): _inherit = "account.move" mandate_id = fields.Many2one( "account.banking.mandate", string="Direct Debit Mandate", ondelete="restrict", readonly=True, check_company=True, states={"draft": [("readonly", False)]}, ) mandate_required = fields.Boolean( related="payment_mode_id.payment_method_id.mandate_required", readonly=True ) @api.model def create(self, vals): """Fill the mandate_id from the partner if none is provided on creation, using same method as upstream.""" onchanges = { "_onchange_partner_id": ["mandate_id"], "_onchange_payment_mode_id": ["mandate_id"], } for onchange_method, changed_fields in list(onchanges.items()): if any(f not in vals for f in changed_fields): move = self.new(vals) move = move.with_company(move.company_id.id) getattr(move, onchange_method)() for field in changed_fields: if field not in vals and move[field]: vals[field] = move._fields[field].convert_to_write( move[field], move ) return super().create(vals) def set_mandate(self): if self.payment_mode_id.payment_method_id.mandate_required: self.mandate_id = self.partner_id.valid_mandate_id else: self.mandate_id = False @api.onchange("partner_id", "company_id") def _onchange_partner_id(self): """Select by default the first valid mandate of the partner""" res = super()._onchange_partner_id() self.set_mandate() return res @api.onchange("payment_mode_id") def _onchange_payment_mode_id(self): self.set_mandate()
35.086207
2,035
7,694
py
PYTHON
15.0
# Copyright 2014 Compassion CH - Cyril Sester <[email protected]> # Copyright 2014 Tecnativa - Pedro M. Baeza # Copyright 2015-2020 Akretion - Alexis de Lattre <[email protected]> # Copyright 2020 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class AccountBankingMandate(models.Model): """The banking mandate is attached to a bank account and represents an authorization that the bank account owner gives to a company for a specific operation (such as direct debit) """ _name = "account.banking.mandate" _description = "A generic banking mandate" _inherit = ["mail.thread", "mail.activity.mixin"] _order = "signature_date desc" _check_company_auto = True def _get_default_partner_bank_id_domain(self): if "default_partner_id" in self.env.context: return [("partner_id", "=", self.env.context.get("default_partner_id"))] else: return [] format = fields.Selection( [("basic", "Basic Mandate")], default="basic", required=True, string="Mandate Format", tracking=20, ) type = fields.Selection( [("generic", "Generic Mandate")], string="Type of Mandate", tracking=30, ) partner_bank_id = fields.Many2one( comodel_name="res.partner.bank", string="Bank Account", tracking=40, domain=lambda self: self._get_default_partner_bank_id_domain(), ondelete="restrict", index=True, check_company=True, ) partner_id = fields.Many2one( comodel_name="res.partner", related="partner_bank_id.partner_id", string="Partner", store=True, index=True, ) company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, default=lambda self: self.env.company, ) unique_mandate_reference = fields.Char(tracking=10, copy=False) signature_date = fields.Date( string="Date of Signature of the Mandate", tracking=50, ) scan = fields.Binary(string="Scan of the Mandate") last_debit_date = fields.Date(string="Date of the Last Debit", readonly=True) state = fields.Selection( [ ("draft", "Draft"), ("valid", "Valid"), ("expired", "Expired"), ("cancel", "Cancelled"), ], string="Status", default="draft", tracking=60, help="Only valid mandates can be used in a payment line. A cancelled " "mandate is a mandate that has been cancelled by the customer.", ) payment_line_ids = fields.One2many( comodel_name="account.payment.line", inverse_name="mandate_id", string="Related Payment Lines", ) payment_line_ids_count = fields.Integer(compute="_compute_payment_line_ids_count") _sql_constraints = [ ( "mandate_ref_company_uniq", "unique(unique_mandate_reference, company_id)", "A Mandate with the same reference already exists for this company!", ) ] def name_get(self): result = [] for mandate in self: name = mandate.unique_mandate_reference acc_number = mandate.partner_bank_id.acc_number if acc_number: name = "{} [...{}]".format(name, acc_number[-4:]) result.append((mandate.id, name)) return result @api.depends("payment_line_ids") def _compute_payment_line_ids_count(self): payment_line_model = self.env["account.payment.line"] domain = [("mandate_id", "in", self.ids)] res = payment_line_model.read_group( domain=domain, fields=["mandate_id"], groupby=["mandate_id"] ) payment_line_dict = {} for dic in res: mandate_id = dic["mandate_id"][0] payment_line_dict.setdefault(mandate_id, 0) payment_line_dict[mandate_id] += dic["mandate_id_count"] for rec in self: rec.payment_line_ids_count = payment_line_dict.get(rec.id, 0) def show_payment_lines(self): self.ensure_one() return { "name": _("Payment lines"), "type": "ir.actions.act_window", "view_mode": "tree,form", "res_model": "account.payment.line", "domain": [("mandate_id", "=", self.id)], } @api.constrains("signature_date", "last_debit_date") def _check_dates(self): today = fields.Date.context_today(self) for mandate in self: if mandate.signature_date and mandate.signature_date > today: raise ValidationError( _("The date of signature of mandate '%s' " "is in the future!") % mandate.unique_mandate_reference ) if ( mandate.signature_date and mandate.last_debit_date and mandate.signature_date > mandate.last_debit_date ): raise ValidationError( _( "The mandate '%s' can't have a date of last debit " "before the date of signature." ) % mandate.unique_mandate_reference ) @api.constrains("state", "partner_bank_id", "signature_date") def _check_valid_state(self): for mandate in self: if mandate.state == "valid": if not mandate.signature_date: raise ValidationError( _( "Cannot validate the mandate '%s' without a date of " "signature." ) % mandate.unique_mandate_reference ) if not mandate.partner_bank_id: raise ValidationError( _( "Cannot validate the mandate '%s' because it is not " "attached to a bank account." ) % mandate.unique_mandate_reference ) @api.model def create(self, vals=None): unique_mandate_reference = vals.get("unique_mandate_reference") if not unique_mandate_reference or unique_mandate_reference == "New": vals["unique_mandate_reference"] = ( self.env["ir.sequence"].next_by_code("account.banking.mandate") or "New" ) return super().create(vals) @api.onchange("partner_bank_id") def mandate_partner_bank_change(self): for mandate in self: mandate.partner_id = mandate.partner_bank_id.partner_id def validate(self): for mandate in self: if mandate.state != "draft": raise UserError(_("Mandate should be in draft state.")) self.write({"state": "valid"}) def cancel(self): for mandate in self: if mandate.state not in ("draft", "valid"): raise UserError(_("Mandate should be in draft or valid state.")) self.write({"state": "cancel"}) def back2draft(self): """Allows to set the mandate back to the draft state. This is for mandates cancelled by mistake. """ for mandate in self: if mandate.state != "cancel": raise UserError(_("Mandate should be in cancel state.")) self.write({"state": "draft"})
36.813397
7,694
1,214
py
PYTHON
15.0
# Copyright Akretion (http://www.akretion.com/) # Copyright 2017 Carlos Dauden <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class AccountMoveLine(models.Model): _inherit = "account.move.line" def _prepare_payment_line_vals(self, payment_order): vals = super()._prepare_payment_line_vals(payment_order) if payment_order.payment_type != "inbound": return vals mandate = self.move_id.mandate_id if not mandate and vals.get("mandate_id", False): mandate = mandate.browse(vals["mandate_id"]) partner_bank_id = vals.get("partner_bank_id", False) if not mandate: if partner_bank_id: domain = [("partner_bank_id", "=", partner_bank_id)] else: domain = [("partner_id", "=", self.partner_id.id)] domain.append(("state", "=", "valid")) mandate = mandate.search(domain, limit=1) vals.update( { "mandate_id": mandate.id, "partner_bank_id": mandate.partner_bank_id.id or partner_bank_id, } ) return vals
36.787879
1,214
458
py
PYTHON
15.0
# Copyright 2016-2020 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountPaymentMethod(models.Model): _inherit = "account.payment.method" mandate_required = fields.Boolean( help="Activate this option if this payment method requires your " "customer to sign a direct debit mandate with your company.", )
35.230769
458
1,463
py
PYTHON
15.0
# Copyright 2014 Compassion CH - Cyril Sester <[email protected]> # Copyright 2014 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ResPartnerBank(models.Model): _inherit = "res.partner.bank" mandate_ids = fields.One2many( comodel_name="account.banking.mandate", inverse_name="partner_bank_id", string="Direct Debit Mandates", help="Banking mandates represent an authorization that the bank " "account owner gives to a company for a specific operation.", ) @api.constrains("company_id") def _company_constrains(self): for rpb in self: if rpb.company_id and ( self.env["account.banking.mandate"] .sudo() .search( [ ("partner_bank_id", "=", rpb.id), ("company_id", "!=", rpb.company_id.id), ], limit=1, ) ): raise ValidationError( _( "You cannot change the company of Partner Bank %s, " "as there exists mandates referencing it that " "belong to another company." ) % (rpb.display_name,) )
35.682927
1,463
1,913
py
PYTHON
15.0
# Copyright 2016 Akretion (Alexis de Lattre <[email protected]>) # Copyright 2017 Carlos Dauden <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResPartner(models.Model): _inherit = "res.partner" mandate_count = fields.Integer( compute="_compute_mandate_count", string="Number of Mandates", readonly=True ) valid_mandate_id = fields.Many2one( comodel_name="account.banking.mandate", compute="_compute_valid_mandate_id", string="First Valid Mandate", ) def _compute_mandate_count(self): mandate_data = self.env["account.banking.mandate"].read_group( [("partner_id", "in", self.ids)], ["partner_id"], ["partner_id"] ) mapped_data = { mandate["partner_id"][0]: mandate["partner_id_count"] for mandate in mandate_data } for partner in self: partner.mandate_count = mapped_data.get(partner.id, 0) def _compute_valid_mandate_id(self): # Dict for reducing the duplicated searches on parent/child partners company_id = self.env.company.id mandates_dic = {} for partner in self: commercial_partner_id = partner.commercial_partner_id.id if commercial_partner_id in mandates_dic: partner.valid_mandate_id = mandates_dic[commercial_partner_id] else: mandates = partner.commercial_partner_id.bank_ids.mapped( "mandate_ids" ).filtered( lambda x: x.state == "valid" and x.company_id.id == company_id ) first_valid_mandate_id = mandates[:1].id partner.valid_mandate_id = first_valid_mandate_id mandates_dic[commercial_partner_id] = first_valid_mandate_id
40.702128
1,913
658
py
PYTHON
15.0
from odoo.tools import sql def pre_init_hook(cr): """Prepare new partner_bank_id computed field. Add column to avoid MemoryError on an existing Odoo instance with lots of data. partner_bank_id on account.move.line requires payment_order_ok to be True which it won't be as it's newly introduced - nothing to compute. (see AccountMoveLine._compute_partner_bank_id() in models/account_move_line.py and AccountMove._compute_payment_order_ok() in models/account_move.py) """ if not sql.column_exists(cr, "account_move_line", "partner_bank_id"): sql.create_column(cr, "account_move_line", "partner_bank_id", "int4")
41.125
658
1,563
py
PYTHON
15.0
# © 2009 EduSense BV (<http://www.edusense.nl>) # © 2011-2013 Therp BV (<https://therp.nl>) # © 2013-2014 ACSONE SA (<https://acsone.eu>). # © 2016 Akretion (<https://www.akretion.com>). # © 2016 Aselcis (<https://www.aselcis.com>). # © 2014-2023 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Payment Order", "version": "15.0.2.0.2", "license": "AGPL-3", "author": "ACSONE SA/NV, " "Therp BV, " "Tecnativa, " "Akretion, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/bank-payment", "development_status": "Mature", "category": "Banking addons", "external_dependencies": {"python": ["lxml"]}, "depends": ["account_payment_partner", "base_iban"], # for manual_bank_tranfer "data": [ "views/account_payment_method.xml", "security/payment_security.xml", "security/ir.model.access.csv", "wizard/account_payment_line_create_view.xml", "wizard/account_invoice_payment_line_multi_view.xml", "views/account_payment_mode.xml", "views/account_payment_order.xml", "views/account_payment_line.xml", "views/account_move_line.xml", "views/ir_attachment.xml", "views/account_invoice_view.xml", "data/payment_seq.xml", "report/print_account_payment_order.xml", "report/account_payment_order.xml", ], "demo": ["demo/payment_demo.xml"], "installable": True, "pre_init_hook": "pre_init_hook", }
36.209302
1,557
252
py
PYTHON
15.0
# Copyright 2023 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.remove_tables_fks(env.cr, ["bank_payment_line"])
31.5
252
6,959
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from openupgradelib import openupgrade _logger = logging.getLogger(__name__) def _insert_account_payments(env): openupgrade.logged_query( env.cr, "ALTER TABLE account_payment ADD old_bank_payment_line_id INT4" ) # Create an account.payment record for each bank.payment.line openupgrade.logged_query( env.cr, """ INSERT INTO account_payment ( create_date, create_uid, write_date, write_uid, old_bank_payment_line_name, payment_order_id, partner_id, amount, currency_id, payment_method_id, old_bank_payment_line_id, payment_type, partner_type, destination_account_id, payment_reference, move_id ) SELECT bpl.create_date, bpl.create_uid, bpl.write_date, bpl.write_uid, bpl.name, bpl.order_id, bpl.partner_id, bpl.amount_currency, 1, apm.payment_method_id, bpl.id, apo.payment_type, CASE WHEN apo.payment_type = 'inbound' THEN 'customer' ELSE 'supplier' END, aml.account_id, bpl.communication, aml.move_id FROM bank_payment_line bpl JOIN account_payment_order apo ON apo.id = bpl.order_id JOIN account_payment_mode apm ON apm.id = apo.payment_mode_id LEFT JOIN account_move_line aml ON aml.bank_payment_line_id = bpl.id WHERE apo.state not in ('uploaded', 'done') or aml.move_id is not null """, ) # As the information is asymmetric: N payment lines > 1 bank payment line, but there # are some related non-stored fields to payment lines, we need a second query to # update some of the fields openupgrade.logged_query( env.cr, """ UPDATE account_payment ap SET currency_id = apl.currency_id, partner_bank_id = apl.partner_bank_id FROM account_payment_line apl WHERE apl.bank_line_id = ap.old_bank_payment_line_id """, ) def _create_hooks(env): """Avoid errors due to locked dates, overriding involved methods.""" def _check_fiscalyear_lock_date(self): return True def _check_tax_lock_date(self): return True def _check_reconciliation(self): return True # create hooks _check_fiscalyear_lock_date._original_method = type( env["account.move"] )._check_fiscalyear_lock_date type(env["account.move"])._check_fiscalyear_lock_date = _check_fiscalyear_lock_date _check_tax_lock_date._original_method = type( env["account.move.line"] )._check_tax_lock_date type(env["account.move.line"])._check_tax_lock_date = _check_tax_lock_date _check_reconciliation._original_method = type( env["account.move.line"] )._check_reconciliation type(env["account.move.line"])._check_reconciliation = _check_reconciliation def create_moves_from_orphan_account_payments(env): """Recreate missing journal entries on the newly created account payments.""" env.cr.execute( """ SELECT ap.id, MIN(apl.date), MIN(bpl.company_id), MIN(apo.name), MIN(apo.journal_id), MIN(apl.currency_id), MIN(apo.state), MIN(apo.id) FROM bank_payment_line bpl JOIN account_payment ap ON ap.old_bank_payment_line_id = bpl.id JOIN account_payment_order apo ON apo.id = bpl.order_id JOIN account_payment_line apl ON apl.bank_line_id = bpl.id LEFT JOIN account_move_line aml ON aml.bank_payment_line_id = bpl.id WHERE aml.move_id IS NULL GROUP BY ap.id """ ) deprecated_acc_by_company = {} for row in env.cr.fetchall(): payment = ( env["account.payment"] .with_context( check_move_validity=False, tracking_disable=True, ) .browse(row[0]) ) move = env["account.move"].create( { "name": "/", "date": row[1], "payment_id": payment.id, "move_type": "entry", "company_id": row[2], "ref": row[3], "journal_id": row[4], "currency_id": row[5], "state": "draft" if row[6] in {"open", "generated"} else "cancel", "payment_order_id": row[7], } ) payment.move_id = move # Avoid deprecated account warning if payment.company_id not in deprecated_acc_by_company: deprecated_accounts = env["account.account"].search( [("deprecated", "=", True), ("company_id", "=", payment.company_id.id)] ) deprecated_acc_by_company[payment.company_id] = deprecated_accounts deprecated_accounts.deprecated = False try: payment._synchronize_to_moves(["date"]) # no more changed fields needed except Exception as e: _logger.error("Failed for payment with id %s: %s", payment.id, e) raise # Restore deprecated accounts for deprecated_accounts in deprecated_acc_by_company.values(): deprecated_accounts.deprecated = True def _delete_hooks(env): """Restore the locking dates original methods.""" type(env["account.move"])._check_fiscalyear_lock_date = type( env["account.move"] )._check_fiscalyear_lock_date._original_method type(env["account.move.line"])._check_tax_lock_date = type( env["account.move.line"] )._check_tax_lock_date._original_method type(env["account.move.line"])._check_reconciliation = type( env["account.move.line"] )._check_reconciliation._original_method def _insert_payment_line_payment_link(env): openupgrade.logged_query( env.cr, """ INSERT INTO account_payment_account_payment_line_rel (account_payment_id, account_payment_line_id) SELECT ap.id, apl.id FROM account_payment_line apl JOIN account_payment ap ON ap.old_bank_payment_line_id = apl.bank_line_id """, ) @openupgrade.migrate() def migrate(env, version): if openupgrade.column_exists(env.cr, "account_payment", "old_bank_payment_line_id"): # No execution if the column exists, as that means that this DB comes from v14 # with the refactoring already applied return openupgrade.logged_query( env.cr, "ALTER TABLE account_payment ALTER move_id DROP NOT NULL" ) _insert_account_payments(env) _create_hooks(env) create_moves_from_orphan_account_payments(env) openupgrade.logged_query( env.cr, "ALTER TABLE account_payment ALTER move_id SET NOT NULL" ) _delete_hooks(env) _insert_payment_line_payment_link(env) openupgrade.delete_records_safely_by_xml_id( env, ["account_payment_order.bank_payment_line_company_rule"] )
38.236264
6,959
15,918
py
PYTHON
15.0
# © 2017 Camptocamp SA # © 2017 Creu Blanca # Copyright 2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from datetime import date, datetime, timedelta from odoo import fields from odoo.exceptions import UserError, ValidationError from odoo.tests import Form, tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("-at_install", "post_install") class TestPaymentOrderOutboundBase(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company = cls.company_data["company"] cls.env.user.company_id = cls.company.id cls.partner = cls.env["res.partner"].create( { "name": "Test Partner", } ) cls.invoice_line_account = cls.env["account.account"].create( { "name": "Test account", "code": "TEST1", "user_type_id": cls.env.ref("account.data_account_type_expenses").id, } ) cls.mode = cls.env["account.payment.mode"].create( { "name": "Test Credit Transfer to Suppliers", "company_id": cls.company.id, "bank_account_link": "variable", "payment_method_id": cls.env.ref( "account.account_payment_method_manual_out" ).id, } ) cls.creation_mode = cls.env["account.payment.mode"].create( { "name": "Test Direct Debit of suppliers from Société Générale", "company_id": cls.company.id, "bank_account_link": "variable", "payment_method_id": cls.env.ref( "account.account_payment_method_manual_out" ).id, } ) cls.invoice = cls._create_supplier_invoice(cls, "F1242") cls.invoice_02 = cls._create_supplier_invoice(cls, "F1243") cls.bank_journal = cls.company_data["default_journal_bank"] # Make sure no other payment orders are in the DB cls.domain = [ ("state", "=", "draft"), ("payment_type", "=", "outbound"), ("company_id", "=", cls.env.user.company_id.id), ] cls.env["account.payment.order"].search(cls.domain).unlink() def _create_supplier_invoice(self, ref): invoice = self.env["account.move"].create( { "partner_id": self.partner.id, "move_type": "in_invoice", "ref": ref, "payment_mode_id": self.mode.id, "invoice_date": fields.Date.today(), "invoice_line_ids": [ ( 0, None, { "product_id": self.env.ref("product.product_product_4").id, "quantity": 1.0, "price_unit": 100.0, "name": "product that cost 100", "account_id": self.invoice_line_account.id, }, ) ], } ) return invoice def _create_supplier_refund(self, move, manual=False): if manual: # Do the supplier refund manually vals = { "partner_id": self.partner.id, "move_type": "in_refund", "ref": move.ref, "payment_mode_id": self.mode.id, "invoice_date": fields.Date.today(), "invoice_line_ids": [ ( 0, None, { "product_id": self.env.ref("product.product_product_4").id, "quantity": 1.0, "price_unit": 90.0, "name": "refund of 90.0", "account_id": self.invoice_line_account.id, }, ) ], } move = self.env["account.move"].create(vals) return move wizard = ( self.env["account.move.reversal"] .with_context(active_model="account.move", active_ids=move.ids) .create( { "date_mode": "entry", "refund_method": "refund", "journal_id": move.journal_id.id, } ) ) wizard.reverse_moves() return wizard.new_move_ids @tagged("-at_install", "post_install") class TestPaymentOrderOutbound(TestPaymentOrderOutboundBase): def test_creation_due_date(self): self.mode.variable_journal_ids = self.bank_journal self.mode.group_lines = False self.order_creation("due") def test_creation_no_date(self): self.mode.group_lines = True self.creation_mode.write( { "group_lines": False, "bank_account_link": "fixed", "default_date_prefered": "due", "fixed_journal_id": self.bank_journal.id, } ) self.mode.variable_journal_ids = self.bank_journal self.order_creation(False) def test_creation_fixed_date(self): self.mode.write( { "bank_account_link": "fixed", "default_date_prefered": "fixed", "fixed_journal_id": self.bank_journal.id, } ) self.invoice_02.action_post() self.order_creation("fixed") def order_creation(self, date_prefered): # Open invoice self.invoice.action_post() order_vals = { "payment_type": "outbound", "payment_mode_id": self.creation_mode.id, } if date_prefered: order_vals["date_prefered"] = date_prefered order = self.env["account.payment.order"].create(order_vals) with self.assertRaises(UserError): order.draft2open() order.payment_mode_id = self.mode.id order.payment_mode_id_change() self.assertEqual(order.journal_id.id, self.bank_journal.id) self.assertEqual(len(order.payment_line_ids), 0) if date_prefered: self.assertEqual(order.date_prefered, date_prefered) with self.assertRaises(UserError): order.draft2open() line_create = ( self.env["account.payment.line.create"] .with_context(active_model="account.payment.order", active_id=order.id) .create( {"date_type": "move", "move_date": datetime.now() + timedelta(days=1)} ) ) line_create.payment_mode = "any" line_create.move_line_filters_change() line_create.populate() line_create.create_payment_lines() line_created_due = ( self.env["account.payment.line.create"] .with_context(active_model="account.payment.order", active_id=order.id) .create( {"date_type": "due", "due_date": datetime.now() + timedelta(days=1)} ) ) line_created_due.populate() line_created_due.create_payment_lines() self.assertGreater(len(order.payment_line_ids), 0) order.draft2open() order.open2generated() order.generated2uploaded() self.assertEqual(order.move_ids[0].date, order.payment_ids[0].date) self.assertEqual(order.state, "uploaded") def test_cancel_payment_order(self): # Open invoice self.invoice.action_post() # Add to payment order using the wizard self.env["account.invoice.payment.line.multi"].with_context( active_model="account.move", active_ids=self.invoice.ids ).create({}).run() payment_order = self.env["account.payment.order"].search(self.domain) self.assertEqual(len(payment_order), 1) payment_order.write({"journal_id": self.bank_journal.id}) self.assertEqual(len(payment_order.payment_line_ids), 1) self.assertFalse(payment_order.payment_ids) # Open payment order payment_order.draft2open() self.assertEqual(payment_order.payment_count, 1) # Generate and upload payment_order.open2generated() payment_order.generated2uploaded() self.assertEqual(payment_order.state, "uploaded") with self.assertRaises(UserError): payment_order.unlink() payment_order.action_uploaded_cancel() self.assertEqual(payment_order.state, "cancel") payment_order.cancel2draft() payment_order.unlink() self.assertEqual(len(self.env["account.payment.order"].search(self.domain)), 0) def test_constrains(self): outbound_order = self.env["account.payment.order"].create( { "payment_type": "outbound", "payment_mode_id": self.mode.id, "journal_id": self.bank_journal.id, } ) with self.assertRaises(ValidationError): outbound_order.date_scheduled = date.today() - timedelta(days=2) def test_manual_line_and_manual_date(self): # Create payment order outbound_order = self.env["account.payment.order"].create( { "date_prefered": "due", "payment_type": "outbound", "payment_mode_id": self.mode.id, "journal_id": self.bank_journal.id, "description": "order with manual line", } ) self.assertEqual(len(outbound_order.payment_line_ids), 0) # Create a manual payment order line with custom date vals = { "order_id": outbound_order.id, "partner_id": self.partner.id, "communication": "manual line and manual date", "currency_id": outbound_order.payment_mode_id.company_id.currency_id.id, "amount_currency": 192.38, "date": date.today() + timedelta(days=8), } self.env["account.payment.line"].create(vals) self.assertEqual(len(outbound_order.payment_line_ids), 1) self.assertEqual( outbound_order.payment_line_ids[0].date, date.today() + timedelta(days=8) ) # Create a manual payment order line with normal date vals = { "order_id": outbound_order.id, "partner_id": self.partner.id, "communication": "manual line", "currency_id": outbound_order.payment_mode_id.company_id.currency_id.id, "amount_currency": 200.38, } self.env["account.payment.line"].create(vals) self.assertEqual(len(outbound_order.payment_line_ids), 2) self.assertEqual(outbound_order.payment_line_ids[1].date, False) # Open payment order self.assertFalse(outbound_order.payment_ids) outbound_order.draft2open() self.assertEqual(outbound_order.payment_count, 2) self.assertEqual( outbound_order.payment_line_ids[0].date, outbound_order.payment_line_ids[0].payment_ids.date, ) self.assertEqual(outbound_order.payment_line_ids[1].date, date.today()) self.assertEqual( outbound_order.payment_line_ids[1].date, fields.Date.context_today(outbound_order), ) self.assertEqual( outbound_order.payment_line_ids[1].payment_ids.date, fields.Date.context_today(outbound_order), ) def test_supplier_refund(self): """ Confirm the supplier invoice Create a credit note based on that one with an inferior amount Confirm the credit note Create the payment order The communication should be a combination of the invoice reference and the credit note one """ self.invoice.action_post() self.refund = self._create_supplier_refund(self.invoice) with Form(self.refund) as refund_form: refund_form.ref = "R1234" with refund_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 75.0 self.refund.action_post() self.env["account.invoice.payment.line.multi"].with_context( active_model="account.move", active_ids=self.invoice.ids ).create({}).run() payment_order = self.env["account.payment.order"].search(self.domain) self.assertEqual(len(payment_order), 1) payment_order.write({"journal_id": self.bank_journal.id}) self.assertEqual(len(payment_order.payment_line_ids), 1) self.assertEqual("F1242 R1234", payment_order.payment_line_ids.communication) def test_supplier_refund_reference(self): """ Confirm the supplier invoice Set a payment referece Create a credit note based on that one with an inferior amount Confirm the credit note Create the payment order The communication should be a combination of the invoice payment reference and the credit note one """ self.invoice.payment_reference = "F/1234" self.invoice.action_post() self.refund = self._create_supplier_refund(self.invoice) with Form(self.refund) as refund_form: refund_form.ref = "R1234" with refund_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 75.0 self.refund.action_post() # The user add the outstanding payment to the invoice invoice_line = self.invoice.line_ids.filtered( lambda line: line.account_internal_type == "payable" ) refund_line = self.refund.line_ids.filtered( lambda line: line.account_internal_type == "payable" ) (invoice_line | refund_line).reconcile() self.env["account.invoice.payment.line.multi"].with_context( active_model="account.move", active_ids=self.invoice.ids ).create({}).run() payment_order = self.env["account.payment.order"].search(self.domain) self.assertEqual(len(payment_order), 1) payment_order.write({"journal_id": self.bank_journal.id}) self.assertEqual(len(payment_order.payment_line_ids), 1) self.assertEqual("F/1234 R1234", payment_order.payment_line_ids.communication) def test_supplier_manual_refund(self): """ Confirm the supplier invoice with reference Create a credit note manually Confirm the credit note Reconcile move lines together Create the payment order The communication should be a combination of the invoice payment reference and the credit note one """ self.invoice.action_post() self.refund = self._create_supplier_refund(self.invoice, manual=True) with Form(self.refund) as refund_form: refund_form.ref = "R1234" self.refund.action_post() (self.invoice.line_ids + self.refund.line_ids).filtered( lambda line: line.account_internal_type == "payable" ).reconcile() self.env["account.invoice.payment.line.multi"].with_context( active_model="account.move", active_ids=self.invoice.ids ).create({}).run() payment_order = self.env["account.payment.order"].search(self.domain) self.assertEqual(len(payment_order), 1) payment_order.write({"journal_id": self.bank_journal.id}) self.assertEqual(len(payment_order.payment_line_ids), 1) self.assertEqual("F1242 R1234", payment_order.payment_line_ids.communication)
38.25
15,912
4,753
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2017 Creu Blanca # Copyright 2019-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from datetime import date, timedelta from odoo.exceptions import UserError, ValidationError from odoo.tests import tagged from odoo.tests.common import Form from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("-at_install", "post_install") class TestPaymentOrderInboundBase(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company = cls.company_data["company"] cls.env.user.company_id = cls.company.id cls.partner = cls.env["res.partner"].create( { "name": "Test Partner", } ) cls.inbound_mode = cls.env["account.payment.mode"].create( { "name": "Test Direct Debit of customers", "bank_account_link": "variable", "payment_method_id": cls.env.ref( "account.account_payment_method_manual_in" ).id, "company_id": cls.company.id, } ) cls.invoice_line_account = cls.company_data["default_account_revenue"] cls.journal = cls.company_data["default_journal_bank"] cls.inbound_mode.variable_journal_ids = cls.journal # Make sure no others orders are present cls.domain = [ ("state", "=", "draft"), ("payment_type", "=", "inbound"), ("company_id", "=", cls.env.user.company_id.id), ] cls.payment_order_obj = cls.env["account.payment.order"] cls.payment_order_obj.search(cls.domain).unlink() # Create payment order cls.inbound_order = cls.env["account.payment.order"].create( { "payment_type": "inbound", "payment_mode_id": cls.inbound_mode.id, "journal_id": cls.journal.id, } ) # Open invoice cls.invoice = cls._create_customer_invoice(cls) cls.invoice.action_post() # Add to payment order using the wizard cls.env["account.invoice.payment.line.multi"].with_context( active_model="account.move", active_ids=cls.invoice.ids ).create({}).run() def _create_customer_invoice(self): with Form( self.env["account.move"].with_context(default_move_type="out_invoice") ) as invoice_form: invoice_form.partner_id = self.partner with invoice_form.invoice_line_ids.new() as invoice_line_form: invoice_line_form.product_id = self.env.ref("product.product_product_4") invoice_line_form.name = "product that cost 100" invoice_line_form.quantity = 1 invoice_line_form.price_unit = 100.0 invoice_line_form.account_id = self.invoice_line_account invoice_line_form.tax_ids.clear() invoice = invoice_form.save() invoice_form = Form(invoice) invoice_form.payment_mode_id = self.inbound_mode return invoice_form.save() @tagged("-at_install", "post_install") class TestPaymentOrderInbound(TestPaymentOrderInboundBase): def test_constrains_type(self): with self.assertRaises(ValidationError): order = self.env["account.payment.order"].create( {"payment_mode_id": self.inbound_mode.id, "journal_id": self.journal.id} ) order.payment_type = "outbound" def test_constrains_date(self): with self.assertRaises(ValidationError): self.inbound_order.date_scheduled = date.today() - timedelta(days=1) def test_creation(self): payment_order = self.inbound_order self.assertEqual(len(payment_order.ids), 1) payment_order.write({"journal_id": self.journal.id}) self.assertEqual(len(payment_order.payment_line_ids), 1) self.assertFalse(payment_order.payment_ids) # Open payment order payment_order.draft2open() self.assertEqual(payment_order.payment_count, 1) # Generate and upload payment_order.open2generated() payment_order.generated2uploaded() self.assertEqual(payment_order.state, "uploaded") with self.assertRaises(UserError): payment_order.unlink() payment_order.action_uploaded_cancel() self.assertEqual(payment_order.state, "cancel") payment_order.cancel2draft() payment_order.unlink() self.assertEqual(len(self.payment_order_obj.search(self.domain)), 0)
39.280992
4,753
7,060
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from unittest.mock import patch from odoo.tests import tagged from odoo.addons.account.models.account_payment_method import AccountPaymentMethod from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("-at_install", "post_install") class TestAccountPayment(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) Method_get_payment_method_information = ( AccountPaymentMethod._get_payment_method_information ) def _get_payment_method_information(self): res = Method_get_payment_method_information(self) res["IN"] = {"mode": "multi", "domain": [("type", "=", "bank")]} res["IN2"] = {"mode": "multi", "domain": [("type", "=", "bank")]} res["OUT"] = {"mode": "multi", "domain": [("type", "=", "bank")]} return res cls.company = cls.company_data["company"] cls.env.user.company_ids += cls.company # MODELS cls.account_payment_model = cls.env["account.payment"] cls.account_journal_model = cls.env["account.journal"] cls.payment_method_model = cls.env["account.payment.method"] # INSTANCES # Payment methods with patch.object( AccountPaymentMethod, "_get_payment_method_information", _get_payment_method_information, ): cls.inbound_payment_method_01 = cls.payment_method_model.create( { "name": "inbound", "code": "IN", "payment_type": "inbound", } ) cls.inbound_payment_method_02 = cls.inbound_payment_method_01.copy( { "name": "inbound 2", "code": "IN2", "payment_type": "inbound", } ) cls.outbound_payment_method_01 = cls.payment_method_model.create( { "name": "outbound", "code": "OUT", "payment_type": "outbound", } ) # Journals cls.manual_in = cls.env.ref("account.account_payment_method_manual_in") cls.manual_out = cls.env.ref("account.account_payment_method_manual_out") cls.bank_journal = cls.company_data["default_journal_bank"] def test_account_payment_01(self): self.assertFalse(self.inbound_payment_method_01.payment_order_only) self.assertFalse(self.inbound_payment_method_02.payment_order_only) self.assertFalse(self.bank_journal.inbound_payment_order_only) self.inbound_payment_method_01.payment_order_only = True self.assertTrue(self.inbound_payment_method_01.payment_order_only) self.assertFalse(self.inbound_payment_method_02.payment_order_only) self.assertFalse(self.bank_journal.inbound_payment_order_only) for p in self.bank_journal.inbound_payment_method_line_ids.payment_method_id: p.payment_order_only = True self.assertTrue(self.bank_journal.inbound_payment_order_only) def test_account_payment_02(self): self.assertFalse(self.outbound_payment_method_01.payment_order_only) self.assertFalse(self.bank_journal.outbound_payment_order_only) self.outbound_payment_method_01.payment_order_only = True self.assertTrue(self.outbound_payment_method_01.payment_order_only) payment_method_id = ( self.bank_journal.outbound_payment_method_line_ids.payment_method_id ) payment_method_id.payment_order_only = True self.assertTrue(self.bank_journal.outbound_payment_order_only) def test_account_payment_03(self): self.assertFalse(self.inbound_payment_method_01.payment_order_only) self.assertFalse(self.inbound_payment_method_02.payment_order_only) self.assertFalse(self.bank_journal.inbound_payment_order_only) new_account_payment = self.account_payment_model.with_context( default_company_id=self.company.id ).new( { "journal_id": self.bank_journal.id, "payment_type": "inbound", "amount": 1, "company_id": self.company.id, } ) # check journals journals = new_account_payment._get_default_journal() self.assertIn(self.bank_journal, journals) # check payment methods payment_methods = ( new_account_payment.available_payment_method_line_ids.filtered( lambda x: x.payment_type == "inbound" ) .mapped("payment_method_id") .ids ) self.assertIn(self.inbound_payment_method_01.id, payment_methods) self.assertIn(self.inbound_payment_method_02.id, payment_methods) # Set one payment method of the bank journal 'payment order only' self.inbound_payment_method_01.payment_order_only = True # check journals journals = new_account_payment._get_default_journal() self.assertIn(self.bank_journal, journals) # check payment methods new_account_payment2 = self.account_payment_model.with_context( default_company_id=self.company.id ).new( { "journal_id": self.bank_journal.id, "payment_type": "inbound", "amount": 1, "company_id": self.company.id, } ) payment_methods = new_account_payment2.available_payment_method_line_ids.mapped( "payment_method_id" ).ids self.assertNotIn(self.inbound_payment_method_01.id, payment_methods) self.assertIn(self.inbound_payment_method_02.id, payment_methods) # Set all payment methods of the bank journal 'payment order only' for p in self.bank_journal.inbound_payment_method_line_ids.payment_method_id: p.payment_order_only = True self.assertTrue(self.bank_journal.inbound_payment_order_only) # check journals journals = new_account_payment._get_default_journal() self.assertNotIn(self.bank_journal, journals) # check payment methods new_account_payment3 = self.account_payment_model.with_context( default_company_id=self.company.id ).new( { "journal_id": self.bank_journal.id, "payment_type": "inbound", "amount": 1, "company_id": self.company.id, } ) payment_methods = new_account_payment3.available_payment_method_line_ids.mapped( "payment_method_id" ).ids self.assertNotIn(self.inbound_payment_method_01.id, payment_methods) self.assertNotIn(self.inbound_payment_method_02.id, payment_methods)
43.04878
7,060
403
py
PYTHON
15.0
# © 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestBank(TransactionCase): def test_bank(self): bank = self.env["res.bank"].search([], limit=1) self.assertTrue(bank) with self.assertRaises(ValidationError): bank.bic = "TEST"
30.923077
402
3,171
py
PYTHON
15.0
# © 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from unittest.mock import patch from odoo.tests.common import TransactionCase from odoo.addons.account.models.account_payment_method import AccountPaymentMethod class TestPaymentMode(TransactionCase): def setUp(self): super(TestPaymentMode, self).setUp() Method_get_payment_method_information = ( AccountPaymentMethod._get_payment_method_information ) def _get_payment_method_information(self): res = Method_get_payment_method_information(self) res["IN"] = {"mode": "multi", "domain": [("type", "=", "bank")]} res["IN2"] = {"mode": "multi", "domain": [("type", "=", "bank")]} res["electronic_out"] = {"mode": "multi", "domain": [("type", "=", "bank")]} return res # Company self.company = self.env.ref("base.main_company") self.journal_c1 = self.env["account.journal"].create( { "name": "Journal 1", "code": "J1", "type": "bank", "company_id": self.company.id, } ) self.account = self.env["account.account"].search( [("reconcile", "=", True), ("company_id", "=", self.company.id)], limit=1 ) self.manual_out = self.env.ref("account.account_payment_method_manual_out") self.manual_in = self.env.ref("account.account_payment_method_manual_in") with patch.object( AccountPaymentMethod, "_get_payment_method_information", _get_payment_method_information, ): self.electronic_out = self.env["account.payment.method"].create( { "name": "Electronic Out", "code": "electronic_out", "payment_type": "outbound", } ) self.payment_mode_c1 = self.env["account.payment.mode"].create( { "name": "Direct Debit of suppliers from Bank 1", "bank_account_link": "variable", "payment_method_id": self.manual_out.id, "company_id": self.company.id, "fixed_journal_id": self.journal_c1.id, "variable_journal_ids": [(6, 0, [self.journal_c1.id])], } ) def test_onchange_payment_type(self): self.payment_mode_c1.payment_method_id = self.manual_in self.payment_mode_c1.payment_method_id_change() self.assertTrue( all( [ journal.type in ["sale_refund", "sale"] for journal in self.payment_mode_c1.default_journal_ids ] ) ) self.payment_mode_c1.payment_method_id = self.manual_out self.payment_mode_c1.payment_method_id_change() self.assertTrue( all( [ journal.type in ["purchase_refund", "purchase"] for journal in self.payment_mode_c1.default_journal_ids ] ) )
34.835165
3,170
650
py
PYTHON
15.0
# © 2016 Akretion (<https://www.akretion.com>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class AccountInvoicePaymentLineMulti(models.TransientModel): _name = "account.invoice.payment.line.multi" _description = "Create payment lines from invoice tree view" def run(self): self.ensure_one() assert ( self._context["active_model"] == "account.move" ), "Active model should be account.move" invoices = self.env["account.move"].browse(self._context["active_ids"]) action = invoices.create_account_payment_line() return action
36.055556
649
6,742
py
PYTHON
15.0
# © 2009 EduSense BV (<http://www.edusense.nl>) # © 2011-2013 Therp BV (<https://therp.nl>) # © 2014-2015 ACSONE SA/NV (<https://acsone.eu>) # © 2015-2016 Akretion (<https://www.akretion.com>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models class AccountPaymentLineCreate(models.TransientModel): _name = "account.payment.line.create" _description = "Wizard to create payment lines" order_id = fields.Many2one( comodel_name="account.payment.order", string="Payment Order" ) journal_ids = fields.Many2many( comodel_name="account.journal", string="Journals Filter" ) partner_ids = fields.Many2many( comodel_name="res.partner", string="Partners", domain=[("parent_id", "=", False)], ) target_move = fields.Selection( selection=[("posted", "All Posted Entries"), ("all", "All Entries")], string="Target Moves", ) allow_blocked = fields.Boolean(string="Allow Litigation Move Lines") invoice = fields.Boolean(string="Linked to an Invoice or Refund") date_type = fields.Selection( selection=[("due", "Due Date"), ("move", "Move Date")], string="Type of Date Filter", required=True, ) due_date = fields.Date() move_date = fields.Date(default=fields.Date.context_today) payment_mode = fields.Selection( selection=[("same", "Same"), ("same_or_null", "Same or Empty"), ("any", "Any")], ) move_line_ids = fields.Many2many( comodel_name="account.move.line", string="Move Lines" ) @api.model def default_get(self, field_list): res = super(AccountPaymentLineCreate, self).default_get(field_list) context = self.env.context assert ( context.get("active_model") == "account.payment.order" ), "active_model should be payment.order" assert context.get("active_id"), "Missing active_id in context !" order = self.env["account.payment.order"].browse(context["active_id"]) mode = order.payment_mode_id res.update( { "journal_ids": mode.default_journal_ids.ids or False, "target_move": mode.default_target_move, "invoice": mode.default_invoice, "date_type": mode.default_date_type, "payment_mode": mode.default_payment_mode, "order_id": order.id, } ) return res def _prepare_move_line_domain(self): self.ensure_one() domain = [ ("reconciled", "=", False), ("company_id", "=", self.order_id.company_id.id), ] if self.journal_ids: domain += [("journal_id", "in", self.journal_ids.ids)] if self.partner_ids: domain += [("partner_id", "in", self.partner_ids.ids)] if self.target_move == "posted": domain += [("move_id.state", "=", "posted")] if not self.allow_blocked: domain += [("blocked", "!=", True)] if self.date_type == "due": domain += [ "|", ("date_maturity", "<=", self.due_date), ("date_maturity", "=", False), ] elif self.date_type == "move": domain.append(("date", "<=", self.move_date)) if self.invoice: domain.append( ( "move_id.move_type", "in", ("in_invoice", "out_invoice", "in_refund", "out_refund"), ) ) if self.payment_mode: if self.payment_mode == "same": domain.append( ("payment_mode_id", "=", self.order_id.payment_mode_id.id) ) elif self.payment_mode == "same_or_null": domain += [ "|", ("payment_mode_id", "=", False), ("payment_mode_id", "=", self.order_id.payment_mode_id.id), ] if self.order_id.payment_type == "outbound": # For payables, propose all unreconciled credit lines, # including partially reconciled ones. # If they are partially reconciled with a supplier refund, # the residual will be added to the payment order. # # For receivables, propose all unreconciled credit lines. # (ie customer refunds): they can be refunded with a payment. # Do not propose partially reconciled credit lines, # as they are deducted from a customer invoice, and # will not be refunded with a payment. domain += [ ("credit", ">", 0), ("account_id.internal_type", "in", ["payable", "receivable"]), ] elif self.order_id.payment_type == "inbound": domain += [ ("debit", ">", 0), ("account_id.internal_type", "in", ["receivable", "payable"]), ] # Exclude lines that are already in a non-cancelled # and non-uploaded payment order; lines that are in a # uploaded payment order are proposed if they are not reconciled, paylines = self.env["account.payment.line"].search( [ ("state", "in", ("draft", "open", "generated")), ("move_line_id", "!=", False), ] ) if paylines: move_lines_ids = [payline.move_line_id.id for payline in paylines] domain += [("id", "not in", move_lines_ids)] return domain def populate(self): domain = self._prepare_move_line_domain() lines = self.env["account.move.line"].search(domain) self.move_line_ids = lines action = { "name": _("Select Move Lines to Create Transactions"), "type": "ir.actions.act_window", "res_model": "account.payment.line.create", "view_mode": "form", "target": "new", "res_id": self.id, "context": self._context, } return action @api.onchange( "date_type", "move_date", "due_date", "journal_ids", "invoice", "target_move", "allow_blocked", "payment_mode", "partner_ids", ) def move_line_filters_change(self): domain = self._prepare_move_line_domain() res = {"domain": {"move_line_ids": domain}} return res def create_payment_lines(self): if self.move_line_ids: self.move_line_ids.create_payment_line_from_move_line(self.order_id) return True
38.067797
6,738
9,065
py
PYTHON
15.0
# © 2015-2016 Akretion - Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError class AccountPaymentLine(models.Model): _name = "account.payment.line" _description = "Payment Lines" _check_company_auto = True name = fields.Char(string="Payment Reference", readonly=True, copy=False) order_id = fields.Many2one( comodel_name="account.payment.order", string="Payment Order", ondelete="cascade", index=True, check_company=True, ) company_id = fields.Many2one( related="order_id.company_id", store=True, readonly=True ) company_currency_id = fields.Many2one( related="order_id.company_currency_id", store=True, readonly=True ) payment_type = fields.Selection( related="order_id.payment_type", store=True, readonly=True ) bank_account_required = fields.Boolean( related="order_id.payment_method_id.bank_account_required", readonly=True ) state = fields.Selection( related="order_id.state", string="State", readonly=True, store=True ) move_line_id = fields.Many2one( comodel_name="account.move.line", string="Journal Item", ondelete="restrict", check_company=True, ) ml_maturity_date = fields.Date(related="move_line_id.date_maturity", readonly=True) currency_id = fields.Many2one( comodel_name="res.currency", string="Currency of the Payment Transaction", required=True, default=lambda self: self.env.user.company_id.currency_id, ) amount_currency = fields.Monetary(string="Amount", currency_field="currency_id") amount_company_currency = fields.Monetary( compute="_compute_amount_company_currency", string="Amount in Company Currency", currency_field="company_currency_id", ) partner_id = fields.Many2one( comodel_name="res.partner", string="Partner", required=True, domain=[("parent_id", "=", False)], check_company=True, ) partner_bank_id = fields.Many2one( comodel_name="res.partner.bank", string="Partner Bank Account", required=False, ondelete="restrict", check_company=True, ) date = fields.Date(string="Payment Date") # communication field is required=False because we don't want to block # the creation of lines from move/invoices when communication is empty # This field is required in the form view and there is an error message # when going from draft to confirm if the field is empty communication = fields.Char( required=False, help="Label of the payment that will be seen by the destinee" ) communication_type = fields.Selection( selection=[("normal", "Free")], required=True, default="normal" ) payment_ids = fields.Many2many( comodel_name="account.payment", string="Payment transaction", readonly=True, ) _sql_constraints = [ ( "name_company_unique", "unique(name, company_id)", "A payment line already exists with this reference in the same company!", ) ] @api.model def create(self, vals): if vals.get("name", "New") == "New": vals["name"] = ( self.env["ir.sequence"].next_by_code("account.payment.line") or "New" ) return super(AccountPaymentLine, self).create(vals) @api.depends("amount_currency", "currency_id", "company_currency_id", "date") def _compute_amount_company_currency(self): for line in self: if line.currency_id and line.company_currency_id: line.amount_company_currency = line.currency_id._convert( line.amount_currency, line.company_currency_id, line.company_id, line.date or fields.Date.today(), ) else: line.amount_company_currency = 0 @api.model def _get_payment_line_grouping_fields(self): """This list of fields is used o compute the grouping hashcode.""" return [ "currency_id", "partner_id", "partner_bank_id", "date", "communication_type", ] def payment_line_hashcode(self): self.ensure_one() values = [] for field in self._get_payment_line_grouping_fields(): values.append(str(self[field])) # Don't group the payment lines that are attached to the same supplier # but to move lines with different accounts (very unlikely), # for easier generation/comprehension of the transfer move values.append(str(self.move_line_id.account_id or False)) # Don't group the payment lines that use a structured communication # otherwise it would break the structured communication system ! if self.communication_type != "normal": values.append(str(self.id)) return "-".join(values) @api.onchange("partner_id") def partner_id_change(self): partner_bank = False if self.partner_id.bank_ids: partner_bank = self.partner_id.bank_ids[0] self.partner_bank_id = partner_bank @api.onchange("move_line_id") def move_line_id_change(self): if self.move_line_id: vals = self.move_line_id._prepare_payment_line_vals(self.order_id) vals.pop("order_id") for field, value in vals.items(): self[field] = value else: self.partner_id = False self.partner_bank_id = False self.amount_currency = 0.0 self.currency_id = self.env.user.company_id.currency_id self.communication = False def invoice_reference_type2communication_type(self): """This method is designed to be inherited by localization modules""" # key = value of 'reference_type' field on account_invoice # value = value of 'communication_type' field on account_payment_line res = {"none": "normal", "structured": "structured"} return res def draft2open_payment_line_check(self): self.ensure_one() if self.bank_account_required and not self.partner_bank_id: raise UserError( _("Missing Partner Bank Account on payment line %s") % self.name ) if not self.communication: raise UserError(_("Communication is empty on payment line %s.") % self.name) def _prepare_account_payment_vals(self): """Prepare the dictionary to create an account payment record from a set of payment lines. """ journal = self.order_id.journal_id vals = { "payment_type": self.order_id.payment_type, "partner_id": self.partner_id.id, "destination_account_id": self.move_line_id.account_id.id, "company_id": self.order_id.company_id.id, "amount": sum(self.mapped("amount_currency")), "date": self[:1].date, "currency_id": self.currency_id.id, "ref": self.order_id.name, "payment_reference": "-".join([line.communication for line in self]), "journal_id": journal.id, "partner_bank_id": self.partner_bank_id.id, "payment_order_id": self.order_id.id, "payment_line_ids": [(6, 0, self.ids)], } # Determine payment method line according payment method and journal line = self.env["account.payment.method.line"].search( [ ( "payment_method_id", "=", self.order_id.payment_mode_id.payment_method_id.id, ), ("journal_id", "=", journal.id), ], limit=1, ) if line: vals["payment_method_line_id"] = line.id # Determine partner_type move_type = self[:1].move_line_id.move_id.move_type if move_type in {"out_invoice", "out_refund"}: vals["partner_type"] = "customer" elif move_type in {"in_invoice", "in_refund"}: vals["partner_type"] = "supplier" else: p_type = "customer" if vals["payment_type"] == "inbound" else "supplier" vals["partner_type"] = p_type # Fill destination account if manual payment line with no linked journal item if not vals["destination_account_id"]: if vals["partner_type"] == "customer": vals[ "destination_account_id" ] = self.partner_id.property_account_receivable_id.id else: vals[ "destination_account_id" ] = self.partner_id.property_account_payable_id.id return vals
39.068966
9,064
17,302
py
PYTHON
15.0
# © 2009 EduSense BV (<http://www.edusense.nl>) # © 2011-2013 Therp BV (<https://therp.nl>) # © 2016 Akretion (Alexis de Lattre - [email protected]) # Copyright 2016-2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import base64 from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class AccountPaymentOrder(models.Model): _name = "account.payment.order" _description = "Payment Order" _inherit = ["mail.thread", "mail.activity.mixin"] _order = "id desc" _check_company_auto = True name = fields.Char(string="Number", readonly=True, copy=False) payment_mode_id = fields.Many2one( comodel_name="account.payment.mode", required=True, ondelete="restrict", tracking=True, readonly=True, states={"draft": [("readonly", False)]}, check_company=True, ) payment_type = fields.Selection( selection=[("inbound", "Inbound"), ("outbound", "Outbound")], readonly=True, required=True, ) payment_method_id = fields.Many2one( comodel_name="account.payment.method", related="payment_mode_id.payment_method_id", readonly=True, store=True, ) company_id = fields.Many2one( related="payment_mode_id.company_id", store=True, readonly=True ) company_currency_id = fields.Many2one( related="payment_mode_id.company_id.currency_id", store=True, readonly=True ) bank_account_link = fields.Selection( related="payment_mode_id.bank_account_link", readonly=True ) allowed_journal_ids = fields.Many2many( comodel_name="account.journal", compute="_compute_allowed_journal_ids", string="Allowed journals", ) journal_id = fields.Many2one( comodel_name="account.journal", string="Bank Journal", ondelete="restrict", readonly=True, states={"draft": [("readonly", False)]}, tracking=True, check_company=True, ) # The journal_id field is only required at confirm step, to # allow auto-creation of payment order from invoice company_partner_bank_id = fields.Many2one( related="journal_id.bank_account_id", string="Company Bank Account", readonly=True, ) state = fields.Selection( selection=[ ("draft", "Draft"), ("open", "Confirmed"), ("generated", "File Generated"), ("uploaded", "File Uploaded"), ("cancel", "Cancel"), ], string="Status", readonly=True, copy=False, default="draft", tracking=True, ) date_prefered = fields.Selection( selection=[ ("now", "Immediately"), ("due", "Due Date"), ("fixed", "Fixed Date"), ], string="Payment Execution Date Type", required=True, default="due", tracking=True, readonly=True, states={"draft": [("readonly", False)]}, ) date_scheduled = fields.Date( string="Payment Execution Date", readonly=True, states={"draft": [("readonly", False)]}, tracking=True, help="Select a requested date of execution if you selected 'Due Date' " "as the Payment Execution Date Type.", ) date_generated = fields.Date(string="File Generation Date", readonly=True) date_uploaded = fields.Date(string="File Upload Date", readonly=True) generated_user_id = fields.Many2one( comodel_name="res.users", string="Generated by", readonly=True, ondelete="restrict", copy=False, check_company=True, ) payment_line_ids = fields.One2many( comodel_name="account.payment.line", inverse_name="order_id", string="Transactions", readonly=True, states={"draft": [("readonly", False)]}, ) payment_ids = fields.One2many( comodel_name="account.payment", inverse_name="payment_order_id", string="Payment Transactions", readonly=True, ) payment_count = fields.Integer( compute="_compute_payment_count", string="Number of Payment Transactions", ) total_company_currency = fields.Monetary( compute="_compute_total", store=True, currency_field="company_currency_id" ) move_ids = fields.One2many( comodel_name="account.move", inverse_name="payment_order_id", string="Journal Entries", readonly=True, ) move_count = fields.Integer( compute="_compute_move_count", string="Number of Journal Entries" ) description = fields.Char() @api.depends("payment_mode_id") def _compute_allowed_journal_ids(self): for record in self: if record.payment_mode_id.bank_account_link == "fixed": record.allowed_journal_ids = record.payment_mode_id.fixed_journal_id elif record.payment_mode_id.bank_account_link == "variable": record.allowed_journal_ids = record.payment_mode_id.variable_journal_ids else: record.allowed_journal_ids = False def unlink(self): for order in self: if order.state == "uploaded": raise UserError( _( "You cannot delete an uploaded payment order. You can " "cancel it in order to do so." ) ) return super(AccountPaymentOrder, self).unlink() @api.constrains("payment_type", "payment_mode_id") def payment_order_constraints(self): for order in self: if ( order.payment_mode_id.payment_type and order.payment_mode_id.payment_type != order.payment_type ): raise ValidationError( _( "The payment type (%(ptype)s) is not the same as the payment " "type of the payment mode (%(pmode)s)", ptype=order.payment_type, pmode=order.payment_mode_id.payment_type, ) ) @api.constrains("date_scheduled") def check_date_scheduled(self): today = fields.Date.context_today(self) for order in self: if order.date_scheduled: if order.date_scheduled < today: raise ValidationError( _( "On payment order %(porder)s, the Payment Execution Date " "is in the past (%(exedate)s).", porder=order.name, exedate=order.date_scheduled, ) ) @api.depends("payment_line_ids", "payment_line_ids.amount_company_currency") def _compute_total(self): for rec in self: rec.total_company_currency = sum( rec.mapped("payment_line_ids.amount_company_currency") or [0.0] ) @api.depends("payment_ids") def _compute_payment_count(self): for order in self: order.payment_count = len(order.payment_ids) @api.depends("move_ids") def _compute_move_count(self): rg_res = self.env["account.move"].read_group( [("payment_order_id", "in", self.ids)], ["payment_order_id"], ["payment_order_id"], ) mapped_data = { x["payment_order_id"][0]: x["payment_order_id_count"] for x in rg_res } for order in self: order.move_count = mapped_data.get(order.id, 0) @api.model def create(self, vals): if vals.get("name", "New") == "New": vals["name"] = ( self.env["ir.sequence"].next_by_code("account.payment.order") or "New" ) if vals.get("payment_mode_id"): payment_mode = self.env["account.payment.mode"].browse( vals["payment_mode_id"] ) vals["payment_type"] = payment_mode.payment_type if payment_mode.bank_account_link == "fixed": vals["journal_id"] = payment_mode.fixed_journal_id.id if not vals.get("date_prefered") and payment_mode.default_date_prefered: vals["date_prefered"] = payment_mode.default_date_prefered return super(AccountPaymentOrder, self).create(vals) @api.onchange("payment_mode_id") def payment_mode_id_change(self): if len(self.allowed_journal_ids) == 1: self.journal_id = self.allowed_journal_ids if self.payment_mode_id.default_date_prefered: self.date_prefered = self.payment_mode_id.default_date_prefered def action_uploaded_cancel(self): self.action_cancel() return True def cancel2draft(self): self.write({"state": "draft"}) return True def action_cancel(self): # Unreconcile and cancel payments self.payment_ids.action_draft() self.payment_ids.action_cancel() self.write({"state": "cancel"}) return True def draft2open(self): """ Called when you click on the 'Confirm' button Set the 'date' on payment line depending on the 'date_prefered' setting of the payment.order Re-generate the account payments. """ today = fields.Date.context_today(self) for order in self: if not order.journal_id: raise UserError( _("Missing Bank Journal on payment order %s.") % order.name ) if ( order.payment_method_id.bank_account_required and not order.journal_id.bank_account_id ): raise UserError( _("Missing bank account on bank journal '%s'.") % order.journal_id.display_name ) if not order.payment_line_ids: raise UserError( _("There are no transactions on payment order %s.") % order.name ) # Unreconcile, cancel and delete existing account payments order.payment_ids.action_draft() order.payment_ids.action_cancel() order.payment_ids.unlink() # Prepare account payments from the payment lines payline_err_text = [] group_paylines = {} # key = hashcode for payline in order.payment_line_ids: try: payline.draft2open_payment_line_check() except UserError as e: payline_err_text.append(e.args[0]) # Compute requested payment date if order.date_prefered == "due": requested_date = payline.ml_maturity_date or payline.date or today elif order.date_prefered == "fixed": requested_date = order.date_scheduled or today else: requested_date = today # No payment date in the past requested_date = max(today, requested_date) # inbound: check option no_debit_before_maturity if ( order.payment_type == "inbound" and order.payment_mode_id.no_debit_before_maturity and payline.ml_maturity_date and requested_date < payline.ml_maturity_date ): payline_err_text.append( _( "The payment mode '%(pmode)s' has the option " "'Disallow Debit Before Maturity Date'. The " "payment line %(pline)s has a maturity date %(mdate)s " "which is after the computed payment date %(pdate)s.", pmode=order.payment_mode_id.name, pline=payline.name, mdate=payline.ml_maturity_date, pdate=requested_date, ) ) # Write requested_date on 'date' field of payment line # norecompute is for avoiding a chained recomputation # payment_line_ids.date # > payment_line_ids.amount_company_currency # > total_company_currency with self.env.norecompute(): payline.date = requested_date # Group options hashcode = ( payline.payment_line_hashcode() if order.payment_mode_id.group_lines else payline.id ) if hashcode in group_paylines: group_paylines[hashcode]["paylines"] += payline group_paylines[hashcode]["total"] += payline.amount_currency else: group_paylines[hashcode] = { "paylines": payline, "total": payline.amount_currency, } # Raise errors that happened on the validation process if payline_err_text: raise UserError( _("There's at least one validation error:\n") + "\n".join(payline_err_text) ) order.recompute() # Create account payments payment_vals = [] for paydict in list(group_paylines.values()): # Block if a bank payment line is <= 0 if paydict["total"] <= 0: raise UserError( _( "The amount for Partner '%(partner)s' is negative " "or null (%(amount).2f) !", partner=paydict["paylines"][0].partner_id.name, amount=paydict["total"], ) ) payment_vals.append(paydict["paylines"]._prepare_account_payment_vals()) self.env["account.payment"].create(payment_vals) self.write({"state": "open"}) return True def generate_payment_file(self): """Returns (payment file as string, filename)""" self.ensure_one() if self.payment_method_id.code == "manual": return (False, False) else: raise UserError( _( "No handler for this payment method. Maybe you haven't " "installed the related Odoo module." ) ) def open2generated(self): self.ensure_one() payment_file_str, filename = self.generate_payment_file() action = {} if payment_file_str and filename: attachment = self.env["ir.attachment"].create( { "res_model": "account.payment.order", "res_id": self.id, "name": filename, "datas": base64.b64encode(payment_file_str), } ) simplified_form_view = self.env.ref( "account_payment_order.view_attachment_simplified_form" ) action = { "name": _("Payment File"), "view_mode": "form", "view_id": simplified_form_view.id, "res_model": "ir.attachment", "type": "ir.actions.act_window", "target": "current", "res_id": attachment.id, } self.write( { "date_generated": fields.Date.context_today(self), "state": "generated", "generated_user_id": self._uid, } ) return action def generated2uploaded(self): self.payment_ids.action_post() # Perform the reconciliation of payments and source journal items for payment in self.payment_ids: ( payment.payment_line_ids.move_line_id + payment.move_id.line_ids.filtered( lambda x: x.account_id == payment.destination_account_id ) ).reconcile() self.write( {"state": "uploaded", "date_uploaded": fields.Date.context_today(self)} ) return True def action_move_journal_line(self): self.ensure_one() action = self.env.ref("account.action_move_journal_line").sudo().read()[0] if self.move_count == 1: action.update( { "view_mode": "form,tree,kanban", "views": False, "view_id": False, "res_id": self.move_ids[0].id, } ) else: action["domain"] = [("id", "in", self.move_ids.ids)] ctx = self.env.context.copy() ctx.update({"search_default_misc_filter": 0}) action["context"] = ctx return action
38.103524
17,299
6,033
py
PYTHON
15.0
# © 2013-2014 ACSONE SA (<https://acsone.eu>). # © 2014 Serv. Tecnol. Avanzados - Pedro M. Baeza # © 2016 Akretion (Alexis de Lattre <[email protected]>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError class AccountMove(models.Model): _inherit = "account.move" payment_order_id = fields.Many2one( comodel_name="account.payment.order", string="Payment Order", copy=False, readonly=True, check_company=True, ) payment_order_ok = fields.Boolean(compute="_compute_payment_order_ok") # we restore this field from <=v11 for now for preserving behavior # TODO: Check if we can remove it and base everything in something at # payment mode or company level reference_type = fields.Selection( selection=[("none", "Free Reference"), ("structured", "Structured Reference")], readonly=True, states={"draft": [("readonly", False)]}, default="none", ) @api.depends("payment_mode_id", "line_ids", "line_ids.payment_mode_id") def _compute_payment_order_ok(self): for move in self: payment_mode = move.line_ids.filtered(lambda x: not x.reconciled).mapped( "payment_mode_id" )[:1] if not payment_mode: payment_mode = move.payment_mode_id move.payment_order_ok = payment_mode.payment_order_ok def _prepare_new_payment_order(self, payment_mode=None): self.ensure_one() if payment_mode is None: payment_mode = self.env["account.payment.mode"] vals = {"payment_mode_id": payment_mode.id or self.payment_mode_id.id} # other important fields are set by the inherit of create # in account_payment_order.py return vals def get_account_payment_domain(self, payment_mode): return [("payment_mode_id", "=", payment_mode.id), ("state", "=", "draft")] def create_account_payment_line(self): apoo = self.env["account.payment.order"] result_payorder_ids = set() action_payment_type = "debit" for move in self: if move.state != "posted": raise UserError(_("The invoice %s is not in Posted state") % move.name) applicable_lines = move.line_ids.filtered( lambda x: ( not x.reconciled and x.payment_mode_id.payment_order_ok and x.account_id.internal_type in ("receivable", "payable") and not any( p_state in ("draft", "open", "generated") for p_state in x.payment_line_ids.mapped("state") ) ) ) if not applicable_lines: raise UserError( _( "No Payment Line created for invoice %s because " "it already exists or because this invoice is " "already paid." ) % move.name ) payment_modes = applicable_lines.mapped("payment_mode_id") if not payment_modes: raise UserError(_("No Payment Mode on invoice %s") % move.name) for payment_mode in payment_modes: payorder = apoo.search( move.get_account_payment_domain(payment_mode), limit=1 ) new_payorder = False if not payorder: payorder = apoo.create( move._prepare_new_payment_order(payment_mode) ) new_payorder = True result_payorder_ids.add(payorder.id) action_payment_type = payorder.payment_type count = 0 for line in applicable_lines.filtered( lambda x: x.payment_mode_id == payment_mode ): line.create_payment_line_from_move_line(payorder) count += 1 if new_payorder: move.message_post( body=_( "%(count)d payment lines added to the new draft payment " "order <a href=# data-oe-model=account.payment.order " "data-oe-id=%(order_id)d>%(name)s</a>, which has been " "automatically created.", count=count, order_id=payorder.id, name=payorder.name, ) ) else: move.message_post( body=_( "%(count)d payment lines added to the existing draft " "payment order " "<a href=# data-oe-model=account.payment.order " "data-oe-id=%(order_id)d>%(name)s</a>.", count=count, order_id=payorder.id, name=payorder.name, ) ) action = self.env["ir.actions.act_window"]._for_xml_id( "account_payment_order.account_payment_order_%s_action" % action_payment_type, ) if len(result_payorder_ids) == 1: action.update( { "view_mode": "form,tree,pivot,graph", "res_id": payorder.id, "views": False, } ) else: action.update( { "view_mode": "tree,form,pivot,graph", "domain": "[('id', 'in', %s)]" % result_payorder_ids, "views": False, } ) return action
41.586207
6,030
1,188
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class AccountJournal(models.Model): _inherit = "account.journal" inbound_payment_order_only = fields.Boolean( compute="_compute_inbound_payment_order_only", readonly=True, store=True ) outbound_payment_order_only = fields.Boolean( compute="_compute_outbound_payment_order_only", readonly=True, store=True ) @api.depends("inbound_payment_method_line_ids.payment_method_id.payment_order_only") def _compute_inbound_payment_order_only(self): for rec in self: rec.inbound_payment_order_only = all( p.payment_order_only for p in rec.inbound_payment_method_line_ids.payment_method_id ) @api.depends( "outbound_payment_method_line_ids.payment_method_id.payment_order_only" ) def _compute_outbound_payment_order_only(self): for rec in self: rec.outbound_payment_order_only = all( p.payment_order_only for p in rec.outbound_payment_method_line_ids.payment_method_id )
36
1,188
5,755
py
PYTHON
15.0
# © 2014-2016 Akretion (Alexis de Lattre <[email protected]>) # © 2014 Serv. Tecnol. Avanzados - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models from odoo.fields import first class AccountMoveLine(models.Model): _inherit = "account.move.line" partner_bank_id = fields.Many2one( comodel_name="res.partner.bank", string="Partner Bank Account", compute="_compute_partner_bank_id", readonly=False, store=True, help="Bank account on which we should pay the supplier", check_company=True, ) payment_line_ids = fields.One2many( comodel_name="account.payment.line", inverse_name="move_line_id", string="Payment lines", check_company=True, ) @api.depends("move_id", "move_id.partner_bank_id", "move_id.payment_mode_id") def _compute_partner_bank_id(self): for ml in self: if ( ml.move_id.move_type in ("in_invoice", "in_refund") and not ml.reconciled and ml.payment_mode_id.payment_order_ok and ml.account_id.internal_type in ("receivable", "payable") and not any( p_state in ("draft", "open", "generated") for p_state in ml.payment_line_ids.mapped("state") ) ): ml.partner_bank_id = ml.move_id.partner_bank_id.id else: ml.partner_bank_id = ml.partner_bank_id def _get_linked_move_communication(self): """ This will collect the references from referral moves: - Reversal moves - Partial payments """ self.ensure_one() references = [] # Build a recordset to gather moves from which references have already # taken in order to avoid duplicates reference_moves = self.env["account.move"].browse() # If we have credit note(s) - reversal_move_id is a one2many if self.move_id.reversal_move_id: references.extend( [ move.payment_reference or move.ref for move in self.move_id.reversal_move_id if move.payment_reference or move.ref ] ) reference_moves |= self.move_id.reversal_move_id # Retrieve partial payments - e.g.: manual credit notes for ( _, _, payment_move_line, ) in self.move_id._get_reconciled_invoices_partials(): payment_move = payment_move_line.move_id if payment_move not in reference_moves and ( payment_move.payment_reference or payment_move.ref ): references.append(payment_move.payment_reference or payment_move.ref) return references def _get_communication(self): """ Retrieve the communication string for the payment order """ aplo = self.env["account.payment.line"] # default values for communication_type and communication communication_type = "normal" communication = self.ref or self.name # change these default values if move line is linked to an invoice if self.move_id.is_invoice(): if (self.move_id.reference_type or "none") != "none": communication = self.move_id.ref ref2comm_type = aplo.invoice_reference_type2communication_type() communication_type = ref2comm_type[self.move_id.reference_type] else: if ( self.move_id.move_type in ("in_invoice", "in_refund") and self.move_id.ref ): communication = self.move_id.payment_reference or self.move_id.ref elif "out" in self.move_id.move_type: # Force to only put invoice number here communication = self.move_id.payment_reference or self.move_id.name references = self._get_linked_move_communication() if references: communication += " " + " ".join(references) return communication_type, communication def _prepare_payment_line_vals(self, payment_order): self.ensure_one() communication_type, communication = self._get_communication() if self.currency_id: currency_id = self.currency_id.id amount_currency = self.amount_residual_currency else: currency_id = self.company_id.currency_id.id amount_currency = self.amount_residual # TODO : check that self.amount_residual_currency is 0 # in this case if payment_order.payment_type == "outbound": amount_currency *= -1 partner_bank_id = self.partner_bank_id.id or first(self.partner_id.bank_ids).id vals = { "order_id": payment_order.id, "partner_bank_id": partner_bank_id, "partner_id": self.partner_id.id, "move_line_id": self.id, "communication": communication, "communication_type": communication_type, "currency_id": currency_id, "amount_currency": amount_currency, "date": False, # date is set when the user confirms the payment order } return vals def create_payment_line_from_move_line(self, payment_order): vals_list = [] for mline in self: vals_list.append(mline._prepare_payment_line_vals(payment_order)) return self.env["account.payment.line"].create(vals_list)
41.388489
5,753
431
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountPaymentMethod(models.Model): _inherit = "account.payment.method" payment_order_only = fields.Boolean( string="Only for payment orders", help="This option helps enforcing the use of payment orders for " "some payment methods.", default=False, )
28.733333
431
846
py
PYTHON
15.0
# © 2015-2016 Akretion - Alexis de Lattre <[email protected]> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError class ResBank(models.Model): _inherit = "res.bank" @api.constrains("bic") def check_bic_length(self): for bank in self: if bank.bic and len(bank.bic) not in (8, 11): raise ValidationError( _( "A valid BIC contains 8 or 11 characters. The BIC '%(bic)s' " "contains %(num)d characters, so it is not valid.", bic=bank.bic, num=len(bank.bic), ) ) # starting from v9, on res.partner.bank bank_bic is a related of bank_id.bic
33.8
845
2,102
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # Copyright 2022 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class AccountPayment(models.Model): _inherit = "account.payment" payment_order_id = fields.Many2one(comodel_name="account.payment.order") payment_line_ids = fields.Many2many(comodel_name="account.payment.line") # Compatibility with previous approach for returns - To be removed on v16 old_bank_payment_line_name = fields.Char() def _get_default_journal(self): res = super()._get_default_journal() return res.filtered(lambda journal: not journal.inbound_payment_order_only) @api.depends("payment_type", "journal_id") def _compute_payment_method_line_fields(self): res = super()._compute_payment_method_line_fields() for pay in self: pay.available_payment_method_line_ids = ( pay.journal_id._get_available_payment_method_lines( pay.payment_type ).filtered(lambda x: not x.payment_method_id.payment_order_only) ) to_exclude = pay._get_payment_method_codes_to_exclude() if to_exclude: pay.available_payment_method_line_ids = ( pay.available_payment_method_line_ids.filtered( lambda x: x.code not in to_exclude ) ) if ( pay.payment_method_line_id.id not in pay.available_payment_method_line_ids.ids ): # In some cases, we could be linked to a payment method # line that has been unlinked from the journal. # In such cases, we want to show it on the payment. pay.hide_payment_method_line = False else: pay.hide_payment_method_line = ( len(pay.available_payment_method_line_ids) == 1 and pay.available_payment_method_line_ids.code == "manual" ) return res
42.897959
2,102