from odoo import models, fields, api from odoo.exceptions import ValidationError class UploadPayments(models.Model): _name = "upload.payments" _description = "Upload Payments" no_invoice = fields.Char('Invoice Number', required=True) date_invoice = fields.Date('Invoice Date', required=True) move_id = fields.Many2one('account.move', string='Invoice') payment_id = fields.Many2one('account.payment', string='Created Payment') @api.model def create(self, vals): record = super(UploadPayments, self).create(vals) record._create_payment_from_invoice() return record def _create_payment_from_invoice(self): self.ensure_one() # Find the invoice based on the marketplace number invoice = self.env['account.move'].search([ ('invoice_marketplace', '=', self.no_invoice) ], limit=1) if not invoice: raise ValidationError(f"No invoice found with marketplace number {self.no_invoice}") self.move_id = invoice.id # Create payment payment_vals = { 'payment_type': 'inbound' if invoice.move_type in ('out_invoice', 'out_refund') else 'outbound', 'partner_id': invoice.partner_id.id, 'amount': invoice.amount_residual, 'date': self.date_invoice or fields.Date.today(), 'ref': invoice.name, 'journal_id': invoice.journal_id.id, 'currency_id': invoice.currency_id.id, } payment = self.env['account.payment'].create(payment_vals) payment.action_post() # Reconcile with invoice lines_to_reconcile = invoice.line_ids.filtered( lambda line: line.account_id.account_type in ('asset_receivable', 'liability_payable') ) payment_lines = payment.line_ids.filtered( lambda line: line.account_id.account_type in ('asset_receivable', 'liability_payable') ) (lines_to_reconcile + payment_lines).reconcile() self.payment_id = payment.id return payment