Debian Codegraph @

addons/point_of_sale/models/pos_payment.py

raw
1 from odoo import api, fields, models, _
2 from odoo.tools import formatLang, float_is_zero
3 from odoo.exceptions import ValidationError
4 from uuid import uuid4
5
6
7 class PosPayment(models.Model):
8 """ Used to register payments made in a pos.order.
9
10 See `payment_ids` field of pos.order model.
11 The main characteristics of pos.payment can be read from
12 `payment_method_id`.
13 """
14
15 _name = 'pos.payment'
16 _description = "Point of Sale Payments"
17 _order = "id desc"
18 _inherit = ['pos.load.mixin']
19
20 name = fields.Char(string='Label', readonly=True)
21 pos_order_id = fields.Many2one('pos.order', string='Order', required=True, index=True, ondelete='cascade')
22 amount = fields.Monetary(string='Amount', required=True, currency_field='currency_id', help="Total amount of the payment.")
23 payment_method_id = fields.Many2one('pos.payment.method', string='Payment Method', required=True)
24 payment_date = fields.Datetime(string='Date', required=True, readonly=True, default=lambda self: fields.Datetime.now())
25 currency_id = fields.Many2one('res.currency', string='Currency', related='pos_order_id.currency_id')
26 currency_rate = fields.Float(string='Conversion Rate', related='pos_order_id.currency_rate', help='Conversion rate from company currency to order currency.')
27 partner_id = fields.Many2one('res.partner', string='Customer', related='pos_order_id.partner_id')
28 session_id = fields.Many2one('pos.session', string='Session', related='pos_order_id.session_id', store=True, index=True)
29 user_id = fields.Many2one('res.users', string='Employee', related='session_id.user_id')
30 company_id = fields.Many2one('res.company', string='Company', related='pos_order_id.company_id', store=True)
31 card_type = fields.Char(string='Type of card used', help='The type of the payment card (e.g. CREDIT CARD OR DEBIT CARD)')
32 card_brand = fields.Char(string='Brand of card', help='The brand of the payment card (e.g. Visa, AMEX, ...)')
33 card_no = fields.Char(string='Card Number(Last 4 Digit)')
34 cardholder_name = fields.Char(string='Card Owner name')
35 payment_ref_no = fields.Char(string='Payment reference number', help='Payment reference number from payment provider terminal')
36 payment_method_authcode = fields.Char(string='Payment APPR Code')
37 payment_method_issuer_bank = fields.Char(string='Payment Issuer Bank')
38 payment_method_payment_mode = fields.Char(string='Payment Mode')
39 transaction_id = fields.Char(string='Payment Transaction ID')
40 payment_status = fields.Char(string='Payment Status')
41 ticket = fields.Char(string='Payment Receipt Info')
42 is_change = fields.Boolean(string='Is this payment change?', default=False)
43 account_move_id = fields.Many2one('account.move', index='btree_not_null')
44 uuid = fields.Char(string='Uuid', readonly=True, default=lambda self: str(uuid4()), copy=False)
45
46 _unique_uuid = models.Constraint('unique (uuid)', 'A payment with this uuid already exists')
47
48 @api.model
49 def _load_pos_data_domain(self, data, config):
50 return [('pos_order_id', 'in', [order['id'] for order in data['pos.order']])]
51
52 @api.depends('amount', 'currency_id')
53 def _compute_display_name(self):
54 for payment in self:
55 if payment.name:
56 payment.display_name = f'{payment.name} {formatLang(self.env, payment.amount, currency_obj=payment.currency_id)}'
57 else:
58 payment.display_name = formatLang(self.env, payment.amount, currency_obj=payment.currency_id)
59
60 @api.constrains('amount')
61 def _check_amount(self):
62 for payment in self:
63 if payment.pos_order_id.state == 'done' or payment.pos_order_id.account_move:
64 raise ValidationError(_('You cannot edit a payment for a posted order.'))
65
66 @api.constrains('payment_method_id')
67 def _check_payment_method_id(self):
68 for payment in self:
69 if payment.payment_method_id not in payment.session_id.config_id.payment_method_ids:
70 raise ValidationError(_('The payment method selected is not allowed in the config of the POS session.'))
71
72 def _create_payment_moves(self, is_reverse=False):
73 result = self.env['account.move']
74 change_payment = self.filtered(lambda p: p.is_change and p.payment_method_id.type == 'cash')
75 payment_to_change = self.filtered(lambda p: not p.is_change and p.payment_method_id.type == 'cash')[:1]
76 for payment in self - change_payment:
77 order = payment.pos_order_id
78 payment_method = payment.payment_method_id
79 if payment_method.type == 'pay_later' or float_is_zero(payment.amount, precision_rounding=order.currency_id.rounding):
80 continue
81 accounting_partner = self.env["res.partner"]._find_accounting_partner(payment.partner_id)
82 pos_session = order.session_id
83 journal = pos_session.config_id.journal_id
84 if change_payment and payment == payment_to_change:
85 pos_payment_ids = payment.ids + change_payment.ids
86 payment_amount = payment.amount + change_payment.amount
87 else:
88 pos_payment_ids = payment.ids
89 payment_amount = payment.amount
90 payment_move = self.env['account.move'].with_context(default_journal_id=journal.id).create({
91 'journal_id': journal.id,
92 'date': fields.Date.context_today(order, order.date_order),
93 'ref': _('Invoice payment for %(order)s (%(account_move)s) using %(payment_method)s', order=order.name, account_move=order.account_move.name, payment_method=payment_method.name),
94 'pos_payment_ids': pos_payment_ids,
95 })
96 result |= payment_move
97 payment.write({'account_move_id': payment_move.id})
98 amounts = pos_session._update_amounts({'amount': 0, 'amount_converted': 0}, {'amount': payment_amount}, payment.payment_date)
99 credit_line_vals = pos_session._credit_amounts({
100 'account_id': accounting_partner.with_company(order.company_id).property_account_receivable_id.id, # The field being company dependant, we need to make sure the right value is received.
101 'partner_id': accounting_partner.id,
102 'move_id': payment_move.id,
103 'no_followup': False,
104 }, amounts['amount'], amounts['amount_converted'])
105 is_split_transaction = payment.payment_method_id.split_transactions
106 if is_split_transaction and is_reverse:
107 reversed_move_receivable_account_id = accounting_partner.with_company(order.company_id).property_account_receivable_id.id
108 elif is_reverse:
109 reversed_move_receivable_account_id = payment.payment_method_id.receivable_account_id.id or self.company_id.account_default_pos_receivable_account_id.id
110 else:
111 reversed_move_receivable_account_id = self.company_id.account_default_pos_receivable_account_id.id
112 debit_line_vals = pos_session._debit_amounts({
113 'account_id': reversed_move_receivable_account_id,
114 'move_id': payment_move.id,
115 'partner_id': accounting_partner.id if is_split_transaction and is_reverse else False,
116 'no_followup': False,
117 }, amounts['amount'], amounts['amount_converted'])
118 self.env['account.move.line'].create([credit_line_vals, debit_line_vals])
119 payment_move._post()
120 return result
121
122 def _get_receivable_lines_for_invoice_reconciliation(self, receivable_account):
123 """
124 If this payment is linked to an account.move, this returns the corresponding receivable lines
125 that should be reconciled with the invoice's receivable lines.
126 The introduced heuristics here is important for cases where the pos receivable account is the same
127 as the receivable account of the customer.
128
129 - positive payment -> negative balance lines
130 - negative payment -> positive balance lines
131 """
132
133 result = self.env['account.move.line']
134 for payment in self:
135 if not payment.account_move_id:
136 continue
137
138 currency = payment.currency_id
139 is_positive_amount = currency.compare_amounts(payment.amount, 0) > 0
140
141 for line in payment.account_move_id.line_ids:
142 if currency.compare_amounts(line.balance, 0) == 0 or line.account_id != receivable_account or line.reconciled:
143 continue
144
145 if is_positive_amount:
146 if currency.compare_amounts(line.balance, 0) < 0:
147 result |= line
148 else:
149 if currency.compare_amounts(line.balance, 0) > 0:
150 result |= line
151
152 return result