from netforce.model import Model, get_model

class InvoicePayment(Model):
    _inherit="invoice.payment"

    def add_payment(self,ids,context={}):
        obj=self.browse(ids)[0]
        inv=obj.invoice_id
        if inv.inv_type not in ("invoice","debit"):
            raise Exception("Wrong invoice type")
        if obj.amount>inv.amount_due:
            raise Exception("Amount paid exceeds due amount")
        vals={
            "type": inv.type=="out" and "in" or "out",
            "pay_type": "invoice",
            "partner_id": inv.partner_id.id,
            "date": obj.date,
            "ref": obj.ref,
            "account_id": obj.account_id.id,
            "currency_id": inv.currency_id.id,
            "lines": [("create",{
                "type": "invoice",
                "invoice_id": inv.id,
                "account_id": inv.account_id.id,
                "amount": obj.amount,
            })],
        }
        pmt_id=get_model("account.payment").create(vals,context={"type":vals["type"]})
        # to check when before payment post
        ctx={
            'hdcase_reconcile':inv.hdcase_reconcile,
        }
        get_model("account.payment").post([pmt_id],context=ctx)
        return {
            "next": {
                "name": "view_invoice",
                "active_id": inv.id,
            }
        }

InvoicePayment.register()