Merge branch 'mig/16.0/sale_payment_deposit' into '16.0'

WIP: mig/16.0/sale_payment_deposit into 16.0

See merge request hibou-io/hibou-odoo/suite!1549
This commit is contained in:
Jared Kipe
2022-10-26 00:26:53 +00:00
9 changed files with 266 additions and 0 deletions

View File

@@ -0,0 +1 @@
from . import models

View File

@@ -0,0 +1,25 @@
{
'name': 'Sale Payment Deposit',
'author': 'Hibou Corp. <hello@hibou.io>',
'category': 'Sales',
'license': 'AGPL-3',
'version': '16.0.1.0.0',
'description':
"""
Sale Deposits
=============
Automates the creation of 'Deposit' invoices and payments. For example, someone confirming
a sale with "50% Deposit, 50% on Delivery" payment terms, will pay the
50% deposit payment up front instead of the entire order.
""",
'depends': [
'sale',
'payment',
],
'auto_install': False,
'data': [
'views/account_views.xml',
'views/sale_portal_templates.xml',
],
}

View File

@@ -0,0 +1,4 @@
from . import account
from . import payment
from . import sale
from . import sale_patch

View File

@@ -0,0 +1,32 @@
from odoo import api, fields, models
class AccountPaymentTerm(models.Model):
_inherit = 'account.payment.term'
deposit_percentage = fields.Float(string='Deposit Percentage',
help='Require Percentage deposit when paying on the front end.')
deposit_flat = fields.Float(string='Deposit Flat',
help='Require Flat deposit when paying on the front end.')
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
def _post_process_after_done(self):
now = fields.Datetime.now()
res = super(PaymentTransaction, self)._post_process_after_done()
# Post Process Payments made on the front of the website, reconciling to Deposit.
for transaction in self.filtered(lambda t: t.payment_id
and t.sale_order_ids
and sum(t.sale_order_ids.mapped('amount_total_deposit'))
and not t.invoice_ids and (now - t.date).seconds < 1200):
if not transaction.sale_order_ids.mapped('invoice_ids'):
# don't process ones that we might still be able to process later...
transaction.write({'is_processed': False})
else:
# we have a payment and could attempt to reconcile to an invoice
# Leave the payment in 'is_processed': True
transaction.sale_order_ids._auto_deposit_payment_match()
return res

View File

@@ -0,0 +1,33 @@
from odoo import models, _
import logging
_logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
# Override to confirm payments totaling the amount_total_deposit
def _check_amount_and_confirm_order(self):
self.ensure_one()
for order in self.sale_order_ids.filtered(lambda so: so.state in ('draft', 'sent')):
# default amount as originally calculated
amount = order.amount_total
if order.amount_total_deposit:
amount = order.amount_total_deposit
if order.currency_id.compare_amounts(self.amount, amount) == 0:
order.with_context(send_email=True).action_confirm()
else:
_logger.warning(
'<%s> transaction AMOUNT MISMATCH for order %s (ID %s): expected %r, got %r',
self.acquirer_id.provider,order.name, order.id,
amount, self.amount,
)
order.message_post(
subject=_("Amount Mismatch (%s)") % self.acquirer_id.provider,
body=_("The order was not confirmed despite response from the acquirer (%s): order total is %r but acquirer replied with %r.") % (
self.acquirer_id.provider,
amount,
self.amount,
)
)

View File

@@ -0,0 +1,49 @@
from odoo import api, fields, models
from json import loads as json_loads
class SaleOrder(models.Model):
_inherit = 'sale.order'
amount_total_deposit = fields.Monetary(string='Deposit', compute='_amount_total_deposit')
@api.depends('amount_total', 'payment_term_id.deposit_percentage', 'payment_term_id.deposit_flat')
def _amount_total_deposit(self):
for order in self:
percent_deposit = order.amount_total * float(order.payment_term_id.deposit_percentage) / 100.0
flat_deposite = float(order.payment_term_id.deposit_flat)
order.amount_total_deposit = percent_deposit + flat_deposite
def action_confirm(self):
res = super(SaleOrder, self).action_confirm()
self._auto_deposit_invoice()
return res
def _auto_deposit_invoice(self):
wizard_model = self.env['sale.advance.payment.inv'].sudo()
for sale in self.sudo().filtered(lambda o: not o.invoice_ids and o.amount_total_deposit):
# Create Deposit Invoices
wizard = wizard_model.create({
'advance_payment_method': 'fixed',
'fixed_amount': sale.amount_total_deposit,
})
wizard.with_context(active_ids=sale.ids).create_invoices()
# Validate Invoices
sale.invoice_ids.filtered(lambda i: i.state == 'draft').post()
# Attempt to reconcile
sale._auto_deposit_payment_match()
def _auto_deposit_payment_match(self):
# Attempt to find payments that could be used on this new invoice and reconcile them.
# Note that this probably doesn't work for a payment made on the front, see .account.PaymentTransaction
aml_model = self.env['account.move.line'].sudo()
for sale in self.sudo():
for invoice in sale.invoice_ids.filtered(lambda i: i.state == 'posted'):
outstanding = json_loads(invoice.invoice_outstanding_credits_debits_widget)
if isinstance(outstanding, dict) and outstanding.get('content'):
for line in outstanding.get('content'):
if abs(line.get('amount', 0.0) - invoice.amount_residual) < 0.01 and line.get('id'):
aml = aml_model.browse(line.get('id'))
aml += invoice.line_ids.filtered(lambda l: l.account_id == aml.account_id)
if aml.reconcile():
break

