[MIG] website_sale_payment_terms: migrate to 15.0

1. Use new web assets management
2. Set company currency in unit tests
3. Refactor payment transaction creation
This commit is contained in:
Cedric Collins
2022-01-27 17:57:17 -06:00
parent 862914cd69
commit e4b3631565
8 changed files with 35 additions and 126 deletions

View File

@@ -2,7 +2,7 @@
'name': 'Website Payment Terms',
'author': 'Hibou Corp. <hello@hibou.io>',
'category': 'Sales',
'version': '14.0.1.0.0',
'version': '15.0.1.0.0',
'description':
"""
Website Payment Terms
@@ -20,8 +20,12 @@ Allow customers to choose payment terms if order total meets a configured thresh
'security/ir.model.access.csv',
'views/account_views.xml',
'views/res_config_views.xml',
'views/web_assets.xml',
'views/website_templates.xml',
'views/website_views.xml',
],
'assets': {
'web.assets_frontend': [
'/website_sale_payment_terms/static/src/js/payment_terms.js',
],
},
}

View File

@@ -4,9 +4,14 @@ from odoo.addons.website_sale_delivery.controllers.main import WebsiteSaleDelive
class WebsiteSalePaymentTerms(WebsiteSaleDelivery):
def _get_shop_payment_values(self, order, **kwargs):
values = super(WebsiteSalePaymentTerms, self)._get_shop_payment_values(order, **kwargs)
values['amount'] = order.amount_due_today
return values
# In case payment_term_id is set by query-string in a link (from website_sale_delivery)
@route(['/shop/payment'], type='http', auth="public", website=True)
def payment(self, **post):
@route('/shop/payment', type='http', auth='public', website=True, sitemap=False)
def shop_payment(self, **post):
order = request.website.sale_get_order()
payment_term_id = post.get('payment_term_id')
if order.amount_total > request.website.payment_deposit_threshold:
@@ -19,7 +24,7 @@ class WebsiteSalePaymentTerms(WebsiteSaleDelivery):
else:
order.payment_term_id = False
return super(WebsiteSalePaymentTerms, self).payment(**post)
return super(WebsiteSalePaymentTerms, self).shop_payment(**post)
# Main JS driven payment term updater.
@route(['/shop/update_payment_term'], type='json', auth='public', methods=['POST'], website=True, csrf=False)
@@ -79,4 +84,5 @@ class WebsiteSalePaymentTerms(WebsiteSaleDelivery):
currency = order.currency_id
if order:
res['amount_due_today'] = Monetary.value_to_html(order.amount_due_today, {'display_currency': currency})
res['amount_due_today_raw'] = order.amount_due_today
return res

View File

@@ -2,5 +2,4 @@ from . import account
from . import payment
from . import res_config
from . import sale
from . import sale_patch
from . import website

View File

@@ -6,22 +6,6 @@ _logger = logging.getLogger(__name__)
class PaymentTransaction(models.Model):
_inherit = 'payment.transaction'
def render_sale_button(self, order, submit_txt=None, render_values=None):
values = {
'partner_id': order.partner_id.id,
'type': self.type,
}
if render_values:
values.update(render_values)
# Not very elegant to do that here but no choice regarding the design.
self._log_payment_transaction_sent()
return self.acquirer_id.with_context(submit_class='btn btn-primary', submit_txt=submit_txt or _('Pay Now')).sudo().render(
self.reference,
order.amount_due_today,
order.pricelist_id.currency_id.id,
values=values,
)
# Override to confirm payments totaling the amount_due_today
def _check_amount_and_confirm_order(self):
self.ensure_one()

View File

@@ -1,86 +0,0 @@
from odoo.exceptions import ValidationError
from odoo.addons.sale.models.sale import SaleOrder
def _create_payment_transaction(self, vals):
# Code copied from sale_payment_deposit to use order.amount_due_today
#
# 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_due_today'):
amount = sum(self.mapped('amount_due_today'))
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

@@ -21,7 +21,7 @@ odoo.define('website_sale_payment_terms.payment_terms', function (require) {
* @override
*/
start: function () {
console.log('Payment Terms V10.3');
console.log('Payment Terms V10.4');
return this._super.apply(this, arguments).then(function () {
var available_term = $('input[name="payment_term_id"]').length;
if (available_term > 0) {
@@ -57,6 +57,15 @@ odoo.define('website_sale_payment_terms.payment_terms', function (require) {
}).then(this._onPaymentTermUpdateAnswer.bind(this)));
},
/**
* Update the total cost according to the selected shipping method
*
* @private
* @param {float} amount : The new total amount of to be paid
*/
_updatePaymentAmount: function(amount){
core.bus.trigger('update_shipping_cost', amount);
},
/**
* Show amount due if operation is a success
*
@@ -65,12 +74,10 @@ odoo.define('website_sale_payment_terms.payment_terms', function (require) {
*/
_onPaymentTermUpdateAnswer: function (result) {
if (!result.error) {
console.log("_onPaymentTermUpdateAnswer");
console.log(result);
// Get Payment Term note/description for modal
var note = result.note;
if (!result.note) {
note = result.payment_term_name;
var note = $.parseHTML(result.note);
if (!$(note).text()) {
note = $.parseHTML('<p>' + result.payment_term_name + '</p>');
}
// Change forms based on order payment requirement
@@ -79,12 +86,13 @@ odoo.define('website_sale_payment_terms.payment_terms', function (require) {
$('#payment_method').hide();
$('#non_payment_method').show();
} else {
this._updatePaymentAmount(result.amount_due_today);
$('#payment_method').show();
$('#non_payment_method').hide();
}
// Open success modal with message
$('#payment_term_success_modal .success-modal-note').text(note);
$('#payment_term_success_modal .success-modal-note').html(note);
$('#payment_term_success_modal').modal();
} else {
// Open error modal
@@ -117,7 +125,10 @@ odoo.define('website_sale_payment_terms.payment_terms', function (require) {
publicWidget.registry.websiteSaleDelivery.include({
_handleCarrierUpdateResult: function (result) {
this._super.apply(this, arguments);
$('#order_due_today .monetary_field').html(result.amount_due_today);
if (result.amount_due_today_raw !== undefined) {
this._updateShippingCost(result.amount_due_today_raw);
$('#order_due_today .monetary_field').html(result.amount_due_today);
}
},
});

View File

@@ -5,6 +5,7 @@ from odoo.tests import tagged, TransactionCase
class TestWebsiteSalePaymentTerms(TransactionCase):
def setUp(self):
super(TestWebsiteSalePaymentTerms, self).setUp()
self.env.company.currency_id = self.browse_ref('base.USD')
self.so = self.env['sale.order'].create({
'partner_id': self.ref('base.res_partner_12'),
'order_line': [(0, 0, {

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<odoo>
<template id="web_assets_frontend" inherit_id="website.assets_frontend">
<xpath expr="//script[last()]" position="after">
<script type="text/javascript" src="/website_sale_payment_terms/static/src/js/payment_terms.js"/>
</xpath>
</template>
</odoo>