[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
This commit is contained in:
wan
2019-04-04 10:42:41 +00:00
parent 2190568d9e
commit 3c2e3b8c5a
13 changed files with 393 additions and 608 deletions
+4
View File
@@ -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()
+236 -255
View File
@@ -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
@@ -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',
@@ -67,7 +67,7 @@
<t t-if="context.journal_id">
<button class="button_back_to_statement btn btn-secondary" t-att-data_journal_id='context.journal_id'>Go to bank statement(s)</button>
</t>
<t t-if="context['active_model'] === 'account.bank.statement'">
<t t-if="context['active_model'] === 'account.bank.statement.line'">
<button class="button_close_statement btn btn-primary" style="display: inline-block;">Close statement</button>
</t>
</p>
@@ -236,7 +236,7 @@
<t t-name="reconciliation.line.mv_line.amount">
<span t-att-class="(line.is_move_line &amp;&amp; proposition == true) ? 'cell' : ''">
<span class="line_amount">
<span t-if="line.amount_currency_str"
t-attf-class="o_multi_currency o_multi_currency_color_#{line.currency_id%8} line_info_button fa fa-money"
+32 -157
View File
@@ -1,5 +1,6 @@
from odoo.addons.account.tests.account_test_classes import AccountingTestCase
from odoo.tests import tagged
from odoo.tests.common import Form
import time
@@ -8,7 +9,7 @@ class TestPayment(AccountingTestCase):
def setUp(self):
super(TestPayment, self).setUp()
self.register_payments_model = self.env['account.register.payments'].with_context(active_model='account.invoice')
self.register_payments_model = self.env['account.payment.register'].with_context(active_model='account.invoice')
self.payment_model = self.env['account.payment']
self.invoice_model = self.env['account.invoice']
self.invoice_line_model = self.env['account.invoice.line']
@@ -41,6 +42,8 @@ class TestPayment(AccountingTestCase):
self.diff_income_account = self.env['res.users'].browse(self.env.uid).company_id.income_currency_exchange_account_id
self.diff_expense_account = self.env['res.users'].browse(self.env.uid).company_id.expense_currency_exchange_account_id
self.form_payment = Form(self.env['account.payment'])
def create_invoice(self, amount=100, type='out_invoice', currency_id=None, partner=None, account_id=None):
""" Returns an open invoice """
invoice = self.invoice_model.create({
@@ -82,12 +85,11 @@ class TestPayment(AccountingTestCase):
return bank_stmt
def test_full_payment_process(self):
""" Create a payment for two invoices, post it and reconcile it with a bank statement """
inv_1 = self.create_invoice(amount=100, currency_id=self.currency_eur_id, partner=self.partner_agrolait.id)
inv_2 = self.create_invoice(amount=200, currency_id=self.currency_eur_id, partner=self.partner_agrolait.id)
""" Create a payment for one invoice, post it and reconcile it with a bank statement """
inv_1 = self.create_invoice(amount=300, currency_id=self.currency_eur_id, partner=self.partner_agrolait.id)
ctx = {'active_model': 'account.invoice', 'active_ids': [inv_1.id, inv_2.id]}
register_payments = self.register_payments_model.with_context(ctx).create({
ids = [inv_1.id]
register_payments = self.register_payments_model.with_context(active_ids=ids).create({
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal_euro.id,
'payment_method_id': self.payment_method_manual_in.id,
@@ -99,7 +101,6 @@ class TestPayment(AccountingTestCase):
self.assertEqual(payment.state, 'posted')
self.assertEqual(payment.state, 'posted')
self.assertEqual(inv_1.state, 'paid')
self.assertEqual(inv_2.state, 'paid')
self.assertRecordValues(payment.move_line_ids, [
{'account_id': self.account_eur.id, 'debit': 300.0, 'credit': 0.0, 'amount_currency': 0, 'currency_id': False},
@@ -108,7 +109,7 @@ class TestPayment(AccountingTestCase):
self.assertTrue(payment.move_line_ids.filtered(lambda l: l.account_id == inv_1.account_id)[0].full_reconcile_id)
liquidity_aml = payment.move_line_ids.filtered(lambda r: r.account_id == self.account_eur)
bank_statement = self.reconcile(liquidity_aml, 200, 0, False)
bank_statement = self.reconcile(liquidity_aml, 300, 0, False)
self.assertEqual(liquidity_aml.statement_id, bank_statement)
self.assertEqual(liquidity_aml.statement_line_id, bank_statement.line_ids[0])
@@ -168,15 +169,14 @@ class TestPayment(AccountingTestCase):
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal_euro.id,
'payment_method_id': self.payment_method_manual_in.id,
'group_invoices': True,
})
register_payments.create_payments()
payment_ids = self.payment_model.search([('invoice_ids', 'in', ids)], order="id desc")
self.assertEqual(len(payment_ids), 3)
self.assertAlmostEquals(register_payments.amount, 750)
self.assertEqual(len(payment_ids), 4)
self.assertAlmostEquals(sum(payment_ids.filtered(lambda r: r.payment_type == 'inbound').mapped('amount')) - sum(payment_ids.filtered(lambda r: r.payment_type == 'outbound').mapped('amount')), 750)
inv_1_2_pay = None
inv_1_2_pay = self.env['account.payment']
inv_3_pay = None
inv_4_pay = None
for payment_id in payment_ids:
@@ -186,29 +186,24 @@ class TestPayment(AccountingTestCase):
self.assertEqual(payment_id.amount, 50)
inv_4_pay = payment_id
else:
self.assertEqual(payment_id.amount, 600)
inv_1_2_pay = payment_id
self.assertTrue(payment_id.amount in (100, 500))
inv_1_2_pay |= payment_id
else:
self.assertEqual(payment_id.amount, 200)
inv_3_pay = payment_id
self.assertIsNotNone(inv_1_2_pay)
self.assertIsNotNone(inv_3_pay)
self.assertIsNotNone(inv_4_pay)
self.assertRecordValues(inv_1_2_pay.move_line_ids, [
{'account_id': self.account_eur.id, 'debit': 600.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': False},
{'account_id': inv_1.account_id.id, 'debit': 0.0, 'credit': 600.0, 'amount_currency': 0.0, 'currency_id': False},
])
self.assertTrue(len(inv_1_2_pay) == 2)
self.assertEqual(inv_1.state, 'paid')
self.assertEqual(inv_2.state, 'paid')
self.assertIsNotNone(inv_3_pay)
self.assertRecordValues(inv_3_pay.move_line_ids, [
{'account_id': self.account_eur.id, 'debit': 200.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': False},
{'account_id': inv_1.account_id.id, 'debit': 0.0, 'credit': 200.0, 'amount_currency': 0.0, 'currency_id': False},
])
self.assertEqual(inv_3.state, 'paid')
self.assertIsNotNone(inv_4_pay)
self.assertRecordValues(inv_4_pay.move_line_ids, [
{'account_id': self.account_eur.id, 'debit': 0.0, 'credit': 50.0, 'amount_currency': 0.0, 'currency_id': False},
{'account_id': inv_1.account_id.id, 'debit': 50.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': False},
@@ -220,16 +215,15 @@ class TestPayment(AccountingTestCase):
# Test Customer Invoice
inv_1 = self.create_invoice(amount=600)
ids = [inv_1.id]
register_payments = self.register_payments_model.with_context(active_ids=ids).create({
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal_euro.id,
'payment_method_id': self.payment_method_manual_in.id,
})
payment_register = Form(self.env['account.payment'].with_context(active_model='account.invoice', active_ids=ids))
with payment_register as pr:
pr.payment_date = time.strftime('%Y') + '-07-15'
pr.journal_id = self.bank_journal_euro
pr.payment_method_id = self.payment_method_manual_in
# Perform the partial payment by setting the amount at 550 instead of 600
register_payments.amount = 550
# Perform the partial payment by setting the amount at 550 instead of 600
pr.amount = 550
register_payments.create_payments()
payment_ids = self.payment_model.search([('invoice_ids', 'in', ids)], order="id desc")
self.assertEqual(len(payment_ids), 1)
@@ -245,16 +239,16 @@ class TestPayment(AccountingTestCase):
# Test Vendor Bill
inv_2 = self.create_invoice(amount=500, type='in_invoice', partner=self.partner_china_exp.id)
ids = [inv_2.id]
register_payments = self.register_payments_model.with_context(active_ids=ids).create({
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal_euro.id,
'payment_method_id': self.payment_method_manual_in.id,
})
payment_register = Form(self.env['account.payment'].with_context(active_model='account.invoice', active_ids=ids))
with payment_register as pr:
pr.payment_date = time.strftime('%Y') + '-07-15'
pr.journal_id = self.bank_journal_euro
pr.payment_method_id = self.payment_method_manual_in
# Perform the partial payment by setting the amount at 300 instead of 500
register_payments.amount = 300
# Perform the partial payment by setting the amount at 300 instead of 500
pr.amount = 300
register_payments.create_payments()
payment_register.save()
payment_ids = self.payment_model.search([('invoice_ids', 'in', ids)], order="id desc")
self.assertEqual(len(payment_ids), 1)
@@ -267,91 +261,6 @@ class TestPayment(AccountingTestCase):
self.assertEqual(payment_id.partner_id, self.partner_china_exp)
self.assertEqual(payment_id.partner_type, 'supplier')
def test_multiple_receivables(self):
""" Create test to pay several invoices with same partner but multiple receivable accounts """
# One payment for inv_1, inv_2 (same receivable account) and inv_3 (another receivable account)
account_receivable_id_1 = self.account_receivable.id
account_receivable_id_2 = self.account_receivable.copy(default={
'code': '%s (%s)' % (self.account_receivable.code, 'duplicate 1')
}).id
inv_1 = self.create_invoice(amount=100, account_id=account_receivable_id_1)
inv_2 = self.create_invoice(amount=150, account_id=account_receivable_id_1)
inv_3 = self.create_invoice(amount=300, account_id=account_receivable_id_2)
ids = [inv_1.id, inv_2.id, inv_3.id]
register_payments = self.register_payments_model.with_context(active_ids=ids).create({
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal_euro.id,
'payment_method_id': self.payment_method_manual_in.id,
'group_invoices': True,
})
register_payments.create_payments()
payment_ids = self.payment_model.search([('invoice_ids', 'in', ids)], order="id desc")
self.assertEqual(len(payment_ids), 2)
self.assertAlmostEquals(register_payments.amount, 550)
inv_1_pay = payment_ids.filtered(lambda p: p.state == 'posted' and p.invoice_ids and p.invoice_ids == inv_1 + inv_2)
inv_2_pay = payment_ids.filtered(lambda p: p.state == 'posted' and p.invoice_ids and p.invoice_ids == inv_3)
self.assertTrue(inv_1_pay)
self.assertTrue(inv_2_pay)
self.assertRecordValues(inv_1_pay.move_line_ids, [
{'account_id': self.account_eur.id, 'debit': 250.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': False},
{'account_id': inv_1.account_id.id, 'debit': 0.0, 'credit': 250.0, 'amount_currency': 0.0, 'currency_id': False},
])
self.assertRecordValues(inv_2_pay.move_line_ids, [
{'account_id': self.account_eur.id, 'debit': 300.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': False},
{'account_id': inv_3.account_id.id, 'debit': 0.0, 'credit': 300.0, 'amount_currency': 0.0, 'currency_id': False},
])
def test_register_payment_group_invoices(self):
""" Tests the 'group invoices' option of the payment registering wizard
"""
account_receivable_id_1 = self.account_receivable.id
account_receivable_id_2 = self.account_receivable.copy(default={
'code': '%s (%s)' % (self.account_receivable.code, 'duplicate 1')
}).id
inv_1 = self.create_invoice(amount=100, account_id=account_receivable_id_1)
inv_2 = self.create_invoice(amount=150, account_id=account_receivable_id_1)
inv_3 = self.create_invoice(amount=300, account_id=account_receivable_id_2)
inv_4 = self.create_invoice(amount=300, account_id=account_receivable_id_2, partner=self.partner_china_exp.id)
inv_5 = self.create_invoice(amount=42, account_id=account_receivable_id_1)
inv_6 = self.create_invoice(amount=1111, account_id=account_receivable_id_1)
inv_7 = self.create_invoice(amount=666, account_id=account_receivable_id_2)
inv_8 = self.create_invoice(amount=300, account_id=account_receivable_id_2, partner=self.partner_china_exp.id)
# When grouping invoices, we should have one payment per receivable account
ids1 = [inv_1.id, inv_2.id, inv_3.id, inv_4.id]
register_payments1 = self.register_payments_model.with_context(active_ids=ids1).create({
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal_euro.id,
'payment_method_id': self.payment_method_manual_in.id,
'group_invoices': True,
})
register_payments1.create_payments()
payment_ids1 = self.payment_model.search([('invoice_ids', 'in', ids1)], order="id desc")
self.assertEqual(len(payment_ids1), 3, "3 payments should have been created, one fo each (partner, receivable account).")
# When not grouping, we should have one payment per invoice
ids2 = [inv_5.id, inv_6.id, inv_7.id, inv_8.id]
register_payments2 = self.register_payments_model.with_context(active_ids=ids2).create({
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal_euro.id,
'payment_method_id': self.payment_method_manual_in.id,
'group_invoices': False,
})
register_payments2.create_payments()
payment_ids2 = self.payment_model.search([('invoice_ids', 'in', ids2)], order="id desc")
self.assertEqual(len(payment_ids2), 4, "Not grouping payments should always create a distinct payment per invoice.")
def test_payment_and_writeoff_in_other_currency_1(self):
# Use case:
# Company is in EUR, create a customer invoice for 25 EUR and register payment of 25 USD.
@@ -595,37 +504,3 @@ class TestPayment(AccountingTestCase):
# The invoice should now be paid
self.assertEqual(invoice.state, 'paid', "Invoice should be in 'paid' state after having reconciled the two payments with a bank statement")
def test_register_payments_multi_invoices(self):
inv1 = self.create_invoice(amount=40)
inv2 = inv1.copy()
inv2.action_invoice_open()
batch_payment = self.env['account.register.payments'].with_context(active_ids=(inv1 + inv2).ids).create({
'amount': 70,
'partner_id': inv1.partner_id.id,
'journal_id': self.bank_journal_usd.id,
'invoice_ids': [(6, False, (inv1 + inv2).ids)],
'partner_type': 'customer',
'payment_difference_handling': 'reconcile',
'payment_type': 'inbound',
'payment_method_id': self.payment_method_manual_in.id,
'writeoff_account_id': self.account_revenue.id,
'writeoff_label': "why can't we live together"})
payment_id = batch_payment.create_payments()['res_id']
payment_id = self.env['account.payment'].browse(payment_id)
self.assertEqual(inv1.state, 'paid')
self.assertEqual(inv2.state, 'paid')
receivable_inv1 = inv1.move_id.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable')
receivable_inv2 = inv2.move_id.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable')
receivable_payment = payment_id.move_line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable')
self.assertEqual(
receivable_inv1.full_reconcile_id.reconciled_line_ids,
receivable_inv1 + receivable_inv2 + receivable_payment
)
write_off_line = payment_id.move_line_ids.filtered(lambda l: l.account_id == payment_id.writeoff_account_id)
self.assertEqual(write_off_line.debit, 10)
@@ -267,7 +267,7 @@
<form string="Vendor Bill">
<header>
<button name="action_invoice_open" type="object" states="draft" string="Validate" class="oe_highlight" groups="account.group_account_invoice"/>
<button name="%(action_account_invoice_payment)d" type="action" states="open" string="Register Payment" groups="account.group_account_invoice" class="oe_highlight"/>
<button name="action_register_payment" type="object" states="open" string="Register Payment" groups="account.group_account_invoice" class="oe_highlight"/>
<button name="%(action_account_invoice_refund)d" type='action' string='Ask for a Credit Note' groups="account.group_account_invoice" attrs="{'invisible': ['|',('type', 'in', ['in_refund','out_refund']),('state','not in',('open','in_payment','paid'))]}"/>
<button name="action_invoice_draft" states="cancel" string="Set to Draft" type="object" groups="account.group_account_invoice"/>
<field name="state" widget="statusbar" statusbar_visible="draft,open,paid" />
@@ -420,7 +420,7 @@
<header>
<button name="action_invoice_sent" string="Send &amp; Print" type="object" attrs="{'invisible':['|',('sent','=',True), ('state', 'not in', ('open','in_payment','paid'))]}" class="oe_highlight" groups="base.group_user"/>
<button name="action_invoice_sent" string="Send &amp; Print" type="object" attrs="{'invisible':['|',('sent','=',False), ('state', 'not in', ('open','in_payment','paid'))]}" groups="base.group_user"/>
<button name="%(action_account_invoice_payment)d" id="account_invoice_payment_btn" type="action"
<button name="action_register_payment" id="account_invoice_payment_btn" type="object"
attrs="{'invisible': [('state', '!=', 'open')]}"
string="Register Payment" groups="account.group_account_invoice" class="oe_highlight"/>
<button name="action_invoice_open" type="object" states="draft" string="Validate" class="oe_highlight o_invoice_validate" groups="account.group_account_invoice"/>
+66 -107
View File
@@ -24,19 +24,12 @@
<record id="view_account_supplier_payment_tree" model="ir.ui.view">
<field name="name">account.supplier.payment.tree</field>
<field name="model">account.payment</field>
<field name="inherit_id" ref="account.view_account_payment_tree"/>
<field name="mode">primary</field>
<field name="arch" type="xml">
<tree decoration-info="state == 'draft'" decoration-muted="state in ['reconciled', 'cancelled']" edit="false">
<field name="payment_date"/>
<field name="name"/>
<field name="journal_id"/>
<field name="payment_method_id"/>
<field name="partner_id" string="Vendor"/>
<field name="amount" sum="Amount"/>
<field name="company_id" groups="base.group_multi_company"/>
<field name="state"/>
<field name="currency_id" invisible="1"/>
<field name="partner_type" invisible="1"/>
</tree>
<field name="partner_id" position="attributes">
<attribute name="string">Vendor</attribute>
</field>
</field>
</record>
@@ -150,34 +143,72 @@
<h1><field name="name"/></h1>
</div>
<group>
<field name="invoice_ids" invisible="1"/>
<group name="partner_group">
<field name="payment_type" widget="radio"/>
<field name="partner_type" widget="selection" attrs="{'required': [('state', '=', 'draft'), ('payment_type', 'in', ('inbound', 'outbound'))], 'invisible': [('payment_type', 'not in', ('inbound', 'outbound'))]}"/>
<field name="partner_id" attrs="{'required': [('state', '=', 'draft'), ('payment_type', 'in', ('inbound', 'outbound'))], 'invisible': [('payment_type', 'not in', ('inbound', 'outbound'))]}" context="{'default_is_company': True, 'default_supplier': payment_type == 'outbound', 'default_customer': payment_type == 'inbound'}"/>
</group>
<group name="right_column">
<field name="payment_date"/>
<field name="communication"/>
</group>
<group>
<field name="payment_type" widget="radio" attrs="{'readonly': [('state', '!=', 'draft')]}"/>
<field name="partner_type" widget="selection" attrs="{'required': [('state', '=', 'draft'), ('payment_type', 'in', ('inbound', 'outbound'))], 'invisible': [('payment_type', 'not in', ('inbound', 'outbound'))], 'readonly': [('state', '!=', 'draft')]}"/>
<field name="partner_id" attrs="{'required': [('state', '=', 'draft'), ('payment_type', 'in', ('inbound', 'outbound'))], 'invisible': [('payment_type', 'not in', ('inbound', 'outbound'))], 'readonly': [('state', '!=', 'draft')]}" context="{'default_is_company': True, 'default_supplier': payment_type == 'outbound', 'default_customer': payment_type == 'inbound'}"/>
<label for="amount"/>
<div name="amount_div" class="o_row">
<field name="amount" attrs="{'readonly': [('state', '!=', 'draft')]}"/>
<field name="currency_id" options="{'no_create': True, 'no_open': True}" groups="base.group_multi_currency" attrs="{'readonly': [('state', '!=', 'draft')]}"/>
<field name="amount"/>
<field name="currency_id" options="{'no_create': True, 'no_open': True}" groups="base.group_multi_currency"/>
</div>
<field name="journal_id" widget="selection" attrs="{'readonly': [('state', '!=', 'draft')]}"/>
<field name="destination_journal_id" widget="selection" attrs="{'required': [('payment_type', '=', 'transfer')], 'invisible': [('payment_type', '!=', 'transfer')], 'readonly': [('state', '!=', 'draft')]}"/>
<field name="journal_id" widget="selection" attrs="{'invisible': [('amount', '=', 0), ('state', '!=', 'draft')]}"/>
<field name="destination_journal_id" widget="selection" attrs="{'required': [('payment_type', '=', 'transfer')], 'invisible': [('payment_type', '!=', 'transfer')]}"/>
<field name="hide_payment_method" invisible="1"/>
<field name="payment_method_id" string=" " widget="radio" attrs="{'invisible': [('hide_payment_method', '=', True)], 'readonly': [('state', '!=', 'draft')]}"/>
<field name="partner_bank_account_id" attrs="{'invisible': [('show_partner_bank_account', '!=', True)], 'required': [('show_partner_bank_account', '=', True)], 'readonly': [('state', '!=', 'draft')]}" context="{'default_partner_id': partner_id}"/>
<field name="payment_method_id" string=" " widget="radio" attrs="{'invisible': [('hide_payment_method', '=', True)]}"/>
<field name="partner_bank_account_id" attrs="{'invisible': [('show_partner_bank_account', '!=', True)], 'required': [('show_partner_bank_account', '=', True)]}" context="{'default_partner_id': partner_id}"/>
<field name="show_partner_bank_account" invisible="1"/>
<field name="payment_method_code" invisible="1"/>
</group>
<group>
<field name="payment_date" attrs="{'readonly': [('state', '!=', 'draft')]}"/>
<field name="communication" attrs="{'invisible': [('state', '!=', 'draft'), ('communication', '=', False)], 'readonly': [('state', '!=', 'draft')]}"/>
<group attrs="{'invisible': [('payment_difference', '=', 0.0)]}">
<label for="payment_difference"/>
<div>
<field name="payment_difference"/>
<field name="payment_difference_handling" widget="radio" nolabel="1"/>
<div attrs="{'invisible': [('payment_difference_handling','=','open')]}">
<label for="writeoff_account_id" class="oe_edit_only" string="Post Difference In"/>
<field name="writeoff_account_id" options="{'no_create': True}" string="Post Difference In" attrs="{'required': [('payment_difference_handling', '=', 'reconcile')]}"/>
<label for="writeoff_label" class="oe_edit_only" string="Label"/>
<field name="writeoff_label" attrs="{'required': [('payment_difference_handling', '=', 'reconcile')]}"/>
</div>
</div>
</group>
</group>
</sheet>
<div class="oe_chatter">
<field name="message_follower_ids" widget="mail_followers" groups="base.group_user"/>
<field name="activity_ids" widget="mail_activity"/>
<field name="message_ids" widget="mail_thread"/>
</div>
<field name="message_follower_ids" widget="mail_followers" groups="base.group_user"/>
<field name="activity_ids" widget="mail_activity"/>
<field name="message_ids" widget="mail_thread"/>
</div>
</form>
</field>
</record>
<record id="view_account_payment_form_multi" model="ir.ui.view">
<field name="name">account.payment.form.multi</field>
<field name="model">account.payment.register</field>
<field name="arch" type="xml">
<form string="Register Payment">
<group>
<group>
<field name="payment_method_id" string=" " widget="radio"/>
</group>
<group>
<field name="journal_id" widget="selection"/>
<field name="payment_date"/>
</group>
</group>
<footer>
<button string="Create Payment" name="create_payments" type="object" class="oe_highlight"/>
<button string="Cancel" class="btn btn-secondary" special="cancel"/>
</footer>
</form>
</field>
</record>
@@ -302,88 +333,16 @@
</field>
</record>
<record id="action_account_invoice_payment" model="ir.actions.act_window">
<record id="action_account_invoice_from_list" model="ir.actions.server">
<field name="name">Register Payment</field>
<field name="res_model">account.payment</field>
<field name="view_type">form</field>
<field name="view_mode">form</field>
<field name="view_id" ref="view_account_payment_invoice_form"/>
<field name="context">{'default_invoice_ids': [(4, active_id, None)]}</field>
<field name="target">new</field>
</record>
<!-- Register payment from several invoices -->
<record id="view_account_payment_from_invoices" model="ir.ui.view">
<field name="name">account.register.payments.wizard</field>
<field name="model">account.register.payments</field>
<field name="arch" type="xml">
<form string="Register Payment">
<group>
<field name="payment_type" invisible="1"/>
<field name="partner_type" invisible="1"/>
<field name="invoice_ids" invisible="1"/>
<field name="partner_id" invisible="1"/>
<field name="multi" invisible="1"/>
<group>
<label for="amount"/>
<div name="amount_div" class="o_row">
<field name="amount" attrs="{'readonly': [('multi', '=', True)]}"/>
<field name="currency_id"
attrs="{'readonly': [('multi', '=', True)]}"
options="{'no_create': True, 'no_open': True}"
groups="base.group_multi_currency"/>
</div>
<field name="journal_id" widget="selection" attrs="{'invisible': [('amount', '=', 0)]}"/>
<field name="hide_payment_method" invisible="1"/>
<field name="payment_method_id" widget="radio" attrs="{'invisible': ['|', ('hide_payment_method', '=', True), ('amount', '=', 0.0)]}"/>
<field name="partner_bank_account_id" attrs="{'invisible': [('show_partner_bank_account', '!=', True)], 'required': [('show_partner_bank_account', '=', True)]}" context="{'default_partner_id': partner_id}"/>
<field name="show_partner_bank_account" invisible="1"/>
<field name="payment_method_code" invisible="1"/>
</group>
<group>
<field name="payment_date"/>
<field name="group_invoices"/>
<field name="show_communication_field" invisible="1"/>
<field name="communication" attrs="{'invisible': [('show_communication_field', '=', False)]}"/>
<p colspan="2" attrs="{'invisible': [('show_communication_field', '=', True)]}">Memo will be computed from invoices</p>
</group>
<group attrs="{'invisible': [('payment_difference', '=', 0.0)]}">
<label for="payment_difference"/>
<div>
<field name="payment_difference"/>
<field name="payment_difference_handling" widget="radio" nolabel="1"/>
<div attrs="{'invisible': [('payment_difference_handling','=','open')]}">
<label for="writeoff_account_id" class="oe_edit_only" string="Post Difference In"/>
<field name="writeoff_account_id" options="{'no_create': True}" string="Post Difference In" attrs="{'required': [('payment_difference_handling', '=', 'reconcile')]}"/>
<label for="journal_id" string="Journal" attrs="{'invisible': [('amount', '!=', 0)]}"/>
<field name="journal_id" string="Journal" widget="selection" attrs="{'invisible': [('amount', '!=', 0)]}"/>
<label for="writeoff_label" class="oe_edit_only" string="Label"/>
<field name="writeoff_label" attrs="{'required': [('payment_difference_handling', '=', 'reconcile')]}"/>
</div>
</div>
</group>
</group>
<footer>
<button string='Validate' name="create_payments" type="object" class="btn-primary"/>
<button string="Cancel" class="btn-secondary" special="cancel"/>
</footer>
</form>
<field name="model_id" ref="account.model_account_payment"/>
<field name="binding_model_id" ref="account.model_account_invoice"/>
<field name="state">code</field>
<field name="code">
action = model.action_register_payment()
</field>
</record>
<act_window
id="action_account_payment_from_invoices"
name="Register Payment"
res_model="account.register.payments"
src_model="account.invoice"
view_mode="form"
multi="True"
target="new"
key2="client_action_multi"
/>
<!-- Action confirm_payments for multi -->
<record id="action_account_confirm_payments" model="ir.actions.server">
<field name="name">Post Payments</field>
@@ -392,7 +351,7 @@
<field name="model_id" ref="account.model_account_payment"/>
<field name="binding_model_id" ref="account.model_account_payment"/>
<field name="code">
records.post()
records.post()
</field>
</record>
@@ -7,34 +7,15 @@ from odoo.tools.misc import formatLang, format_date
INV_LINES_PER_STUB = 9
class AccountRegisterPayments(models.TransientModel):
_inherit = "account.register.payments"
check_amount_in_words = fields.Char(string="Amount in Words")
check_manual_sequencing = fields.Boolean(related='journal_id.check_manual_sequencing', readonly=1)
# Note: a check_number == 0 means that it will be attributed when the check is printed
check_number = fields.Char(string="Check Number", readonly=True, copy=False, default=0,
help="Number of the check corresponding to this payment. If your pre-printed check are not already numbered, "
"you can manage the numbering in the journal configuration page.")
@api.onchange('journal_id')
def _onchange_journal_id(self):
if hasattr(super(AccountRegisterPayments, self), '_onchange_journal_id'):
super(AccountRegisterPayments, self)._onchange_journal_id()
if self.journal_id.check_manual_sequencing:
self.check_number = self.journal_id.check_sequence_id.number_next_actual
@api.onchange('amount')
def _onchange_amount(self):
if hasattr(super(AccountRegisterPayments, self), '_onchange_amount'):
super(AccountRegisterPayments, self)._onchange_amount()
self.check_amount_in_words = self.currency_id.amount_to_text(self.amount) if self.currency_id else False
class AccountPaymentRegister(models.TransientModel):
_inherit = "account.payment.register"
def _prepare_payment_vals(self, invoices):
res = super(AccountRegisterPayments, self)._prepare_payment_vals(invoices)
res = super(AccountPaymentRegister, self)._prepare_payment_vals(invoices)
if self.payment_method_id == self.env.ref('account_check_printing.account_payment_method_check'):
currency_id = self.env['res.currency'].browse(res['currency_id'])
res.update({
'check_amount_in_words': self.currency_id.amount_to_text(res['amount']) if self.multi else self.check_amount_in_words,
'check_amount_in_words': currency_id.amount_to_text(res['amount']),
})
return res
@@ -48,12 +29,19 @@ class AccountPayment(models.Model):
help="The selected journal is configured to print check numbers. If your pre-printed check paper already has numbers "
"or if the current numbering is wrong, you can change it in the journal configuration page.")
@api.onchange('amount','currency_id')
@api.onchange('amount', 'currency_id')
def _onchange_amount(self):
res = super(AccountPayment, self)._onchange_amount()
self.check_amount_in_words = self.currency_id.amount_to_text(self.amount) if self.currency_id else ''
return res
@api.onchange('journal_id')
def _onchange_journal_id(self):
if hasattr(super(AccountPayment, self), '_onchange_journal_id'):
super(AccountPayment, self)._onchange_journal_id()
if self.journal_id.check_manual_sequencing:
self.check_number = self.journal_id.check_sequence_id.number_next_actual
def _check_communication(self, payment_method_id, communication):
super(AccountPayment, self)._check_communication(payment_method_id, communication)
if payment_method_id == self.env.ref('account_check_printing.account_payment_method_check').id:
@@ -90,7 +78,7 @@ class AccountPayment(models.Model):
('journal_id', '=', self[0].journal_id.id),
('check_number', '!=', "0")], order="check_number desc", limit=1)
next_check_number = last_printed_check and int(last_printed_check.check_number) + 1 or 1
return {
'name': _('Print Pre-numbered Checks'),
'type': 'ir.actions.act_window',
@@ -0,0 +1 @@
from . import test_print_check
@@ -2,13 +2,14 @@
from __future__ import division
from odoo.addons.account.tests.account_test_classes import AccountingTestCase
from odoo.addons.l10n_us_check_printing.report import print_check
from odoo.addons.account_check_printing.models.account_payment import INV_LINES_PER_STUB
from odoo.tests import tagged
from odoo.tests.common import Form
import time
import math
@tagged('post_install', '-at_install')
class TestPrintCheck(AccountingTestCase):
@@ -17,7 +18,7 @@ class TestPrintCheck(AccountingTestCase):
self.invoice_model = self.env['account.invoice']
self.invoice_line_model = self.env['account.invoice.line']
self.register_payments_model = self.env['account.register.payments']
self.payment_model = self.env['account.payment']
self.partner_axelor = self.env.ref("base.res_partner_2")
self.product = self.env.ref("product.product_product_4")
@@ -49,28 +50,41 @@ class TestPrintCheck(AccountingTestCase):
return invoice
def create_payment(self, invoices):
register_payments = self.register_payments_model.with_context({
'active_model': 'account.invoice',
'active_ids': invoices.ids
}).create({
'payment_date': time.strftime('%Y') + '-07-15',
'journal_id': self.bank_journal.id,
'payment_method_id': self.payment_method_check.id,
})
register_payments.create_payments()
return self.env['account.payment'].search([], order="id desc", limit=1)
payment_register = Form(self.env['account.payment'].with_context(active_model='account.invoice', active_ids=invoices.ids))
payment_register.payment_date = time.strftime('%Y') + '-07-15'
payment_register.journal_id = self.bank_journal
payment_register.payment_method_id = self.payment_method_check
payment = payment_register.save()
payment.post()
return payment
def test_print_check(self):
# Make a payment for 10 invoices and 5 credit notes
invoices = self.env['account.invoice']
for i in range(0,15):
for i in range(0, 15):
invoices |= self.create_invoice(is_refund=(i % 3 == 0))
payment = self.create_payment(invoices)
self.assertEqual(all(payment.mapped('check_amount_in_words')), True, 'The amount in words is not set on all the payments')
self.assertEqual(all(payment.mapped('check_number')), True, 'The check number is not set on all the payments')
# Check the data generated for the report
self.env.ref('base.main_company').write({'account_check_printing_multi_stub': True})
report_pages = payment._check_get_pages()
self.assertEqual(len(report_pages), int(math.ceil(len(invoices.ids) / print_check.INV_LINES_PER_STUB)))
self.assertEqual(len(report_pages), int(math.ceil(len(invoices.ids) / INV_LINES_PER_STUB)))
self.env.ref('base.main_company').write({'account_check_printing_multi_stub': False})
report_pages = payment._check_get_pages()
self.assertEqual(len(report_pages), 1)
def test_from_register(self):
invoices = self.env['account.invoice']
for i in range(0, 3):
invoices |= self.create_invoice(is_refund=(i % 3 == 0))
payment_register = Form(self.env['account.payment.register'].with_context(active_model='account.invoice', active_ids=invoices.ids))
payment_register.payment_date = time.strftime('%Y') + '-07-15'
payment_register.journal_id = self.bank_journal
payment_register.payment_method_id = self.payment_method_check
domain = payment_register.save().create_payments()['domain']
payment = self.env['account.payment'].search(domain)
self.assertEqual(all(payment.mapped('check_amount_in_words')), True, 'The amount in words is not set on all the payments')
@@ -19,33 +19,6 @@
</field>
</record>
<record id="view_account_payment_invoice_form_inherited" model="ir.ui.view">
<field name="name">account.payment.invoice.form.inherited</field>
<field name="model">account.payment</field>
<field name="inherit_id" ref="account.view_account_payment_invoice_form" />
<field name="arch" type="xml">
<xpath expr="//div[@name='amount_div']" position="after">
<field name="check_amount_in_words" attrs="{'invisible': [('payment_method_code', '!=', 'check_printing')]}"/>
</xpath>
</field>
</record>
<record id="view_account_payment_from_invoices_inherited" model="ir.ui.view">
<field name="name">account.register.payments.wizard.inherited</field>
<field name="model">account.register.payments</field>
<field name="inherit_id" ref="account.view_account_payment_from_invoices" />
<field name="arch" type="xml">
<xpath expr="//div[@name='amount_div']" position="after">
<field name="check_amount_in_words"
attrs="{'invisible': ['|', ('payment_method_code', '!=', 'check_printing'), ('multi', '=', True)]}"/>
</xpath>
<xpath expr="//field[@name='communication']" position="after">
<field name="check_manual_sequencing" invisible="1" readonly="1"/>
<field name="check_number" attrs="{'invisible': ['|', ('payment_method_code', '!=', 'check_printing'), ('check_manual_sequencing', '=', False)]}"/>
</xpath>
</field>
</record>
<record id="view_payment_check_printing_search" model="ir.ui.view">
<field name="name">account.payment.check.printing.search</field>
<field name="model">account.payment</field>
+1 -10
View File
@@ -7,16 +7,8 @@
<field name="inherit_id" ref="account.view_account_payment_form"/>
<field name="arch" type="xml">
<xpath expr='//group[2]' position="inside">
<field name="payment_transaction_id"/>
<field name="payment_transaction_id" groups="base.group_no_one" attrs="{'invisible': [('payment_method_code', '!=', 'electronic')]}"/>
</xpath>
</field>
</record>
<record id="view_account_payment_invoice_form_inherit_payment" model="ir.ui.view">
<field name="name">view.account.payment.invoice.form.inherit.payment</field>
<field name="model">account.payment</field>
<field name="inherit_id" ref="account.view_account_payment_invoice_form"/>
<field name="arch" type="xml">
<field name="payment_method_id" position="after">
<field name="payment_method_code" invisible="1"/>
<field name="payment_token_id" options="{'no_create': True}"
@@ -25,6 +17,5 @@
</field>
</field>
</record>
</data>
</odoo>
@@ -537,7 +537,7 @@ tour.register('main_flow_tour', {
content: _t("Register Payment"),
position: "bottom",
}, {
trigger: ".modal-footer .btn-primary",
trigger: ".o_form_sheet_bg .btn-primary",
content: _t("Validate"),
position: "bottom",
}, {
@@ -673,12 +673,11 @@ tour.register('main_flow_tour', {
position: "bottom",
}, {
trigger: "select.o_field_widget[name=journal_id]",
extra_trigger: ".modal-dialog",
content: _t("Select Journal"),
position: "bottom",
run: 'text(Bank (USD))',
run: 'text Bank(USD)',
}, {
trigger: ".modal-footer .btn-primary",
trigger: ".btn-primary",
content: _t("Validate"),
position: "bottom",
}, {
@@ -773,7 +772,7 @@ tour.register('main_flow_tour', {
position: "right",
}, {
edition: "enterprise",
trigger: ".button_close_statement",
trigger: ".button_back_to_statement",
content: _t('<p><b>Close this statement.</p>'),
position: "bottom",
}]);