From 3c2e3b8c5a7d073fe8f0f6d781b1ccdbc320edd0 Mon Sep 17 00:00:00 2001 From: wan Date: Wed, 20 Feb 2019 14:51:34 +0000 Subject: [PATCH] [REF] account: simplification of payments objects simplification of payments objects and refactoring of the code * registering payment(s) from the list of invoice now generate a single payment per invoice selected * no more abstract object for payments/payment wizard as the logic is now really simple: - group_invoices option is now removed and we never try to group payments based on the currency/customer of whatsoever (see above), - the payment amount is the full residual amount of invoice and users cannot change it anymore * partner_bank_account_id not required as soon as visible (depends on the payment method) * refactoring to name tags and allow easier inheritance via xpath part of task #1918423 --- addons/account/models/account_invoice.py | 4 + addons/account/models/account_payment.py | 491 +++++++++--------- .../reconciliation/reconciliation_action.js | 4 +- .../static/src/xml/account_reconciliation.xml | 4 +- addons/account/tests/test_payment.py | 189 ++----- addons/account/views/account_invoice_view.xml | 4 +- addons/account/views/account_payment_view.xml | 173 +++--- .../models/account_payment.py | 40 +- .../account_check_printing/tests/__init__.py | 1 + .../tests/test_print_check.py | 44 +- .../views/account_payment_views.xml | 27 - .../payment/views/account_payment_views.xml | 11 +- .../test_main_flows/static/src/js/tour.js | 9 +- 13 files changed, 393 insertions(+), 608 deletions(-) create mode 100644 addons/account_check_printing/tests/__init__.py diff --git a/addons/account/models/account_invoice.py b/addons/account/models/account_invoice.py index 0b1595efd3b..2a739f399a6 100644 --- a/addons/account/models/account_invoice.py +++ b/addons/account/models/account_invoice.py @@ -1032,6 +1032,10 @@ class AccountInvoice(models.Model): raise UserError(_('Invoice must be paid in order to set it to register payment.')) return self.write({'state': 'open'}) + @api.multi + def action_register_payment(self): + return self.env['account.payment'].with_context(active_ids=self.ids, active_model='account.invoice').action_register_payment() + @api.multi def action_invoice_cancel(self): return self.filtered(lambda inv: inv.state != 'cancel').action_cancel() diff --git a/addons/account/models/account_payment.py b/addons/account/models/account_payment.py index 72ea7718c08..c89da637742 100644 --- a/addons/account/models/account_payment.py +++ b/addons/account/models/account_payment.py @@ -6,7 +6,6 @@ from odoo.tools import float_compare from itertools import groupby - MAP_INVOICE_TYPE_PARTNER_TYPE = { 'out_invoice': 'customer', 'out_refund': 'customer', @@ -21,6 +20,7 @@ MAP_INVOICE_TYPE_PAYMENT_SIGN = { 'out_refund': 1, } + class account_payment_method(models.Model): _name = "account.payment.method" _description = "Payment Methods" @@ -30,16 +30,36 @@ class account_payment_method(models.Model): payment_type = fields.Selection([('inbound', 'Inbound'), ('outbound', 'Outbound')], required=True) -class account_abstract_payment(models.AbstractModel): - _name = "account.abstract.payment" - _description = "Contains the logic shared between models which allows to register payments" +class account_payment(models.Model): + _name = "account.payment" + _inherit = ['mail.thread', 'mail.activity.mixin'] + _description = "Payments" + _order = "payment_date desc, name desc" - invoice_ids = fields.Many2many('account.invoice', string='Invoices', copy=False) - multi = fields.Boolean(string='Multi', - help='Technical field indicating if the user selected invoices from multiple partners or from different types.') + name = fields.Char(readonly=True, copy=False) # The name is attributed upon post() + payment_reference = fields.Char(copy=False, readonly=True, help="Reference of the document used to issue this payment. Eg. check number, file name, etc.") + move_name = fields.Char(string='Journal Entry Name', readonly=True, + default=False, copy=False, + help="Technical field holding the number given to the journal entry, automatically set when the statement line is reconciled then stored to set the same number again if the line is cancelled, set to draft and re-processed again.") - payment_type = fields.Selection([('outbound', 'Send Money'), ('inbound', 'Receive Money')], string='Payment Type', required=True) - payment_method_id = fields.Many2one('account.payment.method', string='Payment Method Type', required=True, oldname="payment_method", + # Money flows from the journal_id's default_debit_account_id or default_credit_account_id to the destination_account_id + destination_account_id = fields.Many2one('account.account', compute='_compute_destination_account_id', readonly=True) + # For money transfer, money goes from journal_id to a transfer account, then from the transfer account to destination_journal_id + destination_journal_id = fields.Many2one('account.journal', string='Transfer To', domain=[('type', 'in', ('bank', 'cash'))], readonly=True, states={'draft': [('readonly', False)]}) + + invoice_ids = fields.Many2many('account.invoice', 'account_invoice_payment_rel', 'payment_id', 'invoice_id', string="Invoices", copy=False, readonly=True, + help="""Technical field containing the invoice for which the payment has been generated. + This does not especially correspond to the invoices reconciled with the payment, + as it can have been generated first, and reconciled later""") + reconciled_invoice_ids = fields.Many2many('account.invoice', string='Reconciled Invoices', compute='_compute_reconciled_invoice_ids', help="Invoices whose journal items have been reconciled with this payment's.") + has_invoices = fields.Boolean(compute="_compute_reconciled_invoice_ids", help="Technical field used for usability purposes") + + move_line_ids = fields.One2many('account.move.line', 'payment_id', readonly=True, copy=False, ondelete='restrict') + move_reconciled = fields.Boolean(compute="_get_move_reconciled", readonly=True) + + state = fields.Selection([('draft', 'Draft'), ('posted', 'Posted'), ('sent', 'Sent'), ('reconciled', 'Reconciled'), ('cancelled', 'Cancelled')], readonly=True, default='draft', copy=False, string="Status") + payment_type = fields.Selection([('outbound', 'Send Money'), ('inbound', 'Receive Money'), ('transfer', 'Internal Transfer')], string='Payment Type', required=True, readonly=True, states={'draft': [('readonly', False)]}) + payment_method_id = fields.Many2one('account.payment.method', string='Payment Method Type', required=True, readonly=True, states={'draft': [('readonly', False)]}, oldname="payment_method", help="Manual: Get paid by cash, check or any other method outside of Odoo.\n"\ "Electronic: Get paid automatically through a payment acquirer by requesting a transaction on a card saved by the customer when buying or subscribing online (payment token).\n"\ "Check: Pay bill by check and print it from Odoo.\n"\ @@ -48,17 +68,20 @@ class account_abstract_payment(models.AbstractModel): payment_method_code = fields.Char(related='payment_method_id.code', help="Technical field used to adapt the interface to the payment type selected.", readonly=True) - partner_type = fields.Selection([('customer', 'Customer'), ('supplier', 'Vendor')], tracking=True) - partner_id = fields.Many2one('res.partner', string='Partner', tracking=True) + partner_type = fields.Selection([('customer', 'Customer'), ('supplier', 'Vendor')], tracking=True, readonly=True, states={'draft': [('readonly', False)]}) + partner_id = fields.Many2one('res.partner', string='Partner', tracking=True, readonly=True, states={'draft': [('readonly', False)]}) - amount = fields.Monetary(string='Payment Amount', required=True, tracking=True) - currency_id = fields.Many2one('res.currency', string='Currency', required=True, default=lambda self: self.env.user.company_id.currency_id) - payment_date = fields.Date(string='Payment Date', default=fields.Date.context_today, required=True, copy=False, tracking=True) - communication = fields.Char(string='Memo') - journal_id = fields.Many2one('account.journal', string='Payment Journal', required=True, tracking=True, domain=[('type', 'in', ('bank', 'cash'))]) + amount = fields.Monetary(string='Payment Amount', required=True, readonly=True, states={'draft': [('readonly', False)]}, tracking=True) + currency_id = fields.Many2one('res.currency', string='Currency', required=True, readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.user.company_id.currency_id) + payment_date = fields.Date(string='Payment Date', default=fields.Date.context_today, required=True, readonly=True, states={'draft': [('readonly', False)]}, copy=False, tracking=True) + communication = fields.Char(string='Memo', readonly=True, states={'draft': [('readonly', False)]}) + journal_id = fields.Many2one('account.journal', string='Payment Journal', required=True, readonly=True, states={'draft': [('readonly', False)]}, tracking=True, domain=[('type', 'in', ('bank', 'cash'))]) + company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', readonly=True) hide_payment_method = fields.Boolean(compute='_compute_hide_payment_method', - help="Technical field used to hide the payment method if the selected journal has only one available which is 'manual'") + help="Technical field used to hide the payment method if the" + "selected journal has only one available which is 'manual'") + payment_difference = fields.Monetary(compute='_compute_payment_difference', readonly=True) payment_difference_handling = fields.Selection([('open', 'Keep open'), ('reconcile', 'Mark invoice as fully paid')], default='open', string="Payment Difference Handling", copy=False) writeoff_account_id = fields.Many2one('account.account', string="Difference Account", domain=[('deprecated', '=', False)], copy=False) @@ -66,13 +89,13 @@ class account_abstract_payment(models.AbstractModel): string='Journal Item Label', help='Change label of the counterpart that will hold the payment difference', default='Write-Off') - partner_bank_account_id = fields.Many2one('res.partner.bank', string="Recipient Bank Account") + partner_bank_account_id = fields.Many2one('res.partner.bank', string="Recipient Bank Account", readonly=True, states={'draft': [('readonly', False)]}) show_partner_bank_account = fields.Boolean(compute='_compute_show_partner_bank', help='Technical field used to know whether the field `partner_bank_account_id` needs to be displayed or not in the payments form views') @api.model def default_get(self, fields): - rec = super(account_abstract_payment, self).default_get(fields) - active_ids = self._context.get('active_ids') + rec = super(account_payment, self).default_get(fields) + active_ids = self._context.get('active_ids') or self._context.get('active_id') active_model = self._context.get('active_model') # Check for selected invoices ids @@ -84,30 +107,16 @@ class account_abstract_payment(models.AbstractModel): # Check all invoices are open if any(invoice.state != 'open' for invoice in invoices): raise UserError(_("You can only register payments for open invoices")) - # Check all invoices have the same currency - if any(inv.currency_id != invoices[0].currency_id for inv in invoices): - raise UserError(_("In order to pay multiple invoices at once, they must use the same currency.")) - - # Look if we are mixin multiple commercial_partner or customer invoices with vendor bills - multi = any(inv.commercial_partner_id != invoices[0].commercial_partner_id - or MAP_INVOICE_TYPE_PARTNER_TYPE[inv.type] != MAP_INVOICE_TYPE_PARTNER_TYPE[invoices[0].type] - or inv.account_id != invoices[0].account_id - or inv.partner_bank_id != invoices[0].partner_bank_id - for inv in invoices) - - currency = invoices[0].currency_id - - total_amount = self._compute_payment_amount(invoices=invoices, currency=currency) + amount = self._compute_payment_amount(invoices, invoices[0].currency_id) rec.update({ - 'amount': abs(total_amount), - 'currency_id': currency.id, - 'payment_type': total_amount > 0 and 'inbound' or 'outbound', - 'partner_id': False if multi else invoices[0].commercial_partner_id.id, - 'partner_type': False if multi else MAP_INVOICE_TYPE_PARTNER_TYPE[invoices[0].type], - 'communication': ' '.join([ref for ref in invoices.mapped('reference') if ref]), + 'currency_id': invoices[0].currency_id.id, + 'amount': abs(amount), + 'payment_type': 'inbound' if amount > 0 else 'outbound', + 'partner_id': invoices[0].commercial_partner_id.id, + 'partner_type': MAP_INVOICE_TYPE_PARTNER_TYPE[invoices[0].type], + 'communication': invoices[0].reference or invoices[0].number, 'invoice_ids': [(6, 0, invoices.ids)], - 'multi': multi, }) return rec @@ -126,7 +135,7 @@ class account_abstract_payment(models.AbstractModel): """ Computes if the destination bank account must be displayed in the payment form view. By default, it won't be displayed but some modules might change that, depending on the payment type.""" for payment in self: - payment.show_partner_bank_account = payment.payment_method_code in self._get_method_codes_using_bank_account() and not self.multi + payment.show_partner_bank_account = payment.payment_method_code in self._get_method_codes_using_bank_account() @api.multi @api.depends('payment_type', 'journal_id') @@ -140,9 +149,9 @@ class account_abstract_payment(models.AbstractModel): or payment.journal_id.outbound_payment_method_ids payment.hide_payment_method = len(journal_payment_methods) == 1 and journal_payment_methods[0].code == 'manual' - @api.depends('invoice_ids', 'amount', 'payment_date', 'currency_id') + @api.depends('invoice_ids', 'amount', 'payment_date', 'currency_id', 'payment_type') def _compute_payment_difference(self): - for pay in self.filtered(lambda p: p.invoice_ids): + for pay in self.filtered(lambda p: p.invoice_ids and p.state == 'draft'): payment_amount = -pay.amount if pay.payment_type == 'outbound' else pay.amount pay.payment_difference = pay._compute_payment_amount() - payment_amount @@ -162,12 +171,20 @@ class account_abstract_payment(models.AbstractModel): # Set payment method domain (restrict to methods enabled for the journal and to selected payment type) payment_type = self.payment_type in ('outbound', 'transfer') and 'outbound' or 'inbound' - return {'domain': {'payment_method_id': [('payment_type', '=', payment_type), ('id', 'in', payment_methods_list)]}} + + domain = {'payment_method_id': [('payment_type', '=', payment_type), ('id', 'in', payment_methods_list)]} + + if self.env.context.get('active_model') == 'account.invoice': + active_ids = self._context.get('active_ids') + invoices = self.env['account.invoice'].browse(active_ids) + self.amount = abs(self._compute_payment_amount(invoices)) + + return {'domain': domain} return {} @api.onchange('partner_id') def _onchange_partner_id(self): - if not self.multi and self.invoice_ids and self.invoice_ids[0].partner_bank_id: + if self.invoice_ids and self.invoice_ids[0].partner_bank_id: self.partner_bank_account_id = self.invoice_ids[0].partner_bank_id elif self.partner_id != self.partner_bank_account_id.partner_id: # This condition ensures we use the default value provided into @@ -182,9 +199,38 @@ class account_abstract_payment(models.AbstractModel): self.partner_bank_account_id = False return {'domain': {'partner_bank_account_id': [('partner_id', 'in', [self.partner_id.id, self.partner_id.commercial_partner_id.id])]}} + @api.onchange('partner_type') + def _onchange_partner_type(self): + self.ensure_one() + # Set partner_id domain + if self.partner_type: + return {'domain': {'partner_id': [(self.partner_type, '=', True)]}} + + @api.onchange('payment_type') + def _onchange_payment_type(self): + if not self.invoice_ids: + # Set default partner type for the payment type + if self.payment_type == 'inbound': + self.partner_type = 'customer' + elif self.payment_type == 'outbound': + self.partner_type = 'supplier' + else: + self.partner_type = False + # Set payment method domain + res = self._onchange_journal() + if not res.get('domain', {}): + res['domain'] = {} + jrnl_filters = self._compute_journal_domain_and_types() + journal_types = jrnl_filters['journal_types'] + journal_types.update(['bank', 'cash']) + res['domain']['journal_id'] = jrnl_filters['domain'] + [('type', 'in', list(journal_types))] + return res + def _compute_journal_domain_and_types(self): journal_type = ['bank', 'cash'] domain = [] + if self.invoice_ids: + domain.append(('company_id', '=', self.invoice_ids[0].company_id.id)) if self.currency_id.is_zero(self.amount) and self.has_invoices: # In case of payment with 0 amount, allow to select a journal of type 'general' like # 'Miscellaneous Operations' and set this journal by default. @@ -202,7 +248,9 @@ class account_abstract_payment(models.AbstractModel): jrnl_filters = self._compute_journal_domain_and_types() journal_types = jrnl_filters['journal_types'] domain_on_types = [('type', 'in', list(journal_types))] - if self.journal_id.type not in journal_types: + if self.invoice_ids: + domain_on_types.append(('company_id', '=', self.invoice_ids[0].company_id.id)) + if self.journal_id.type not in journal_types or (self.invoice_ids and self.journal_id.company_id != self.invoice_ids[0].company_id): self.journal_id = self.env['account.journal'].search(domain_on_types, limit=1) return {'domain': {'journal_id': jrnl_filters['domain'] + domain_on_types}} @@ -210,11 +258,14 @@ class account_abstract_payment(models.AbstractModel): def _onchange_currency(self): self.amount = abs(self._compute_payment_amount()) - # Set by default the first liquidity journal having this currency if exists. - if self.journal_id: + if self.journal_id: # TODO: only return if currency differ? return - journal = self.env['account.journal'].search( - [('type', 'in', ('bank', 'cash')), ('currency_id', '=', self.currency_id.id)], limit=1) + + # Set by default the first liquidity journal having this currency if exists. + domain = [('type', 'in', ('bank', 'cash')), ('currency_id', '=', self.currency_id.id)] + if self.invoice_ids: + domain.append(('company_id', '=', self.invoice_ids[0].company_id.id)) + journal = self.env['account.journal'].search(domain, limit=1) if journal: return {'value': {'journal_id': journal.id}} @@ -233,7 +284,7 @@ class account_abstract_payment(models.AbstractModel): # Get the payment currency if not currency: - currency = self.currency_id or self.journal_id.currency_id or self.journal_id.company_id.currency_id or invoices and invoices[0].currency_id + currency = self.currency_id or self.journal_id.currency_id or self.journal_id.company_id.currency_id # Avoid currency rounding issues by summing the amounts according to the company_currency_id before invoice_datas = invoices.read_group( @@ -250,154 +301,6 @@ class account_abstract_payment(models.AbstractModel): total += payment_currency._convert(amount_total, currency, self.env.user.company_id, self.payment_date or fields.Date.today()) return total - -class account_register_payments(models.TransientModel): - _name = "account.register.payments" - _inherit = 'account.abstract.payment' - _description = "Register Payments" - - group_invoices = fields.Boolean(string="Group Invoices", help="""If enabled, groups invoices by commercial partner, invoice account, - type and recipient bank account in the generated payments. If disabled, - a distinct payment will be generated for each invoice.""") - show_communication_field = fields.Boolean(compute='_compute_show_communication_field') - - @api.depends('invoice_ids.partner_id', 'group_invoices') - def _compute_show_communication_field(self): - """ We allow choosing a common communication for payments if the group - option has been activated, and all the invoices relate to the same - partner. - """ - for record in self: - record.show_communication_field = len(record.invoice_ids) == 1 \ - or record.group_invoices and len(record.mapped('invoice_ids.partner_id.commercial_partner_id')) == 1 - - @api.onchange('journal_id') - def _onchange_journal(self): - res = super(account_register_payments, self)._onchange_journal() - active_ids = self._context.get('active_ids') - invoices = self.env['account.invoice'].browse(active_ids) - self.amount = abs(self._compute_payment_amount(invoices)) - return res - - @api.model - def default_get(self, fields): - rec = super(account_register_payments, self).default_get(fields) - active_ids = self._context.get('active_ids') - - if not active_ids: - raise UserError(_("Programming error: wizard action executed without active_ids in context.")) - - return rec - - @api.multi - def _groupby_invoices(self): - '''Groups the invoices linked to the wizard. - - If the group_invoices option is activated, invoices will be grouped - according to their commercial partner, their account, their type and - the account where the payment they expect should end up. Otherwise, - invoices will be grouped so that each of them belongs to a - distinct group. - - :return: a dictionary mapping, grouping invoices as a recordset under each of its keys. - ''' - if not self.group_invoices: - return {inv.id: inv for inv in self.invoice_ids} - - results = {} - # Create a dict dispatching invoices according to their commercial_partner_id, account_id, invoice_type and partner_bank_id - for inv in self.invoice_ids: - partner_id = inv.commercial_partner_id.id - account_id = inv.account_id.id - invoice_type = MAP_INVOICE_TYPE_PARTNER_TYPE[inv.type] - recipient_account = inv.partner_bank_id - key = (partner_id, account_id, invoice_type, recipient_account) - if not key in results: - results[key] = self.env['account.invoice'] - results[key] += inv - return results - - @api.multi - def _prepare_payment_vals(self, invoices): - '''Create the payment values. - - :param invoices: The invoices that should have the same commercial partner and the same type. - :return: The payment values as a dictionary. - ''' - amount = self._compute_payment_amount(invoices=invoices) if self.multi else self.amount - payment_type = ('inbound' if amount > 0 else 'outbound') if self.multi else self.payment_type - bank_account = self.multi and invoices[0].partner_bank_id or self.partner_bank_account_id - pmt_communication = self.show_communication_field and self.communication \ - or self.group_invoices and ' '.join([inv.reference or inv.number for inv in invoices]) \ - or invoices[0].reference # in this case, invoices contains only one element, since group_invoices is False - values = { - 'journal_id': self.journal_id.id, - 'payment_method_id': self.payment_method_id.id, - 'payment_date': self.payment_date, - 'communication': pmt_communication, - 'invoice_ids': [(6, 0, invoices.ids)], - 'payment_type': payment_type, - 'amount': abs(amount), - 'currency_id': self.currency_id.id, - 'partner_id': invoices[0].commercial_partner_id.id, - 'partner_type': MAP_INVOICE_TYPE_PARTNER_TYPE[invoices[0].type], - 'partner_bank_account_id': bank_account.id, - 'multi': False, - 'payment_difference_handling': self.payment_difference_handling, - 'writeoff_account_id': self.writeoff_account_id.id, - 'writeoff_label': self.writeoff_label, - } - - return values - - @api.multi - def get_payments_vals(self): - '''Compute the values for payments. - - :return: a list of payment values (dictionary). - ''' - if self.multi: - groups = self._groupby_invoices() - return [self._prepare_payment_vals(invoices) for invoices in groups.values()] - return [self._prepare_payment_vals(self.invoice_ids)] - - @api.multi - def create_payments(self): - '''Create payments according to the invoices. - Having invoices with different commercial_partner_id or different type (Vendor bills with customer invoices) - leads to multiple payments. - In case of all the invoices are related to the same commercial_partner_id and have the same type, - only one payment will be created. - - :return: The ir.actions.act_window to show created payments. - ''' - Payment = self.env['account.payment'] - payments = Payment - for payment_vals in self.get_payments_vals(): - payments += Payment.create(payment_vals) - payments.post() - - action_vals = { - 'name': _('Payments'), - 'domain': [('id', 'in', payments.ids), ('state', '=', 'posted')], - 'view_type': 'form', - 'res_model': 'account.payment', - 'view_id': False, - 'type': 'ir.actions.act_window', - } - if len(payments) == 1: - action_vals.update({'res_id': payments[0].id, 'view_mode': 'form'}) - else: - action_vals['view_mode'] = 'tree,form' - return action_vals - - -class account_payment(models.Model): - _name = "account.payment" - _inherit = ['mail.thread', 'mail.activity.mixin', 'account.abstract.payment'] - _description = "Payments" - _order = "payment_date desc, name desc" - @api.multi def name_get(self): return [(payment.id, payment.name or _('Draft Payment')) for payment in self] @@ -410,40 +313,16 @@ class account_payment(models.Model): for aml in payment.move_line_ids.filtered(lambda x: x.account_id.reconcile): if not aml.reconciled: rec = False + break payment.move_reconciled = rec - company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', readonly=True) - name = fields.Char(readonly=True, copy=False) # The name is attributed upon post() - state = fields.Selection([('draft', 'Draft'), ('posted', 'Posted'), ('sent', 'Sent'), ('reconciled', 'Reconciled'), ('cancelled', 'Cancelled')], readonly=True, default='draft', copy=False, string="Status") - - payment_type = fields.Selection(selection_add=[('transfer', 'Internal Transfer')]) - payment_reference = fields.Char(copy=False, readonly=True, help="Reference of the document used to issue this payment. Eg. check number, file name, etc.") - move_name = fields.Char(string='Journal Entry Name', readonly=True, - default=False, copy=False, - help="Technical field holding the number given to the journal entry, automatically set when the statement line is reconciled then stored to set the same number again if the line is cancelled, set to draft and re-processed again.") - - # Money flows from the journal_id's default_debit_account_id or default_credit_account_id to the destination_account_id - destination_account_id = fields.Many2one('account.account', compute='_compute_destination_account_id', readonly=True) - # For money transfer, money goes from journal_id to a transfer account, then from the transfer account to destination_journal_id - destination_journal_id = fields.Many2one('account.journal', string='Transfer To', domain=[('type', 'in', ('bank', 'cash'))]) - - invoice_ids = fields.Many2many('account.invoice', 'account_invoice_payment_rel', 'payment_id', 'invoice_id', string="Invoices", copy=False, readonly=True, help="""Technical field containing the invoices for which the payment has been generated. - This does not especially correspond to the invoices reconciled with the payment, - as it can have been generated first, and reconciled later""") - reconciled_invoice_ids = fields.Many2many('account.invoice', string='Reconciled Invoices', compute='_compute_reconciled_invoice_ids', help="Invoices whose journal items have been reconciled with this payment's.") - has_invoices = fields.Boolean(compute="_compute_reconciled_invoice_ids", help="Technical field used for usability purposes") - - # FIXME: ondelete='restrict' not working (eg. cancel a bank statement reconciliation with a payment) - move_line_ids = fields.One2many('account.move.line', 'payment_id', readonly=True, copy=False, ondelete='restrict') - move_reconciled = fields.Boolean(compute="_get_move_reconciled", readonly=True) - def open_payment_matching_screen(self): # Open reconciliation view for customers/suppliers move_line_id = False for move_line in self.move_line_ids: if move_line.account_id.reconcile: move_line_id = move_line.id - break; + break if not self.partner_id: raise UserError(_("Payments without a customer can't be matched")) action_context = {'company_ids': [self.company_id.id], 'partner_ids': [self.partner_id.commercial_partner_id.id]} @@ -484,9 +363,10 @@ class account_payment(models.Model): def _compute_reconciled_invoice_ids(self): for record in self: record.reconciled_invoice_ids = (record.move_line_ids.mapped('matched_debit_ids.debit_move_id.invoice_id') | - record.move_line_ids.mapped('matched_credit_ids.credit_move_id.invoice_id')) + record.move_line_ids.mapped('matched_credit_ids.credit_move_id.invoice_id')) record.has_invoices = bool(record.reconciled_invoice_ids) +<<<<<<< HEAD @api.onchange('partner_type') def _onchange_partner_type(self): self.ensure_one() @@ -527,18 +407,24 @@ class account_payment(models.Model): rec['partner_id'] = invoice['partner_id'][0] rec['amount'] = invoice['residual'] return rec +======= + @api.multi + def action_register_payment(self): + active_ids = self.env.context.get('active_ids') + if not active_ids: + return '' +>>>>>>> [REF] account: simplification of payments objects - @api.model - def create(self, vals): - rslt = super(account_payment, self).create(vals) - # When a payment is created by the multi payments wizard in 'multi' mode, - # its partner_bank_account_id will never be displayed, and hence stay empty, - # even if the payment method requires it. This condition ensures we set - # the first (and thus most prioritary) account of the partner in this field - # in that situation. - if not rslt.partner_bank_account_id and rslt.show_partner_bank_account and rslt.partner_id.bank_ids: - rslt.partner_bank_account_id = rslt.partner_id.bank_ids[0] - return rslt + return { + 'name': _('Register Payment'), + 'res_model': len(active_ids) == 1 and 'account.payment' or 'account.payment.register', + 'view_type': 'form', + 'view_mode': 'form', + 'view_id': len(active_ids) != 1 and self.env.ref('account.view_account_payment_form_multi').id or self.env.ref('account.view_account_payment_invoice_form').id, + 'context': {**self.env.context, **{'active_model': 'account.invoice', 'active_ids': active_ids}}, + 'target': 'new', + 'type': 'ir.actions.act_window', + } @api.multi def button_journal_entries(self): @@ -569,10 +455,6 @@ class account_payment(models.Model): 'domain': [('id', 'in', [x.id for x in self.reconciled_invoice_ids])], } - @api.multi - def button_dummy(self): - return True - @api.multi def unreconcile(self): """ Set back the payments in 'posted' or 'sent' state, without deleting the journal entries. @@ -588,7 +470,7 @@ class account_payment(models.Model): def cancel(self): for rec in self: for move in rec.move_line_ids.mapped('move_id'): - if rec.invoice_ids: + if rec.reconciled_invoice_ids: move.line_ids.remove_move_reconcile() move.button_cancel() move.unlink() @@ -656,17 +538,6 @@ class account_payment(models.Model): def action_draft(self): return self.write({'state': 'draft'}) - def action_validate_invoice_payment(self): - """ Posts a payment used to pay an invoice. This function only posts the - payment by default but can be overridden to apply specific post or pre-processing. - It is called by the "validate" button of the popup window - triggered on invoice form by the "Register Payment" button. - """ - if any(len(record.invoice_ids) != 1 for record in self): - # For multiple invoices, there is account.register.payments wizard - raise UserError(_("This method should only be called to process a single invoice's payment.")) - return self.post() - def _create_payment_entry(self, amount): """ Create a journal entry corresponding to a payment, if the payment references invoice(s) they are reconciled. Return the journal entry. @@ -810,7 +681,7 @@ class account_payment(models.Model): name = _('Transfer to %s') % self.destination_journal_id.name vals = { 'name': name, - 'account_id': self.payment_type in ('outbound','transfer') and self.journal_id.default_debit_account_id.id or self.journal_id.default_credit_account_id.id, + 'account_id': self.payment_type in ('outbound', 'transfer') and self.journal_id.default_debit_account_id.id or self.journal_id.default_credit_account_id.id, 'journal_id': self.journal_id.id, 'currency_id': self.currency_id != self.company_id.currency_id and self.currency_id.id or False, } @@ -825,3 +696,113 @@ class account_payment(models.Model): }) return vals + + +class payment_register(models.TransientModel): + _name = 'account.payment.register' + _description = 'Register Payment' + + payment_date = fields.Date(required=True, default=fields.Date.context_today) + journal_id = fields.Many2one('account.journal', required=True, domain=[('type', 'in', ('bank', 'cash'))]) + payment_method_id = fields.Many2one('account.payment.method', string='Payment Method Type', required=True, + help="Manual: Get paid by cash, check or any other method outside of Odoo.\n" + "Electronic: Get paid automatically through a payment acquirer by requesting a transaction on a card saved by the customer when buying or subscribing online (payment token).\n" + "Check: Pay bill by check and print it from Odoo.\n" + "Batch Deposit: Encase several customer checks at once by generating a batch deposit to submit to your bank. When encoding the bank statement in Odoo, you are suggested to reconcile the transaction with the batch deposit.To enable batch deposit, module account_batch_payment must be installed.\n" + "SEPA Credit Transfer: Pay bill from a SEPA Credit Transfer file you submit to your bank. To enable sepa credit transfer, module account_sepa must be installed ") + invoice_ids = fields.Many2many('account.invoice', 'account_invoice_payment_rel_transient', 'payment_id', 'invoice_id', string="Invoices", copy=False, readonly=True) + + @api.model + def default_get(self, fields): + rec = super(payment_register, self).default_get(fields) + active_ids = self._context.get('active_ids') + active_model = self._context.get('active_model') + invoices = self.env['account.invoice'].browse(active_ids) + + # Check all invoices are open + if any(invoice.state != 'open' for invoice in invoices): + raise UserError(_("You can only register payments for open invoices")) + if 'invoice_ids' not in rec: + rec['invoice_ids'] = [(6, 0, invoices.ids)] + if 'journal_id' not in rec: + rec['journal_id'] = self.env['account.journal'].search([('company_id', '=', self.env.user.company_id.id), ('type', 'in', ('bank', 'cash'))], limit=1).id + if 'payment_method_id' not in rec: + if invoices[0].type in ('out_invoice', 'in_refund'): + domain = [('payment_type', '=', 'inbound')] + else: + domain = [('payment_type', '=', 'outbound')] + rec['payment_method_id'] = self.env['account.payment.method'].search(domain, limit=1).id + return rec + + @api.model + def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): + res = super(payment_register, self).fields_view_get(view_id, view_type, toolbar, submenu) + if 'active_domain' not in self.env.context: + return res + + type = [dom[2] for dom in self.env.context['active_domain'] if dom[0] == 'type'][0] + if type in ('out_invoice', 'in_refund'): + res['fields']['payment_method_id']['domain'] = [('payment_type', '=', 'inbound')] + else: + res['fields']['payment_method_id']['domain'] = [('payment_type', '=', 'outbound')] + return res + + @api.multi + def _prepare_payment_vals(self, invoice): + '''Create the payment values. + + :param invoice: A single invoice/bill to pay. + :return: The payment values as a dictionary. + ''' + amount = self.env['account.payment']._compute_payment_amount(invoices=invoice, currency=invoice.currency_id) + values = { + 'journal_id': self.journal_id.id, + 'payment_method_id': self.payment_method_id.id, + 'payment_date': self.payment_date, + 'communication': invoice.reference or invoice.number, + 'invoice_ids': [(6, 0, invoice.ids)], + 'payment_type': ('inbound' if amount > 0 else 'outbound'), + 'amount': abs(amount), + 'currency_id': invoice.currency_id.id, + 'partner_id': invoice.commercial_partner_id.id, + 'partner_type': MAP_INVOICE_TYPE_PARTNER_TYPE[invoice.type], + 'partner_bank_account_id': invoice.partner_bank_id.id, + } + return values + + @api.multi + def get_payments_vals(self): + '''Compute the values for payments. + + :return: a list of payment values (dictionary). + ''' + return [self._prepare_payment_vals(invoice) for invoice in self.invoice_ids] + + @api.multi + def create_payments(self): + '''Create payments according to the invoices. + Having invoices with different commercial_partner_id or different type + (Vendor bills with customer invoices) leads to multiple payments. + In case of all the invoices are related to the same + commercial_partner_id and have the same type, only one payment will be + created. + + :return: The ir.actions.act_window to show created payments. + ''' + Payment = self.env['account.payment'] + payments = Payment.create(self.get_payments_vals()) + payments.post() + + action_vals = { + 'name': _('Payments'), + 'domain': [('id', 'in', payments.ids), ('state', '=', 'posted')], + 'view_type': 'form', + 'res_model': 'account.payment', + 'view_id': False, + 'type': 'ir.actions.act_window', + } + if len(payments) == 1: + action_vals.update({'res_id': payments[0].id, 'view_mode': 'form'}) + else: + action_vals['view_mode'] = 'tree,form' + return action_vals diff --git a/addons/account/static/src/js/reconciliation/reconciliation_action.js b/addons/account/static/src/js/reconciliation/reconciliation_action.js index 6c4fb9c912a..67d5de9de08 100644 --- a/addons/account/static/src/js/reconciliation/reconciliation_action.js +++ b/addons/account/static/src/js/reconciliation/reconciliation_action.js @@ -259,7 +259,7 @@ var StatementAction = AbstractAction.extend({ } }); }, - + /** * @private * @param {OdooEvent} ev @@ -308,7 +308,7 @@ var StatementAction = AbstractAction.extend({ return this.model.closeStatement().then(function (result) { self.do_action({ name: 'Bank Statements', - res_model: 'account.bank.statement', + res_model: 'account.bank.statement.line', res_id: result, views: [[false, 'form']], type: 'ir.actions.act_window', diff --git a/addons/account/static/src/xml/account_reconciliation.xml b/addons/account/static/src/xml/account_reconciliation.xml index d76ef05e917..2555b348990 100644 --- a/addons/account/static/src/xml/account_reconciliation.xml +++ b/addons/account/static/src/xml/account_reconciliation.xml @@ -67,7 +67,7 @@ - +

@@ -236,7 +236,7 @@ - +