From 3694786630287043ee3aa6e5d0d3443743f19ee3 Mon Sep 17 00:00:00 2001
From: Abdurrahman Saber
Date: Mon, 14 Apr 2025 13:12:04 +0200
Subject: [PATCH] [MIG][IMP][ADD] payment_applepay, p_donation_theme,
ensan_sale_management: migrate applypay to v14 and encapsulate shared logic
into a new model to fix dependency cycles
---
.../ensan_sale_management/__init__.py | 1 +
.../ensan_sale_management/__manifest__.py | 17 ++
.../data/sms_data.xml | 3 +-
.../ensan_sale_management/models/__init__.py | 2 +
.../models/product.py | 0
.../models/sale_order.py} | 8 +-
.../security/ir.model.access.csv | 2 +
.../views/product_views.xml | 42 +++
.../views/sale_order_views.xml | 29 ++
odex25_donation/p_donation_theme/__init__.py | 3 +-
.../p_donation_theme/__manifest__.py | 10 +-
.../p_donation_theme/controllers/main.py | 4 +-
.../p_donation_theme/models/__init__.py | 3 -
.../security/ir.model.access.csv | 2 -
.../p_donation_theme/views/views.xml | 64 -----
.../payment_applepay/__manifest__.py | 3 +-
.../payment_applepay/controllers/main.py | 249 ++++++++++++------
.../data/payment_acquirer_data.xml | 18 +-
.../payment_applepay/models/__init__.py | 1 -
.../models/account_payment_method.py | 14 -
.../payment_applepay/models/payment copy.py | 126 ---------
.../payment_applepay/models/payment.py | 248 ++++++++---------
.../models/payment_before_email_patch.py | 138 ----------
.../models/payment_transaction.py | 109 +++-----
.../static/src/js/applepay_iframe.js | 131 +++++++++
.../src/scss/applepay_iframe_content.scss | 27 ++
.../views/applepay_iframe.xml | 19 ++
.../views/payment_applepay_templates.xml | 2 +-
.../views/payment_popup_template.xml | 2 +-
.../payment_applepay/views/payment_views.xml | 11 +-
.../payment_hyperpay/__manifest__.py | 3 +-
31 files changed, 624 insertions(+), 667 deletions(-)
create mode 100644 odex25_donation/ensan_sale_management/__init__.py
create mode 100644 odex25_donation/ensan_sale_management/__manifest__.py
rename odex25_donation/{p_donation_theme => ensan_sale_management}/data/sms_data.xml (61%)
create mode 100644 odex25_donation/ensan_sale_management/models/__init__.py
rename odex25_donation/{p_donation_theme => ensan_sale_management}/models/product.py (100%)
rename odex25_donation/{p_donation_theme/models/sale.py => ensan_sale_management/models/sale_order.py} (93%)
create mode 100644 odex25_donation/ensan_sale_management/security/ir.model.access.csv
create mode 100644 odex25_donation/ensan_sale_management/views/product_views.xml
create mode 100644 odex25_donation/ensan_sale_management/views/sale_order_views.xml
delete mode 100644 odex25_donation/p_donation_theme/models/__init__.py
delete mode 100644 odex25_donation/p_donation_theme/security/ir.model.access.csv
delete mode 100644 odex25_donation/payment_applepay/models/account_payment_method.py
delete mode 100644 odex25_donation/payment_applepay/models/payment copy.py
delete mode 100644 odex25_donation/payment_applepay/models/payment_before_email_patch.py
create mode 100644 odex25_donation/payment_applepay/static/src/js/applepay_iframe.js
create mode 100644 odex25_donation/payment_applepay/static/src/scss/applepay_iframe_content.scss
create mode 100644 odex25_donation/payment_applepay/views/applepay_iframe.xml
diff --git a/odex25_donation/ensan_sale_management/__init__.py b/odex25_donation/ensan_sale_management/__init__.py
new file mode 100644
index 000000000..9a7e03ede
--- /dev/null
+++ b/odex25_donation/ensan_sale_management/__init__.py
@@ -0,0 +1 @@
+from . import models
\ No newline at end of file
diff --git a/odex25_donation/ensan_sale_management/__manifest__.py b/odex25_donation/ensan_sale_management/__manifest__.py
new file mode 100644
index 000000000..5044c11d1
--- /dev/null
+++ b/odex25_donation/ensan_sale_management/__manifest__.py
@@ -0,0 +1,17 @@
+{
+ 'name': 'Ensan Sale Management',
+ 'version': '14.0',
+ 'description': '',
+ 'summary': '',
+ 'author': 'Ensan',
+ 'website': 'https://ensan.com',
+ 'license': 'LGPL-3',
+ 'category': 'Sales',
+ 'depends': ['base', 'website_sale'],
+ 'data': [
+ 'security/ir.model.access.csv',
+ 'data/sms_data.xml',
+ 'views/sale_order_views.xml',
+ 'views/product_views.xml'
+ ],
+}
diff --git a/odex25_donation/p_donation_theme/data/sms_data.xml b/odex25_donation/ensan_sale_management/data/sms_data.xml
similarity index 61%
rename from odex25_donation/p_donation_theme/data/sms_data.xml
rename to odex25_donation/ensan_sale_management/data/sms_data.xml
index b176d1849..e585f45ca 100644
--- a/odex25_donation/p_donation_theme/data/sms_data.xml
+++ b/odex25_donation/ensan_sale_management/data/sms_data.xml
@@ -9,10 +9,9 @@
Donation on Behalf Confirmed
-
+
ar
بكل الود أهديك تبرع عبر منصة إنسان لمشروع: {{object.product_id.name}} من : {{object.sale_id.order_name}}
-
\ No newline at end of file
diff --git a/odex25_donation/ensan_sale_management/models/__init__.py b/odex25_donation/ensan_sale_management/models/__init__.py
new file mode 100644
index 000000000..bd901bd44
--- /dev/null
+++ b/odex25_donation/ensan_sale_management/models/__init__.py
@@ -0,0 +1,2 @@
+from . import sale_order
+from . import product
diff --git a/odex25_donation/p_donation_theme/models/product.py b/odex25_donation/ensan_sale_management/models/product.py
similarity index 100%
rename from odex25_donation/p_donation_theme/models/product.py
rename to odex25_donation/ensan_sale_management/models/product.py
diff --git a/odex25_donation/p_donation_theme/models/sale.py b/odex25_donation/ensan_sale_management/models/sale_order.py
similarity index 93%
rename from odex25_donation/p_donation_theme/models/sale.py
rename to odex25_donation/ensan_sale_management/models/sale_order.py
index f84577588..bd52ab54f 100644
--- a/odex25_donation/p_donation_theme/models/sale.py
+++ b/odex25_donation/ensan_sale_management/models/sale_order.py
@@ -4,6 +4,7 @@ from odoo.tools.json import scriptsafe as json_scriptsafe
class SaleOrder_Inherit(models.Model):
_inherit = 'sale.order'
+
done_with_quick_donation = fields.Boolean(default=False)
order_mobile_number = fields.Char("Donor Number")
order_name = fields.Char("Donor Name")
@@ -12,8 +13,7 @@ class SaleOrder_Inherit(models.Model):
def get_sale_order_portal_url(self):
for sale in self:
- sale.sale_order_portal_url = self.env['ir.config_parameter'].sudo().get_param(
- 'web.base.url') + sale.get_portal_url()
+ sale.sale_order_portal_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') + sale.get_portal_url()
def _cart_update(self, *args, **kwargs):
res = super(SaleOrder_Inherit, self)._cart_update(*args, **kwargs)
@@ -48,13 +48,13 @@ class SaleOrder_Inherit(models.Model):
if call_super == True:
for rec in self:
if rec.order_mobile_number:
- sms_template_id = self.env.ref('p_donation_theme.sms_template_data_donation')
+ sms_template_id = self.env.ref('ensan_sale_management.sms_template_data_donation')
rec._message_sms_with_template(
template=sms_template_id,
put_in_queue=False,
sms_numbers=[rec.order_mobile_number]
)
- donar_sms_template_id = self.env.ref('p_donation_theme.sms_template_donors_data_donation')
+ donar_sms_template_id = self.env.ref('ensan_sale_management.sms_template_donors_data_donation')
for donator in rec.donators_ids:
donator._message_sms_with_template(
template=donar_sms_template_id,
diff --git a/odex25_donation/ensan_sale_management/security/ir.model.access.csv b/odex25_donation/ensan_sale_management/security/ir.model.access.csv
new file mode 100644
index 000000000..c092a283f
--- /dev/null
+++ b/odex25_donation/ensan_sale_management/security/ir.model.access.csv
@@ -0,0 +1,2 @@
+id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
+access_sale_order_extra_donators,access.sale.order.extra_donators,model_sale_order_extra_donators,,1,1,1,1
\ No newline at end of file
diff --git a/odex25_donation/ensan_sale_management/views/product_views.xml b/odex25_donation/ensan_sale_management/views/product_views.xml
new file mode 100644
index 000000000..3ca172efd
--- /dev/null
+++ b/odex25_donation/ensan_sale_management/views/product_views.xml
@@ -0,0 +1,42 @@
+
+
+
+
+ product.template.form.inherit
+ product.template
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/odex25_donation/ensan_sale_management/views/sale_order_views.xml b/odex25_donation/ensan_sale_management/views/sale_order_views.xml
new file mode 100644
index 000000000..74e4eee97
--- /dev/null
+++ b/odex25_donation/ensan_sale_management/views/sale_order_views.xml
@@ -0,0 +1,29 @@
+
+
+
+
+ extrafield.sale.order.form.view
+ sale.order
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/odex25_donation/p_donation_theme/__init__.py b/odex25_donation/p_donation_theme/__init__.py
index 511a0ca3a..457bae27e 100644
--- a/odex25_donation/p_donation_theme/__init__.py
+++ b/odex25_donation/p_donation_theme/__init__.py
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
-from . import controllers
-from . import models
\ No newline at end of file
+from . import controllers
\ No newline at end of file
diff --git a/odex25_donation/p_donation_theme/__manifest__.py b/odex25_donation/p_donation_theme/__manifest__.py
index bf52f559f..75bd517ce 100644
--- a/odex25_donation/p_donation_theme/__manifest__.py
+++ b/odex25_donation/p_donation_theme/__manifest__.py
@@ -12,13 +12,17 @@
'license': 'LGPL-3',
'category': 'Uncategorized',
'version': '14.0.1',
- 'depends': ['base', 'website_sale', 'theme_prime', 'droggol_theme_common', 'payment_hyperpay', 'payment_applepay'],
+ 'depends': ['base',
+ 'website_sale',
+ 'theme_prime',
+ 'droggol_theme_common',
+ 'payment_hyperpay',
+ 'payment_applepay',
+ 'ensan_sale_management'],
'data': [
- 'security/ir.model.access.csv',
'views/templates.xml',
'views/views.xml',
- 'data/sms_data.xml'
],
'images': ['static/description/banner.png'],
}
diff --git a/odex25_donation/p_donation_theme/controllers/main.py b/odex25_donation/p_donation_theme/controllers/main.py
index 4b37cd21d..00dacdb7e 100644
--- a/odex25_donation/p_donation_theme/controllers/main.py
+++ b/odex25_donation/p_donation_theme/controllers/main.py
@@ -122,10 +122,10 @@ class WebsiteSaleExtended(WebsiteSale):
try:
if acquire_id:
payment_acquire_id = request.env['payment.acquirer'].sudo().search(
- [('code', 'in', ['hyperpay', 'applepay']), ('company_id', 'in', (False, order.company_id.id)), ('id', '=', int(acquire_id))], limit=1)
+ [('provider', '=', 'hyperpay'), ('company_id', 'in', (False, order.company_id.id)), ('id', '=', int(acquire_id))], limit=1)
else:
payment_acquire_id = request.env['payment.acquirer'].sudo().search(
- [('code', '=', 'hyperpay'), ('company_id', 'in', (False, order.company_id.id))], limit=1)
+ [('provider', '=', 'hyperpay'), ('company_id', 'in', (False, order.company_id.id))], limit=1)
# Create transaction
vals = {'acquirer_id': payment_acquire_id,
diff --git a/odex25_donation/p_donation_theme/models/__init__.py b/odex25_donation/p_donation_theme/models/__init__.py
deleted file mode 100644
index 114b41426..000000000
--- a/odex25_donation/p_donation_theme/models/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# -*- coding: utf-8 -*-
-
-from . import sale, product
\ No newline at end of file
diff --git a/odex25_donation/p_donation_theme/security/ir.model.access.csv b/odex25_donation/p_donation_theme/security/ir.model.access.csv
deleted file mode 100644
index f382e04fe..000000000
--- a/odex25_donation/p_donation_theme/security/ir.model.access.csv
+++ /dev/null
@@ -1,2 +0,0 @@
-id,name,model_id/id,group_id/id,perm_read,perm_write,perm_create,perm_unlink
-access_sale_order_extra_donators,access.sale.order.extra_donators,model_sale_order_extra_donators,,1,1,1,1
\ No newline at end of file
diff --git a/odex25_donation/p_donation_theme/views/views.xml b/odex25_donation/p_donation_theme/views/views.xml
index 6aedd93a5..17cc0da35 100644
--- a/odex25_donation/p_donation_theme/views/views.xml
+++ b/odex25_donation/p_donation_theme/views/views.xml
@@ -1,70 +1,6 @@
-
- product.template.form.inherit
- product.template
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- extrafield.sale.order.form.view
- sale.order
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/odex25_donation/payment_applepay/__manifest__.py b/odex25_donation/payment_applepay/__manifest__.py
index 3c8de5c3f..eecdd8396 100644
--- a/odex25_donation/payment_applepay/__manifest__.py
+++ b/odex25_donation/payment_applepay/__manifest__.py
@@ -14,12 +14,13 @@
'price': 79.99,
'currency': 'EUR',
'license': 'Other proprietary',
- 'depends': ['payment'],
+ 'depends': ['payment', 'website_sale', 'ensan_sale_management'],
'data': [
'views/payment_views.xml',
'views/payment_popup_template.xml',
'views/payment_applepay_templates.xml',
'data/payment_acquirer_data.xml',
+ 'views/applepay_iframe.xml',
],
'images': ['images/main_screenshot.gif'],
'installable': True,
diff --git a/odex25_donation/payment_applepay/controllers/main.py b/odex25_donation/payment_applepay/controllers/main.py
index 251eca97f..15630381a 100644
--- a/odex25_donation/payment_applepay/controllers/main.py
+++ b/odex25_donation/payment_applepay/controllers/main.py
@@ -1,77 +1,172 @@
-# -*- coding: utf-8 -*-
-# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
-# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
-
-import json
-import logging
-import pprint
-
-import requests
-import werkzeug
-from werkzeug import urls
-
-from odoo import http, _
-from odoo.addons.payment.models.payment_provider import ValidationError
-from odoo.http import request
-from odoo.exceptions import UserError, Warning
-
-_logger = logging.getLogger(__name__)
-
-
-class ApplepayController(http.Controller):
-
- @http.route('/payment/applepay/return', type='http', auth='public', csrf=False)
- def applepay_return(self, **post):
- """ applepay."""
- acquirer = request.env['payment.provider'].sudo().search([('code', '=', 'applepay')], limit=1)
- _logger.info("acquirer......applepay%s" % (acquirer.state))
- _logger.info("Post Return = %s" % (post))
- if post.get('resourcePath'):
- if acquirer.state == 'test':
- url = "https://eu-test.oppwa.com"
- else:
- url = "https://eu-prod.oppwa.com"
- url += post.get('resourcePath')
- url += '?entityId=' + acquirer.applepay_entity_id
- authorization_bearer = "Bearer " + acquirer.applepay_authorization_bearer
- _logger.info("Url = %s",url)
- _logger.info("Headers = %s",authorization_bearer)
- try:
- headers = {'Authorization': authorization_bearer}
-
- response = requests.get(
- url,
- headers=headers,
- )
- response = json.loads(response.text)
- except Exception as e:
- raise UserError(_(e))
- _logger.info(
- 'applepay: entering form_feedback with post data %s', pprint.pformat(post))
- _logger.info("Response = %s",response)
- payment = request.env['payment.transaction'].sudo()
- tx_id = payment.search([('applepay_checkout_id', '=', post.get('id',''))])
- #tx_sudo = request.env['payment.transaction'].sudo().
- #response.update({'tx_id': tx})
- _logger.info("Tx Sudo = %s",tx_id)
- tx = response.get('customParameters',{}).get('SHOPPER_tx_id') or tx_id or ''
- response.update({'tx_id': tx})
- #tx = response.get('customParameters',{}).get('SHOPPER_tx_id') or tx_sudo and tx_sudo.id or ''
- #response.update({'tx_id': tx})
-
- tx._handle_notification_data('applepay', response)
- return werkzeug.utils.redirect(f'/payment/status')
-
- @http.route('/shop/applepay/payment/', type='http', auth="none", methods=['POST'], csrf=False)
- def _payment_applepay_card(self, **kw):
- acquirer = request.env['payment.provider'].sudo().search([('code', '=', 'applepay')], limit=1)
-
- kw['currency'] = 'SAR'
- _logger.info("Post Values From Apple Payment = %s",kw)
-
- if acquirer.state == 'test':
- return request.render("payment_applepay.payment_applepay_card",
- {'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
- else:
- return request.render("payment_applepay.payment_applepay_card_live",
- {'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
+# -*- coding: utf-8 -*-
+# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
+# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
+
+import json
+import logging
+import pprint
+
+import requests
+from odoo import http, _
+from odoo.addons.payment.controllers.portal import PaymentProcessing
+from odoo.http import request
+from odoo.exceptions import UserError
+
+_logger = logging.getLogger(__name__)
+
+
+class ApplepayController(http.Controller):
+
+ def check_mobile_number_validation(self, phone):
+ if phone[0] == '+' and phone[1] != '0':
+ if phone[1:4] == '966':
+ if len(phone[4:]) >= 8:
+ return phone.replace('+', '')
+ else:
+ phone = phone[0] + '966' + phone[1:]
+ elif phone[0] == '+' and phone[1] == '0':
+ phone = phone[0] + '966' + phone[2:]
+ elif phone[0] == '0' and phone[1] == '5':
+ phone = '+966' + phone[1:]
+ elif phone[0:2] == '00': # 00966555555555
+ if phone[2:5] == '966':
+ phone = '+' + '966' + phone[5:]
+ elif phone[0] == '0': # 0966555555555
+ if phone[1:4] == '966':
+ phone = '+' + '966' + phone[4:]
+ else:
+ if phone[0:3] == '966':
+ phone = '+' + phone
+ else:
+ phone = '+' + '966' + phone
+ return phone.replace('+', '')
+
+ @http.route('/payment/applepay/return', type='http', auth='public', csrf=False)
+ def applepay_return(self, **post):
+ """ applepay."""
+ acquirer = request.env['payment.acquirer'].sudo().search([('provider', '=', 'applepay')], limit=1)
+ _logger.info("Post Return = %s" % (post))
+ if post.get('resourcePath'):
+ if acquirer.state == 'test':
+ url = "https://eu-test.oppwa.com"
+ else:
+ url = "https://oppwa.com"
+ url += post.get('resourcePath')
+ url += '?entityId=' + acquirer.applepay_entity_id
+ authorization_bearer = "Bearer " + acquirer.applepay_authorization_bearer
+ _logger.info("Url = %s", url)
+ _logger.info("Headers = %s", authorization_bearer)
+ try:
+ headers = {'Authorization': authorization_bearer}
+ response = requests.get(url, headers=headers)
+ response = json.loads(response.text)
+ except Exception as e:
+ raise UserError(_(e))
+ _logger.info('applepay: entering form_feedback with post data %s', pprint.pformat(post))
+ _logger.info("Response = %s", response)
+ phone = response.get('customer', {}).get('phone', '')
+ phone = self.check_mobile_number_validation(phone)
+ payment = request.env['payment.transaction'].sudo()
+ tx_id = payment.search([('applepay_checkout_id', '=', post.get('id', ''))])
+ tx_id.sale_order_ids.sudo().write({'order_mobile_number': phone})
+ _logger.info("Tx Sudo = %s", tx_id)
+ tx = response.get('customParameters', {}).get('SHOPPER_tx_id') or tx_id or ''
+ response.update({'tx_id': tx})
+ ids = tx_id.sale_order_ids.sudo().ids
+ request.session['sale_last_order_id'] = ids[0] if len(ids) else None
+ request.env['payment.transaction'].sudo().form_feedback(response, "applepay")
+ return request.redirect('/payment/process')
+
+ @http.route('/shop/applepay/payment/', type='http', auth="none", methods=['POST'], csrf=False)
+ def _payment_applepay_card(self, **kw):
+ acquirer = request.env['payment.acquirer'].sudo().search([('provider', '=', 'applepay')], limit=1)
+
+ kw['currency'] = 'SAR'
+ _logger.info("Post Values From Apple Payment = %s", kw)
+
+ if acquirer.state == 'test':
+ return request.render("payment_applepay.payment_applepay_card",
+ {'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
+ else:
+ return request.render("payment_applepay.payment_applepay_card_live",
+ {'check_out_id': kw.get('check_out_id'), 'return_url': kw.get('applepay_return')})
+
+
+ @http.route('/applepay', type='http', auth='public', website=True, csrf=False)
+ def apple_pay_iframe(self, **kwargs):
+ response = request.render("payment_applepay.apple_pay_iframe")
+ response.headers['Content-Security-Policy'] = "script-src blob: 'self' 'unsafe-inline' 'unsafe-eval' https://*; worker-src blob: 'self' 'unsafe-inline' 'unsafe-eval' https://*;connect-src 'self' https://* wss://*;frame-src 'self' blob: https://*;"
+ return response
+
+ @http.route('/applepay/checkout', type='json', auth='public', website=True)
+ def apple_pay_create_checkout(self, **post):
+ data = json.loads(request.httprequest.data.decode('utf-8'))
+ checkout_id = self._apple_pay_create_checkout(data)
+ return {'checkout_id': checkout_id}
+
+ def _apple_pay_create_checkout(self, data):
+ try:
+ order = request.website.sale_get_order(force_create=True)
+ product_ids = data.get('product_ids', [])
+ gifts = data.get('gifts', [])
+ use_current_order = data.get('use_current_order', False)
+
+ if not order:
+ return ''
+
+ if not use_current_order:
+
+ order_mobile_number = data.get('mobile', '')
+ order_name = data.get('name', '')
+
+ extra_donators_ids = [(0, 0, {
+ 'sale_id': order.id,
+ 'product_id': gift.get('product_id'),
+ 'donated_amount': gift.get('amount'),
+ 'donator_name': gift.get('receiver_name'),
+ 'donator_mobile_number': gift.get('receiver_mobile')
+ }) for gift in gifts if gift.get('product_id')]
+
+ order_line = [(0, 0, {
+ 'product_id': product.get('id'),
+ 'extra_donators_ids': extra_donators_ids,
+ 'product_uom_qty': product.get('quantity', 1),
+ 'price_unit': product.get('price_unit', 0) + sum(gift.get('amount', 0) for gift in gifts if gift.get('product_id') == product.get('id'))}) for product in product_ids if product.get('id')]
+
+ if order_line:
+ order.order_line.sudo().unlink()
+ order.write({
+ 'order_line': order_line,
+ 'order_mobile_number': order_mobile_number,
+ 'order_name': order_name
+ })
+
+ payment_acquire_id = request.env['payment.acquirer'].sudo().search([('provider', '=', 'applepay'),
+ ('company_id', 'in', (False, order.company_id.id))], limit=1)
+
+ # Create transaction
+ vals = {'acquirer_id': payment_acquire_id.id,
+ 'return_url': '/payment/applepay/return'}
+
+ tx = order._create_payment_transaction(vals)
+
+ # store the new transaction into the transaction list and if there's an old one, we remove it
+ # until the day the ecommerce supports multiple orders at the same time
+ last_tx_id = request.session.get('__website_sale_last_tx_id')
+ last_tx = request.env['payment.transaction'].browse(last_tx_id).sudo().exists()
+ if last_tx:
+ PaymentProcessing.remove_payment_transaction(last_tx)
+ PaymentProcessing.add_payment_transaction(tx)
+ request.session['__website_sale_last_tx_id'] = tx.id
+
+ vals = {'partner_id': tx.partner_id.id,
+ 'reference': tx.reference,
+ 'amount': tx.amount}
+
+ checkout_id = payment_acquire_id._get_authenticate_apple_pay(vals)
+ tx.sale_order_ids.sudo().write({'done_with_quick_donation': data.get('done_with_quick_donation', False)})
+
+ return checkout_id
+ except Exception as e:
+ _logger.error("Error in Apple pay Payment: %s" % (e))
+ return ''
diff --git a/odex25_donation/payment_applepay/data/payment_acquirer_data.xml b/odex25_donation/payment_applepay/data/payment_acquirer_data.xml
index eee41e03f..f0bac1d42 100644
--- a/odex25_donation/payment_applepay/data/payment_acquirer_data.xml
+++ b/odex25_donation/payment_applepay/data/payment_acquirer_data.xml
@@ -1,22 +1,16 @@
-
-
+
+
Applepay
-
- applepay
-
-
+
+ applepay
+
You will be redirected to the applepay payment form after clicking on the payment button.
]]>
dummy
dummy
-
- Applepay
- applepay
- inbound
-
+
diff --git a/odex25_donation/payment_applepay/models/__init__.py b/odex25_donation/payment_applepay/models/__init__.py
index 817d0e5d4..9fdd9ae5b 100644
--- a/odex25_donation/payment_applepay/models/__init__.py
+++ b/odex25_donation/payment_applepay/models/__init__.py
@@ -4,4 +4,3 @@
from . import payment
from . import payment_transaction
-from . import account_payment_method
diff --git a/odex25_donation/payment_applepay/models/account_payment_method.py b/odex25_donation/payment_applepay/models/account_payment_method.py
deleted file mode 100644
index 4843301aa..000000000
--- a/odex25_donation/payment_applepay/models/account_payment_method.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# -*- coding: utf-8 -*-
-# Part of Odoo. See LICENSE file for full copyright and licensing details.
-
-from odoo import api, models
-
-
-class AccountPaymentMethod(models.Model):
- _inherit = 'account.payment.method'
-
- @api.model
- def _get_payment_method_information(self):
- res = super()._get_payment_method_information()
- res['applepay'] = {'mode': 'unique', 'domain': [('type', '=', 'bank')]}
- return res
diff --git a/odex25_donation/payment_applepay/models/payment copy.py b/odex25_donation/payment_applepay/models/payment copy.py
deleted file mode 100644
index c3262b66a..000000000
--- a/odex25_donation/payment_applepay/models/payment copy.py
+++ /dev/null
@@ -1,126 +0,0 @@
-# -*- coding: utf-8 -*-
-# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
-# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
-
-import json
-import re
-import logging
-from odoo.exceptions import UserError
-
-from urllib.parse import urljoin
-from odoo import api, fields, models, _
-from odoo.addons.payment.models.payment_provider import ValidationError
-import requests
-
-from odoo.http import request
-
-_logger = logging.getLogger(__name__)
-
-
-class AcquirerApplepay(models.Model):
- _inherit = 'payment.provider'
-
- code = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
-
- applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay',
- groups='base.group_user')
- applepay_authorization_bearer = fields.Char(
- string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
-
- @api.model
- def _get_authorize_urls(self):
- base_url = self.get_base_url()
- """ ApplePay URLS """
- return base_url + 'shop/applepay/payment/'
-
- def _partner_split_name(self, partner_name):
- return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
-
- def _get_authenticate_apple_pay(self, values):
- url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://eu-prod.oppwa.com/v1/checkouts"
- authorization_bearer = "Bearer " + self.applepay_authorization_bearer
- currency = self.env['res.currency'].browse(values['currency_id'])
- partner = self.env['res.partner'].browse(values['partner_id'])
- last_name = self._partner_split_name(partner.name)[1]
- _logger.info(">>%s" % (authorization_bearer))
- data = {
- 'entityId': self.applepay_entity_id,
- 'amount': str(format(values['amount'], '.2f')),
- 'currency': 'SAR',
- 'paymentType': 'DB',
- 'merchantTransactionId': values.get('reference'),
- 'customer.email': partner.email,
- 'customer.givenName': partner.name,
- 'customer.companyName': partner.company_id.name,
- 'customer.phone': partner.phone,
- 'billing.street1': partner.street,
- 'billing.state': partner.state_id.name,
- 'billing.country': partner.country_id.code,
- 'billing.postcode': partner.zip,
- 'customer.surname': last_name
-
- }
- try:
- headers = {'Authorization': authorization_bearer}
- response = requests.post(
- url,
- headers=headers,
- data=data
- )
- response = json.loads(response.text)
- _logger.info("Info From Authorization = %s " % (response))
- return response.get('id')
- except Exception as e:
- raise UserError(_(e))
-
- def applepay_form_generate_values(self, values):
- currency = self.env['res.currency'].browse(values['currency_id'])
- base_url = self.get_base_url()
- check_out_id = self._get_authenticate_apple_pay(values)
- _logger.info(">>%s" % (self.applepay_authorization_bearer))
- authorization_bearer = "Bearer " + self.applepay_authorization_bearer
- applepay_tx_values = dict(values)
- applepay_tx_values.update({
- 'entityId': self.applepay_entity_id,
- 'check_out_id': check_out_id,
- 'Authorization': authorization_bearer,
- 'amount': str(format(values['amount'], '.2f')),
- 'currency': currency.id and currency.name or '',
- 'paymentBrand': 'APPLEPAY',
- 'paymentType': 'DB',
- 'merchantTransactionId': values.get('reference'),
- 'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
- 'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
- 'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
- 'return_url') else False,
- })
- return applepay_tx_values
- #New method added to core
- def _get_default_payment_method_id(self,code):
- provider_method_id = self._get_provider_payment_method(code)
- if provider_method_id:
- return provider_method_id.id
- return self.env.ref('payment_applepay.payment_method_applepay').id
-
- #def _get_default_payment_method_id(self):
- # self.ensure_one()
- # if self.provider != 'applepay':
- # return super()._get_default_payment_method_id()
- # return self.env.ref('payment_applepay.payment_method_applepay').id
-
- def applepay_get_form_action_url(self):
- self.ensure_one()
- environment = 'prod' if self.state == 'enabled' else 'test'
- return self._get_authorize_urls_apple_pay(environment)['url']
-
- @api.model
- def _get_compatible_providers(self, *args, currency_id=None, **kwargs):
- """ Override of payment to unlist PayPal providers when the currency is not supported. """
- providers = super()._get_compatible_providers(*args, currency_id=currency_id, **kwargs)
-
- currency = self.env['res.currency'].browse(currency_id).exists()
- #if currency and currency.name:
-
- # providers = providers.filtered(lambda p: p.code != 'applepay')
-
- return providers
\ No newline at end of file
diff --git a/odex25_donation/payment_applepay/models/payment.py b/odex25_donation/payment_applepay/models/payment.py
index add388870..cd6282f68 100644
--- a/odex25_donation/payment_applepay/models/payment.py
+++ b/odex25_donation/payment_applepay/models/payment.py
@@ -1,139 +1,109 @@
-# -*- coding: utf-8 -*-
-# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
-# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
-
-import json
-import re
-import logging
-import random
-from odoo.exceptions import UserError
-
-from urllib.parse import urljoin
-from odoo import api, fields, models, _
-from odoo.addons.payment.models.payment_provider import ValidationError
-import requests
-
-from odoo.http import request
-
-_logger = logging.getLogger(__name__)
-
-
-class AcquirerApplepay(models.Model):
- _inherit = 'payment.provider'
-
- code = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
-
- applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay',
- groups='base.group_user')
- applepay_authorization_bearer = fields.Char(
- string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
-
- @api.model
- def _get_authorize_urls(self):
- base_url = self.get_base_url()
- """ ApplePay URLS """
- return base_url + 'shop/applepay/payment/'
-
- def _partner_split_name(self, partner_name):
- if partner_name:
- return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
- else:
- return ['', '']
-
- def _get_authenticate_apple_pay(self, values):
- url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://eu-prod.oppwa.com/v1/checkouts"
- authorization_bearer = "Bearer " + self.applepay_authorization_bearer
- # currency = self.env['res.currency'].browse(values['currency_id'])
- partner = self.env['res.partner'].sudo().browse(values['partner_id']).sudo()
- order_no = values.get('reference', '').split('-', 1)
- partner_name = partner.name or ''
- partner_mobile = partner.mobile or ''
- if order_no:
- order_id = request.env['sale.order'].sudo().search([('name', '=', order_no[0])], limit=1).sudo()
- if order_id:
- partner_mobile = order_id.order_mobile_number
- partner_name = order_id.order_name
- last_name = self._partner_split_name(partner_name)[-1] if partner_name else ''
- _logger.info(">>%s" % (authorization_bearer))
-
- data = {
- 'entityId': self.applepay_entity_id,
- 'amount': str(format(values['amount'], '.2f')),
- 'currency': 'SAR',
- 'paymentType': 'DB',
- 'merchantTransactionId': values.get('reference'),
- 'customer.email': '{seq}@ensan.sa'.format(seq=random.randint(0,10000)),
- 'customer.givenName': partner_name or 'guest',
- 'customer.companyName': partner.company_id.name,
- 'customer.phone': partner_mobile,
- 'billing.street1': partner.street or 'Riyadh',
- 'billing.state': partner.state_id.name or 'Riyadh',
- 'billing.country': partner.country_id.code or 'SA',
- 'billing.postcode': partner.zip,
- 'customer.surname': last_name or 'guest'
-
- }
- try:
- headers = {'Authorization': authorization_bearer}
- response = requests.post(
- url,
- headers=headers,
- data=data
- )
- response = json.loads(response.text)
- _logger.info("Info From Authorization = %s ",response)
- return response.get('id')
- except Exception as e:
- raise UserError(_(e))
-
- def applepay_form_generate_values(self, values):
- currency = self.env['res.currency'].browse(values['currency_id'])
- base_url = self.get_base_url()
- check_out_id = self._get_authenticate_apple_pay(values)
- _logger.info(">>%s" % (self.applepay_authorization_bearer))
- authorization_bearer = "Bearer " + self.applepay_authorization_bearer
- applepay_tx_values = dict(values)
- applepay_tx_values.update({
- 'entityId': self.applepay_entity_id,
- 'check_out_id': check_out_id,
- 'Authorization': authorization_bearer,
- 'amount': str(format(values['amount'], '.2f')),
- 'currency': currency.id and currency.name or '',
- 'paymentBrand': 'APPLEPAY',
- 'paymentType': 'DB',
- 'merchantTransactionId': values.get('reference'),
- 'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
- 'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
- 'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
- 'return_url') else False,
- })
- return applepay_tx_values
- #New method added to core
- def _get_default_payment_method_id(self,code):
- provider_method_id = self._get_provider_payment_method(code)
- if provider_method_id:
- return provider_method_id.id
- return self.env.ref('payment_applepay.payment_method_applepay').id
-
- #def _get_default_payment_method_id(self):
- # self.ensure_one()
- # if self.provider != 'applepay':
- # return super()._get_default_payment_method_id()
- # return self.env.ref('payment_applepay.payment_method_applepay').id
-
- def applepay_get_form_action_url(self):
- self.ensure_one()
- environment = 'prod' if self.state == 'enabled' else 'test'
- return self._get_authorize_urls_apple_pay(environment)['url']
-
- @api.model
- def _get_compatible_providers(self, *args, currency_id=None, **kwargs):
- """ Override of payment to unlist PayPal providers when the currency is not supported. """
- providers = super()._get_compatible_providers(*args, currency_id=currency_id, **kwargs)
-
- currency = self.env['res.currency'].browse(currency_id).exists()
- #if currency and currency.name:
-
- # providers = providers.filtered(lambda p: p.code != 'applepay')
-
- return providers
+# -*- coding: utf-8 -*-
+# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
+# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
+
+import json
+import logging
+import random
+from urllib.parse import urljoin
+import requests
+
+from odoo.exceptions import UserError
+from odoo import api, fields, models, _
+from odoo.http import request
+
+_logger = logging.getLogger(__name__)
+
+
+class AcquirerApplepay(models.Model):
+ _inherit = 'payment.acquirer'
+
+ provider = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
+ applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay', groups='base.group_user')
+ applepay_authorization_bearer = fields.Char(string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
+
+ def _partner_split_name(self, partner_name):
+ if partner_name:
+ return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
+ else:
+ return ['', '']
+
+ def _get_authenticate_apple_pay(self, values):
+ url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://oppwa.com/v1/checkouts"
+ authorization_bearer = "Bearer " + self.applepay_authorization_bearer
+ partner = self.env['res.partner'].sudo().browse(values['partner_id']).sudo()
+ order_no = values.get('reference', '').split('-', 1)
+ partner_name = partner.name or ''
+ partner_mobile = partner.mobile or ''
+ if order_no:
+ order_id = request.env['sale.order'].sudo().search([('name', '=', order_no[0])], limit=1).sudo()
+ if order_id:
+ partner_mobile = order_id.order_mobile_number
+ partner_name = order_id.order_name
+ last_name = self._partner_split_name(partner_name)[-1] if partner_name else ''
+ _logger.info(">>%s" % (authorization_bearer))
+
+ data = {
+ 'entityId': self.applepay_entity_id,
+ 'amount': str(format(values['amount'], '.2f')),
+ 'currency': 'SAR',
+ 'paymentType': 'DB',
+ 'merchantTransactionId': values.get('reference'),
+ 'customer.email': '{seq}@ensan.sa'.format(seq=random.randint(0, 10000)),
+ 'customer.givenName': partner_name or 'guest',
+ 'customer.companyName': partner.company_id.name,
+ 'billing.street1': partner.street or 'Riyadh',
+ 'billing.state': partner.state_id.name or 'Riyadh',
+ 'billing.country': partner.country_id.code or 'SA',
+ 'billing.postcode': partner.zip,
+ 'customer.surname': last_name or 'guest'
+
+ }
+ try:
+ headers = {'Authorization': authorization_bearer}
+ response = requests.post(
+ url,
+ headers=headers,
+ data=data
+ )
+ response = json.loads(response.text)
+ _logger.info("Info From Authorization = %s ", response)
+ return response.get('id')
+ except Exception as e:
+ raise UserError(_(e))
+
+ def applepay_form_generate_values(self, values):
+ currency = self.env['res.currency'].browse(values['currency_id'])
+ base_url = self.get_base_url()
+ check_out_id = self._get_authenticate_apple_pay(values)
+ _logger.info(">>%s" % (self.applepay_authorization_bearer))
+ authorization_bearer = "Bearer " + self.applepay_authorization_bearer
+ applepay_tx_values = dict(values)
+ applepay_tx_values.update({
+ 'entityId': self.applepay_entity_id,
+ 'check_out_id': check_out_id,
+ 'Authorization': authorization_bearer,
+ 'amount': str(format(values['amount'], '.2f')),
+ 'currency': currency.id and currency.name or '',
+ 'paymentBrand': 'APPLEPAY',
+ 'paymentType': 'DB',
+ 'merchantTransactionId': values.get('reference'),
+ 'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
+ 'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
+ 'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
+ 'return_url') else False,
+ })
+ return applepay_tx_values
+
+ @api.model
+ def _get_authorize_urls_apple_pay(self, environment):
+ """ applepay URLS """
+ if environment == 'prod':
+ return {'applepay_form_url': 'https://oppwa.com/v1/checkouts'}
+ else:
+ return {'applepay_form_url': 'https://test.oppwa.com/v1/checkouts'}
+
+ def applepay_get_form_action_url(self):
+ self.ensure_one()
+ environment = 'prod' if self.state == 'enabled' else 'test'
+ return self._get_authorize_urls_apple_pay(environment)['applepay_form_url']
diff --git a/odex25_donation/payment_applepay/models/payment_before_email_patch.py b/odex25_donation/payment_applepay/models/payment_before_email_patch.py
deleted file mode 100644
index fbc5efbe4..000000000
--- a/odex25_donation/payment_applepay/models/payment_before_email_patch.py
+++ /dev/null
@@ -1,138 +0,0 @@
-# -*- coding: utf-8 -*-
-# This module and its content is copyright of Technaureus Info Solutions Pvt. Ltd.
-# - © Technaureus Info Solutions Pvt. Ltd 2020. All rights reserved.
-
-import json
-import re
-import logging
-from odoo.exceptions import UserError
-
-from urllib.parse import urljoin
-from odoo import api, fields, models, _
-from odoo.addons.payment.models.payment_provider import ValidationError
-import requests
-
-from odoo.http import request
-
-_logger = logging.getLogger(__name__)
-
-
-class AcquirerApplepay(models.Model):
- _inherit = 'payment.provider'
-
- code = fields.Selection(selection_add=[('applepay', 'applepay')], ondelete={'applepay': 'set default'})
-
- applepay_entity_id = fields.Char(string='Merchant ID/Entity Id', required_if_provider='applepay',
- groups='base.group_user')
- applepay_authorization_bearer = fields.Char(
- string='Authorization Bearer', required_if_provider='applepay', groups='base.group_user')
-
- @api.model
- def _get_authorize_urls(self):
- base_url = self.get_base_url()
- """ ApplePay URLS """
- return base_url + 'shop/applepay/payment/'
-
- def _partner_split_name(self, partner_name):
- if partner_name:
- return [' '.join(partner_name.split()[:-1]), ' '.join(partner_name.split()[-1:])]
- else:
- return ['', '']
-
- def _get_authenticate_apple_pay(self, values):
- url = "https://eu-test.oppwa.com/v1/checkouts" if self.state == 'test' else "https://eu-prod.oppwa.com/v1/checkouts"
- authorization_bearer = "Bearer " + self.applepay_authorization_bearer
- # currency = self.env['res.currency'].browse(values['currency_id'])
- partner = self.env['res.partner'].sudo().browse(values['partner_id']).sudo()
- order_no = values.get('reference', '').split('-', 1)
- partner_name = partner.name or ''
- partner_mobile = partner.mobile or ''
- if order_no:
- order_id = request.env['sale.order'].sudo().search([('name', '=', order_no[0])], limit=1).sudo()
- if order_id:
- partner_mobile = order_id.order_mobile_number
- partner_name = order_id.order_name
- last_name = self._partner_split_name(partner_name)[-1] if partner_name else ''
- _logger.info(">>%s" % (authorization_bearer))
-
- data = {
- 'entityId': self.applepay_entity_id,
- 'amount': str(format(values['amount'], '.2f')),
- 'currency': 'SAR',
- 'paymentType': 'DB',
- 'merchantTransactionId': values.get('reference'),
- 'customer.email': partner.email,
- 'customer.givenName': partner_name or 'guest',
- 'customer.companyName': partner.company_id.name,
- 'customer.phone': partner_mobile,
- 'billing.street1': partner.street or 'Riyadh',
- 'billing.state': partner.state_id.name or 'Riyadh',
- 'billing.country': partner.country_id.code or 'SA',
- 'billing.postcode': partner.zip,
- 'customer.surname': last_name or 'guest'
-
- }
- try:
- headers = {'Authorization': authorization_bearer}
- response = requests.post(
- url,
- headers=headers,
- data=data
- )
- response = json.loads(response.text)
- _logger.info("Info From Authorization = %s ",response)
- return response.get('id')
- except Exception as e:
- raise UserError(_(e))
-
- def applepay_form_generate_values(self, values):
- currency = self.env['res.currency'].browse(values['currency_id'])
- base_url = self.get_base_url()
- check_out_id = self._get_authenticate_apple_pay(values)
- _logger.info(">>%s" % (self.applepay_authorization_bearer))
- authorization_bearer = "Bearer " + self.applepay_authorization_bearer
- applepay_tx_values = dict(values)
- applepay_tx_values.update({
- 'entityId': self.applepay_entity_id,
- 'check_out_id': check_out_id,
- 'Authorization': authorization_bearer,
- 'amount': str(format(values['amount'], '.2f')),
- 'currency': currency.id and currency.name or '',
- 'paymentBrand': 'APPLEPAY',
- 'paymentType': 'DB',
- 'merchantTransactionId': values.get('reference'),
- 'shopperResultUrl': '%s' % urljoin(base_url, '/shop/applepay/payment/'),
- 'applepay_return': '%s' % urljoin(base_url, '/payment/applepay/return'),
- 'custom': json.dumps({'return_url': '%s' % applepay_tx_values.pop('return_url')}) if applepay_tx_values.get(
- 'return_url') else False,
- })
- return applepay_tx_values
- #New method added to core
- def _get_default_payment_method_id(self,code):
- provider_method_id = self._get_provider_payment_method(code)
- if provider_method_id:
- return provider_method_id.id
- return self.env.ref('payment_applepay.payment_method_applepay').id
-
- #def _get_default_payment_method_id(self):
- # self.ensure_one()
- # if self.provider != 'applepay':
- # return super()._get_default_payment_method_id()
- # return self.env.ref('payment_applepay.payment_method_applepay').id
-
- def applepay_get_form_action_url(self):
- self.ensure_one()
- environment = 'prod' if self.state == 'enabled' else 'test'
- return self._get_authorize_urls_apple_pay(environment)['url']
-
- @api.model
- def _get_compatible_providers(self, *args, currency_id=None, **kwargs):
- """ Override of payment to unlist PayPal providers when the currency is not supported. """
- providers = super()._get_compatible_providers(*args, currency_id=currency_id, **kwargs)
-
- currency = self.env['res.currency'].browse(currency_id).exists()
- #if currency and currency.name:
-
- # providers = providers.filtered(lambda p: p.code != 'applepay')
-
- return providers
\ No newline at end of file
diff --git a/odex25_donation/payment_applepay/models/payment_transaction.py b/odex25_donation/payment_applepay/models/payment_transaction.py
index 2b4b6164d..038d48ffe 100644
--- a/odex25_donation/payment_applepay/models/payment_transaction.py
+++ b/odex25_donation/payment_applepay/models/payment_transaction.py
@@ -1,14 +1,9 @@
-# Part of Odoo. See LICENSE file for full copyright and licensing details.
-
import logging
-
-from werkzeug import urls
+import dateutil.parser
import re
-from odoo import _, api, models,fields
+import pytz
+from odoo import _, models,fields, api
from odoo.exceptions import ValidationError
-from odoo.tools.float_utils import float_compare
-
-from odoo.addons.payment_applepay.controllers.main import ApplepayController
_logger = logging.getLogger(__name__)
@@ -18,78 +13,54 @@ class PaymentTransaction(models.Model):
applepay_checkout_id = fields.Char('Checkout Id', groups='base.group_user', help='Unique checkout id for every applepay transasction')
- def _get_specific_rendering_values(self, processing_values):
- res = super()._get_specific_rendering_values(processing_values)
- if self.provider_code != 'applepay':
- return res
-
- base_url = self.provider_id.get_base_url()
- rendering_values = self.provider_id.applepay_form_generate_values(processing_values)
- tx = self.env['payment.transaction'].sudo().search([('reference', '=', self.reference)])
- tx.applepay_checkout_id = rendering_values.get('check_out_id')
- rendering_values.update({
- 'api_url': self.provider_id._get_authorize_urls(),
- "txId": tx.id,
- 'reference':self.reference
- })
- return rendering_values
-
-
- def _get_tx_from_notification_data(self, provider_code, notification_data):
- if provider_code != 'applepay':
- return tx
- _logger.info("Notification Data = %s",notification_data)
- reference = notification_data.get('ndc')
- tx_id = notification_data.get('tx_id')
- tx = tx_id and self.sudo().browse(int(tx_id))
- if not tx or len(tx) > 1:
- error_msg = _('received data for reference %s') % (pprint.pformat(reference))
- if not tx:
- error_msg += _('; no order found')
- else:
- error_msg += _('; multiple order found')
+ @api.model
+ def _applepay_form_get_tx_from_data(self, data):
+ reference, txn_id = data.get('ndc'), data.get('tx_id')
+ if not reference or not txn_id:
+ error_msg = _('ApplePay: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
_logger.info(error_msg)
raise ValidationError(error_msg)
- return tx
- def _process_notification_data(self, data):
- super()._process_notification_data(data)
- if self.provider_code != 'applepay':
- return
+ txs = self.env['payment.transaction'].search([('id', '=', int(txn_id))])
+ if not txs or len(txs) > 1:
+ error_msg = 'ApplePay: received data for reference %s' % (reference)
+ if not txs:
+ error_msg += '; no order found'
+ else:
+ error_msg += '; multiple order found'
+ _logger.info(error_msg)
+ raise ValidationError(error_msg)
+ return txs[0]
+ def _applepay_form_validate(self, data):
+ _logger.info('Validated ApplePay payment for tx %s: set as pending' % (self.reference))
+
+ result = data.get('result')
status_code = data.get('result').get('code')
+ res = {
+ 'acquirer_reference': data.get('id'),
+ 'state_message': result.get('description', '')
+ }
+
success_regex_1 = re.compile(r'000\.000\.|000\.100\.1|000\.[36]').search(status_code)
success_regex_2 = re.compile(r'000\.400\.0[^3]|000\.400\.100').search(status_code)
pending_regex_1 = re.compile(r'000\.200').search(status_code)
pending_regex_2 = re.compile(r'800\.400\.5|100\.400\.500').search(status_code)
error_regex_1 = re.compile(r'000\.100\.2').search(status_code)
+
+ _logger.info("Apple Pay Status Code = %s",status_code)
+
if success_regex_1 or success_regex_2:
- success_message = data.get('result').get('description') or 'success'
- logger_msg = _('applepay:' + success_message)
- _logger.info(logger_msg)
- self.write({
- 'provider_reference': data.get('id'),
- })
- self._set_done()
- return True
+ date_validate = dateutil.parser.parse(data.get('timestamp')).astimezone(pytz.utc).replace(tzinfo=None)
+ res.update(provider_reference=data.get('id'), date=date_validate)
+ self._set_transaction_done()
elif pending_regex_1 or pending_regex_2:
- pending_message = data.get('result').get('description') or 'pending'
- logger_msg = _('applepay:' + pending_message)
- _logger.info(logger_msg)
- self.write({'provider_reference': data.get('id')})
- self._set_pending()
- return True
+ self._set_transaction_pending()
elif error_regex_1:
- error_message = data.get('result').get('description') or 'error'
- error = _('applepay:' + error_message)
- _logger.info(error)
- self.write({'state_message': error})
- self._set_canceled()
- return False
+ self._set_transaction_error()
else:
- cancel_message = data.get('result').get('description') or 'cancel'
- logger_msg = _('applepay:' + cancel_message)
- _logger.info(logger_msg)
- self.write({'provider_reference': data.get('id')})
- self._set_canceled()
- return True
+ error = 'Received unrecognized status for ApplePay payment %s: %s, set as error' % (self.reference, status_code)
+ _logger.info(error)
+ self._set_transaction_cancel()
+ return self.write(res)
+
diff --git a/odex25_donation/payment_applepay/static/src/js/applepay_iframe.js b/odex25_donation/payment_applepay/static/src/js/applepay_iframe.js
new file mode 100644
index 000000000..b9f6db5d0
--- /dev/null
+++ b/odex25_donation/payment_applepay/static/src/js/applepay_iframe.js
@@ -0,0 +1,131 @@
+var wpwlOptions = {
+ applePay: {
+ version: 3,
+ displayName: "ENSAN",
+ total: { label: "ENSAN", amount: "10" },
+ checkAvailability: "applePayCapabilities",
+ currencyCode: "SAR",
+ supportedNetworks: ["mada","masterCard", "visa"],
+ merchantCapabilities: ["supports3DS", "supportsCredit", "supportsDebit"],
+ merchantIdentifier: "8ac9a4ca811e7d6f018132e7a3654ddf",
+ supportedCountries: ["SA"],
+ buttonSource: "css",
+ buttonStyle: "black",
+ buttonType: "pay",
+ countryCode: "SA",
+ submitOnPaymentAuthorized: ["customer"],
+ requiredShippingContactFields: ["phone"],
+ onCancel: function() {
+ if (window.wpwl && window.wpwl.checkout && window.wpwl.checkout.id) {
+ window.wpwl.checkout.id = "";
+ }
+ },
+
+ },
+ locale: "ar-AB",
+ onReady: function(){
+ const amounts = $('.donation-product-detail-layout .single-amount', window.parent.document);
+ const fixedQty = $('#fixedqtyinput-1', window.parent.document);
+ if (amounts.length > 0) {
+ window.wpwlOptions.applePay.total.amount = amounts.get(0).dataset.amount;
+ console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
+ } else if(fixedQty.length > 0){
+ window.wpwlOptions.applePay.total.amount = fixedQty.data('price');
+ console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
+ }
+ window.parent.document.addEventListener('applePayAmountUpdate', function(e) {
+ window.wpwlOptions.applePay.total.amount = e.detail.amount;
+ console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
+ });
+ let isCheckoutPage = $("#oe_structure_website_sale_payment_1", window.parent.document).length;
+ if (isCheckoutPage) {
+ let applepayButton = $('apple-pay-button');
+ let totalAmount = $("tr#order_total", window.parent.document).find("span.oe_currency_value").text().replaceAll(",", "");
+ window.wpwlOptions.applePay.total.amount = totalAmount;
+ console.log("Apple Pay Amount updated to:", window.wpwlOptions.applePay.total.amount);
+ applepayButton.css({
+ '--apple-pay-button-height': '60px',
+ '--apple-pay-button-border-radius': '4px',
+ '--apple-pay-button-padding': '15px 5px',
+ '--apple-pay-button-box-sizing': 'border-box'
+ });
+ }
+ },
+ createCheckout: function() {
+ let name = "";
+ let product_ids = gifts = [];
+ let done_with_quick_donation = false;
+ let use_current_order = false;
+
+ // product details screen
+ if ($(".js_product", window.parent.document).length) {
+ let hasGifts = $("#sendAsGiftCheckbox", window.parent.document).is(":checked");
+ let product_id = parseInt($('.js_product', window.parent.document).find('.product_id').val());
+ let amount = parseFloat($("input.personal-donation-amount", window.parent.document).val()) || 0;
+ let quantity = parseInt($($('#fixedqtyinput-1', window.parent.document).get(0)).val()) || 1;
+
+ product_ids = [{
+ id: product_id,
+ quantity: hasGifts ? 1 : quantity,
+ price_unit: hasGifts ? 0 : amount
+ }];
+
+ if (hasGifts) {
+ let $giftBoxElements = $(".gifteeBoxDetails", window.parent.document);
+ gifts = $giftBoxElements.map(function() {
+ let result = {};
+ result.product_id = product_id;
+ result.amount = parseFloat($(this).find('input.gift-donation-amount').val(), 10) || 0;
+ result.receiver_name = $(this).find('.input-gifteeName').val();
+ result.receiver_mobile = $(this).find('.input-gifteeNumber').val();
+ return result;
+ }).get();
+
+ }
+
+ }
+ // checkout page
+ else if ($("#oe_structure_website_sale_payment_1", window.parent.document).length) {
+ name = $("#order_name", window.parent.document).val();
+ let $productRows = $("table#cart_products tbody tr", window.parent.document);
+ product_ids = $productRows.map(function() {
+ let result = {};
+ result.id = parseInt($(this).data('product-id'));
+ result.quantity = parseInt($(this).find('td.td-qty').text().replaceAll(",", ""));
+ result.price_unit = parseFloat($(this).find('td.td-price span.oe_currency_value').text().replaceAll(",", ""));
+ return result;
+ }).get();
+ use_current_order = true;
+ }
+ // quick donation page
+ else {
+ done_with_quick_donation = true;
+ let amount = parseFloat($("#qd_amount", window.parent.document).val());
+ product_ids = [{
+ id: parseInt($("#qd-options li.active", window.parent.document).data('product_id')),
+ quantity: 1,
+ price_unit: amount
+ }];
+ }
+
+ let requestData = { product_ids: product_ids,
+ gifts: gifts,
+ name: name,
+ done_with_quick_donation: done_with_quick_donation,
+ use_current_order: use_current_order};
+
+ console.log(requestData);
+ const rootUrl = `${window.location.protocol}//${window.location.host}/`;
+ return $.ajax({
+ url: `${rootUrl}applepay/checkout`,
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify(requestData),
+ dataType: "json",
+ })
+ .then(function(response) {
+ console.log(response);
+ return response.result.checkout_id;
+ });
+ }
+}
\ No newline at end of file
diff --git a/odex25_donation/payment_applepay/static/src/scss/applepay_iframe_content.scss b/odex25_donation/payment_applepay/static/src/scss/applepay_iframe_content.scss
new file mode 100644
index 000000000..24c96e5c1
--- /dev/null
+++ b/odex25_donation/payment_applepay/static/src/scss/applepay_iframe_content.scss
@@ -0,0 +1,27 @@
+body {
+ max-width: 100%;
+}
+
+.wpwl-form {
+ max-width: 100%;
+}
+
+.wpwl-container {
+ max-width: 100%;
+}
+
+.wpwl-clearfix:after {
+ clear: none;
+}
+.wpwl-group {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 100%;
+}
+
+apple-pay-button {
+ width: 100%;
+ max-width: 100%;
+ height: auto;
+}
diff --git a/odex25_donation/payment_applepay/views/applepay_iframe.xml b/odex25_donation/payment_applepay/views/applepay_iframe.xml
new file mode 100644
index 000000000..e52437df0
--- /dev/null
+++ b/odex25_donation/payment_applepay/views/applepay_iframe.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/odex25_donation/payment_applepay/views/payment_applepay_templates.xml b/odex25_donation/payment_applepay/views/payment_applepay_templates.xml
index 4c07c8605..916cd5a38 100644
--- a/odex25_donation/payment_applepay/views/payment_applepay_templates.xml
+++ b/odex25_donation/payment_applepay/views/payment_applepay_templates.xml
@@ -49,7 +49,7 @@
-
+
diff --git a/odex25_donation/payment_applepay/views/payment_popup_template.xml b/odex25_donation/payment_applepay/views/payment_popup_template.xml
index ce29a318b..6cea85d88 100644
--- a/odex25_donation/payment_applepay/views/payment_popup_template.xml
+++ b/odex25_donation/payment_applepay/views/payment_popup_template.xml
@@ -65,7 +65,7 @@
APPLEPAY