View File

@@ -0,0 +1,84 @@
from odoo.exceptions import ValidationError
from odoo.addons.sale.models.sale_order import SaleOrder
def _create_payment_transaction(self, vals):
# This is a copy job from odoo.addons.sale.models.sale due to the closed nature of the vals.update(dict) call
# Ultimately, only the 'vals.update' with the new amount is really used.
'''Similar to self.env['payment.transaction'].create(vals) but the values are filled with the
current sales orders fields (e.g. the partner or the currency).
:param vals: The values to create a new payment.transaction.
:return: The newly created payment.transaction record.
'''
# Ensure the currencies are the same.
# extract variable for use later.
sale = self[0]
currency = sale.pricelist_id.currency_id
if any([so.pricelist_id.currency_id != currency for so in self]):
raise ValidationError(_('A transaction can\'t be linked to sales orders having different currencies.'))
# Ensure the partner are the same.
partner = sale.partner_id
if any([so.partner_id != partner for so in self]):
raise ValidationError(_('A transaction can\'t be linked to sales orders having different partners.'))
# Try to retrieve the acquirer. However, fallback to the token's acquirer.
acquirer_id = vals.get('acquirer_id')
acquirer = False
payment_token_id = vals.get('payment_token_id')
if payment_token_id:
payment_token = self.env['payment.token'].sudo().browse(payment_token_id)
# Check payment_token/acquirer matching or take the acquirer from token
if acquirer_id:
acquirer = self.env['payment.acquirer'].browse(acquirer_id)
if payment_token and payment_token.acquirer_id != acquirer:
raise ValidationError(_('Invalid token found! Token acquirer %s != %s') % (
payment_token.acquirer_id.name, acquirer.name))
if payment_token and payment_token.partner_id != partner:
raise ValidationError(_('Invalid token found! Token partner %s != %s') % (
payment_token.partner.name, partner.name))
else:
acquirer = payment_token.acquirer_id
# Check an acquirer is there.
if not acquirer_id and not acquirer:
raise ValidationError(_('A payment acquirer is required to create a transaction.'))
if not acquirer:
acquirer = self.env['payment.acquirer'].browse(acquirer_id)
# Check a journal is set on acquirer.
if not acquirer.journal_id:
raise ValidationError(_('A journal must be specified of the acquirer %s.' % acquirer.name))
if not acquirer_id and acquirer:
vals['acquirer_id'] = acquirer.id
# Override for Deposit
amount = sum(self.mapped('amount_total'))
# This is a patch, all databases will run this code even if this field doesn't exist.
if hasattr(sale, 'amount_total_deposit') and sum(self.mapped('amount_total_deposit')):
amount = sum(self.mapped('amount_total_deposit'))
vals.update({
'amount': amount,
'currency_id': currency.id,
'partner_id': partner.id,
'sale_order_ids': [(6, 0, self.ids)],
})
transaction = self.env['payment.transaction'].create(vals)
# Process directly if payment_token
if transaction.payment_token_id:
transaction.s2s_do_transaction()
return transaction
# Patch core implementation.
SaleOrder._create_payment_transaction = _create_payment_transaction

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<record id="view_payment_term_form_inherit" model="ir.ui.view">
<field name="name">account.payment.term.form.inherit</field>
<field name="model">account.payment.term</field>
<field name="inherit_id" ref="account.view_payment_term_form"/>
<field name="arch" type="xml">
<xpath expr="//group/group" position="inside">
<field name="deposit_percentage"/>
<field name="deposit_flat"/>
</xpath>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<template id="sale_order_portal_template_deposit" name="Sales Order Portal Template - Deposit" inherit_id="sale.sale_order_portal_template">
<!-- Set payment amount here rather than overriding the controller -->
<xpath expr="//div[1]" position="before">
<t t-if="sale_order.has_to_be_paid(True)">
<t t-set="amount" t-value="sale_order.amount_total_deposit or amount"/>
</t>
</xpath>
<!-- Display the Deposit amount prominently -->
<xpath expr="//t[@t-set='title']/h2" position="after">
<h5 t-if="sale_order.amount_total_deposit"><b t-field="sale_order.amount_total_deposit"/> Deposit</h5>
</xpath>
<!-- Display the Deposit and Total when Signing -->
<xpath expr="//div[@id='modalaccept']/div/form/main/p/ul/li[2]" position="after">
<li t-if="sale_order.amount_total_deposit"><span>Deposit today of:</span> <b data-id="total_amount_deposit" t-field="sale_order.amount_total_deposit"/></li>
</xpath>
<!-- Display the Deposit when Paying -->
<xpath expr="//div[@id='modalaccept']/div/div/main/p/ul/li[2]" position="replace">
<li t-if="sale_order.amount_total_deposit"><span>For the deposit amount of:</span> <b data-id="total_amount_deposit" t-field="sale_order.amount_total_deposit"/></li>
<li t-else=""><span>For an amount of:</span> <b data-id="total_amount" t-field="sale_order.amount_total"/></li>
</xpath>
</template>
</odoo>