diff --git a/payment_monero_rpc/LICENSE b/monero-rpc-odoo-pos/LICENSE similarity index 100% rename from payment_monero_rpc/LICENSE rename to monero-rpc-odoo-pos/LICENSE diff --git a/monero-rpc-odoo-pos/README.md b/monero-rpc-odoo-pos/README.md new file mode 100755 index 00000000..64941e0a --- /dev/null +++ b/monero-rpc-odoo-pos/README.md @@ -0,0 +1,69 @@ +Monero Odoo +========================= + + +[![Build Status](https://api.travis-ci.com/t-900-a/moneroodoo.svg?branch=main)](https://travis-ci.com/t-900-a/moneroodoo) +[![codecov](https://codecov.io/gh/t-900-a/moneroodoo/branch/main/graph/badge.svg?token=10S5GGNRHH)](https://codecov.io/gh/t-900-a/moneroodoo) + +Allows you to accept Monero as Payment within your Odoo Ecommerce shop + +Configuration +============= + +* Monero - This quickstart guide can guide you through the configuration of Monero specific +components. https://monero-python.readthedocs.io/en/latest/quickstart.html + * monerod + * https://www.getmonero.org/resources/moneropedia/daemon.html + * Download: https://www.getmonero.org/downloads/#cli + * monero-wallet-rpc + * Use a view-key on the server + * https://www.getmonero.org/resources/developer-guides/wallet-rpc.html + * Download: https://www.getmonero.org/downloads/#cli +* Odoo - Add-ons are installed by adding the specific module folder to the add-ons + directory (restart + required) + * queue-job + * https://github.com/OCA/queue + * monero-rpc-odoo-pos + * https://github.com/monero-integrations/moneroodoo + * The Monero payment acquirer is configured similar to other payment acquirers + * https://www.odoo.com/documentation/user/14.0/general/payment_acquirers/payment_acquirers.html#configuration + * Currency rate + * You will need to manually add currency rate for Monero + * https://www.odoo.com/documentation/user/14.0/accounting/others/multicurrencies/how_it_works.html + * Pricelist + * A pricelist should be created specifically for Monero + * https://www.odoo.com/documentation/user/14.0/website/publish/multi_website.html#pricelists + + + +Usage +===== + +* At Ecommerce checkout your customer's will be presented with the option to pay + with Monero + +Bug Tracker +=========== + +Bugs are tracked on [GitHub Issues](https://github.com/monero-integrations/moneroodoo/issues). +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us smashing it by providing a detailed and welcomed +[feedback](https://github.com/monero-integrations/moneroodoo/issues/new?body=module:%20monero-rpc-odoo%0Aversion:%14.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**)? + +Credits +======= + +Contributors + +* T-900 + +Maintainers + +This module is maintained by Monero-Integrations. +![Monero-Integrations](/monero-rpc-odoo/static/src/img/monero-integrations.png) + + +This module is part of the [monero-integrations/moneroodoo](https://github.com/monero-integrations/moneroodoo) project on GitHub. + +You are welcome to contribute. To learn how please visit the [Monero Taiga](https://taiga.getmonero.org/project/t-900-monero-x-odoo-integrations/). diff --git a/monero-rpc-odoo-pos/__init__.py b/monero-rpc-odoo-pos/__init__.py new file mode 100755 index 00000000..72d3ea60 --- /dev/null +++ b/monero-rpc-odoo-pos/__init__.py @@ -0,0 +1 @@ +from . import controllers, models diff --git a/monero-rpc-odoo-pos/__manifest__.py b/monero-rpc-odoo-pos/__manifest__.py new file mode 100755 index 00000000..37df2978 --- /dev/null +++ b/monero-rpc-odoo-pos/__manifest__.py @@ -0,0 +1,36 @@ +{ + "name": "monero-rpc-odoo-pos", + "summary": "Allows you to accept Monero Payments within Odoo Point Of Sale", + "author": "Monero Integrations", + "website": "https://monerointegrations.com/", + # Categories can be used to filter modules in modules listing + # for the full list + "category": "Accounting", + "version": "14.0.0.0.1", + # any module necessary for this one to work correctly + "depends": [ + "account", + "base_setup", + "web", + "queue_job", + "point_of_sale", + ], + "external_dependencies": {"python": ["monero"]}, + # always loaded + "data": [ + # "data/currency.xml", # not including as xmr may already be there + "data/monero_xmr_payment_method.xml", + "data/queue.xml", + "views/pos_payment_method_form.xml", + "views/pos_payment_method_views.xml", + "views/pos_payment_views.xml", + ], + # only loaded in demonstration mode + # TODO add demo data + "demo": [ + "demo/demo.xml", + ], + "installable": True, + "application": True, + "classifiers": ["License :: OSI Approved :: MIT License"], +} diff --git a/monero-rpc-odoo-pos/controllers/__init__.py b/monero-rpc-odoo-pos/controllers/__init__.py new file mode 100755 index 00000000..18a28d4d --- /dev/null +++ b/monero-rpc-odoo-pos/controllers/__init__.py @@ -0,0 +1 @@ +from . import monero_controller diff --git a/monero-rpc-odoo-pos/controllers/monero_controller.py b/monero-rpc-odoo-pos/controllers/monero_controller.py new file mode 100755 index 00000000..a7e67394 --- /dev/null +++ b/monero-rpc-odoo-pos/controllers/monero_controller.py @@ -0,0 +1,110 @@ +import logging + +from odoo.http import request +from odoo import http +from odoo.exceptions import ValidationError + +from monero.wallet import Wallet + +from monero.backends.jsonrpc import Unauthorized +from requests.exceptions import SSLError +from odoo.addons.queue_job.exception import RetryableJobError + + +class MoneroPaymentMethodRPCUnauthorized(Unauthorized): + pass + + +class MoneroPaymentMethodRPCSSLError(SSLError): + pass + + +class NoTXFound(RetryableJobError): + pass + + +class NumConfirmationsNotMet(RetryableJobError): + pass + + +class MoneroAddressReuse(Exception): + pass + + +_logger = logging.getLogger(__name__) + + +class MoneroController(http.Controller): + @http.route( + "/pos/monero/get_address", + type="json", + auth="public", + website=True, + methods=["POST"], + ) + def get_address(self, **kwargs): + """ + Function retrieves a Monero subaddress that will be used on the client side + Client side will display a qr code + Client side will pass subaddress via field "wallet_address" when + pos.order.create_from_ui is called + :param kwargs: payment_method_id + :return: wallet_address + """ + + payment_method = ( + request.env["pos.payment.method"] + .sudo() + .browse(int(kwargs.get("payment_method_id"))) + ) + + if payment_method is not None: + try: + wallet: Wallet = payment_method.get_wallet() + except MoneroPaymentMethodRPCUnauthorized: + _logger.error( + "USER IMPACT: Monero POS Payment Method " + "can't authenticate with RPC " + "due to user name or password" + ) + raise ValidationError( + "Current technical issues " + "prevent Monero from being accepted, " + "choose another payment method" + ) + except MoneroPaymentMethodRPCSSLError: + _logger.error( + "USER IMPACT: Monero POS Payment Method " + "experienced an SSL Error with RPC" + ) + raise ValidationError( + "Current technical issues " + "prevent Monero from being accepted, " + "choose another payment method" + ) + except Exception as e: + _logger.error( + f"USER IMPACT: Monero POS Payment Method " + f"experienced an Error with RPC: {e.__class__.__name__}" + ) + raise ValidationError( + "Current technical issues " + "prevent Monero from being accepted, " + "choose another payment method" + ) + + res = { + "wallet_address": wallet.new_address()[0], + } + else: + _logger.error( + "USER IMPACT: Monero POS Payment Method" + "experienced an Error with payment method: Not Found" + ) + raise ValidationError( + "Current technical issues " + "prevent Monero from being accepted, " + "choose another payment method" + ) + + return res diff --git a/monero-rpc-odoo-pos/data/currency.xml b/monero-rpc-odoo-pos/data/currency.xml new file mode 100755 index 00000000..106bedcb --- /dev/null +++ b/monero-rpc-odoo-pos/data/currency.xml @@ -0,0 +1,17 @@ + + + + + + XMR + Monero + Monero + ɱ + after + True + + 6 + 0.000001 + + + diff --git a/monero-rpc-odoo-pos/data/monero_xmr_payment_method.xml b/monero-rpc-odoo-pos/data/monero_xmr_payment_method.xml new file mode 100644 index 00000000..81b697cf --- /dev/null +++ b/monero-rpc-odoo-pos/data/monero_xmr_payment_method.xml @@ -0,0 +1,18 @@ + + + + + Monero RPC + monero-rpc + True + True + xmr + 0 + http + 127.0.0.1 + 18082 + user + password + + + diff --git a/monero-rpc-odoo-pos/data/queue.xml b/monero-rpc-odoo-pos/data/queue.xml new file mode 100644 index 00000000..4c3d7d58 --- /dev/null +++ b/monero-rpc-odoo-pos/data/queue.xml @@ -0,0 +1,26 @@ + + + + + monero_pos_zeroconf_processing + + + + + process_transaction + + + + + monero_pos_secure_processing + + + + + process_transaction + + + + + diff --git a/payment_monero_rpc/demo/demo.xml b/monero-rpc-odoo-pos/demo/demo.xml similarity index 100% rename from payment_monero_rpc/demo/demo.xml rename to monero-rpc-odoo-pos/demo/demo.xml diff --git a/monero-rpc-odoo-pos/models/__init__.py b/monero-rpc-odoo-pos/models/__init__.py new file mode 100755 index 00000000..921eaca9 --- /dev/null +++ b/monero-rpc-odoo-pos/models/__init__.py @@ -0,0 +1,5 @@ +from . import pos_order, pos_payment, pos_payment_method, exceptions + +# TODO automate prices list for currencies, +# the lists would be updated at a chosen interval with the correct conversion +# https://taiga.getmonero.org/project/t-900-monero-x-odoo-integrations/us/23 diff --git a/monero-rpc-odoo-pos/models/exceptions.py b/monero-rpc-odoo-pos/models/exceptions.py new file mode 100644 index 00000000..4a1a657f --- /dev/null +++ b/monero-rpc-odoo-pos/models/exceptions.py @@ -0,0 +1,23 @@ +from monero.backends.jsonrpc import Unauthorized +from requests.exceptions import SSLError +from odoo.addons.queue_job.exception import RetryableJobError + + +class MoneroPaymentMethodRPCUnauthorized(Unauthorized): + pass + + +class MoneroPaymentMethodRPCSSLError(SSLError): + pass + + +class NoTXFound(RetryableJobError): + pass + + +class NumConfirmationsNotMet(RetryableJobError): + pass + + +class MoneroAddressReuse(Exception): + pass diff --git a/monero-rpc-odoo-pos/models/pos_order.py b/monero-rpc-odoo-pos/models/pos_order.py new file mode 100755 index 00000000..bc028c24 --- /dev/null +++ b/monero-rpc-odoo-pos/models/pos_order.py @@ -0,0 +1,9 @@ +import logging + +from odoo import models + +_logger = logging.getLogger(__name__) + + +class MoneroPosOrder(models.Model): + _inherit = "pos.order" diff --git a/monero-rpc-odoo-pos/models/pos_payment.py b/monero-rpc-odoo-pos/models/pos_payment.py new file mode 100644 index 00000000..aa6ea978 --- /dev/null +++ b/monero-rpc-odoo-pos/models/pos_payment.py @@ -0,0 +1,132 @@ +from odoo import api, fields, models, _ + +from monero.wallet import Wallet +from .exceptions import NoTXFound, NumConfirmationsNotMet, MoneroAddressReuse +from .exceptions import MoneroPaymentMethodRPCUnauthorized +from .exceptions import MoneroPaymentMethodRPCSSLError + +import logging + +_logger = logging.getLogger(__name__) + + +class MoneroPosPayment(models.Model): + """ + OVERRIDING METHOD FROM + odoo/addons/point_of_sale/models/pos_payment.py + + Used to register payments made in a pos.order. + + See `payment_ids` field of pos.order model. + The main characteristics of pos.payment can be read from + `payment_method_id`. + """ + + _inherit = "pos.payment" + + wallet_address = fields.Char("Payment Wallet Address") + + def process_transaction(self): + + try: + wallet: Wallet = self.payment_method_id.get_wallet() + except MoneroPaymentMethodRPCUnauthorized: + raise MoneroPaymentMethodRPCUnauthorized( + "Monero Processing Queue: " + "Monero Payment Acquirer " + "can't authenticate with RPC " + "due to user name or password" + ) + except MoneroPaymentMethodRPCSSLError: + raise MoneroPaymentMethodRPCSSLError( + "Monero Processing Queue: Monero Payment Acquirer " + "experienced an SSL Error with RPC" + ) + except Exception as e: + raise Exception( + f"Monero Processing Queue: Monero Payment Acquirer " + f"experienced an Error with RPC: {e.__class__.__name__}" + ) + + incoming_payment = wallet.incoming( + local_address=self.wallet_address, unconfirmed=True + ) + + if incoming_payment == []: + job = ( + self.env["queue.job"] + .sudo() + .search([("uuid", "=", self.env.context.get("job_uuid"))]) + ) + _logger.info(job.max_retries) + _logger.info(job.retry) + if job.retry == job.max_retries - 1: + self.write({"state": "cancel", "is_expired": "true"}) + log_msg = ( + f"PaymentMethod: {self.payment_method_id.name} " + f"Subaddress: {self.wallet_address} " + "Status: No transaction found. Too much time has passed, " + "customer has most likely not sent payment. " + f"Cancelling order # {self.pos_order_id.id}. " + f"Action: Nothing" + ) + _logger.warning(log_msg) + return log_msg + else: + exception_msg = ( + f"PaymentMethod: {self.payment_method_id.name} " + f"Subaddress: {self.wallet_address} " + "Status: No transaction found. " + "TX probably hasn't been added to a block or mem-pool yet. " + "This is fine. " + f"Another job will execute. Action: Nothing" + ) + raise NoTXFound(exception_msg) + + if len(incoming_payment) > 1: + # TODO custom logic if the end user sends + # multiple transactions for one order + # this would involve creating another "payment.transaction" + # and notifying both the buyer and seller + raise MoneroAddressReuse( + f"PaymentMethod: {self.payment_method_id.name} " + f"Subaddress: {self.wallet_address} " + "Status: Address reuse found. " + "The end user most likely sent " + "multiple transactions for a single order. " + "Action: Reconcile transactions manually" + ) + + if len(incoming_payment) == 1: + this_payment = incoming_payment.pop() + num_confirmation_required = self.payment_method_id.num_confirmation_required + conf_err_msg = ( + f"PaymentMethod: {self.payment_method_id.name} " + f"Subaddress: {self.wallet_address} " + "Status: Waiting for more confirmations " + f"Confirmations: current {this_payment.transaction.confirmations}, " + f"expected {num_confirmation_required} " + "Action: none" + ) + # TODO set transaction state to "authorized" once a monero transaction is + # found within the transaction pool + # note that when the NumConfirmationsNotMe is raised any database commits + # are lost + if this_payment.transaction.confirmations is None: + if num_confirmation_required > 0: + raise NumConfirmationsNotMet(conf_err_msg) + else: + if this_payment.transaction.confirmations < num_confirmation_required: + raise NumConfirmationsNotMet(conf_err_msg) + + transaction_amount_rounded = float( + round(this_payment.amount, self.currency_id.decimal_places) + ) + if self.amount == transaction_amount_rounded: + self.pos_order_id.write({"state": "done"}) + self.write({"payment_status": "done"}) + _logger.info( + f"Monero payment recorded for pos order: {self.pos_order_id.id}, " + f"associated with subaddress: {self.wallet_address}" + ) + # TODO handle situation where the transaction amount is not equal diff --git a/monero-rpc-odoo-pos/models/pos_payment_method.py b/monero-rpc-odoo-pos/models/pos_payment_method.py new file mode 100755 index 00000000..476c62e5 --- /dev/null +++ b/monero-rpc-odoo-pos/models/pos_payment_method.py @@ -0,0 +1,134 @@ +import logging + +from monero.backends.jsonrpc import JSONRPCWallet, Unauthorized +from monero.wallet import Wallet +from odoo import api, fields, models +from requests.exceptions import SSLError +from .exceptions import ( + MoneroPaymentMethodRPCUnauthorized, + MoneroPaymentMethodRPCSSLError, +) + +_logger = logging.getLogger(__name__) + + +class MoneroPosPaymentMethod(models.Model): + """ + Inherits from pos.payment.method + Custom fields added: is_cryptocurrency, environment, type + """ + + _inherit = "pos.payment.method" + + def _get_payment_terminal_selection(self): + return super(MoneroPosPaymentMethod, self)._get_payment_terminal_selection() + [ + ("monero-rpc", "Monero RPC") + ] + + def get_wallet(self): + rpc_server: JSONRPCWallet = JSONRPCWallet( + protocol=self.rpc_protocol, + host=self.monero_rpc_config_host, + port=self.monero_rpc_config_port, + user=self.monero_rpc_config_user, + password=self.monero_rpc_config_password, + ) + try: + wallet: Wallet = Wallet(rpc_server) + except Unauthorized: + raise MoneroPaymentMethodRPCUnauthorized + except SSLError: + raise MoneroPaymentMethodRPCSSLError + except Exception as e: + _logger.critical("Monero RPC Error", exc_info=True) + raise e + + return wallet + + @api.onchange( + "rpc_protocol", + "monero_rpc_config_host", + "monero_rpc_config_port", + "monero_rpc_config_user", + "monero_rpc_config_password", + ) + def check_rpc_server_connection(self): + _logger.info("Trying new Monero RPC Server configuration") + wallet = None + try: + wallet = self.get_wallet() + except MoneroPaymentMethodRPCUnauthorized: + message = "Invalid Monero RPC user name or password" + pass + except MoneroPaymentMethodRPCSSLError: + message = "Monero RPC TLS Error" + pass + except Exception as e: + message = ( + f"Monero RPC Connection Failed or other error: {e.__class__.__name__}" + ) + pass + + title = "Monero RPC Connection Test" + if type(wallet) is Wallet: + _logger.info("Connection to Monero RPC successful") + warning = {"title": title, "message": "Connection is successful"} + else: + _logger.info(message) + warning = {"title": title, "message": f"{message}"} + + return {"warning": warning} + + is_cryptocurrency = fields.Boolean("Cryptocurrency?", default=False) + # not used right now, could be used to update price data? + type = fields.Selection( + [("xmr", "XMR")], + "none", + default="xmr", + required=True, + help="Monero: A Private Digital Currency", + ) + + rpc_protocol = fields.Selection( + [ + ("http", "HTTP"), + ("https", "HTTPS"), + ], + "RPC Protocol", + default="http", + ) + monero_rpc_config_host = fields.Char( + string="RPC Host", + help="The ip address or host name of the Monero RPC", + default="127.0.0.1", + ) + monero_rpc_config_port = fields.Char( + string="RPC Port", + help="The port the Monero RPC is listening on", + default="18082", + ) + monero_rpc_config_user = fields.Char( + string="RPC User", + help="The user to authenticate with the Monero RPC", + default=None, + ) + monero_rpc_config_password = fields.Char( + string="RPC Password", + help="The password to authenticate with the Monero RPC", + default=None, + ) + num_confirmation_required = fields.Selection( + [ + ("0", "Low; 0-conf"), + ("1", "Low-Med; 1-conf"), + ("3", "Med; 3-conf"), + ("6", "Med-High; 6-conf"), + ("9", "High; 9-conf"), + ("12", "High-Extreme; 12-conf"), + ("15", "Extreme; 15-conf"), + ], + "Security Level (Confirmations)", + default="0", + help="Required Number of confirmations " + "before an order's transactions is set to done", + ) diff --git a/payment_monero_rpc/static/description/icon.png b/monero-rpc-odoo-pos/static/description/icon.png similarity index 100% rename from payment_monero_rpc/static/description/icon.png rename to monero-rpc-odoo-pos/static/description/icon.png diff --git a/payment_monero_rpc/static/src/img/logo.png b/monero-rpc-odoo-pos/static/src/img/logo.png similarity index 100% rename from payment_monero_rpc/static/src/img/logo.png rename to monero-rpc-odoo-pos/static/src/img/logo.png diff --git a/payment_monero_rpc/static/src/img/monero-integrations.png b/monero-rpc-odoo-pos/static/src/img/monero-integrations.png similarity index 100% rename from payment_monero_rpc/static/src/img/monero-integrations.png rename to monero-rpc-odoo-pos/static/src/img/monero-integrations.png diff --git a/payment_monero_rpc/static/src/img/monero-symbol-480.png b/monero-rpc-odoo-pos/static/src/img/monero-symbol-480.png similarity index 100% rename from payment_monero_rpc/static/src/img/monero-symbol-480.png rename to monero-rpc-odoo-pos/static/src/img/monero-symbol-480.png diff --git a/payment_monero_rpc/static/src/js/jquery.qrcode.min.js b/monero-rpc-odoo-pos/static/src/js/jquery.qrcode.min.js similarity index 100% rename from payment_monero_rpc/static/src/js/jquery.qrcode.min.js rename to monero-rpc-odoo-pos/static/src/js/jquery.qrcode.min.js diff --git a/monero-rpc-odoo-pos/tests/__init__.py b/monero-rpc-odoo-pos/tests/__init__.py new file mode 100755 index 00000000..e69de29b diff --git a/monero-rpc-odoo-pos/views/pos_payment_method_form.xml b/monero-rpc-odoo-pos/views/pos_payment_method_form.xml new file mode 100755 index 00000000..29cbd7a9 --- /dev/null +++ b/monero-rpc-odoo-pos/views/pos_payment_method_form.xml @@ -0,0 +1,30 @@ + + + + pos.payment.method.form.inherit.pos.payment.monero + pos.payment.method + + + + + + + + + + + + + + + + diff --git a/monero-rpc-odoo-pos/views/pos_payment_method_views.xml b/monero-rpc-odoo-pos/views/pos_payment_method_views.xml new file mode 100644 index 00000000..5ce6b2c2 --- /dev/null +++ b/monero-rpc-odoo-pos/views/pos_payment_method_views.xml @@ -0,0 +1,27 @@ + + + + pos.payment.method.tree + pos.payment.method + + + + + + + + + + + + + + + + {} + Payments Methods + pos.payment.method + + tree,form,kanban + + diff --git a/monero-rpc-odoo-pos/views/pos_payment_views.xml b/monero-rpc-odoo-pos/views/pos_payment_views.xml new file mode 100644 index 00000000..91424670 --- /dev/null +++ b/monero-rpc-odoo-pos/views/pos_payment_views.xml @@ -0,0 +1,18 @@ + + + + pos.payment.tree + pos.payment + + + + + + + + + + + + + diff --git a/monero-rpc-odoo/LICENSE b/monero-rpc-odoo/LICENSE new file mode 100755 index 00000000..58777e31 --- /dev/null +++ b/monero-rpc-odoo/LICENSE @@ -0,0 +1,661 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/monero-rpc-odoo/README.md b/monero-rpc-odoo/README.md new file mode 100755 index 00000000..c5e2b5a2 --- /dev/null +++ b/monero-rpc-odoo/README.md @@ -0,0 +1,69 @@ +Monero Odoo +========================= + + +[![Build Status](https://api.travis-ci.com/t-900-a/moneroodoo.svg?branch=main)](https://travis-ci.com/t-900-a/moneroodoo) +[![codecov](https://codecov.io/gh/t-900-a/moneroodoo/branch/main/graph/badge.svg?token=10S5GGNRHH)](https://codecov.io/gh/t-900-a/moneroodoo) + +Allows you to accept Monero as Payment within your Odoo Ecommerce shop + +Configuration +============= + +* Monero - This quickstart guide can guide you through the configuration of Monero specific +components. https://monero-python.readthedocs.io/en/latest/quickstart.html + * monerod + * https://www.getmonero.org/resources/moneropedia/daemon.html + * Download: https://www.getmonero.org/downloads/#cli + * monero-wallet-rpc + * Use a view-key on the server + * https://www.getmonero.org/resources/developer-guides/wallet-rpc.html + * Download: https://www.getmonero.org/downloads/#cli +* Odoo - Add-ons are installed by adding the specific module folder to the add-ons + directory (restart + required) + * queue-job + * https://github.com/OCA/queue + * monero-rpc-odoo + * https://github.com/monero-integrations/moneroodoo + * The Monero payment acquirer is configured similar to other payment acquirers + * https://www.odoo.com/documentation/user/14.0/general/payment_acquirers/payment_acquirers.html#configuration + * Currency rate + * You will need to manually add currency rate for Monero + * https://www.odoo.com/documentation/user/14.0/accounting/others/multicurrencies/how_it_works.html + * Pricelist + * A pricelist should be created specifically for Monero + * https://www.odoo.com/documentation/user/14.0/website/publish/multi_website.html#pricelists + + + +Usage +===== + +* At Ecommerce checkout your customer's will be presented with the option to pay + with Monero + +Bug Tracker +=========== + +Bugs are tracked on [GitHub Issues](https://github.com/monero-integrations/moneroodoo/issues). +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us smashing it by providing a detailed and welcomed +[feedback](https://github.com/monero-integrations/moneroodoo/issues/new?body=module:%20monero-rpc-odoo%0Aversion:%14.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**)? + +Credits +======= + +Contributors + +* T-900 + +Maintainers + +This module is maintained by Monero-Integrations. +![Monero-Integrations](/monero-rpc-odoo/static/src/img/monero-integrations.png) + + +This module is part of the [monero-integrations/moneroodoo](https://github.com/monero-integrations/moneroodoo) project on GitHub. + +You are welcome to contribute. To learn how please visit the [Monero Taiga](https://taiga.getmonero.org/project/t-900-monero-x-odoo-integrations/). diff --git a/monero-rpc-odoo/__init__.py b/monero-rpc-odoo/__init__.py new file mode 100755 index 00000000..72d3ea60 --- /dev/null +++ b/monero-rpc-odoo/__init__.py @@ -0,0 +1 @@ +from . import controllers, models diff --git a/monero-rpc-odoo/__manifest__.py b/monero-rpc-odoo/__manifest__.py new file mode 100755 index 00000000..ae4dae22 --- /dev/null +++ b/monero-rpc-odoo/__manifest__.py @@ -0,0 +1,39 @@ +{ + "name": "monero-rpc-odoo", + "summary": "Allows you to accept Monero Payments", + "author": "Monero Integrations", + "website": "https://monerointegrations.com/", + # Categories can be used to filter modules in modules listing + # for the full list + "category": "Accounting", + "version": "14.0.1.0.2", + # any module necessary for this one to work correctly + "depends": [ + "website_sale", + "website_payment", + "website", + "payment_transfer", + "payment", + "base_setup", + "web", + "queue_job", + ], + "external_dependencies": {"python": ["monero"]}, + # always loaded + "data": [ + "views/monero_acquirer_form.xml", + "views/monero_payment_confirmation.xml", + "data/currency.xml", + "data/monero_xmr_payment_acquirer.xml", + "data/payment_icon_data.xml", + "data/queue.xml", + ], + # only loaded in demonstration mode + # TODO add demo data + "demo": [ + "demo/demo.xml", + ], + "installable": True, + "application": True, + "classifiers": ["License :: OSI Approved :: MIT License"], +} diff --git a/monero-rpc-odoo/controllers/__init__.py b/monero-rpc-odoo/controllers/__init__.py new file mode 100755 index 00000000..842d7786 --- /dev/null +++ b/monero-rpc-odoo/controllers/__init__.py @@ -0,0 +1 @@ +from . import monero_controller, website_sale diff --git a/monero-rpc-odoo/controllers/monero_controller.py b/monero-rpc-odoo/controllers/monero_controller.py new file mode 100755 index 00000000..9c5dddc5 --- /dev/null +++ b/monero-rpc-odoo/controllers/monero_controller.py @@ -0,0 +1,228 @@ +import logging + +from odoo import http +from odoo.addons.payment.controllers.portal import PaymentProcessing +from odoo.http import request +from monero.address import SubAddress + +_logger = logging.getLogger(__name__) + + +class MoneroController(http.Controller): + @http.route("/shop/payment/monero/submit", type="json", auth="public", website=True) + def monero_transaction(self, verify_validity=False, **kwargs): + """ + Function creates a transaction and + payment token using the sessions sales order + Calls MoneroSalesOrder.salesorder_payment_sync() + :param verify_validity: + :param kwargs: + :return: + """ + sales_order = request.website.sale_get_order() + _logger.info(f"received sales_order: {sales_order.id}") + _logger.info(f"processing sales_order: {sales_order.id}") + + # Ensure there is something to proceed + if not sales_order or (sales_order and not sales_order.order_line): + return False + + assert sales_order.partner_id.id != request.website.partner_id.id + # at this time the sales order has to be in xmr + # the user cannot use a fiat pricelist when checking out + # this won't be fixed until after a job is added to automatically + # update res.currency.rate + currency = request.env["res.currency"].sudo().browse(sales_order.currency_id.id) + if currency.name != "XMR": + raise Exception( + "This pricelist is not supported, go back and select the " + "Monero Pricelist" + ) + + payment_acquirer_id = int(kwargs.get("acquirer_id")) + + payment_partner_id = int(kwargs.get("partner_id")) + + wallet_sub_address = SubAddress(kwargs.get("wallet_address")) + + # security check, enforce one time usage of subaddresses + payment_tokens = ( + request.env["payment.token"] + .sudo() + .search([("name", "=", wallet_sub_address)]) + ) + assert len(payment_tokens) < 1 + + # define payment token + payment_token = { + "name": wallet_sub_address.__repr__(), + "partner_id": payment_partner_id, + # partner_id creating sales order + "active": False, + # token shoudn't be active, the subaddress shouldn't be reused + "acquirer_id": payment_acquirer_id, + # surrogate key for payment acquirer + "acquirer_ref": "payment.payment_acquirer_monero_rpc", + } + + _logger.info(f"creating payment token " f"for sales_order: {sales_order.id}") + token = request.env["payment.token"].sudo().create(payment_token) + token_id = token.id + token_short_name = token.short_name + + # assign values for transaction creation + tx_val = { + "amount": sales_order.amount_total, + "reference": sales_order.name, + "currency_id": sales_order.currency_id.id, + "partner_id": sales_order.partner_id.id, + # Referencing the Sale Order Partner ID + "payment_token_id": token_id, # Associating the Payment Token ID. + "acquirer_id": payment_acquirer_id, # Payment Acquirer - Monero + "state": "pending", + # tx is pending, + # because the customer will know the address to send the tx to, + # but hasn't yet sent it + } + + _logger.info(f"getting the transaction " f"for sales_order: {sales_order.id}") + # transaction = sales_order._create_payment_transaction(tx_val) + transaction = sales_order.get_portal_last_transaction() + if transaction.id is False: + transaction = sales_order._create_payment_transaction(tx_val) + _logger.info(f"created transaction: {transaction.id}") + else: + _logger.info(f"retrieved transaction: {transaction.id}") + + # 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(transaction) + request.session["__website_sale_last_tx_id"] = transaction.id + + # Sale Order is quotation sent + # , so the state should be set to "sent" + # , until the transaction has been verified + _logger.info( + f'setting sales_order state to "sent" ' f"for sales_order: {sales_order.id}" + ) + request.env.user.sale_order_ids.sudo().update( + {"require_payment": "true", "state": "sent"} + ) + + payment_acquirer = ( + request.env["payment.acquirer"].sudo().browse(payment_acquirer_id) + ) + # set queue channel and max_retries settings + # for queue depending on num conf settings + num_conf_req = int(payment_acquirer.num_confirmation_required) + if num_conf_req == 0: + queue_channel = "monero_zeroconf_processing" + queue_max_retries = 44 + else: + queue_channel = "monero_secure_processing" + queue_max_retries = num_conf_req * 25 + + # Add payment token and sale order to transaction processing queue + + sales_order.with_delay( + channel=queue_channel, max_retries=queue_max_retries + ).process_transaction(transaction, token, num_conf_req) + + if transaction: + res = { + "result": True, + "id": token_id, + "short_name": token_short_name, + "3d_secure": False, + "verified": False, + } + + if verify_validity is not False: + token.validate() + res["verified"] = token.verified + + return res + + @http.route( + "/shop/payment/token", type="http", auth="public", website=True, sitemap=False + ) + def payment_token(self, pm_id=None, **kwargs): + """OVERRIDING METHOD FROM odoo/addons/website_sale/controllers/main.py + Method that handles payment using saved tokens + :param int pm_id: id of the payment.token that we want to use to pay. + + This route is requested after payment submission : + /shop/payment/monero/submit - it's called everytime, + since we will use monero sub addresses + as one time addresses + """ + + # order already created, get it + sales_order = request.website.sale_get_order() + _logger.info(f"received token for sales_order: {sales_order.id}") + _logger.info(f"processing token for sales_order: {sales_order.id}") + + # do not crash if the user has already paid and try to pay again + if not sales_order: + _logger.error("no order found") + return request.redirect("/shop/?error=no_order") + + # see overriden method + assert sales_order.partner_id.id != request.website.partner_id.id + + try: + # pm_id is passed, make sure it's a valid int + pm_id = int(pm_id) + except ValueError: + _logger.error("invalid token id") + return request.redirect("/shop/?error=invalid_token_id") + + # payment token already created, get it + token = request.env["payment.token"].sudo().browse(pm_id) + + if not token: + return request.redirect("/shop/?error=token_not_found") + + # has the transaction already been created? + tx_id = request.session["__website_sale_last_tx_id"] + if tx_id: + # transaction was already + # established in /shop/payment/monero/submit + transaction = request.env["payment.transaction"].sudo().browse(tx_id) + PaymentProcessing.add_payment_transaction(transaction) + # clear the tx in session, because we're done with it + request.session["__website_sale_last_tx_id"] = None + return request.redirect("/shop/payment/validate") + else: + # transaction hasn't been created + tx_val = {"payment_token_id": pm_id, "return_url": "/shop/payment/validate"} + transaction = sales_order._create_payment_transaction(tx_val) + _logger.info( + f"created transaction: {transaction.id} " + f"for payment token: {token.id}" + ) + if transaction.acquirer_id.is_cryptocurrency: + _logger.info( + f"Processing cryptocurrency " + f"payment acquirer: {transaction.acquirer_id.name}" + ) + _logger.info( + f"setting sales_order state to " + f'"sent" for sales_order: {sales_order.id}' + ) + sales_order.sudo().update({"state": "sent"}) + _logger.info( + f"setting transaction state to " + f'"pending" for sales_order: {sales_order.id}' + ) + transaction.sudo().update({"state": "pending"}) + PaymentProcessing.add_payment_transaction(transaction) + return request.redirect("/shop/payment/validate") + + PaymentProcessing.add_payment_transaction(transaction) + return request.redirect("/payment/process") diff --git a/monero-rpc-odoo/controllers/website_sale.py b/monero-rpc-odoo/controllers/website_sale.py new file mode 100755 index 00000000..bbf10bb0 --- /dev/null +++ b/monero-rpc-odoo/controllers/website_sale.py @@ -0,0 +1,86 @@ +import logging + +from odoo import http +from odoo.addons.website_sale.controllers.main import WebsiteSale +from odoo.exceptions import ValidationError + +from ..models.exceptions import MoneroPaymentAcquirerRPCUnauthorized +from ..models.exceptions import MoneroPaymentAcquirerRPCSSLError +from odoo.http import request + +_logger = logging.getLogger(__name__) + + +class MoneroWebsiteSale(WebsiteSale): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + @http.route( + ["/shop/payment"], type="http", auth="public", website=True, sitemap=False + ) + def payment(self, **post): + """ + OVERRIDING METHOD FROM + odoo/addons/website_sale/controllers/main.py + Payment step. This page proposes several + payment means based on available + payment.acquirer. State at this point : + - a draft sales order with lines; otherwise, clean context / session and + back to the shop + - no transaction in context / session, or only a draft one, if the customer + did go to a payment.acquirer website but closed the tab without + paying / canceling + """ + order = request.website.sale_get_order() + redirection = self.checkout_redirection(order) + if redirection: + return redirection + + render_values = self._get_shop_payment_values(order, **post) + render_values["only_services"] = order and order.only_services or False + + for acquirer in render_values["acquirers"]: + if "monero-rpc" in acquirer.provider: + wallet = None + try: + wallet = acquirer.get_wallet() + except MoneroPaymentAcquirerRPCUnauthorized: + _logger.error( + "USER IMPACT: Monero Payment Acquirer " + "can't authenticate with RPC " + "due to user name or password" + ) + raise ValidationError( + "Current technical issues " + "prevent Monero from being accepted, " + "choose another payment method" + ) + except MoneroPaymentAcquirerRPCSSLError: + _logger.error( + "USER IMPACT: Monero Payment Acquirer " + "experienced an SSL Error with RPC" + ) + raise ValidationError( + "Current technical issues " + "prevent Monero from being accepted, " + "choose another payment method" + ) + except Exception as e: + _logger.error( + f"USER IMPACT: Monero Payment Acquirer " + f"experienced an Error with RPC: {e.__class__.__name__}" + ) + raise ValidationError( + "Current technical issues " + "prevent Monero from being accepted, " + "choose another payment method" + ) + + request.wallet_address = wallet.new_address()[0] + _logger.debug("new monero payment subaddress generated") + + if render_values["errors"]: + render_values.pop("acquirers", "") + render_values.pop("tokens", "") + + return request.render("website_sale.payment", render_values) diff --git a/monero-rpc-odoo/data/currency.xml b/monero-rpc-odoo/data/currency.xml new file mode 100755 index 00000000..01d7a9a8 --- /dev/null +++ b/monero-rpc-odoo/data/currency.xml @@ -0,0 +1,17 @@ + + + + + + XMR + Monero + Monero + ɱ + after + True + + 6 + 0.000001 + + + diff --git a/monero-rpc-odoo/data/monero_xmr_payment_acquirer.xml b/monero-rpc-odoo/data/monero_xmr_payment_acquirer.xml new file mode 100755 index 00000000..010a42b8 --- /dev/null +++ b/monero-rpc-odoo/data/monero_xmr_payment_acquirer.xml @@ -0,0 +1,52 @@ + + + + + + + + + Monero RPC + monero-rpc + + + + + + + + + test + s2s + + You will be redirected to the Payment information and processing page after clicking on the payment button.

]]> +
+ + Please pay the amount due to complete your order.

]]> +
+ + + Thanks for using Monero for payment. +


Please note your order number for future reference.

]]> +
+ True + xmr + 0 + http + 127.0.0.1 + 18082 + user + password + Monero +
+
+
diff --git a/monero-rpc-odoo/data/payment_icon_data.xml b/monero-rpc-odoo/data/payment_icon_data.xml new file mode 100755 index 00000000..9ebb6ee0 --- /dev/null +++ b/monero-rpc-odoo/data/payment_icon_data.xml @@ -0,0 +1,8 @@ + + + + Monero + + + diff --git a/payment_monero_rpc/data/queue.xml b/monero-rpc-odoo/data/queue.xml similarity index 98% rename from payment_monero_rpc/data/queue.xml rename to monero-rpc-odoo/data/queue.xml index 3fb38ddb..527615dc 100644 --- a/payment_monero_rpc/data/queue.xml +++ b/monero-rpc-odoo/data/queue.xml @@ -1,5 +1,6 @@ + monero_zeroconf_processing @@ -20,4 +21,5 @@ + diff --git a/monero-rpc-odoo/demo/demo.xml b/monero-rpc-odoo/demo/demo.xml new file mode 100755 index 00000000..8177b5c9 --- /dev/null +++ b/monero-rpc-odoo/demo/demo.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/monero-rpc-odoo/models/__init__.py b/monero-rpc-odoo/models/__init__.py new file mode 100755 index 00000000..d55b85d1 --- /dev/null +++ b/monero-rpc-odoo/models/__init__.py @@ -0,0 +1,5 @@ +from . import monero_acq, sales_order, exceptions + +# TODO automate prices list for currencies, +# the lists would be updated at a chosen interval with the correct conversion +# https://taiga.getmonero.org/project/t-900-monero-x-odoo-integrations/us/23 diff --git a/monero-rpc-odoo/models/exceptions.py b/monero-rpc-odoo/models/exceptions.py new file mode 100644 index 00000000..356f44b8 --- /dev/null +++ b/monero-rpc-odoo/models/exceptions.py @@ -0,0 +1,23 @@ +from monero.backends.jsonrpc import Unauthorized +from requests.exceptions import SSLError +from odoo.addons.queue_job.exception import RetryableJobError + + +class MoneroPaymentAcquirerRPCUnauthorized(Unauthorized): + pass + + +class MoneroPaymentAcquirerRPCSSLError(SSLError): + pass + + +class NoTXFound(RetryableJobError): + pass + + +class NumConfirmationsNotMet(RetryableJobError): + pass + + +class MoneroAddressReuse(Exception): + pass diff --git a/monero-rpc-odoo/models/monero_acq.py b/monero-rpc-odoo/models/monero_acq.py new file mode 100755 index 00000000..f6c23533 --- /dev/null +++ b/monero-rpc-odoo/models/monero_acq.py @@ -0,0 +1,134 @@ +import logging + +from monero.backends.jsonrpc import JSONRPCWallet, Unauthorized +from monero.wallet import Wallet +from odoo import api, fields, models +from requests.exceptions import SSLError +from .exceptions import ( + MoneroPaymentAcquirerRPCUnauthorized, + MoneroPaymentAcquirerRPCSSLError, +) + +_logger = logging.getLogger(__name__) + + +class MoneroPaymentAcquirer(models.Model): + """ + Inherits from payment.acquirer + Custom fields added: is_cryptocurrency, environment, type + """ + + _inherit = "payment.acquirer" + _recent_transactions = [] + + def get_wallet(self): + rpc_server: JSONRPCWallet = JSONRPCWallet( + protocol=self.rpc_protocol, + host=self.monero_rpc_config_host, + port=self.monero_rpc_config_port, + user=self.monero_rpc_config_user, + password=self.monero_rpc_config_password, + ) + try: + wallet = Wallet(rpc_server) + except Unauthorized: + raise MoneroPaymentAcquirerRPCUnauthorized + except SSLError: + raise MoneroPaymentAcquirerRPCSSLError + except Exception as e: + _logger.critical("Monero RPC Error", exc_info=True) + raise e + + return wallet + + @api.onchange( + "rpc_protocol", + "monero_rpc_config_host", + "monero_rpc_config_port", + "monero_rpc_config_user", + "monero_rpc_config_password", + ) + def check_rpc_server_connection(self): + _logger.info("Trying new Monero RPC Server configuration") + wallet = None + try: + wallet = self.get_wallet() + except MoneroPaymentAcquirerRPCUnauthorized: + message = "Invalid Monero RPC user name or password" + pass + except MoneroPaymentAcquirerRPCSSLError: + message = "Monero RPC TLS Error" + pass + except Exception as e: + message = ( + f"Monero RPC Connection Failed or other error: {e.__class__.__name__}" + ) + pass + + title = "Monero RPC Connection Test" + if type(wallet) is Wallet: + _logger.info("Connection to Monero RPC successful") + warning = {"title": title, "message": "Connection is successful"} + else: + _logger.info(message) + warning = {"title": title, "message": f"{message}"} + + return {"warning": warning} + + provider = fields.Selection( + selection_add=[("monero-rpc", "Monero")], ondelete={"monero-rpc": "set default"} + ) + + is_cryptocurrency = fields.Boolean("Cryptocurrency?", default=False) + # not used right now, could be used to update price data? + type = fields.Selection( + [("xmr", "XMR")], + "none", + default="xmr", + required=True, + help="Monero: A Private Digital Currency", + ) + + rpc_protocol = fields.Selection( + [ + ("http", "HTTP"), + ("https", "HTTPS"), + ], + "RPC Protocol", + default="http", + ) + monero_rpc_config_host = fields.Char( + string="RPC Host", + help="The ip address or host name of the Monero RPC", + default="127.0.0.1", + ) + monero_rpc_config_port = fields.Char( + string="RPC Port", + help="The port the Monero RPC is listening on", + default="18082", + ) + monero_rpc_config_user = fields.Char( + string="RPC User", + help="The user to authenticate with the Monero RPC", + default=None, + ) + monero_rpc_config_password = fields.Char( + string="RPC Password", + help="The password to authenticate with the Monero RPC", + default=None, + ) + num_confirmation_required = fields.Selection( + [ + ("0", "Low; 0-conf"), + ("1", "Low-Med; 1-conf"), + ("3", "Med; 3-conf"), + ("6", "Med-High; 6-conf"), + ("9", "High; 9-conf"), + ("12", "High-Extreme; 12-conf"), + ("15", "Extreme; 15-conf"), + ], + "Security Level (Confirmations)", + default="0", + help="Required Number of confirmations " + "before an order's transactions is set to done", + ) diff --git a/monero-rpc-odoo/models/sales_order.py b/monero-rpc-odoo/models/sales_order.py new file mode 100755 index 00000000..5df16e29 --- /dev/null +++ b/monero-rpc-odoo/models/sales_order.py @@ -0,0 +1,115 @@ +import logging + +from odoo import models + +from ..models.exceptions import NoTXFound, NumConfirmationsNotMet, MoneroAddressReuse +from ..models.exceptions import MoneroPaymentAcquirerRPCUnauthorized +from ..models.exceptions import MoneroPaymentAcquirerRPCSSLError + +_logger = logging.getLogger(__name__) + + +class MoneroSalesOrder(models.Model): + _inherit = "sale.order" + + def process_transaction(self, transaction, token, num_confirmation_required): + try: + wallet = transaction.acquirer_id.get_wallet() + except MoneroPaymentAcquirerRPCUnauthorized: + raise MoneroPaymentAcquirerRPCUnauthorized( + "Monero Processing Queue: " + "Monero Payment Acquirer " + "can't authenticate with RPC " + "due to user name or password" + ) + except MoneroPaymentAcquirerRPCSSLError: + raise MoneroPaymentAcquirerRPCSSLError( + "Monero Processing Queue: Monero Payment Acquirer " + "experienced an SSL Error with RPC" + ) + except Exception as e: + raise Exception( + f"Monero Processing Queue: Monero Payment Acquirer " + f"experienced an Error with RPC: {e.__class__.__name__}" + ) + + incoming_payment = wallet.incoming(local_address=token.name, unconfirmed=True) + + if incoming_payment == []: + job = ( + self.env["queue.job"] + .sudo() + .search([("uuid", "=", self.env.context.get("job_uuid"))]) + ) + _logger.info(job.max_retries) + _logger.info(job.retry) + if job.retry == job.max_retries - 1: + self.write({"state": "cancel", "is_expired": "true"}) + log_msg = ( + f"PaymentAcquirer: {transaction.acquirer_id.provider} " + f"Subaddress: {token.name} " + "Status: No transaction found. Too much time has passed, " + "customer has most likely not sent payment. " + f"Cancelling order # {self.id}. " + f"Action: Nothing" + ) + _logger.warning(log_msg) + return log_msg + else: + exception_msg = ( + f"PaymentAcquirer: {transaction.acquirer_id.provider} " + f"Subaddress: {token.name} " + "Status: No transaction found. " + "TX probably hasn't been added to a block or mem-pool yet. " + "This is fine. " + f"Another job will execute. Action: Nothing" + ) + raise NoTXFound(exception_msg) + + if len(incoming_payment) > 1: + # TODO custom logic if the end user sends + # multiple transactions for one order + # this would involve creating another "payment.transaction" + # and notifying both the buyer and seller + raise MoneroAddressReuse( + f"PaymentAcquirer: {transaction.acquirer_id.provider} " + f"Subaddress: {token.name} " + "Status: Address reuse found. " + "The end user most likely sent " + "multiple transactions for a single order. " + "Action: Reconcile transactions manually" + ) + + if len(incoming_payment) == 1: + this_payment = incoming_payment.pop() + + conf_err_msg = ( + f"PaymentAcquirer: {transaction.acquirer_id.provider} " + f"Subaddress: {token.name} " + "Status: Waiting for more confirmations " + f"Confirmations: current {this_payment.transaction.confirmations}, " + f"expected {num_confirmation_required} " + "Action: none" + ) + # TODO set transaction state to "authorized" once a monero transaction is + # found within the transaction pool + # note that when the NumConfirmationsNotMe is raised any database commits + # are lost + if this_payment.transaction.confirmations is None: + if num_confirmation_required > 0: + raise NumConfirmationsNotMet(conf_err_msg) + else: + if this_payment.transaction.confirmations < num_confirmation_required: + raise NumConfirmationsNotMet(conf_err_msg) + + transaction_amount_rounded = float( + round(this_payment.amount, self.currency_id.decimal_places) + ) + if transaction.amount == transaction_amount_rounded: + self.write({"state": "sale"}) + transaction.write({"state": "done", "is_processed": "true"}) + _logger.info( + f"Monero payment recorded for sale order: {self.id}, " + f"associated with subaddress: {token.name}" + ) + # TODO handle situation where the transaction amount is not equal diff --git a/monero-rpc-odoo/static/description/icon.png b/monero-rpc-odoo/static/description/icon.png new file mode 100644 index 00000000..bfcec41b Binary files /dev/null and b/monero-rpc-odoo/static/description/icon.png differ diff --git a/monero-rpc-odoo/static/src/img/logo.png b/monero-rpc-odoo/static/src/img/logo.png new file mode 100755 index 00000000..57a90d8b Binary files /dev/null and b/monero-rpc-odoo/static/src/img/logo.png differ diff --git a/monero-rpc-odoo/static/src/img/monero-integrations.png b/monero-rpc-odoo/static/src/img/monero-integrations.png new file mode 100644 index 00000000..c32fadc2 Binary files /dev/null and b/monero-rpc-odoo/static/src/img/monero-integrations.png differ diff --git a/monero-rpc-odoo/static/src/img/monero-symbol-480.png b/monero-rpc-odoo/static/src/img/monero-symbol-480.png new file mode 100755 index 00000000..9cb993d9 Binary files /dev/null and b/monero-rpc-odoo/static/src/img/monero-symbol-480.png differ diff --git a/monero-rpc-odoo/static/src/js/jquery.qrcode.min.js b/monero-rpc-odoo/static/src/js/jquery.qrcode.min.js new file mode 100644 index 00000000..fe9680e6 --- /dev/null +++ b/monero-rpc-odoo/static/src/js/jquery.qrcode.min.js @@ -0,0 +1,28 @@ +(function(r){r.fn.qrcode=function(h){var s;function u(a){this.mode=s;this.data=a}function o(a,c){this.typeNumber=a;this.errorCorrectLevel=c;this.modules=null;this.moduleCount=0;this.dataCache=null;this.dataList=[]}function q(a,c){if(void 0==a.length)throw Error(a.length+"/"+c);for(var d=0;da||this.moduleCount<=a||0>c||this.moduleCount<=c)throw Error(a+","+c);return this.modules[a][c]},getModuleCount:function(){return this.moduleCount},make:function(){if(1>this.typeNumber){for(var a=1,a=1;40>a;a++){for(var c=p.getRSBlocks(a,this.errorCorrectLevel),d=new t,b=0,e=0;e=d;d++)if(!(-1>=a+d||this.moduleCount<=a+d))for(var b=-1;7>=b;b++)-1>=c+b||this.moduleCount<=c+b||(this.modules[a+d][c+b]= +0<=d&&6>=d&&(0==b||6==b)||0<=b&&6>=b&&(0==d||6==d)||2<=d&&4>=d&&2<=b&&4>=b?!0:!1)},getBestMaskPattern:function(){for(var a=0,c=0,d=0;8>d;d++){this.makeImpl(!0,d);var b=j.getLostPoint(this);if(0==d||a>b)a=b,c=d}return c},createMovieClip:function(a,c,d){a=a.createEmptyMovieClip(c,d);this.make();for(c=0;c=f;f++)for(var i=-2;2>=i;i++)this.modules[b+f][e+i]=-2==f||2==f||-2==i||2==i||0==f&&0==i?!0:!1}},setupTypeNumber:function(a){for(var c= +j.getBCHTypeNumber(this.typeNumber),d=0;18>d;d++){var b=!a&&1==(c>>d&1);this.modules[Math.floor(d/3)][d%3+this.moduleCount-8-3]=b}for(d=0;18>d;d++)b=!a&&1==(c>>d&1),this.modules[d%3+this.moduleCount-8-3][Math.floor(d/3)]=b},setupTypeInfo:function(a,c){for(var d=j.getBCHTypeInfo(this.errorCorrectLevel<<3|c),b=0;15>b;b++){var e=!a&&1==(d>>b&1);6>b?this.modules[b][8]=e:8>b?this.modules[b+1][8]=e:this.modules[this.moduleCount-15+b][8]=e}for(b=0;15>b;b++)e=!a&&1==(d>>b&1),8>b?this.modules[8][this.moduleCount- +b-1]=e:9>b?this.modules[8][15-b-1+1]=e:this.modules[8][15-b-1]=e;this.modules[this.moduleCount-8][8]=!a},mapData:function(a,c){for(var d=-1,b=this.moduleCount-1,e=7,f=0,i=this.moduleCount-1;0g;g++)if(null==this.modules[b][i-g]){var n=!1;f>>e&1));j.getMask(c,b,i-g)&&(n=!n);this.modules[b][i-g]=n;e--; -1==e&&(f++,e=7)}b+=d;if(0>b||this.moduleCount<=b){b-=d;d=-d;break}}}};o.PAD0=236;o.PAD1=17;o.createData=function(a,c,d){for(var c=p.getRSBlocks(a, +c),b=new t,e=0;e8*a)throw Error("code length overflow. ("+b.getLengthInBits()+">"+8*a+")");for(b.getLengthInBits()+4<=8*a&&b.put(0,4);0!=b.getLengthInBits()%8;)b.putBit(!1);for(;!(b.getLengthInBits()>=8*a);){b.put(o.PAD0,8);if(b.getLengthInBits()>=8*a)break;b.put(o.PAD1,8)}return o.createBytes(b,c)};o.createBytes=function(a,c){for(var d= +0,b=0,e=0,f=Array(c.length),i=Array(c.length),g=0;g>>=1;return c},getPatternPosition:function(a){return j.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,c,d){switch(a){case 0:return 0==(c+d)%2;case 1:return 0==c%2;case 2:return 0==d%3;case 3:return 0==(c+d)%3;case 4:return 0==(Math.floor(c/2)+Math.floor(d/3))%2;case 5:return 0==c*d%2+c*d%3;case 6:return 0==(c*d%2+c*d%3)%2;case 7:return 0==(c*d%3+(c+d)%2)%2;default:throw Error("bad maskPattern:"+ +a);}},getErrorCorrectPolynomial:function(a){for(var c=new q([1],0),d=0;dc)switch(a){case 1:return 10;case 2:return 9;case s:return 8;case 8:return 8;default:throw Error("mode:"+a);}else if(27>c)switch(a){case 1:return 12;case 2:return 11;case s:return 16;case 8:return 10;default:throw Error("mode:"+a);}else if(41>c)switch(a){case 1:return 14;case 2:return 13;case s:return 16;case 8:return 12;default:throw Error("mode:"+ +a);}else throw Error("type:"+c);},getLostPoint:function(a){for(var c=a.getModuleCount(),d=0,b=0;b=g;g++)if(!(0>b+g||c<=b+g))for(var h=-1;1>=h;h++)0>e+h||c<=e+h||0==g&&0==h||i==a.isDark(b+g,e+h)&&f++;5a)throw Error("glog("+a+")");return l.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;256<=a;)a-=255;return l.EXP_TABLE[a]},EXP_TABLE:Array(256), +LOG_TABLE:Array(256)},m=0;8>m;m++)l.EXP_TABLE[m]=1<m;m++)l.EXP_TABLE[m]=l.EXP_TABLE[m-4]^l.EXP_TABLE[m-5]^l.EXP_TABLE[m-6]^l.EXP_TABLE[m-8];for(m=0;255>m;m++)l.LOG_TABLE[l.EXP_TABLE[m]]=m;q.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var c=Array(this.getLength()+a.getLength()-1),d=0;d +this.getLength()-a.getLength())return this;for(var c=l.glog(this.get(0))-l.glog(a.get(0)),d=Array(this.getLength()),b=0;b>>7-a%8&1)},put:function(a,c){for(var d=0;d>>c-d-1&1))},getLengthInBits:function(){return this.length},putBit:function(a){var c=Math.floor(this.length/8);this.buffer.length<=c&&this.buffer.push(0);a&&(this.buffer[c]|=128>>>this.length%8);this.length++}};"string"===typeof h&&(h={text:h});h=r.extend({},{render:"canvas",width:256,height:256,typeNumber:-1, +correctLevel:2,background:"#ffffff",foreground:"#000000"},h);return this.each(function(){var a;if("canvas"==h.render){a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();var c=document.createElement("canvas");c.width=h.width;c.height=h.height;for(var d=c.getContext("2d"),b=h.width/a.getModuleCount(),e=h.height/a.getModuleCount(),f=0;f").css("width",h.width+"px").css("height",h.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",h.background);d=h.width/a.getModuleCount();b=h.height/a.getModuleCount();for(e=0;e").css("height",b+"px").appendTo(c);for(i=0;i").css("width", +d+"px").css("background-color",a.isDark(e,i)?h.foreground:h.background).appendTo(f)}}a=c;jQuery(a).appendTo(this)})}})(jQuery); diff --git a/payment_monero_rpc/tests/__init__.py b/monero-rpc-odoo/tests/__init__.py similarity index 100% rename from payment_monero_rpc/tests/__init__.py rename to monero-rpc-odoo/tests/__init__.py diff --git a/monero-rpc-odoo/tests/test_controllers.py b/monero-rpc-odoo/tests/test_controllers.py new file mode 100755 index 00000000..b9bc4748 --- /dev/null +++ b/monero-rpc-odoo/tests/test_controllers.py @@ -0,0 +1,6 @@ +import odoo.tests.common as common + + +class MoneroControllerTest(common.TransactionCase): + def test_monero_transaction(self): + self.assertEqual("test", "test") diff --git a/monero-rpc-odoo/tests/test_monero_acq.py b/monero-rpc-odoo/tests/test_monero_acq.py new file mode 100755 index 00000000..54f36224 --- /dev/null +++ b/monero-rpc-odoo/tests/test_monero_acq.py @@ -0,0 +1,18 @@ +from odoo.addons.payment.tests.common import PaymentAcquirerCommon + + +class MoneroCommon(PaymentAcquirerCommon): + def setUp(self): + super(MoneroCommon, self).setUp() + + # self.monero = self.env.ref("payment_acquirer_monero_rpc") + # self.monero.write({ + # 'is_cryptocurrency': True, + # 'type': 'xmr', + # etc... + # }) + + def test_update_rpc_server(self): + # this is going to fail + # self.monero.update_rpc_server() + self.assertEqual("test", "test") diff --git a/payment_monero_rpc/tests/test_sales_order.py b/monero-rpc-odoo/tests/test_sales_order.py similarity index 88% rename from payment_monero_rpc/tests/test_sales_order.py rename to monero-rpc-odoo/tests/test_sales_order.py index 8303fad3..39edb88c 100644 --- a/payment_monero_rpc/tests/test_sales_order.py +++ b/monero-rpc-odoo/tests/test_sales_order.py @@ -152,6 +152,7 @@ def setUpClass(cls, chart_template_ref=None): SalesOrder = cls.env["sale.order"].with_context(tracking_disable=True) + # set up users cls.crm_team0 = cls.env["crm.team"].create( {"name": "crm team 0", "company_id": cls.company_data["company"].id} ) @@ -174,6 +175,7 @@ def setUpClass(cls, chart_template_ref=None): } ) + # over ride the predefined partner, as it is missing a country id cls.partner_a = cls.env["res.partner"].create( { "name": "test", @@ -182,6 +184,7 @@ def setUpClass(cls, chart_template_ref=None): } ) + # create a generic Sale Order with all classical products and empty pricelist cls.sale_order = SalesOrder.create( { "partner_id": cls.partner_a.id, @@ -235,7 +238,8 @@ def setUpClass(cls, chart_template_ref=None): } ) - cls.payment_provider = cls.env["payment.provider"].create( + # define payment acquirer + cls.payment_acquirer = cls.env["payment.acquirer"].create( {"name": "Monero RPC", "journal_id": 1} ) @@ -247,26 +251,33 @@ def test_sale_order_process_transaction(self, mock_backend): transaction states are updated """ + # current state: test runs and passes, + # but only because we assertRaises(MoneroAddressReuse) + # TODO test all exceptions + # TODO test that a transaction is processed to completion + # START MAIN TEST + # define payment token payment_token = { "name": "BhE3cQvB7VF2uuXcpXp28Wbadez6GgjypdRS1F1Mzqn8Advd6q8VfaX8ZoEDobjejr" "MfpHeNXoX8MjY8q8prW1PEALgr1En", "partner_id": self.sale_order.partner_id.id, "active": False, - "acquirer_id": self.payment_provider.id, - "acquirer_ref": "payment.payment_provider_monero_rpc", + "acquirer_id": self.payment_acquirer.id, + "acquirer_ref": "payment.payment_acquirer_monero_rpc", } token = self.env["payment.token"].sudo().create(payment_token) + # setup transaction tx_val = { "amount": self.sale_order.amount_total, "reference": self.sale_order.name + "main", "currency_id": self.sale_order.currency_id.id, "partner_id": self.partner_a.id, "payment_token_id": token.id, # Associating the Payment Token ID. - "acquirer_id": self.payment_provider.id, # Payment Acquirer - Monero + "acquirer_id": self.payment_acquirer.id, # Payment Acquirer - Monero "state": "pending", } @@ -281,26 +292,30 @@ def test_sale_order_process_transaction(self, mock_backend): self.assertEqual(self.sale_order.state, "sale") self.assertEqual(transaction.state, "done") + # END MAIN TEST + # START EXCEPTION TEST: MoneroAddressReuse + # define payment token payment_token = { "name": "9tQoHWyZ4yXUgbz9nvMcFZUfDy5hxcdZabQCxmNCUukKYicXegsDL7nQpcUa3A1pF6" "K3fhq3scsyY88tdB1MqucULcKzWZC", "partner_id": self.sale_order.partner_id.id, "active": False, - "acquirer_id": self.payment_provider.id, - "acquirer_ref": "payment.payment_provider_monero_rpc", + "acquirer_id": self.payment_acquirer.id, + "acquirer_ref": "payment.payment_acquirer_monero_rpc", } token = self.env["payment.token"].sudo().create(payment_token) + # setup transaction tx_val = { "amount": self.sale_order.amount_total, "reference": self.sale_order.name, "currency_id": self.sale_order.currency_id.id, "partner_id": self.partner_a.id, "payment_token_id": token.id, # Associating the Payment Token ID. - "acquirer_id": self.payment_provider.id, # Payment Acquirer - Monero + "acquirer_id": self.payment_acquirer.id, # Payment Acquirer - Monero "state": "pending", } @@ -314,25 +329,29 @@ def test_sale_order_process_transaction(self, mock_backend): self.sale_order, transaction, token, num_confirmation_required ) + # END EXCEPTION TEST: MoneroAddressReuse + # START EXCEPTION TEST: NumConfirmationsNotMet + # define payment token payment_token = { "name": "Bf6ngv7q2TBWup13nEm9AjZ36gLE6i4QCaZ7XScZUKDUeGbYEHmPRdegKGwLT8tBBK" "7P6L32RELNzCR6QzNFkmogDjvypyV", "partner_id": self.sale_order.partner_id.id, "active": False, - "acquirer_id": self.payment_provider.id, - "acquirer_ref": "payment.payment_provider_monero_rpc", + "acquirer_id": self.payment_acquirer.id, + "acquirer_ref": "payment.payment_acquirer_monero_rpc", } token = self.env["payment.token"].sudo().create(payment_token) + # setup transaction tx_val = { "amount": self.sale_order.amount_total, "reference": self.sale_order.name + "NumConfirmationsNotMet", "currency_id": self.sale_order.currency_id.id, "partner_id": self.partner_a.id, "payment_token_id": token.id, # Associating the Payment Token ID. - "acquirer_id": self.payment_provider.id, # Payment Acquirer - Monero + "acquirer_id": self.payment_acquirer.id, # Payment Acquirer - Monero "state": "pending", } @@ -346,25 +365,30 @@ def test_sale_order_process_transaction(self, mock_backend): self.sale_order, transaction, token, num_confirmation_required ) + # END EXCEPTION TEST: NumConfirmationsNotMet + # START EXCEPTION TEST: NoTXFound + # define payment token + # this address doesn't exist, so there will be no transactions returned payment_token = { "name": "Bbvf3yAShddPnnhzUbzN4CLSaKaY8HG3kJ2pQUHiJx7ZfCDXHJ87M" "aZHWL13xKz7s9LESB4tWWFKsYAkrAd74K38Uw98cfc", "partner_id": self.sale_order.partner_id.id, "active": False, - "acquirer_id": self.payment_provider.id, - "acquirer_ref": "payment.payment_provider_monero_rpc", + "acquirer_id": self.payment_acquirer.id, + "acquirer_ref": "payment.payment_acquirer_monero_rpc", } token = self.env["payment.token"].sudo().create(payment_token) + # setup transaction tx_val = { "amount": self.sale_order.amount_total, "reference": self.sale_order.name + "NoTXFound", "currency_id": self.sale_order.currency_id.id, "partner_id": self.partner_a.id, "payment_token_id": token.id, # Associating the Payment Token ID. - "acquirer_id": self.payment_provider.id, # Payment Acquirer - Monero + "acquirer_id": self.payment_acquirer.id, # Payment Acquirer - Monero "state": "pending", } @@ -378,3 +402,4 @@ def test_sale_order_process_transaction(self, mock_backend): self.sale_order, transaction, token, num_confirmation_required ) + # END EXCEPTION TEST: NoTXFound diff --git a/monero-rpc-odoo/views/monero_acquirer_form.xml b/monero-rpc-odoo/views/monero_acquirer_form.xml new file mode 100755 index 00000000..ca1ad1a8 --- /dev/null +++ b/monero-rpc-odoo/views/monero_acquirer_form.xml @@ -0,0 +1,22 @@ + + + + payment.acquirer.form.inherit.payment.monero + payment.acquirer + + + + + + + + + + + + + + + + + diff --git a/payment_monero_rpc/views/monero_payment_template_confirmation.xml b/monero-rpc-odoo/views/monero_payment_confirmation.xml similarity index 100% rename from payment_monero_rpc/views/monero_payment_template_confirmation.xml rename to monero-rpc-odoo/views/monero_payment_confirmation.xml diff --git a/payment_monero_rpc/README.md b/payment_monero_rpc/README.md deleted file mode 100755 index d9d68045..00000000 --- a/payment_monero_rpc/README.md +++ /dev/null @@ -1,175 +0,0 @@ -# Monero RPC Payment Module for Odoo 18 - -## Overview - -This module provides Monero cryptocurrency payment integration for Odoo 18 using direct RPC calls to the Monero daemon and wallet. The module has been completely refactored from previous versions to ensure compatibility with Odoo 18's architecture while maintaining the core functionality of processing Monero payments. - -## Key Features - -- Full compatibility with Odoo 18 -- RPC communication with Monero daemon/wallet using Python Monero -- Automated payment verification through scheduled jobs -- Support for multiple wallet addresses as long `payment_ids` (which were used in previous version) are no longer supported -- Seamless integration with Odoo's payment flow - -## Technical Migration Details - -### Odoo 18 Compatibility - -This module has been specifically redesigned for Odoo 18, addressing compatibility breaks from previous versions (v15/v16/v17). Key architectural changes have been implemented to align with Odoo 18's framework requirements while maintaining the module's functionality. - -### Payment Provider Implementation - -The module now implements the `payment.provider` model instead of the deprecated `payment.acquirer` model that was used in versions prior to v15. This change follows Odoo's payment framework evolution and ensures proper integration with the current payment flow system. - -### Secondary Address System - -The module has moved away from using the long `payment_ids` (which are no longer supported) to using secondary Monero addresses for payment tracking. This architectural change provides better isolation between transactions and improves the reliability of payment matching. - -### Automated Payment Verification - -The module implements Odoo cron jobs to: - -- Periodically check for incoming transactions -- Verify transaction confirmations -- Update payment statuses accordingly -- Reconcile completed payments with orders - -This automation ensures payment integrity and reduces manual verification requirements. - -## Installation Requirements - -- Odoo 18 -- Access to a Monero wallet RPC instance -- Proper network configuration for RPC communication - -## Configuration - -After installation, the module can be configured through the Odoo Payment Provider settings: - -1. Enable the Monero payment provider -2. Configure Monero RPC connection details -3. Set confirmation thresholds and verification intervals -4. Test the connection to ensure proper communication - -## Package reorganization - -The 2 modules monero-rpc-odoo and monero-rpc-odoo-pos have been merged into one and following the naming convention for payment modules renamed to payment_monero_rpc. - -## Upgrading from Previous Versions - -Due to significant changes in both Odoo's payment framework and this module's architecture, a clean installation is recommended when upgrading from versions prior to Odoo 18. Data migration scripts are included but should be tested in a staging environment before use in production. - -# Odoo Module Migration Compatibility Table - -## Overview of Version Transitions - -| Migration Path | Compatibility Level | Major Changes | Development Effort | -|----------------|---------------------|---------------|-------------------| -| 15 → 16 | Moderate | Architecture changes, View modifications | Medium | -| 16 → 17 | Challenging | Python requirements, Major UI/UX changes | High | -| 17 → 18 | Moderate | API changes, New features integration | Medium | -| 15 → 17 | Difficult | Combined challenges of both migrations | Very High | -| 16 → 18 | Difficult | Multiple architectural changes | High | -| 15 → 18 | Very Difficult | Comprehensive rewrite often needed | Very High | - -## Detailed Migration Compatibility Table - -| Component | Odoo 15 → 16 | Odoo 16 → 17 | Odoo 17 → 18 | -|-----------|-------------|-------------|-------------| -| **Python Requirements** | Python 3.7+ → 3.8+ | Python 3.8+ → 3.10+ | Python 3.10+ → 3.11+ | -| **PostgreSQL** | 12+ → 13+ | 13+ → 14+ | 14+ → 15+ | -| **Model Structure** | Minor changes | Field attribute changes | New model patterns | -| **ORM Methods** | Some deprecations | Several renamed methods | API refinements | -| **View Architecture** | QWeb changes | Major view architecture changes | New view components | -| **JavaScript Framework** | Owl 1.0 → 2.0 | Owl 2.0 → 3.0 | Component architecture improvements | -| **Report System** | Minor changes | Major reporting engine update | Enhanced PDF capabilities | -| **Security Framework** | Compatible | New security features | Enhanced access control | -| **Business Logic** | Mostly compatible | Significant changes in core modules | New business patterns | -| **Module Structure** | Compatible | Directory structure changes | Standardized patterns | - -## Key Technical Changes By Version - -### Odoo 15 → 16 - -- **ORM Changes**: - - Deprecation of `fields.Date.context_today` in favor of new approaches - - Changes to search domain handling - - Enhanced recordset operations - -- **View Changes**: - - Owl 2.0 adoption requiring component rewrites - - Changes to QWeb template inheritance - - New kanban and list view behaviors - -- **API Changes**: - - Modified HTTP controllers architecture - - Changes in RPC call handling - - New decorators for controllers - -### Odoo 16 → 17 - -- **Major Framework Changes**: - - Python 3.10 required with new syntax possibilities - - Large-scale view architecture redesign - - Component-based UI replaces many older patterns - -- **Core Changes**: - - Authentication system modifications - - Database API changes - - New async processing capabilities - -- **Frontend**: - - Comprehensive JavaScript framework changes - - New theming system - - Responsive design improvements - -### Odoo 17 → 18 - -- **Technical Foundation**: - - Python 3.11 optimization advantages - - New database access patterns - - Enhanced caching mechanisms - -- **Developer Experience**: - - New developer tools and debugging - - Improved module testing framework - - Better documentation and typing - -- **Enterprise Features**: - - Enhanced integration capabilities - - New API endpoints - - Better extensibility points - -## Module Migration Strategy - -| Strategy Element | Recommendation | -|------------------|----------------| -| **Assessment** | Conduct thorough code analysis before migration | -| **Database** | Test data migration separately from code updates | -| **Approach** | Consider full rewrites for 15→18 migrations | -| **Testing** | Implement automated tests before migration | -| **Timeline** | Allow 1.5-3x development time compared to original module | -| **Recommended Path** | Migrate one version at a time rather than skipping | -| **Custom Modules** | Consider rebuilding vs migrating for major version jumps | -| **Community Modules** | Check for maintained versions before custom migration | - -## Common Migration Issues - -1. **Database Schema Conflicts**: Fields renamed or removed between versions -2. **API Deprecations**: Methods removed without direct replacements -3. **UI Component Incompatibility**: View definitions becoming invalid -4. **Report Template Failures**: QWeb reports requiring reconstruction -5. **Security Model Changes**: Access rights and rule modifications -6. **Performance Bottlenecks**: Previously efficient code becoming slow -7. **Third-party Dependencies**: Library compatibility issues - -## Best Practices for Migration - -1. **Modular Approach**: Migrate core functionality first, then extensions -2. **Testing Framework**: Build comprehensive tests before migration -3. **Version Control**: Use feature branches for migration work -4. **Documentation**: Document all changes and decisions during migration -5. **Incremental Testing**: Test each component after migration -6. **User Training**: Plan for training on new interfaces after migration -7. **Parallel Running**: Consider running old and new systems in parallel initially diff --git a/payment_monero_rpc/__init__.py b/payment_monero_rpc/__init__.py deleted file mode 100755 index f9d97727..00000000 --- a/payment_monero_rpc/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from . import controllers, models, hooks diff --git a/payment_monero_rpc/__manifest__.py b/payment_monero_rpc/__manifest__.py deleted file mode 100755 index 06ce90be..00000000 --- a/payment_monero_rpc/__manifest__.py +++ /dev/null @@ -1,64 +0,0 @@ -{ - "name": "payment_monero_rpc", - "summary": "Allows you to accept Monero Payments", - "author": "Monero Integrations", - "website": "https://monerointegrations.com/", - "category": "Accounting/Payment Providers", - "version": "18.0.0.0.1", - "depends": [ - "account", - "website_sale", - "website_payment", - "website", - "payment", - "queue_job", - "base_setup", - "web", - "point_of_sale", - "pos_online_payment", - ], - "external_dependencies": { - "python": ["monero"], - "npm": ["monero-ts", "crypto-browserify", "stream-browserify", "buffer"] - }, - "data": [ - "security/ir.model.access.csv", - "data/mail_templates.xml", - "data/monero_payment_data.xml", - "views/monero_daemon_views.xml", - "views/monero_payment_views.xml", - "views/monero_payment_templates.xml", - "views/monero_payment_template_confirmation.xml", - "views/monero_payment_template_email.xml", - "views/monero_payment_template_invoice.xml", - "views/monero_payment_template_proof.xml", - "views/monero_payment_kanban.xml", - "views/pos_payment_views.xml", - "views/menus.xml", - "data/monero_cron.xml", - ], - "assets": { - "web.assets_frontend": [ - "payment_monero_rpc/static/src/css/monero.css", - "payment_monero_rpc/static/src/css/monero_pos.css", - "payment_monero_rpc/static/src/css/payment_page.css", - "payment_monero_rpc/static/src/js/payment_form_monero.js", - "payment_monero_rpc/static/src/js/payment_monero_checkout.js", - ], - "web.assets_qweb": [ - "payment_monero_rpc/static/src/xml/monero_payment_template_page.xml", - ], - "point_of_sale._assets_pos": [ - "payment_monero_rpc/static/src/app/online_payment_popup_monero.js", - "payment_monero_rpc/static/src/app/payment_screen_monero.js", - "payment_monero_rpc/static/src/app/online_payment_popup_monero.xml", - ], - }, - "demo": [ - "demo/demo.xml", - ], - "installable": True, - "application": True, - "classifiers": ["License :: OSI Approved :: MIT License"], - 'post_init_hook': 'associate_monero_with_pos_configs', -} diff --git a/payment_monero_rpc/controllers/__init__.py b/payment_monero_rpc/controllers/__init__.py deleted file mode 100755 index 12a7e529..00000000 --- a/payment_monero_rpc/controllers/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from . import main diff --git a/payment_monero_rpc/controllers/main.py b/payment_monero_rpc/controllers/main.py deleted file mode 100644 index 5447d530..00000000 --- a/payment_monero_rpc/controllers/main.py +++ /dev/null @@ -1,308 +0,0 @@ -import logging -from odoo import http, _, fields -from odoo.http import request, route -from werkzeug import urls -from odoo.exceptions import AccessError, ValidationError -from odoo.addons.website_sale.controllers.main import WebsiteSale - -_logger = logging.getLogger(__name__) - -class MoneroWebsiteSale(WebsiteSale): - """Extends WebsiteSale to add Monero payment handling.""" - - def _validate_order_access(self, order_id, access_token): - """Enhanced order access validation with debug logging.""" - order_sudo = request.env['sale.order'].sudo().browse(order_id) - _logger.debug("Just return order; no validation - %s", order_sudo) - - return order_sudo - - def _validate_and_lock_order(self, order_id, access_token): - """Validate order and acquire lock for payment processing""" - try: - order_sudo = request.env['sale.order'].sudo().browse(order_id) - if not order_sudo.exists() or order_sudo.access_token != access_token: - raise MissingError(_("Order not found or invalid access token")) - - request.env.cr.execute( - SQL('SELECT 1 FROM sale_order WHERE id = %s FOR NO KEY UPDATE NOWAIT', order_id) - ) - - if order_sudo.state == "cancel": - raise ValidationError(_("The order has been cancelled.")) - - order_sudo._check_cart_is_ready_to_be_paid() - - if order_sudo.currency_id.compare_amounts(order_sudo.amount_paid, order_sudo.amount_total) == 0: - raise UserError(_("The cart has already been paid.")) - - return order_sudo - - except MissingError: - raise - except AccessError as e: - raise ValidationError(_("The access token is invalid.")) from e - except LockNotAvailable: - raise UserError(_("Payment is already being processed.")) - - @route('/shop/payment/monero/process/', type='json', auth='public', website=True, csrf=True) - def _process_monero_payment(self, order_sudo, provider, **kwargs): - """Core Monero payment processing logic""" - order = request.env['sale.order'].search([('id', '=', order_sudo)], limit=1) - currency = order.currency_id.name - amount = order.amount_total - provider = request.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - - if currency != 'XMR': - rate = provider.get_xmr_rate(currency) - if not rate or rate <= 0: - raise UserError(_("Could not get exchange rate for %s") % currency) - amount = amount / rate - - payment = provider._create_monero_from_fiat_payment(order.name, order.amount_total, order.currency_id, order) - - currencyXmr = request.env['res.currency'].search([('name', '=', 'XMR')], limit=1) - - required_confirmations = int(request.env['ir.config_parameter'].sudo().get_param('monero.required_confirmations', default=10)) - - if payment.expiration: - expiration_str = payment.expiration.strftime("%Y-%m-%d %H:%M:%S") - else: - expiration_str = None - - invoice_ids = order.invoice_ids.ids - - payment_data = { - 'id': payment.id, - 'address_seller': payment.address_seller, - 'amount_str': '%.12f' % payment.amount, - 'state': payment.state, - 'order_ref': order.name, - 'confirmations': payment.confirmations, - 'required_confirmations': required_confirmations, - 'original_amount_str': '%.2f' % order.amount_total, - 'original_currency': order.currency_id.name, - 'exchange_rate_str': '%.2f' % payment.exchange_rate, - 'payment_id': payment.payment_id, - 'image_qr': payment.image_qr, - 'expiry_time_str': expiration_str, - 'sale_order_id': order.id, - 'status_alert_class': payment._get_status_alert_class(), - 'status_icon': payment._get_status_icon(), - 'status_message': payment._get_status_message(), - 'monero_symbol': currencyXmr.symbol, - 'invoice_ids': invoice_ids, - 'monero_uri': f"monero:{payment.address_seller}?tx_amount={payment.amount:.12f}", - } - - _logger.debug("Payment Data: %s", payment_data) - - request.session['monero_payment_data'] = payment_data - - return { - "success": True, - "payment": payment_data, - "payment_id": payment_data["payment_id"], - } - - @route('/shop/payment/monero/transaction', type='http', auth='public', website=True, csrf=True, methods=['GET']) - def monero_payment_processor(self, **kwargs): - """ - Process Monero payments and display payment page - """ - try: - required_params = ['order_id', 'access_token', 'provider_id', 'amount'] - if not all(k in kwargs for k in required_params): - raise ValueError("Missing required parameters") - - order_id = int(kwargs['order_id']) - access_token = kwargs['access_token'] - amount = float(kwargs['amount']) - provider = request.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - - order_sudo = request.env['sale.order'].sudo().browse(order_id) - if not order_sudo.exists() or not order_sudo._verify_access_token(access_token): - raise AccessError("Order access denied") - - payment = provider._create_monero_from_fiat_payment(order_sudo.name, order_sudo.amount_total, order_sudo.currency_id, order_sudo) - - return request.redirect(f'/shop/payment/monero/page/{payment.id}') - - except Exception as e: - _logger.exception("Monero payment processing failed") - return request.redirect(f'/shop/payment/error?message=monero_processing_error') - - @route('/shop/payment/monero/status/', type='json', auth='public', website=True) - def check_payment_status(self, payment_id, **kwargs): - """Check payment status and confirmations""" - provider = request.env['payment.provider'].sudo().search([('code', '=', 'monero_rpc')], limit=1) - payment = request.env['monero.payment'].sudo().search([('payment_id', '=', payment_id)], limit=1) - - if not payment.exists(): - return {'error': 'Payment not found', 'status': 'error'} - - if not provider: - return {'error': 'Provider not found', 'status': 'error'} - - try: - result = payment.check_payment_status(payment_id) - - return { - 'status': payment.state, - 'status_message': payment._get_status_message(), - 'status_alert_class': payment._get_status_alert_class(), - 'status_icon': payment._get_status_icon(), - 'amount_received': payment.amount, - 'amount_str': "%.12f" % payment.amount, - 'required_amount': payment.amount, - 'confirmations': payment.confirmations, - 'original_amount': payment.original_amount, - 'original_currency': payment.original_currency, - 'exchange_rate': payment.exchange_rate, - 'required_confirmations': provider.confirmation_threshold - payment.confirmations, - 'expired': payment.expiration < fields.Datetime.now(), - 'expiry_time_str': payment.expiration.strftime("%Y-%m-%d %H:%M:%S") if payment.expiration else None - } - except Exception as e: - _logger.exception("Failed to check payment status for payment %s", payment_id) - return { - 'error': str(e), - 'status': 'error', - 'status_message': "Error checking payment status", - 'status_alert_class': 'danger', - 'status_icon': 'fa-exclamation-circle' - } - - @route('/shop/payment/monero/qr/', type='http', auth='public') - def generate_qr_code(self, payment_id): - """Generate Monero payment QR code""" - _logger.debug("Generating QR Code for payment %d: ", payment_id) - payment = request.env['monero.payment'].sudo().browse(payment_id) - if not payment.exists(): - return request.not_found() - - try: - import qrcode - from io import BytesIO - - monero_uri = f"monero:{payment.address_seller}?tx_amount={payment.amount}" - if payment.description: - monero_uri += f"&tx_description={payment.description}" - - qr = qrcode.QRCode( - version=1, - error_correction=qrcode.constants.ERROR_CORRECT_L, - box_size=10, - border=4, - ) - qr.add_data(monero_uri) - qr.make(fit=True) - - img = qr.make_image(fill_color="black", back_color="white") - buffer = BytesIO() - img.save(buffer, format="PNG") - buffer.seek(0) - - return request.make_response( - buffer.getvalue(), - headers=[('Content-Type', 'image/png')] - ) - except Exception as e: - _logger.error("QR generation failed: %s", str(e)) - return request.not_found() - - - @route('/shop/payment/monero/page/', auth='public', website=True) - def payment_page(self, payment_id, **kwargs): - """Display payment page for customers""" - payment = request.env['monero.payment'].sudo().browse(payment_id) - if not payment.exists(): - return request.not_found() - - payment_data = request.session.pop('monero_payment_data', None) - if not payment_data: - return request.redirect('/shop?error=session_expired') - - _logger.debug("About to render: %s", payment_data); - - return request.render('payment_monero_rpc.monero_payment_page', { - 'payment': payment_data, - 'monero_uri': f"monero:{payment_data['address_seller']}?tx_amount={payment_data['amount_str']}", - 'is_dark': False, - }) - - @route('/shop/payment/monero/verify', type='http', auth='none', csrf=False) - def verify_payments(self, payment_ids): - """Bulk verification endpoint for cron jobs""" - try: - payments = request.env['monero.payment'].sudo().browse(payment_ids) - results = [] - for payment in payments: - if payment.state not in ('confirmed', 'failed'): - result = self.check_payment_status(payment.id) - results.append({ - 'payment_id': payment.id, - 'status': result.get('status'), - 'amount_received': result.get('amount_received'), - 'confirmations': result.get('confirmations') - }) - return results - except Exception as e: - _logger.error("Bulk verification failed: %s", str(e)) - return {'error': str(e)} - - @route('/shop/payment/monero/invoice/', type='http', auth='public') - def generate_invoice(self, payment_id, **kwargs): - """Generate PDF invoice for payment""" - payment = request.env['monero.payment'].sudo().browse(payment_id) - if not payment.exists(): - return request.not_found() - - pdf = request.env['ir.actions.report'].sudo()._render_qweb_pdf( - 'payment_monero_rpc.monero_payment_invoice', - [payment.id], - data={'payment': payment} - )[0] - - return request.make_response( - pdf, - headers=[ - ('Content-Type', 'application/pdf'), - ('Content-Disposition', f'attachment; filename=Monero_Payment_{payment.id}.pdf') - ] - ) - - @route('/shop/payment/monero/proof/', type='http', auth='public') - def generate_proof(self, payment_id, **kwargs): - """Generate payment proof PDF""" - payment = request.env['monero.payment'].sudo().browse(payment_id) - if not payment.exists() or payment.state != 'confirmed': - return request.not_found() - - proof_data = { - 'tx_ids': [tx.txid for tx in payment.transaction_ids], - 'amount': payment.amount_received, - 'confirmations': payment.confirmations, - 'timestamp': fields.Datetime.now() - } - - pdf = request.env['ir.actions.report'].sudo()._render_qweb_pdf( - 'payment_monero_rpc.monero_payment_proof', - [payment.id], - data={'proof': proof_data} - )[0] - - return request.make_response( - pdf, - headers=[ - ('Content-Type', 'application/pdf'), - ('Content-Disposition', f'attachment; filename=Monero_Proof_{payment.id}.pdf') - ] - ) - - @http.route('/shop/payment/monero/translation', type='json', auth='public') - def get_translations(self, lang, **kwargs): - return request.env['ir.translation'].sudo().search_read( - [('module', '=', 'payment_monero_rpc'), ('lang', '=', lang)], - ['src', 'value'] - ) diff --git a/payment_monero_rpc/data/mail_templates.xml b/payment_monero_rpc/data/mail_templates.xml deleted file mode 100644 index 91c5306b..00000000 --- a/payment_monero_rpc/data/mail_templates.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - Monero Payment Confirmed - - Your Payment Has Been Confirmed - ${object.company_id.email or 'noreply@example.com'} - ${object.partner_id.email} - -

Payment Confirmed

-

Dear ${object.partner_id.name},

- -

We're pleased to inform you that your Monero payment has been confirmed with the following details:

- - - - - - - - - - - - - - - - - - -
Amount Expected:${object.amount} XMR
Amount Received:${object.amount_received} XMR
Confirmations:${object.confirmations}
Payment Address:${object.address_seller}
- - % if object.transaction_ids: -

Transaction Details:

-
    - % for tx in object.transaction_ids: -
  • - TXID: ${tx.txid}
    - Amount: ${tx.amount} XMR
    - Block Height: ${tx.block_height or 'Pending'}
    - Fee: ${tx.fee} XMR
    - Timestamp: ${tx.timestamp} -
  • - % endfor -
- % endif - -

Thank you for your payment. Your order will now be processed.

- -

Best regards,
- ${object.company_id.name}

- -

- If you have any questions, please contact us at ${object.company_id.email or 'our support email'}. -

- -]]>
-
-
-
diff --git a/payment_monero_rpc/data/monero_cron.xml b/payment_monero_rpc/data/monero_cron.xml deleted file mode 100644 index 5f3e124a..00000000 --- a/payment_monero_rpc/data/monero_cron.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - Update Monero Payment Provider - - code - model._cron_update_payment_provider() - 5 - minutes - True - - - - - Monero: Check Expired Payments - - code - model._cron_check_expired_payments() - 1 - hours - True - - - - Monero: Check Payment Status - - code - model._cron_check_payment_status() - 10 - minutes - True - - - - Monero: Check Payment Expiration - - code - model._cron_check_expired_payments() - 10 - minutes - True - - - - Monero: Update Exchange Rates - - code - model._cron_update_xmr_rates() - 6 - hours - True - - - - Verify Monero Payments - - code - model._cron_verify_pending_payments() - 10 - minutes - True - - - - Check Monero Daemons - - code - model._cron_check_daemon_status() - 5 - minutes - True - - diff --git a/payment_monero_rpc/data/monero_payment_data.xml b/payment_monero_rpc/data/monero_payment_data.xml deleted file mode 100644 index e6b41f1d..00000000 --- a/payment_monero_rpc/data/monero_payment_data.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - - monero.rpc_url - http://localhost:38082/json_rpc - - - - monero.required_confirmations - 2 - - - - XMR - Monero - Monero - ɱ - after - True - - 6 - 0.000001 - - - - Monero RPC - monero_rpc - 10 - True - iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAGRUlEQVR4nO2dP2scVxTFr0OQTaoUShOIIWCCscBFEAiMIao1960IZEuD82dmK+cL5AO4MW5cpE+TwvgTuHCfyoWTGOMiCJMmkMohCrb1Ukha9Gd3dt97971z3+z9we2kmfPOuW/nand2RGQYhmEYhmEYhmEYhmEYhjFo/IQ2/YQ20ToMYXxLn/mO7vmOfvMd+cR64Vu67yd0Db0uYw6+oy3f0S8CYS9bT31LN9DrXmn8hDYLBt5f1gxl8Hfoom/pD3jg82vP36ZLaJ8Gh2+JfUdvFQS87CvCge9ojPatenxLI3iY6WWNEIq/TR8qCE62vqGP0b5Wge/oL3hY+epvtL9q8R39oCCgUnUX7bca/Da9ryAQTI1pDe0/FP8tXYGHgK6WNtA5QPAd/Qw3X089RudRFN/R7wpM11Yv0bkUwXf0rwKztdY+Op+sKDC4ikLnlAXf0Ru0sRXVO3ReoigwtMpC5yaCt2t+StU9E3ib9iVqD51jFN7+zperlp6g8wzC3uHLUlvoXJdipd/bz101fHYAN2nghc63F79aH+mi6gE657koMGclCp3zTHzInTxjWkObqLDWA35W1/sDoffwTX8Pb7qKivTjKibtGUQveIg3f4bXeqqPUGJu3T71+1/TRwpCQNXlU16E//6kbNoziFn4uWOs5kywnsPLohx9Y0dMtIJQipTo+lu6lSfdJfCRX9eae7zVmAnO7fwTfsYcD3PvgL9DF6V3ANHgZ4LLvWuPPS7iC6kp39JdeOxhzgRzd/503bHHbum1TKoBpJhR4hyaSpOnIqQ+nGHp8wxjJli486frTTlPS6O4NCMotSOIqp8Jeq/5SF+TKC200plg6Z2P8jUKf/hAJohQBaHqXl+Jy4AXeBpX9LnrmAmCd/4Jb1PP/Sz23CVFJr1UKZ8Jgq752rytRqTSmSB652vytl/g4RM41YhUELq+9XxH16X0zBJ4T5VhOmaC5J0/XY+EnpYeSumZJVDi2buiL1PgmSDpmn9uLTKa8n2TSMo4cV2YmUBs50/XodTfagSWCl+7/lz61AssNBOI7/ypfuX+6hdI2WcC0Wv+Oe3a/VUv8Fhnnpkg286f6tbur3qBptca4JRemZkg+86f6tXsr+R/6MgicJ7utJkg6zX/nFYhf31HN+XFARugaZoDInovWnvcTJC085n5bbBOzQ0gKTD0vMzsmdkT0YUS+lPOcUZvFn259asTeGwoMyfdA7/kTJC8860B8jWAj3lpPbWG/pkg6ZrPzG9Oag3WZg0wmzMN4DPNBGI73xogcwNIzwQpx1igL0qPNcAZ5hksNBOI73xrgHINkDwTpHD2mr8KDfBCYQMkzwQx9O18cAO8yrHeQ4Et3dfYAFIzQQY9QQg1wKMcaz4UOKFrmhsgdSZYUsvCnQ9tgAlt5li3qMjQcwY0QNaZYNE1X0MD5Fg3XGRgA2SZCUJ2/tAb4Kn2BpCeCRLOH4TAy/9zifX2i2zpRi0NIDETxOx8WAO09GXqeosIDT1fQgMkzQSh13x0A8SuM5jKGiBqJkjZ+YNvgNKkBhE6Ewiez5BAKhBeYiaQ2PnWAMIINoDnnpmAE6/51gCZEG6AmTOB5M63BhBGOpgTAV3IfHxDglwBMfO7HDvfGkCYjA2QtdC+DQZ0kNYAYNBBWgOAQQdpDbAEu7u7n4xGoys5Ch1kbOXywzn3KTrvmaANX5VC5zwXZr6LNmcF6kd0zr0oMGjQhc53IePxeA1t0lBrY2ND/7+PJyJyzm2gzRpaOee+QOcaBDM/Rps2lHLO/YrOMwrn3Eu0ebVX0zR/onNMgpn30SZWXP+h8xNBgZFVFjo3Ufjwo1e4qTXU0Q0rwwNtbC2FzikrbDNBXw3jmr8IZt5TYLaqqn7aD4WZn6BN11LV/p2fys7OzhbafHRV9w6fNKv82UE17+2XgJkfoAMpWD+h/VYLD/uvhH20v1XgnLuqICzRcs59jva1OpxzE3RwAsF/j/axepxzt7iit5Kbpjlwzk3Qvg2O7e3tS8z8Gh1wT/3jnPsA7dNK0DTNSEHgx/UVFXpIpTGDo2Z4VjDw58xc5oFMRjij0eg6Mz9kmc8cXjVN82g0GuV9AqdRHufcTedcnn+wZBiGYRiGYRiGYRiGYRiGoYb/AQAMs8YURpuiAAAAAElFTkSuQmCC - False - True - none - - - - - Monero RPC - monero_rpc - enabled - True - False - True - - - stagenet - http://localhost:38081/json_rpc - http://localhost:38082/json_rpc - rpc_user - rpc_password - 180 - odoo_wallet - odoo_wallet_password - /home/niyid/monero-x86_64-linux-gnu-v0.18.3.4/wallets - - https://api.coingecko.com/api/v3/simple/price - - - - - - Monero RPC - False - True - - - - Monero Payments - monero.payment - list,form - -

- No payments found. You'll see Monero payments here after they're created. -

-
-
- - - Monero Payment Reference - monero.payment - XMR- - 4 - - -
-
diff --git a/payment_monero_rpc/hooks.py b/payment_monero_rpc/hooks.py deleted file mode 100644 index d66c0cc9..00000000 --- a/payment_monero_rpc/hooks.py +++ /dev/null @@ -1,38 +0,0 @@ -import base64 -from odoo.modules.module import get_module_resource -from odoo import SUPERUSER_ID - -def load_monero_logo(): - logo_path = get_module_resource('payment_monero_rpc', 'static/src/img', 'logo.png') - with open(logo_path, 'rb') as logo_file: - return base64.b64encode(logo_file.read()) - -def associate_monero_with_pos_configs(cr, registry): - from odoo.api import Environment - env = Environment(cr, SUPERUSER_ID, {}) - logo_base64 = load_monero_logo() - - PaymentMethod = env['pos.payment.method'] - monero_method = PaymentMethod.search([('name', '=', 'Monero RPC')], limit=1) - if not monero_method: - monero_method = PaymentMethod.create({ - 'name': 'Monero RPC', - 'is_cash_count': False, - 'use_payment_terminal': False, - 'image': logo_base64, - }) - elif not monero_method.image: - monero_method.image = logo_base64 - - PaymentProvider = env['payment.provider'] - monero_provider = PaymentProvider.search([('code', '=', 'monero')], limit=1) - if monero_provider and not monero_provider.image_128: - monero_provider.image_128 = logo_base64 - - target_pos_names = ['Furniture Shop', 'Bakery Shop', 'Clothes Shop'] - PosConfig = env['pos.config'] - for name in target_pos_names: - pos_config = PosConfig.search([('name', '=', name)], limit=1) - if pos_config and monero_method not in pos_config.payment_method_ids: - pos_config.payment_method_ids += monero_method - diff --git a/payment_monero_rpc/models/__init__.py b/payment_monero_rpc/models/__init__.py deleted file mode 100755 index 94ce0288..00000000 --- a/payment_monero_rpc/models/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -from . import payment_provider, monero_payment, monero_transactions, monero_daemons, res_config_settings, pos_payment - - -import hashlib -import os - -def initialize_proof_system(): - if not os.getenv('ODOO_MONERO_PROOF_KEY'): - key = secrets.token_hex(32) - os.environ['ODOO_MONERO_PROOF_KEY'] = key - config = self.env['ir.config_parameter'].sudo() - config.set_param('monero.payment_proof_key', key) diff --git a/payment_monero_rpc/models/monero_daemons.py b/payment_monero_rpc/models/monero_daemons.py deleted file mode 100644 index 2903db5f..00000000 --- a/payment_monero_rpc/models/monero_daemons.py +++ /dev/null @@ -1,105 +0,0 @@ -from odoo import models, fields, api, _ -from odoo.exceptions import UserError -import logging -import monero -from monero.backends.jsonrpc import JSONRPCDaemon -from monero.exceptions import NoDaemonConnection, DaemonIsBusy - -_logger = logging.getLogger(__name__) - -class MoneroDaemon(models.Model): - _name = 'monero.daemon' - _description = 'Monero Daemon Status' - - name = fields.Char(default='Monero Daemon') - last_checked = fields.Datetime(readonly=True) - state = fields.Selection([ - ('online', 'Online'), - ('offline', 'Offline'), - ('syncing', 'Syncing') - ], readonly=True) - network = fields.Selection([ - ('mainnet', 'Mainnet'), - ('testnet', 'Testnet'), - ('stagenet', 'Stagenet') - ], readonly=True) - version = fields.Char(readonly=True) - current_height = fields.Integer(readonly=True) - target_height = fields.Integer(readonly=True) - connections = fields.Integer(readonly=True) - update_available = fields.Boolean(readonly=True) - last_error = fields.Text(readonly=True) - - @api.model - def get_current_height(self): - daemon = self.search([], limit=1, order='id desc') - return daemon.current_height if daemon else 0 - - @api.model - def _cron_check_daemon_status(self): - """Regular daemon status check using monero-python""" - _logger.info("==== CRON JOB STARTED ====") - try: - provider = self.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - if not provider: - error_msg = "Monero RPC provider not found" - _logger.error(error_msg) - return False - - daemon = self.env['monero.daemon'].search([], limit=1, order='id desc') - if not daemon: - self.env['monero.daemon'].sudo().create({ - 'last_checked': fields.Datetime.now(), - 'state': 'offline', - 'network': 'stagenet', - 'version': 'unknown', - 'current_height': 0, - 'target_height': 0, - 'connections': 0, - 'update_available': False, - 'last_error': False - }) - - try: - daemon_rpc = provider._get_daemon() - - info = daemon_rpc.info() - - vals = { - 'last_checked': fields.Datetime.now(), - 'state': 'online', - 'network': provider.network_type, - 'version': info.version, - 'current_height': info.height, - 'target_height': info.target_height, - 'connections': info.incoming_connections_count + info.outgoing_connections_count, - 'update_available': info.update_available, - 'last_error': False - } - - if vals['current_height'] < vals['target_height']: - vals['state'] = 'syncing' - - daemon = self.search([], limit=1, order='id desc') - daemon.sudo().write(vals) - _logger.info("Monero daemon record updated %s", vals) - return True - - except NoDaemonConnection as e: - _logger.error("Daemon connection failed: %s", str(e)) - self.update({ - 'last_checked': fields.Datetime.now(), - 'state': 'offline', - 'last_error': str(e) - }) - except DaemonIsBusy as e: - _logger.error("Daemon is busy: %s", str(e)) - self.update({ - 'last_checked': fields.Datetime.now(), - 'state': 'offline', - 'last_error': str(e) - }) - - except Exception as e: - _logger.exception("Failed to check daemon status") - raise UserError(_("Failed to check daemon status: %s") % str(e)) diff --git a/payment_monero_rpc/models/monero_payment.py b/payment_monero_rpc/models/monero_payment.py deleted file mode 100644 index 74c00811..00000000 --- a/payment_monero_rpc/models/monero_payment.py +++ /dev/null @@ -1,532 +0,0 @@ -import logging -import secrets -import base64 -import hashlib -import json -from decimal import Decimal -from io import BytesIO -from datetime import datetime, timedelta - -import qrcode -import monero -import urllib.parse -from monero.wallet import Wallet -from monero.backends.jsonrpc import JSONRPCWallet -from monero.daemon import Daemon - -from odoo import models, fields, api, _ -from odoo.exceptions import UserError, ValidationError -from odoo.tools import float_compare - -_logger = logging.getLogger(__name__) - - -class MoneroPayment(models.Model): - _name = 'monero.payment' - _description = 'Monero Payment' - _order = 'create_date desc' - _rec_name = 'display_name' - _inherit = ['mail.thread', 'mail.activity.mixin'] - - display_name = fields.Char( - string="Reference", - compute='_compute_display_name', - store=True) - payment_id = fields.Integer( - string="Payment ID", - required=True, - readonly=True, - index=True) - sale_order_id = fields.Many2one( - 'sale.order', - string="Sales Order", - readonly=True, - index=True) - address_seller = fields.Char( - string="Receiving Address", - readonly=True, - required=True) - address_buyer = fields.Char(string="Buyer Address") - subaddress_index = fields.Integer( - string="Subaddress Index", - readonly=True) - amount = fields.Float( - string="Amount (XMR)", - required=True, - digits=(12, 12)) - amount_received = fields.Float( - string="Amount Received (XMR)", - readonly=True, - digits=(12, 12), - default=0.0) - amount_due = fields.Float( - string="Amount Due (XMR)", - compute='_compute_amount_due', - digits=(12, 12)) - currency = fields.Char( - string="Currency", - default="XMR", - required=True, - readonly=True) - order_ref = fields.Char( - string="Order Reference", - index=True) - description = fields.Text(string="Description") - state = fields.Selection( - selection=[ - ('draft', 'Draft'), - ('pending', 'Pending Payment'), - ('partial', 'Partially Paid'), - ('paid_unconfirmed', 'Paid (Unconfirmed)'), - ('confirmed', 'Confirmed'), - ('expired', 'Expired'), - ('failed', 'Failed'), - ('overpaid', 'Overpaid')], - string='Status', - default='draft', - readonly=True, - index=True, - tracking=True) - confirmations = fields.Integer( - string="Confirmations", - readonly=True, - compute='_compute_confirmations', - store=True) - expiration = fields.Datetime( - string="Expiration Date", - required=True, - default=lambda self: fields.Datetime.now() + timedelta(hours=1)) - create_date = fields.Datetime( - string="Creation Date", - readonly=True) - error_message = fields.Text( - string="Error Message", - readonly=True) - transaction_ids = fields.One2many( - 'monero.transaction', - 'payment_id', - string="Transactions") - original_amount = fields.Float( - string="Original Amount", - digits=(16, 2)) - original_currency = fields.Char( - string="Original Currency", - default="USD") - exchange_rate = fields.Float( - string="Exchange Rate", - digits=(16, 6)) - image_qr = fields.Char( - string="QR Code", - compute='_compute_qr_code') - last_check = fields.Datetime( - string="Last checked") - qr_code_uri = fields.Char( - string="Monero URI", - compute='_compute_qr_code_uri') - is_subaddress = fields.Boolean( - string="Uses Subaddress", - default=True, - readonly=True) - - _sql_constraints = [ - ('payment_id_unique', 'UNIQUE(payment_id)', 'Payment ID must be unique!'), - ('amount_positive', 'CHECK(amount > 0)', 'Amount must be positive!'), - ] - - @api.depends('order_ref', 'amount', 'currency') - def _compute_display_name(self): - for payment in self: - payment.display_name = f"{payment.order_ref or 'Payment'} - {payment.amount:.12f} {payment.currency}" - - @api.depends('amount', 'amount_received') - def _compute_amount_due(self): - for payment in self: - payment.amount_due = max(0.0, payment.amount - payment.amount_received) - - @api.depends('transaction_ids.confirmations') - def _compute_confirmations(self): - for payment in self: - if not payment.transaction_ids: - payment.confirmations = 0 - else: - payment.confirmations = min( - tx.confirmations for tx in payment.transaction_ids - if tx.confirmations is not None) - - @api.depends('address_seller', 'amount', 'payment_id', 'order_ref') - def _compute_qr_code_uri(self): - for payment in self: - if payment.address_seller: - desc = f"Order {payment.order_ref}" if payment.order_ref else "Payment" - payment.qr_code_uri = ( - f"monero:{payment.address_seller}" - f"?tx_amount={payment.amount:.12f}" - f"&tx_payment_id={payment.payment_id}" - f"&tx_description={desc}" - ) - else: - payment.qr_code_uri = False - - @api.depends('qr_code_uri') - def _compute_qr_code(self): - for payment in self: - if payment.qr_code_uri: - qr = qrcode.QRCode( - version=1, - error_correction=qrcode.constants.ERROR_CORRECT_L, - box_size=10, - border=4, - ) - qr.add_data(payment.qr_code_uri) - qr.make(fit=True) - - img = qr.make_image() - buffered = BytesIO() - img.save(buffered, format="PNG") - payment.image_qr = base64.b64encode(buffered.getvalue()) - else: - payment.image_qr = False - - @api.model_create_multi - def create(self, vals): - _logger.debug("Creating...%s", vals) - - vals = vals[0] - if not vals['payment_id']: - vals['payment_id'] = secrets.token_hex(32) - - return super().create(vals) - - @api.model - def _get_current_block_height(self): - """Get current blockchain height""" - provider = self.env['payment.provider']._get_monero_provider() - try: - daemon = provider._get_daemon() - return daemon.height() - except Exception as e: - _logger.error("Failed to get block height: %s", str(e)) - return 0 - - def refresh_exchange_rate(self): - """Refresh the exchange rate for this payment""" - self.ensure_one() - provider = self.env['payment.provider']._get_monero_provider() - try: - rate = provider._get_xmr_exchange_rate(self.original_currency) - if rate: - self.exchange_rate = rate - return True - except Exception as e: - _logger.error("Failed to fetch exchange rate: %s", str(e)) - return False - - def serialize_transfer(self, transfer): - data = {} - for key, value in transfer.__dict__.items(): - if isinstance(value, Decimal): - data[key] = float(str(value)) - elif isinstance(value, datetime): - data[key] = value.isoformat() - elif hasattr(value, '__str__'): - data[key] = str(value) - else: - data[key] = value - return data - - def check_payment_status(self, paymentId): - """Check payment status for specific subaddress minor index""" - self.ensure_one() - provider = self.env['payment.provider']._get_monero_provider() - moneroPayment = self.env['monero.payment'].search([('payment_id', '=', int(paymentId))], limit=1) - - try: - wallet = provider._get_wallet_client() - current_height = moneroPayment._get_current_block_height() - - all_incoming = wallet.incoming() - filtered = [ - t for t in all_incoming - if getattr(t, "local_address", None) == moneroPayment.address_seller - ] - _logger.debug("All incoming transfers: %s", filtered) - - _logger.info("Found %d payment(s) for subaddress index=%d", len(filtered), int(paymentId)) - - transactions = [] - total_received = Decimal('0.0') - - for transfer in filtered: - tx_data = { - 'txid': transfer.transaction.hash, - 'amount': float(transfer.amount), - 'fee': float(transfer.transaction.fee), - 'block_height': transfer.transaction.height, - 'timestamp': transfer.transaction.timestamp, - 'confirmations': transfer.transaction.confirmations, - 'payment_id': moneroPayment.id, - } - transactions.append(tx_data) - total_received += Decimal(str(transfer.amount)) - - amount_received_float = float(total_received) - amount_expected_float = float(Decimal(str(self.amount))) - - amount_compare = float_compare( - amount_received_float, - amount_expected_float, - precision_digits=12 - ) - - new_state = 'pending' - if amount_compare == 0: - for t in filtered: - _logger.debug("Confirmation - monero_payment - %d, %d", t.transaction.confirmations, provider.confirmation_threshold) - if t.transaction.confirmations >= provider.confirmation_threshold: - new_state = 'confirmed' - self._payment_confirmed(moneroPayment, { - 'amount_received': total_received, - 'state': new_state, - 'last_check': fields.Datetime.now(), - 'confirmations': max((t['confirmations'] for t in transactions), default=0) - }) - break - else: - _logger.debug("Payment made but unconfirmed") - new_state = 'paid_unconfirmed' - elif amount_compare == -1: - new_state = 'partial' if total_received > 0 else 'pending' - else: - new_state = 'overpaid' - - self.transaction_ids.unlink() - if transactions: - self.env['monero.transaction'].create(transactions) - - update_vals = { - 'amount_received': total_received, - 'state': new_state, - 'last_check': fields.Datetime.now(), - 'confirmations': max((t['confirmations'] for t in transactions), default=0) - } - - self.write(update_vals) - - return { - 'state': new_state, - 'amount_received': total_received, - 'confirmations': update_vals['confirmations'], - 'transactions': transactions - } - - except Exception as e: - _logger.error("Payment check failed: %s", str(e), exc_info=True) - self._handle_rpc_error(str(e)) - return { - 'state': 'error', - 'error': str(e) - } - - - def generate_payment_proof(self): - """Generate cryptographic proof of payment""" - self.ensure_one() - if self.state != 'confirmed': - raise UserError(_("Payment must be confirmed to generate proof")) - - proof_data = { - 'payment_id': self.payment_id, - 'address': self.address, - 'amount': self.amount_received, - 'confirmations': self.confirmations, - 'tx_hashes': [tx.txid for tx in self.transaction_ids], - 'timestamp': fields.Datetime.now().isoformat(), - 'block_height': min(tx.block_height for tx in self.transaction_ids), - 'signature': self._generate_signature() - } - - attachment = self.env['ir.attachment'].create({ - 'name': f"Monero_Payment_Proof_{self.payment_id}.json", - 'type': 'binary', - 'datas': base64.b64encode(json.dumps(proof_data, indent=2).encode()), - 'res_model': self._name, - 'res_id': self.id, - 'mimetype': 'application/json' - }) - - return { - 'proof': proof_data, - 'attachment_id': attachment.id - } - - def _generate_signature(self): - """Create cryptographic signature for payment proof""" - private_key = self.env['ir.config_parameter'].sudo().get_param( - 'monero.payment_proof_key') - if not private_key: - raise UserError(_("Payment proof system not configured - missing private key")) - - data = f"{self.payment_id}:{self.amount_received}:{self.address}" - return hashlib.sha256((data + private_key).encode()).hexdigest() - - def _payment_confirmed(self, payment, values): - """Handle confirmed payment""" - try: - self.write(values) - - if payment.sale_order_id: - tx = self.env['payment.transaction'].sudo().search([ - ('payment_id', '=', payment.id) - ], limit=1) - if tx: - tx._set_done() - if tx.state == 'done': - payment.sale_order_id._send_order_confirmation_mail() - - order = self.env['sale.order'].search([ - ('id', '=', self.sale_order_id.id) - ], limit=1) - if order: - try: - if order.state in ['draft', 'sent']: - order.with_context(send_email=True).action_confirm() - elif order.state == 'sale': - _logger.info(f"Order {self.order_ref} is already confirmed") - else: - _logger.warning(f"Order {self.order_ref} is in unexpected state {order.state}") - except Exception as e: - _logger.error(f"Failed to process order {self.order_ref}: {str(e)}") - - template = self.env.ref('payment_monero_rpc.email_template_payment_confirmed') - template.send_mail(self.id, force_send=True) - - self.message_post(body=_( - "Payment confirmed with %d confirmations. " - "Amount received: %f XMR") % ( - self.confirmations, - self.amount_received - )) - except Exception as e: - _logger.error("Payment confirmation failed: %s", str(e)) - raise - - def _handle_rpc_error(self, error_message): - """Handle RPC errors""" - self.write({ - 'error_message': error_message, - 'state': 'failed', - 'last_check': fields.Datetime.now() - }) - - @api.model - def _cron_check_expired_payments(self): - """Mark expired payments""" - expired = self.search([ - ('state', 'in', ['pending', 'partial']), - ('expiration', '<', fields.Datetime.now()) - ]) - expired.write({'state': 'expired'}) - _logger.info("Marked %d payments as expired", len(expired)) - - @api.model - def _cron_update_payment_rates(self): - """Update exchange rates for pending payments""" - pending_payments = self.search([ - ('state', 'in', ['pending', 'partial']), - ('original_currency', '!=', 'XMR') - ]) - - for payment in pending_payments: - try: - payment.refresh_exchange_rate() - except Exception as e: - _logger.error("Failed to update rate for payment %d: %s", payment.id, str(e)) - - @api.model - def _cron_verify_pending_payments(self): - """Scheduled job to verify pending payments""" - payments = self.search([ - ('state', 'in', ['pending', 'partial', 'paid_unconfirmed']), - ('expiration', '>', fields.Datetime.now()) - ], limit=100) # Process in batches - - _logger.info("Checking %d pending payments...", len(payments)) - for payment in payments: - try: - payment.check_payment_status() - except Exception as e: - _logger.error( - "Failed to verify payment %d: %s", - payment.id, - str(e)) - payment.message_post(body=f"Verification failed: {str(e)}") - - def action_view_transactions(self): - """Action to view payment transactions""" - self.ensure_one() - return { - 'name': _('Transactions'), - 'view_mode': 'tree,form', - 'res_model': 'monero.transaction', - 'type': 'ir.actions.act_window', - 'domain': [('payment_id', '=', self.id)], - 'context': {'default_payment_id': self.id} - } - - def _get_status_alert_class(self): - """Get Bootstrap alert class for current status""" - self.ensure_one() - return { - 'pending': 'info', - 'partial': 'warning', - 'paid_unconfirmed': 'warning', - 'confirmed': 'success', - 'expired': 'danger', - 'failed': 'danger', - 'overpaid': 'success' - }.get(self.state, 'info') - - def _get_status_icon(self): - """Get Font Awesome icon for current status""" - self.ensure_one() - return { - 'pending': 'fa-hourglass-half', - 'partial': 'fa-exclamation-circle', - 'paid_unconfirmed': 'fa-circle-notch fa-spin', - 'confirmed': 'fa-check-circle', - 'expired': 'fa-clock', - 'failed': 'fa-times-circle', - 'overpaid': 'fa-check-circle' - }.get(self.state, 'fa-info-circle') - - def _get_status_message(self): - """Get human-readable status message""" - self.ensure_one() - provider = self.env['payment.provider']._get_monero_provider() - messages = { - 'pending': "Waiting for payment...", - 'partial': "Partial payment received (%.12f/%0.12f XMR)" % ( - self.amount_received, self.amount), - 'paid_unconfirmed': "Payment received (confirming... %d/%d confirmations)" % ( - self.confirmations, provider.confirmation_threshold), - 'confirmed': "Payment confirmed!", - 'expired': "Payment expired", - 'failed': "Payment failed: %s" % (self.error_message or "Unknown error"), - 'overpaid': "Payment received (overpaid)" - } - return _(messages.get(self.state, "Pending")) - - def get_expiry_time(self): - """Get formatted remaining time until expiration""" - self.ensure_one() - if not self.expiration: - return "" - - delta = self.expiration - fields.Datetime.now() - if delta.total_seconds() <= 0: - return "Expired" - - hours, remainder = divmod(delta.seconds, 3600) - minutes = remainder // 60 - return f"{hours}h {minutes}m" - diff --git a/payment_monero_rpc/models/monero_transactions.py b/payment_monero_rpc/models/monero_transactions.py deleted file mode 100644 index bc14aa30..00000000 --- a/payment_monero_rpc/models/monero_transactions.py +++ /dev/null @@ -1,43 +0,0 @@ -from odoo import models, fields, api - - -class MoneroTransaction(models.Model): - _name = 'monero.transaction' - _description = 'Monero Transaction' - _order = 'timestamp desc' - - payment_id = fields.Many2one( - 'monero.payment', - string="Payment", - required=True, - ondelete='cascade') - txid = fields.Char(string="Transaction Hash", required=True, index=True) - amount = fields.Float(string="Amount", digits=(12, 12), required=True) - fee = fields.Float(string="Fee", digits=(12, 12)) - block_height = fields.Integer(string="Block Height", index=True) - unlock_time = fields.Integer(string="Unlock Time") - confirmations = fields.Integer(string="Confirmations", compute='_compute_confirmations', store=True) - timestamp = fields.Datetime(string="Timestamp", required=True) - is_confirmed = fields.Boolean(string="Confirmed", compute='_compute_is_confirmed', store=True) - payment_type = fields.Selection([ - ('in', 'Incoming'), - ('out', 'Outgoing'), - ('pending', 'Pending'), - ('failed', 'Failed')], - string="Type") - - @api.depends('block_height') - def _compute_confirmations(self): - for tx in self: - if not tx.block_height: - tx.confirmations = 0 - continue - - current_height = self.env['monero.payment']._get_current_block_height() - tx.confirmations = max(0, current_height - tx.block_height) if current_height else 0 - - @api.depends('confirmations') - def _compute_is_confirmed(self): - threshold = self.env['payment.provider']._get_monero_provider().confirmation_threshold - for tx in self: - tx.is_confirmed = tx.confirmations >= threshold diff --git a/payment_monero_rpc/models/payment_provider.py b/payment_monero_rpc/models/payment_provider.py deleted file mode 100644 index b850ce18..00000000 --- a/payment_monero_rpc/models/payment_provider.py +++ /dev/null @@ -1,610 +0,0 @@ -import logging -import secrets -import base64 -import hashlib -import json -import os -from io import BytesIO -from datetime import datetime, timedelta - -import qrcode -import monero -import requests -import urllib.parse -from monero.wallet import Wallet -from monero.backends.jsonrpc import JSONRPCWallet -from monero.daemon import Daemon, JSONRPCDaemon -from monero.address import Address, SubAddress - -from odoo import models, fields, api, _ -from odoo.exceptions import UserError, ValidationError -from odoo.tools import float_compare - -_logger = logging.getLogger(__name__) - -class PaymentProviderMonero(models.Model): - _inherit = 'payment.provider' - - code = fields.Selection( - selection_add=[('monero_rpc', 'Monero (RPC)')], - ondelete={'monero_rpc': 'set default'} - ) - - rpc_url = fields.Char( - string="URL", - default=lambda self: self.env['ir.config_parameter'].sudo().get_param( - 'monero.rpc_url', 'http://localhost:38082/json_rpc'), - help="URL of Monero wallet RPC (e.g., http://localhost:38082/json_rpc)" - ) - - rpc_user = fields.Char(string='RPC Username') - rpc_password = fields.Char(string='RPC Password') - wallet_file = fields.Char(string='Wallet File') - wallet_password = fields.Char(string='Wallet Password') - wallet_dir = fields.Char(string='Wallet Directory') - network_type = fields.Selection( - selection=[ - ('mainnet', 'Mainnet'), - ('stagenet', 'Stagenet'), - ('testnet', 'Testnet') - ], - string='Network', - default='mainnet' - ) - - daemon_rpc_url = fields.Char( - string="Daemon URL", - default=lambda self: self.env['ir.config_parameter'].sudo().get_param( - 'monero.daemon_rpc_url', 'http://localhost:38081/json_rpc'), - help="URL of Daemon RPC (e.g., http://localhost:38081/json_rpc)" - ) - - confirmation_threshold = fields.Integer( - string="Confirmations", - default=lambda self: int( - self.env['ir.config_parameter'].sudo().get_param( - 'monero.required_confirmations', 2) or 2), - help="Number of blockchain confirmations required before considering payment complete" - ) - - rpc_timeout = fields.Integer( - string='Timeout', - default=180, - help="Number of seconds before a timeout is issue if not connected" - ) - - restaurant_mode = fields.Boolean( - string='Restaurant Mode', - help="Check to determine whether or not the shop is a restaurant" - ) - - exchange_rate_api = fields.Char( - string="Xchange API", - default="https://api.coingecko.com/api/v3/simple/price" - ) - - manual_rates = fields.Json( - string="Manual Rates", - default={"USD": 200, "EUR": 180} - ) - - wallet_addresses = fields.Json( - string="Available Wallets", - default=[], - readonly=True, - help="Cached list of wallet addresses from last refresh" - ) - - use_subaddresses = fields.Boolean( - string="Use Subaddresses", - default=True, - help="Enable modern subaddresses (recommended). Disable for legacy Payment IDs." - ) - - wallet_address_value = fields.Char(string="Wallet Address Value") - - wallet_address = fields.Selection( - selection='_compute_wallet_selection', - inverse='_inverse_wallet_address', - string="Monero Wallet Address" - ) - - wallet_status = fields.Char(string="Wallet Status") - - account_balance = fields.Float( - string="Balance", - readonly=True, - digits=(12, 12), - compute='_compute_account_details' - ) - unlocked_balance = fields.Float( - string="Unlocked Balance", - readonly=True, - digits=(12, 12), - compute='_compute_account_details' - ) - account_index = fields.Integer( - string="Account Index", - readonly=True, - compute='_compute_account_details' - ) - - def _get_default_monero_image(self): - """Return the default Monero logo in base64 format.""" - image_path = '/payment_monero_rpc/static/src/img/logo.png' - try: - with open(image_path, 'rb') as f: - return base64.b64encode(f.read()).decode('utf-8') - except IOError: - return False - - image_128 = fields.Image(default=_get_default_monero_image) - - @api.model - def _get_monero_provider(self): - """Helper method to get the Monero payment provider""" - return self.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - - def _get_daemon(self): - """Initialize and return Monero Daemon RPC client""" - try: - host = "127.0.0.1" - port = 38082 - provider = self._get_monero_provider() - if provider.daemon_rpc_url: - parsed_url = urllib.parse.urlparse(provider.daemon_rpc_url) - host = parsed_url.hostname or "127.0.0.1" - port = parsed_url.port or 38082 - - daemon_rpc = monero.daemon.Daemon( - JSONRPCDaemon( - host=host, - port=port, - user=provider.rpc_user or None, - password=provider.rpc_password or None, - timeout=provider.rpc_timeout or 180 - ) - ) - return daemon_rpc - except Exception as e: - _logger.error("Daemon connection failed: %s", str(e)) - raise UserError(_("Could not connect to Monero daemon. Please check your RPC settings.")) - - def _get_wallet_client(self): - """Initialize Monero wallet client""" - try: - provider = self.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - _logger.info("RPC Wallet: %s %s %s", provider.rpc_url, provider.rpc_user, provider.rpc_timeout) - host = "127.0.0.1" - port = 38082 - if provider.rpc_url: - parsed_url = urllib.parse.urlparse(provider.rpc_url) - host = parsed_url.hostname or "127.0.0.1" - port = parsed_url.port or 38082 - - wallet_path = os.path.join(provider.wallet_dir, provider.wallet_file) - if not os.path.exists(wallet_path): - raise UserError(_("Wallet file not found at: %s") % wallet_path) - - wallet_name = os.path.splitext(os.path.basename(wallet_path))[0] - - wallet = Wallet( - JSONRPCWallet( - host=host, - port=port, - user=provider.rpc_user, - password=provider.rpc_password, - timeout=180) - ) - - return wallet - except Exception as e: - _logger.error("Wallet connection failed: %s", str(e)) - raise UserError(_("Could not connect to Monero wallet. Please check your RPC settings.")) - - def _get_daemon_client(self): - """Initialize Monero daemon client""" - try: - return Daemon( - host=self.daemon_rpc_url or "http://127.0.0.1:38081", - timeout=self.rpc_timeout - ) - except Exception as e: - _logger.error("Daemon connection failed: %s", str(e)) - raise UserError(_("Could not connect to Monero daemon. Please check your RPC settings.")) - - def _validate_address(self, addr_str, is_subaddress = True): - return True - - @api.model - def _cron_update_payment_provider(self): - """Update Monero Payment Provider""" - provider = self.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - if provider: - provider.fetch_wallet_addresses() - - def get_monero_provider(self): - return self.search([('code', '=', 'monero_rpc')], limit=1) - - def _update_account_from_cache(self, cached_data): - """Update account details from cached wallet data""" - self.write({ - 'account_balance': cached_data.get('balance', 0), - 'unlocked_balance': cached_data.get('unlocked_balance', 0), - 'account_index': cached_data.get('account_index', 0) - }) - - def _create_monero_from_fiat_payment(self, order_ref, amount, currency, order_id): - """Create a payment with proper address generation based on configuration""" - order_currency = currency.name if hasattr(currency, 'name') else currency - rate = self.get_xmr_rate(order_currency) - if not rate: - raise UserError(_("Could not get exchange rate for %s") % currency) - - provider = self.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - - try: - wallet = provider._get_wallet_client() - - if provider.use_subaddresses: - label = f"Order_{order_ref}" - subaddress = wallet.new_address(label=label) - _logger.info("New subaddress: %s", subaddress) - if not self._validate_address(subaddress[0], is_subaddress=True): - raise UserError(_("Generated invalid subaddress for current network")) - - payment_values = { - 'payment_id': subaddress[1], - 'address_seller': subaddress[0], - 'is_subaddress': True, - } - else: - payment_id = secrets.token_hex(8) # 8-byte payment ID - if not provider.wallet_address_value: - raise UserError(_("No base wallet address configured for payment ID mode")) - - integrated_address = wallet.integrated_address( - payment_id=payment_id, - address=provider.wallet_address_value - ) - if not provider._validate_address(integrated_address): - raise UserError(_("Generated invalid integrated address")) - - payment_values = { - 'payment_id': payment_id, - 'address_seller': integrated_address, - 'is_subaddress': False - } - - _logger.info("Payment Values: %s", payment_values) - - payment = self.env['monero.payment'].sudo().create({ - **payment_values, - 'amount': amount / rate, - 'exchange_rate': rate, - 'currency': 'XMR', - 'order_ref': order_ref, - 'state': 'pending', - 'expiration': fields.Datetime.add(fields.Datetime.now(), hours=24), - 'original_amount': amount, - 'original_currency': order_currency, - **({'sale_order_id': order_id.id} if order_id else {}) - }) - - payment._compute_qr_code() - return payment - - except Exception as e: - _logger.error("Payment creation failed: %s", str(e), exc_info=True) - raise UserError(_("Failed to create payment: %s") % str(e)) - - @api.model - def create_monero_from_fiat_payment(self, pos_reference, amount, currency_name, extra_data=None): - """Public method to create fiat payment""" - result = self._create_monero_from_fiat_payment(pos_reference, amount, currency_name, extra_data) - - if hasattr(result, '_fields'): # Check if it's an Odoo model - return { - 'payment_id': result.payment_id, - 'address_seller': result.address_seller, - 'is_subaddress': result.is_subaddress, - 'image_qr': result.image_qr, - 'amount': result.amount, - 'exchange_rate': result.exchange_rate, - 'order_ref': result.order_ref, - 'state': 'pending', - 'expiration': result.expiration, - 'original_amount': result.original_amount, - 'original_currency': result.original_currency, - 'success': True - } - elif isinstance(result, dict): - return result - else: - return { - 'error': str(result) if result else 'Unknown error', - 'success': False - } - - def _generate_subaddress(self, provider, label=None): - """Generate and validate a subaddress for the correct network""" - try: - wallet = self._get_wallet_client() - subaddress = wallet.new_address(label=label or f"Payment_{fields.Datetime.now()}") - - if not self._validate_address(subaddress[0], is_subaddress=True): - raise UserError(_("Wallet generated invalid address %s for network %s") % - (subaddress[0], self.network_type)) - - return { - 'address_index': subaddress[1], - 'address': subaddress[0] - } - except Exception as e: - _logger.error("Subaddress generation failed: %s", str(e)) - raise UserError(_("Address generation failed. Please check wallet configuration")) - - def _generate_integrated_address(self, base_address, payment_id): - """Generate integrated address for payment ID mode""" - try: - wallet = self._get_wallet_client() - return wallet.integrated_address( - payment_id=payment_id, - address=base_address - ) - except Exception as e: - _logger.error("Integrated address generation failed: %s", str(e)) - return base_address - - def get_xmr_rate(self, currency): - """Get current XMR exchange rate for display""" - return self._cron_update_xmr_rates(currency) - - def _compute_wallet_selection(self): - """Generate selection options from wallet_addresses""" - results = [] - for provider in self: - if not provider.wallet_addresses: - continue - - for addr in provider.wallet_addresses: - if not isinstance(addr, dict): - continue - - address_val = addr.get('address') - label = addr.get('label', 'No label') - - if address_val: - display = f"{label} ({address_val[:6]}...{address_val[-4:]})" - results.append((address_val, display)) - - return results - - @api.depends('wallet_address') - def _compute_account_details(self): - """Automatically update balance when address changes""" - for provider in self: - if not provider.wallet_address: - provider.account_balance = 0 - provider.unlocked_balance = 0 - provider.account_index = 0 - continue - - try: - wallet = provider._get_wallet_client() - balance = wallet.balance() - - provider.account_balance = balance.balance / 1e12 - provider.unlocked_balance = balance.unlocked_balance / 1e12 - provider.account_index = 0 # Will be updated in fetch_wallet_addresses - except Exception as e: - _logger.error("Failed to update account details: %s", str(e)) - provider.account_balance = 0 - provider.unlocked_balance = 0 - provider.account_index = 0 - - def _get_account_index(self, address): - """Get account index from address""" - try: - wallet = self._get_wallet_client() - return wallet.address_index(address) - except Exception: - return 0 - - @api.model - def _setup_monero_payment_method(self): - """Create or update the Monero payment method record""" - payment_method = self.env['payment.method'].search( - [('code', '=', 'monero_rpc')], limit=1) - - if not payment_method: - payment_method = self.env['payment.method'].create({ - 'name': 'Monero RPC', - 'code': 'monero_rpc', - 'image': self._get_default_monero_image(), - 'support_tokenization': False, - 'support_express_checkout': False, - 'support_refund': 'none', - }) - return payment_method - - def _get_compatible_payment_methods(self, partner_id, currency_id=None, **kwargs): - """Override to include Monero as compatible payment method""" - payment_methods = super()._get_compatible_payment_methods( - partner_id, currency_id, **kwargs) - - if self.code == 'monero_rpc' and self.state == 'enabled': - monero_method = self._setup_monero_payment_method() - - if currency_id and monero_method.supported_currency_ids: - if currency_id not in monero_method.supported_currency_ids.ids: - return payment_methods - - partner = self.env['res.partner'].browse(partner_id) - if partner.country_id and monero_method.supported_country_ids: - if partner.country_id.id not in monero_method.supported_country_ids.ids: - return payment_methods - - payment_methods = monero_method - - return payment_methods - - def get_manual_rate(self, currency): - """Safely get manual rate from JSON string for a currency""" - try: - currency_name = currency if isinstance(currency, str) else getattr(currency, 'name', None) or currency.name - if not currency_name: - return None - - rates = self.manual_rates - if isinstance(rates, str): - try: - rates = json.loads(rates) - except json.JSONDecodeError: - return None - - if isinstance(rates, dict): - return rates.get(currency_name) - - return None - except Exception: - return None - - @api.model - def _cron_update_xmr_rates(self, currency='USD'): - """Get current XMR exchange rate""" - currency = currency.upper() - provider = self.env['payment.provider'].search([('code', '=', 'monero_rpc')], limit=1) - - try: - response = requests.get( - provider.exchange_rate_api, - params={ - 'ids': 'monero', - 'vs_currencies': currency.lower()}, - timeout=5 - ) - data = response.json() - return data.get('monero', {}).get(currency.lower()) or \ - self.get_manual_rate(currency) - except Exception as e: - _logger.error("Error fetching exchange rate: %s", str(e)) - return self.get_manual_rate(currency) - - def fetch_wallet_addresses(self): - """Fetch all wallet accounts and their primary addresses with balances""" - for provider in self: - try: - wallet = provider._get_wallet_client() - accounts = wallet.accounts() - wallet_data = [] - - for account in accounts: - addr = account.primary_address() - balance = account.balance() - - wallet_data.append({ - 'address': addr.address, - 'label': account.label or f"Account {account.index}", - 'account_index': account.index, - 'balance': balance.balance / 1e12, - 'unlocked_balance': balance.unlocked_balance / 1e12, - 'base_address': addr.address - }) - - if wallet_data: - provider.write({ - 'wallet_addresses': wallet_data, - 'wallet_address': wallet_data[0]['address'], - 'account_balance': wallet_data[0]['balance'], - 'unlocked_balance': wallet_data[0]['unlocked_balance'], - 'account_index': wallet_data[0]['account_index'], - 'wallet_status': 'ready' - }) - else: - provider.write({'wallet_status': 'empty'}) - - return True - - except Exception as e: - _logger.error("Wallet operation failed: %s", str(e), exc_info=True) - provider.write({'wallet_status': 'error'}) - raise UserError(str(e)) from e - - def _handle_fetch_error(self, provider): - """Handle error state for wallet fetch""" - provider.write({ - 'wallet_addresses': [], - 'wallet_address': False, - 'wallet_address_value': False, - 'account_balance': 0, - 'unlocked_balance': 0, - 'account_index': 0 - }) - - def _get_cached_wallet_selection(self): - """Get selection options from cache WITHOUT RPC calls""" - self.ensure_one() - if not self.wallet_addresses: - return [] - return [(addr['address'], addr['label']) for addr in self.wallet_addresses] - - def _update_account_details(self): - """Now uses cached data instead of making RPC calls""" - for provider in self: - if not provider.wallet_address_value or not provider.wallet_addresses: - provider.update({ - 'account_balance': 0, - 'unlocked_balance': 0, - 'account_index': 0 - }) - continue - - cached_data = next( - (addr for addr in provider.wallet_addresses - if addr['address'] == provider.wallet_address_value), - None - ) - - if cached_data: - provider.update({ - 'account_balance': cached_data['balance'], - 'unlocked_balance': cached_data['unlocked_balance'], - 'account_index': cached_data['account_index'] - }) - else: - provider.update({ - 'account_balance': 0, - 'unlocked_balance': 0, - 'account_index': 0 - }) - - def _get_wallet_addresses_selection(self): - """Handle multiple providers by returning combined addresses""" - addresses = [] - for provider in self: - if provider.wallet_addresses: - addresses.extend([ - (addr['address'], addr['label']) - for addr in provider.wallet_addresses - ]) - return addresses - - def _inverse_wallet_address(self): - """Store the selected address""" - for provider in self: - provider.wallet_address_value = provider.wallet_address - if provider.wallet_address: - cached = next( - (a for a in provider.wallet_addresses - if a['address'] == provider.wallet_address), - None - ) - if cached: - provider._update_account_from_cache(cached) - - @api.onchange('wallet_address') - def _onchange_wallet_address(self): - """Update balances when address changes""" - if self.wallet_address: - self._update_account_details() diff --git a/payment_monero_rpc/models/pos_payment.py b/payment_monero_rpc/models/pos_payment.py deleted file mode 100644 index cc475d39..00000000 --- a/payment_monero_rpc/models/pos_payment.py +++ /dev/null @@ -1,100 +0,0 @@ -from odoo import models, fields, api, _ -from odoo.exceptions import ValidationError -import logging -import requests -import json - -_logger = logging.getLogger(__name__) - -class PosPaymentMethod(models.Model): - _inherit = 'pos.payment.method' - - payment_provider_id = fields.Many2one( - 'payment.provider', - string='Payment Provider', - domain="[('code', '=', 'monero_rpc')]", - help="Linked Monero payment provider configuration", - ) - - is_monero = fields.Boolean( - string='Is Monero Payment', - compute='_compute_is_monero', - readonly=True, - store=True - ) - qr_size = fields.Integer( - string='QR Code Size', - default=200, - help="Size of generated QR codes in pixels" - ) - payment_timeout = fields.Integer( - string='Payment Timeout (minutes)', - default=180, - help="Time before payment request expires" - ) - - @api.depends('payment_provider_id') - def _compute_is_monero(self): - for method in self: - method.is_monero = method.payment_provider_id.code == 'monero_rpc' - if method.is_monero: - _logger.debug("This is a Monero Payment Provider") - else: - _logger.debug("This is NOT a Monero Payment Provider") - - - def _get_payment_terminal_selection(self): - selection = super()._get_payment_terminal_selection() - selection.append(('monero_rpc', 'Monero RPC')) - return selection - - def _convert_to_xmr(self, amount, currency): - """Convert amount to XMR using provider's exchange rate""" - self.ensure_one() - if not self.payment_provider_id: - raise ValidationError(_("No Monero payment provider configured")) - - try: - rate = self.payment_provider_id._get_monero_exchange_rate(currency) - return amount / rate - except Exception as e: - raise ValidationError( - _("XMR conversion failed: %s") % str(e) - ) - - @api.constrains('payment_provider_id', 'use_payment_terminal') - def _check_monero_config(self): - for method in self: - if method.use_payment_terminal == 'monero_rpc' and not method.payment_provider_id: - raise ValidationError(_("Monero payment method requires a linked payment provider")) - - -class PosOrder(models.Model): - _inherit = 'pos.order' - - monero_payment_id = fields.Many2one('monero.payment', string='Monero Payment') - monero_payment_status = fields.Selection(related='monero_payment_id.state', string='Payment Status') - monero_confirmations = fields.Integer(related='monero_payment_id.confirmations', string='Confirmations') - - def _create_monero_payment(self, amount): - self.ensure_one() - Payment = self.env['monero.payment'] - return Payment.create({ - 'amount': amount, - 'currency': self.currency_id.name, - 'order_ref': self.pos_reference, - 'description': f"POS Order {self.pos_reference}" - }) - - def _process_monero_payment(self, payment_method, amount): - self.ensure_one() - monero_payment = self._create_monero_payment(amount) - self.write({'monero_payment_id': monero_payment.id}) - - return { - 'payment_id': monero_payment.id, - 'address': payment_method.monero_wallet_address, - 'amount': amount, - 'currency': self.currency_id.name, - 'qr_code_url': f"/monero/qr/{monero_payment.id}?size={payment_method.monero_qr_size}" - } diff --git a/payment_monero_rpc/models/res_config_settings.py b/payment_monero_rpc/models/res_config_settings.py deleted file mode 100644 index 84ab1a6b..00000000 --- a/payment_monero_rpc/models/res_config_settings.py +++ /dev/null @@ -1,43 +0,0 @@ -from odoo import models, fields - -class ResConfigSettings(models.TransientModel): - _inherit = 'res.config.settings' - - monero_rpc_url = fields.Char( - string='Monero RPC URL', - default='http://localhost:38082/json_rpc', - config_parameter='monero.rpc_url', - help="URL of the Monero wallet RPC interface" - ) - monero_rpc_user = fields.Char( - string='RPC Username', - config_parameter='monero.rpc_user', - help="Username for RPC authentication" - ) - monero_rpc_password = fields.Char( - string='RPC Password', - config_parameter='monero.rpc_password', - help="Password for RPC authentication" - ) - monero_rpc_timeout = fields.Integer( - string='RPC Timeout (seconds)', - default=180, - config_parameter='monero.rpc_timeout', - help="Timeout for RPC requests in seconds" - ) - monero_required_confirmations = fields.Integer( - string='Required Confirmations', - default=2, - config_parameter='monero.required_confirmations', - help="Number of confirmations required before considering payment complete" - ) - monero_testnet = fields.Boolean( - string='Use Stagenet', - config_parameter='monero.stagenet', - help="Enable this if using Monero Stagenet" - ) - - def set_values(self): - super(ResConfigSettings, self).set_values() - if self.monero_rpc_url and not self.monero_rpc_url.startswith(('http://', 'https://')): - raise ValidationError("RPC URL must start with http:// or https://") diff --git a/payment_monero_rpc/security/ir.model.access.csv b/payment_monero_rpc/security/ir.model.access.csv deleted file mode 100644 index 345b2d34..00000000 --- a/payment_monero_rpc/security/ir.model.access.csv +++ /dev/null @@ -1,8 +0,0 @@ -id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink -payment_monero_rpc.access_monero_payment,monero.payment,payment_monero_rpc.model_monero_payment,base.group_user,1,1,1,0 -payment_monero_rpc.access_monero_transaction,monero.transaction,payment_monero_rpc.model_monero_transaction,base.group_user,1,0,0,0 -payment_monero_rpc.access_monero_daemon,monero.daemon,payment_monero_rpc.model_monero_daemon,base.group_user,1,1,1,0 -payment_monero_rpc.access_payment_provider_monero,payment.provider.monero,payment_monero_rpc.model_payment_provider,base.group_user,1,1,1,0 -payment_monero_rpc.access_pos_payment_monero,pos.payment.monero,payment_monero_rpc.model_pos_payment_method,base.group_user,1,1,1,0 -payment_monero_rpc.access_pos_order_monero,pos.order.monero,payment_monero_rpc.model_pos_order,base.group_user,1,1,1,0 -payment_monero_rpc.access_res_config_monero,res.config.settings.monero,payment_monero_rpc.model_res_config_settings,base.group_system,1,1,1,0 diff --git a/payment_monero_rpc/static/src/app/online_payment_popup_monero.js b/payment_monero_rpc/static/src/app/online_payment_popup_monero.js deleted file mode 100644 index 918e9bd3..00000000 --- a/payment_monero_rpc/static/src/app/online_payment_popup_monero.js +++ /dev/null @@ -1,78 +0,0 @@ -/** @odoo-module **/ - -import { OnlinePaymentPopup } from "@pos_online_payment/app/online_payment_popup/online_payment_popup"; -import { useState } from "@odoo/owl"; -import { useService } from "@web/core/utils/hooks"; -import { registry } from "@web/core/registry"; - -export class MoneroPaymentPopup extends OnlinePaymentPopup { - static template = "payment_monero_rpc.MoneroPaymentPopup"; - static components = OnlinePaymentPopup.components || {}; - - static props = { - ...OnlinePaymentPopup.props, - qrCode: { type: String }, - formattedAmount: { type: String }, - formattedMoneroAmount: { type: String }, - orderName: { type: String }, - exchangeRate: { type: String }, - sellerAddress: { type: String }, - confirmationCount: { type: Number }, - close: { type: Function, optional: true }, - }; - - setup() { - super.setup(); - this.notification = useService("notification"); - - this.state = useState({ - ...(this.state || {}), - paymentStatus: 'pending', - countdown: 900, // 15 minutes - }); - - this.timer = setInterval(() => { - if (this.state.countdown > 0) { - this.state.countdown--; - } else { - clearInterval(this.timer); - this.props.close?.(); - } - }, 1000); - } - - willUnmount() { - super.willUnmount?.(); - clearInterval(this.timer); - } - - copyToClipboard(text) { - try { - navigator.clipboard.writeText(text); - this.notification.add('Copied to clipboard!', { - type: 'success', - }); - } catch (err) { - console.error('Failed to copy text: ', err); - this.notification.add('Failed to copy to clipboard', { - type: 'danger', - }); - } - } - - - // New method to handle Monero amount copy - copyMoneroAmount() { - this.copyToClipboard(this.props.formattedMoneroAmount); - } - - // New method to handle seller address copy - copySellerAddress() { - this.copyToClipboard(this.props.sellerAddress); - } -} - -registry.category("pos.popups").add("payment_monero_rpc.MoneroPaymentPopup", MoneroPaymentPopup); -registry.category("dialogs").add("MoneroPaymentPopup", { - component: MoneroPaymentPopup, -}); diff --git a/payment_monero_rpc/static/src/app/online_payment_popup_monero.xml b/payment_monero_rpc/static/src/app/online_payment_popup_monero.xml deleted file mode 100644 index 1992fd9f..00000000 --- a/payment_monero_rpc/static/src/app/online_payment_popup_monero.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - -

Scan with Monero wallet

- Monero Payment QR Code - -
-
- Amount: - -
-
- Monero: - ɱ - -
-
- Exchange Rate: - -
-
- -
- Order: - -
-
- Seller: - - -
- -
- Confirmation: - out of confirmations -
- - - - -
-
-
-
- -
- - -
- -
- Payment verifies automatically -
-
-
-
diff --git a/payment_monero_rpc/static/src/app/payment_screen_monero.js b/payment_monero_rpc/static/src/app/payment_screen_monero.js deleted file mode 100644 index 037131dd..00000000 --- a/payment_monero_rpc/static/src/app/payment_screen_monero.js +++ /dev/null @@ -1,434 +0,0 @@ -/** @odoo-module **/ - -// import { _t } from "@web/core/l10n/translation"; // Disabled translation -import { PaymentScreen } from "@point_of_sale/app/screens/payment_screen/payment_screen"; -import { patch } from "@web/core/utils/patch"; -import { OnlinePaymentPopup } from "@pos_online_payment/app/online_payment_popup/online_payment_popup"; -import { AlertDialog } from "@web/core/confirmation_dialog/confirmation_dialog"; -import { Component, Dialog } from "@odoo/owl"; -import { qrCodeSrc } from "@point_of_sale/utils"; -import { ask } from "@point_of_sale/app/store/make_awaitable_dialog"; -import { formatCurrency } from "@web/core/currency"; -import { usePos } from "@point_of_sale/app/store/pos_hook"; -import { useService } from "@web/core/utils/hooks"; -import { registry } from "@web/core/registry"; -import { MoneroPaymentPopup } from "@payment_monero_rpc/app/online_payment_popup_monero"; - -const DEBUG_TAG = "[POS Monero Payment]"; - -patch(PaymentScreen.prototype, { - setup() { - super.setup(); - this.notification = useService("notification"); - this.pos = usePos(); - this.activeMoneroPayments = new Set(); - }, - async addNewPaymentLine(paymentMethod) { - console.debug(`${DEBUG_TAG} addNewPaymentLine called with payment method:`, paymentMethod); - if (paymentMethod.is_online_payment && typeof this.currentOrder.id === "string") { - console.debug(`${DEBUG_TAG} Processing online payment for order:`, this.currentOrder.id); - this.currentOrder.date_order = luxon.DateTime.now().toFormat("yyyy-MM-dd HH:mm:ss"); - this.pos.addPendingOrder([this.currentOrder.id]); - await this.pos.syncAllOrders(); - } - return await super.addNewPaymentLine(...arguments); - }, - - getRemainingOnlinePaymentLines() { - const remainingLines = this.paymentLines.filter( - (line) => line.payment_method_id.is_online_payment && line.get_payment_status() !== "done" - ); - console.debug(`${DEBUG_TAG} Found ${remainingLines.length} remaining online payment lines`); - return remainingLines; - }, - - checkRemainingOnlinePaymentLines(unpaidAmount) { - console.debug(`${DEBUG_TAG} Checking remaining online payments against unpaid amount:`, unpaidAmount); - const remainingLines = this.getRemainingOnlinePaymentLines(); - let remainingAmount = 0; - - for (const line of remainingLines) { - const amount = line.get_amount(); - if (amount <= 0) { - console.error(`${DEBUG_TAG} Invalid negative amount in online payment:`, amount); - this.dialog.add(AlertDialog, { - // title: _t("Invalid online payment"), - title: "Invalid online payment", - // body: _t( - // "Online payments cannot have a negative amount (%s: %s).", - // line.payment_method_id.name, - // this.env.utils.formatCurrency(amount) - // ), - body: `Online payments cannot have a negative amount (${line.payment_method_id.name}: ${this.env.utils.formatCurrency(amount)}).`, - }); - return false; - } - remainingAmount += amount; - } - - if (!this.env.utils.floatIsZero(unpaidAmount - remainingAmount)) { - console.error(`${DEBUG_TAG} Payment amount mismatch. Remaining: ${remainingAmount}, Unpaid: ${unpaidAmount}`); - this.dialog.add(AlertDialog, { - // title: _t("Invalid online payments"), - title: "Invalid online payments", - // body: _t( - // "The total amount of remaining online payments to execute (%s) doesn't correspond to the remaining unpaid amount of the order (%s).", - // this.env.utils.formatCurrency(remainingAmount), - // this.env.utils.formatCurrency(unpaidAmount) - // ), - body: `The total amount of remaining online payments to execute (${this.env.utils.formatCurrency(remainingAmount)}) doesn't correspond to the remaining unpaid amount of the order (${this.env.utils.formatCurrency(unpaidAmount)}).`, - }); - return false; - } - return true; - }, - - async _isOrderValid(isForceValidate = false) { - if (!(await super._isOrderValid(isForceValidate))) { - return false; - } - - if (!this.payment_methods_from_config.some(pm => pm.is_online_payment)) { - return true; - } - - if (this.currentOrder.finalized) { - this.afterOrderValidation(false); - return false; - } - - const pendingPayments = this.getRemainingOnlinePaymentLines(); - if (pendingPayments.length === 0) { - return this.handleExistingOrderCheck(); - } - - const moneroPayment = pendingPayments.find( - line => line.payment_method_id.name === "Monero RPC" - ); - - if (moneroPayment) { - this.onlinePaymentLine = moneroPayment; - const success = await this.processMoneroPayment(); - if (!success) { - this.cancelOnlinePayment(this.currentOrder); - return false; - } - return true; - } - - return this.handleRegularOnlinePayments(pendingPayments); - }, - - async handleExistingOrderCheck() { - console.debug(`${DEBUG_TAG} Checking existing order for payments`); - let orderServerData; - try { - orderServerData = await this.pos.update_online_payments_data_with_server( - this.currentOrder, - 0 - ); - console.debug(`${DEBUG_TAG} Existing order status:`, orderServerData); - } catch (error) { - console.error(`${DEBUG_TAG} Failed to check existing order:`, error); - return ask(this.dialog, { - // title: _t("Online payment unavailable"), - title: "Online payment unavailable", - // body: _t( - // "There is a problem with the server. The order online payment status cannot be retrieved. Are you sure there is no online payment for this order ?" - // ), - body: "There is a problem with the server. The order online payment status cannot be retrieved. Are you sure there is no online payment for this order?", - // confirmLabel: _t("Yes"), - confirmLabel: "Yes", - }); - } - - if (orderServerData?.is_paid) { - console.debug(`${DEBUG_TAG} Order is already paid`); - await this.afterPaidOrderSavedOnServer(orderServerData.paid_order); - return false; - } - - if (orderServerData?.modified_payment_lines) { - console.warn(`${DEBUG_TAG} Server reported modified payment lines`); - this.dialog.add(AlertDialog, { - // title: _t("Updated online payments"), - title: "Updated online payments", - // body: _t("There are online payments that were missing in your view."), - body: "There are online payments that were missing in your view.", - }); - return false; - } - - return true; - }, - - async processMoneroPayment() { - if (!this.pos || !this.currentOrder || !this.onlinePaymentLine) { - console.error(`${DEBUG_TAG} Missing required payment context`); - return false; - } - - try { - const amount = this.onlinePaymentLine.get_amount(); - const currency = this.pos.currency; - const formattedAmount = formatCurrency(amount, currency); - - const moneroResponse = await this.pos.data.call( - "payment.provider", - "create_monero_from_fiat_payment", - [this.currentOrder.id, amount, currency.name] - ); - - if (!moneroResponse?.image_qr) { - throw new Error("Failed to generate Monero payment details"); - } - - console.debug(`${DEBUG_TAG} Showing Monero payment dialog `, moneroResponse); - - const paymentId = moneroResponse.payment_id; - console.debug(`${DEBUG_TAG} Received payment_id - `, paymentId); - this.activeMoneroPayments.add(paymentId); - - const dialogProps = { - qrCode: String(moneroResponse.image_qr), - formattedAmount: String(currency.symbol + formattedAmount), - formattedMoneroAmount: String(Number(moneroResponse.amount).toFixed(12) || "0"), - orderName: String(this.currentOrder.pos_reference), - exchangeRate: String(moneroResponse.exchange_rate || "0"), - sellerAddress: moneroResponse.address_seller, - confirmationCount: moneroResponse.confirmations || 0, - }; - - return await new Promise((resolve) => { - let isResolved = false; - const verificationInterval = this.setupPaymentVerification( - paymentId, - () => { - if (!isResolved) { - isResolved = true; - this.cleanupPayment(paymentId); - resolve(true); - } - } - ); - - const closer = this.dialog.add( - MoneroPaymentPopup, - dialogProps, - { - onClose: () => { - if (!isResolved) { - isResolved = true; - clearInterval(verificationInterval); - this.cleanupPayment(paymentId); - resolve(false); - } - }, - } - ); - }); - - } catch (error) { - console.error(`${DEBUG_TAG} Monero payment failed:`, error); - this.notification.add( - `Monero payment failed: ${error.message}`, - { type: "danger" } - ); - return false; - } - }, - - handleRegularOnlinePayments(pendingPayments) { - console.debug(`${DEBUG_TAG} Under no circumstances should we get here!!!`); - }, - - setupPaymentVerification(payment_id, onSuccess) { - return setInterval(async () => { - try { - console.log(`${DEBUG_TAG} Payment ID being sent:`, payment_id); - const status = await this.pos.data.call( - "monero.payment", - "check_payment_status", - [payment_id] - ); - - Object.assign(this.moneroPaymentPopup.props, this._getStatusConfig(status)); - - if (status.status == 'confirmed') { - onSuccess(); - clearInterval(verificationInterval); - } - } catch (error) { - console.error(`${DEBUG_TAG} Verification failed:`, error); - this.cleanupPayment(paymentId); - clearInterval(verificationInterval); - // Optionally notify user - this.notification.add( - `Payment verification failed: ${error.message}`, - { type: "warning" } - ); - } - }, 60000); - }, - - _getStatusConfig: function(status) { - console.debug(`${DEBUG_TAG} Update screen data with - `, status); - - const statusConfig = { - confirmed: { - paymentStatusClass: 'success', - statusIconClass: 'fa-check-circle', - statusMessage: 'Payment confirmed! Thank you for your purchase.', - progressVariant: 'success', - progressWidth: '90%', - progressHeight: '12px', - stepPercentage: 10, - confirmationCount: 10 // Fully confirmed - }, - paid_unconfirmed: { - paymentStatusClass: 'warning', - statusIconClass: 'fa-clock', - statusMessage: 'Payment received - awaiting confirmation', - progressVariant: 'warning', - progressWidth: '90%', - progressHeight: '12px', - stepPercentage: 10, - confirmationCount: status.confirmations || 1 // Partial progress - }, - pending: { - paymentStatusClass: 'info', - statusIconClass: 'fa-hourglass-half', - statusMessage: 'Payment pending - please complete the transaction', - progressVariant: 'info', - progressWidth: '90%', - progressHeight: '8px', // Thinner as it's not started - stepPercentage: 10, - confirmationCount: 0 // No progress yet - }, - expired: { - paymentStatusClass: 'danger', - statusIconClass: 'fa-exclamation-triangle', - statusMessage: 'Payment expired - please restart the payment process', - progressVariant: 'secondary', - progressWidth: '90%', - progressHeight: '8px', - stepPercentage: 10, - confirmationCount: 0, // Reset progress - additionalMessage: 'The payment session has expired. Please initiate a new payment.' - } - }; - - // Get configuration for current status or default to error state - const config = statusConfig[status.status] || { - paymentStatusClass: 'danger', - statusIconClass: 'fa-exclamation-circle', - statusMessage: status.error || 'Unknown payment status', - progressVariant: 'danger', - progressWidth: '90%', - progressHeight: '8px', - confirmationCount: 0 - }; - - // Update all props at once - this.props = { - ...this.props, - ...config, - // Preserve existing props that aren't being updated - qrCode: this.props.qrCode, - formattedAmount: this.props.formattedAmount, - formattedMoneroAmount: this.props.formattedMoneroAmount, - exchangeRate: this.props.exchangeRate, - orderName: this.props.orderName, - sellerAddress: this.props.sellerAddress - }; - - // Special case for expired status to show additional message - if (status.status === 'expired') { - this.props.statusMessage += ' ' + config.additionalMessage; - } - - // Render the updated component - this.render(); - }, - - cleanupPayment(paymentId) { - this.activeMoneroPayments.delete(paymentId); - }, - - willUnmount() { - this.activeMoneroPayments.clear(); - }, - - cancelOnlinePayment(order) { - console.debug(`${DEBUG_TAG} Canceling online payment for order:`, order.id); - try { - this.pos.data.call("pos.order", "get_and_set_online_payments_data", [order.id, 0]); - } catch (error) { - console.error(`${DEBUG_TAG} Failed to cancel payment:`, error); - } - }, - - async afterPaidOrderSavedOnServer(orderJSON) { - console.debug(`${DEBUG_TAG} Processing paid order:`, orderJSON); - if (!orderJSON) { - console.error(`${DEBUG_TAG} No order data received`); - this.dialog.add(AlertDialog, { - // title: _t("Server error"), - title: "Server error", - // body: _t("The saved order could not be retrieved."), - body: "The saved order could not be retrieved.", - }); - return; - } - - const isInvoiceRequested = this.currentOrder.is_to_invoice(); - if (!orderJSON[0] || this.currentOrder.id !== orderJSON[0].id) { - console.error(`${DEBUG_TAG} Order ID mismatch`); - this.dialog.add(AlertDialog, { - // title: _t("Order saving issue"), - title: "Order saving issue", - // body: _t("The order has not been saved correctly on the server."), - body: "The order has not been saved correctly on the server.", - }); - return; - } - - this.currentOrder.state = "paid"; - this.pos.validated_orders_name_server_id_map[this.currentOrder.name] = this.currentOrder.id; - - if ((this.currentOrder.is_paid_with_cash() || this.currentOrder.get_change()) && - this.pos.config.iface_cashdrawer) { - console.debug(`${DEBUG_TAG} Opening cash drawer`); - this.hardwareProxy.printer.openCashbox(); - } - - if (isInvoiceRequested) { - console.debug(`${DEBUG_TAG} Handling invoice request`); - if (!orderJSON[0].raw.account_move) { - console.error(`${DEBUG_TAG} No invoice generated`); - this.dialog.add(AlertDialog, { - // title: _t("Invoice could not be generated"), - title: "Invoice could not be generated", - // body: _t("The invoice could not be generated."), - body: "The invoice could not be generated.", - }); - } else { - try { - await this.invoiceService.downloadPdf(orderJSON[0].raw.account_move); - } catch (error) { - console.error(`${DEBUG_TAG} Failed to download invoice:`, error); - } - } - } - - try { - await this.postPushOrderResolve([this.currentOrder.id]); - console.debug(`${DEBUG_TAG} Order finalized successfully`); - } catch (error) { - console.error(`${DEBUG_TAG} Failed to finalize order:`, error); - } - - this.afterOrderValidation(true); - }, -}); - diff --git a/payment_monero_rpc/static/src/css/monero.css b/payment_monero_rpc/static/src/css/monero.css deleted file mode 100644 index 2917b6d4..00000000 --- a/payment_monero_rpc/static/src/css/monero.css +++ /dev/null @@ -1,84 +0,0 @@ -/* /static/src/css/monero.css */ -.monero-status-container { - margin: 20px auto; - max-width: 500px; -} - -.monero-timer { - text-align: center; - font-size: 1.5em; - margin: 20px 0; -} - -.monero-timer .countdown { - font-family: monospace; - font-weight: bold; - color: #dc3545; -} - -.progress-bar { - transition: width 1s ease-in-out; -} - -.copy-btn { - cursor: pointer; - padding: 0 5px; -} - -.copy-btn:hover { - color: #007bff; -} - -/* QR code container with subtle border */ -.qr-container { - border: 1px solid #eee; - border-radius: 4px; - padding: 10px; - display: inline-block; - background: white; - width: 200px; - height: 200px; -} - -.monero-payment-container { - margin: 15px 0; - padding: 15px; - border: 1px solid #e6e6e6; - border-radius: 4px; - background: #f9f9f9; -} - -.monero-payment-btn { - background-color: #FF6600 !important; - border-color: #FF6600 !important; - padding: 10px 20px !important; - color: white !important; -} - -.monero-payment-btn:hover { - background-color: #e05a00 !important; - border-color: #e05a00 !important; -} - -.monero-payment-loading { - color: #FF6600; - font-weight: bold; -} - -.monero-payment-btn-container { - margin-top: 15px; - padding: 10px; - background: #f9f9f9; - border-radius: 4px; -} - -.js_monero_payment_btn { - background-color: #FF6600 !important; /* Monero orange */ - border-color: #FF6600 !important; - padding: 8px 16px !important; -} - -.js_monero_loading { - color: #FF6600; - margin-top: 10px; -} diff --git a/payment_monero_rpc/static/src/css/monero_pos.css b/payment_monero_rpc/static/src/css/monero_pos.css deleted file mode 100644 index fe376dc9..00000000 --- a/payment_monero_rpc/static/src/css/monero_pos.css +++ /dev/null @@ -1,111 +0,0 @@ -.monero-payment .body { - text-align: center; - padding: 20px; -} - -.monero-payment .qr-code { - margin: 20px auto; - padding: 10px; - background: white; - display: inline-block; -} - -.monero-payment .qr-code img { - display: block; - margin: 0 auto; -} - -.monero-payment .status { - margin-top: 20px; - padding: 10px; - background: #f8f9fa; - border-radius: 4px; -} - -.monero-payment .progress { - height: 10px; - margin-top: 10px; - background: #e9ecef; - border-radius: 5px; - overflow: hidden; -} - -.monero-payment .progress-bar { - height: 100%; - background: #17a2b8; - transition: width 0.3s; -} - -.popup-monero { - max-width: 500px; - text-align: center; -} - -.popup-monero .monero-payment-container { - display: flex; - flex-direction: column; - align-items: center; -} - -.popup-monero .payment-status { - font-size: 18px; - font-weight: bold; - margin-bottom: 20px; - padding: 10px; - border-radius: 5px; - background-color: #f8f9fa; -} - -.popup-monero .payment-status.paid { - background-color: #28a745; - color: white; -} - -.popup-monero .qr-code-container { - display: flex; - flex-direction: column; - align-items: center; -} - -.popup-monero .qr-code img { - max-width: 200px; - max-height: 200px; - margin: 20px 0; -} - -.popup-monero .payment-details { - margin-bottom: 15px; -} - -.popup-monero .fiat-amount { - font-size: 24px; - font-weight: bold; -} - -.popup-monero .monero-amount { - font-size: 18px; - margin: 5px 0; -} - -.popup-monero .exchange-rate { - font-size: 14px; - color: #6c757d; -} - -.popup-monero .copy-container { - margin-top: 10px; -} - -.popup-monero .copy-button { - background-color: #007bff; - color: white; - border: none; - padding: 8px 15px; - border-radius: 4px; - cursor: pointer; -} - -.popup-monero .copy-button:hover { - background-color: #0069d9; -} - diff --git a/payment_monero_rpc/static/src/css/payment_page.css b/payment_monero_rpc/static/src/css/payment_page.css deleted file mode 100644 index f005bed2..00000000 --- a/payment_monero_rpc/static/src/css/payment_page.css +++ /dev/null @@ -1,15 +0,0 @@ -/* static/src/css/payment_page.css */ - -.dark-mode { - background-color: #1a1a1a; - color: #f0f0f0; -} - -.dark-mode .card { - background-color: #2a2a2a; - border-color: #444; -} - -.dark-mode .table { - color: #f0f0f0; -} diff --git a/payment_monero_rpc/static/src/js/clipboard.min.js b/payment_monero_rpc/static/src/js/clipboard.min.js deleted file mode 100644 index 1103f811..00000000 --- a/payment_monero_rpc/static/src/js/clipboard.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * clipboard.js v2.0.11 - * https://clipboardjs.com/ - * - * Licensed MIT © Zeno Rocha - */ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ClipboardJS=e():t.ClipboardJS=e()}(this,function(){return n={686:function(t,e,n){"use strict";n.d(e,{default:function(){return b}});var e=n(279),i=n.n(e),e=n(370),u=n.n(e),e=n(817),r=n.n(e);function c(t){try{return document.execCommand(t)}catch(t){return}}var a=function(t){t=r()(t);return c("cut"),t};function o(t,e){var n,o,t=(n=t,o="rtl"===document.documentElement.getAttribute("dir"),(t=document.createElement("textarea")).style.fontSize="12pt",t.style.border="0",t.style.padding="0",t.style.margin="0",t.style.position="absolute",t.style[o?"right":"left"]="-9999px",o=window.pageYOffset||document.documentElement.scrollTop,t.style.top="".concat(o,"px"),t.setAttribute("readonly",""),t.value=n,t);return e.container.appendChild(t),e=r()(t),c("copy"),t.remove(),e}var f=function(t){var e=1 -
-
-
-
-

Pay with Monero

- -
-

- XMR - -

- -
- -
- Monero Payment QR Code -

- - Scan with Monero wallet -

-
- - - -
-
-
Payment Details
- - - - - - - - - - - - - - - - - - - - - - - -
Seller Address: - -
Order Reference:N/A
Confirmations: - 0 remaining 2 - -
-
-
- - - -
-
How to Pay:
-
    -
  1. Open your Monero wallet (GUI, CLI, or mobile)
  2. -
  3. - Send XMR to the address above - -
  4. -
  5. Wait for 2 network confirmations
  6. -
- -
-
-
-
-
- -`; - -publicWidget.registry.PaymentForm = publicWidget.Widget.extend({ - selector: '#o_payment_form', - events: { - 'click [name="o_payment_radio"]': '_onPaymentMethodSelected' - }, - - init: function() { - console.debug(`${DEBUG_TAG} Initializing payment form widget`); - this._super.apply(this, arguments); - this.moneroPaymentContainer = null; - this.clipboard = null; - this.statusCheckInterval = null; - this.moneroSelected = false; - this.currentPaymentId = null; - this.submitButton = null; - this._boundOnSubmitPayment = this._onSubmitPayment.bind(this); - }, - - willStart: async function() { - console.debug(`${DEBUG_TAG} Loading dependencies`); - return Promise.all([ - loadJS('/payment_monero_rpc/static/src/js/clipboard.min.js').catch(e => { - console.error(`${DEBUG_TAG} Failed to load clipboard.js:`, e); - }), - this._super.apply(this, arguments) - ]); - }, - - start: function() { - console.debug(`${DEBUG_TAG} Starting payment form widget`); - - this.submitButton = document.querySelector('button[name="o_payment_submit_button"]'); - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Found submit button, attaching handler`); - this.submitButton.addEventListener('click', this._boundOnSubmitPayment); - } - - return this._super.apply(this, arguments).then(() => { - this._handleInitialSelection(); - }); - }, - - _handleInitialSelection: function() { - const selectedRadio = this.el.querySelector('input[name="o_payment_radio"]:checked'); - if (selectedRadio) { - console.debug(`${DEBUG_TAG} Found default payment selection:`, selectedRadio.dataset.providerCode); - this._onPaymentMethodSelected({ currentTarget: selectedRadio }); - } - }, - - _onPaymentMethodSelected: function(ev) { - const providerCode = this._getProviderCode(ev.currentTarget); - console.debug(`${DEBUG_TAG} Payment method changed to:`, providerCode); - - this.moneroSelected = (providerCode === 'monero_rpc'); - this._updatePayButtonText( - this.moneroSelected ? _t("Pay with Monero") : _t("Pay Now") - ); - }, - - _onSubmitPayment: async function(ev) { - console.debug(`${DEBUG_TAG} Form submission initiated`); - ev.preventDefault(); - ev.stopPropagation(); - - if (!this.moneroSelected) { - console.debug(`${DEBUG_TAG} Non-Monero payment selected, using default flow`); - return this._super.apply(this, arguments); - } - - try { - this._disablePaymentForm(); - const checkedRadio = this.el.querySelector('input[name="o_payment_radio"]:checked'); - const paymentResponse = await this._processMoneroPayment(checkedRadio); - - if (paymentResponse.error) { - throw new Error(paymentResponse.error); - } - - if (!paymentResponse || !paymentResponse.payment_id) { - throw new Error("Invalid payment data received"); - } - - const paymentData = paymentResponse.payment || {}; - paymentData.payment_id = paymentResponse.payment_id; - - await this._displayMoneroPaymentPage(paymentData); - } catch (error) { - console.error(`${DEBUG_TAG} Payment processing failed:`, error); - this._displayError( - _t("Payment Error"), - error.message || _t("Failed to process Monero payment. Please try again.") - ); - this._enablePaymentForm(); - } - }, - - _processMoneroPayment: async function(radio) { - console.debug(`${DEBUG_TAG} Creating Monero transaction request`); - - const amountTotal = document.getElementById('amount_total_summary'); - if (!amountTotal) { - throw new Error("Missing order information"); - } - - const orderId = amountTotal.getAttribute('data-oe-id') || amountTotal.dataset.oeId; - if (!orderId) { - throw new Error("Missing order ID"); - } - - const providerId = this._getProviderId(radio); - const providerCode = this._getProviderCode(radio); - - try { - const endpoint = `/shop/payment/monero/process/${orderId}`; - console.debug(`${DEBUG_TAG} Calling endpoint: ${endpoint}`); - - const response = await rpc(endpoint, { - provider: providerId, - provider_code: providerCode, - order_sudo: parseInt(orderId), - csrf_token: odoo.csrf_token, - }, { - shadow: true, - timeout: 30000 - }); - - console.debug(`${DEBUG_TAG} Received response:`, response); - - if (!response) { - throw new Error("Empty response from server"); - } - - if (response.error) { - throw new Error(response.error); - } - - if (!response.payment_id) { - throw new Error("Invalid response format - missing payment_id"); - } - - this.currentPaymentId = response.payment_id; - return response; - } catch (error) { - console.error(`${DEBUG_TAG} RPC call failed:`, { - error: error, - message: error.message, - stack: error.stack, - data: error.data || null - }); - - throw new Error("Payment processing failed. Please try again or contact support."); - } - }, - - _displayMoneroPaymentPage: async function(payment) { - console.debug(`${DEBUG_TAG} Displaying Monero payment page`); - this._cleanupPaymentContainer(); - - this.moneroPaymentContainer = document.createElement('div'); - this.moneroPaymentContainer.id = 'monero_payment_container'; - this.moneroPaymentContainer.className = 'monero-payment-container'; - - this.el.parentNode.insertBefore(this.moneroPaymentContainer, this.el.nextSibling); - this.el.style.display = 'none'; - - try { - this.moneroPaymentContainer.innerHTML = MONERO_PAYMENT_TEMPLATE; - this._populatePaymentData(payment); - await this._setupEventListeners(); - - if (payment.state === 'pending' || payment.state === 'paid_unconfirmed') { - this._startStatusChecking(payment.payment_id); - } - - if (payment.state === 'pending') { - const refreshScript = document.createElement('script'); - refreshScript.textContent = ` - setTimeout(function(){ - const form = document.querySelector('#o_payment_form'); - if (form) { - const moneroRadio = form.querySelector('input[data-provider-code="monero_rpc"]'); - if (moneroRadio) { - moneroRadio.checked = true; - const payButton = form.querySelector('button[name="o_payment_submit_button"]'); - if (payButton) { - payButton.click(); - } - } - } - }, 30000); - `; - this.moneroPaymentContainer.appendChild(refreshScript); - } - - this.call('ui', 'unblock'); - } catch (error) { - console.error(`${DEBUG_TAG} Failed to display payment page:`, error); - this.call('ui', 'unblock'); - throw new Error("Failed to display payment page. Please try again."); - } - }, - - _populatePaymentData: function(payment) { - document.getElementById('payment_amount_str').textContent = payment.amount_str || ''; - document.getElementById('instructions_amount_str').textContent = payment.amount_str || ''; - document.getElementById('seller_address').textContent = payment.address_seller || ''; - document.getElementById('order_reference').textContent = payment.order_ref || 'N/A'; - document.getElementById('required_confirmations').textContent = payment.required_confirmations || '2'; - document.getElementById('instructions_required_confirmations').textContent = payment?.required_confirmations || '2'; - document.getElementById('confirmations').textContent = payment.confirmations || '0'; - - if (payment.id) { - document.getElementById('qr_code_img').src = `/shop/payment/monero/qr/${payment.id}`; - } - - if (payment.payment_id) { - document.getElementById('payment_id').textContent = payment.payment_id; - document.getElementById('payment_id_row').style.display = ''; - } - - if (payment.original_amount_str && payment.original_currency) { - document.getElementById('original_amount_container').style.display = ''; - document.getElementById('original_amount_str').textContent = payment.original_amount_str; - document.getElementById('original_currency').textContent = payment.original_currency; - document.getElementById('instructions_original_amount').style.display = ''; - document.getElementById('instructions_original_amount_value').textContent = payment.original_amount_str; - document.getElementById('instructions_original_currency').textContent = payment.original_currency; - } - - if (payment.exchange_rate_str && payment.original_currency) { - document.getElementById('exchange_rate_container').style.display = ''; - document.getElementById('exchange_rate_str').textContent = payment.exchange_rate_str; - document.getElementById('exchange_rate_currency').textContent = payment.original_currency; - } - - if (payment.expiry_time_str) { - document.getElementById('expiry_time_str').textContent = payment.expiry_time_str; - document.getElementById('expiry_time_row').style.display = ''; - } - - if (payment.confirmations + payment.required_confirmations < 2) { - document.getElementById('confirmations_waiting').style.display = ''; - document.getElementById('confirmations_needed').textContent = - payment.required_confirmations; - } - - const statusAlertClass = payment.status_alert_class || 'info'; - document.getElementById('payment_status_alert').className = `alert alert-${statusAlertClass}`; - document.getElementById('payment_status_message').className = `alert alert-${statusAlertClass}`; - document.getElementById('status_icon').className = `fa ${payment.status_icon || 'fa-info-circle'}`; - document.getElementById('status_message').textContent = payment.status_message || ''; - - if (payment.state === 'pending') { - document.getElementById('status_check_container').style.display = ''; - } - - if (payment.state === 'confirmed') { - document.getElementById('payment_proof_btn').style.display = ''; - } - - if (payment.monero_uri) { - document.getElementById('wallet_uri_container').style.display = ''; - document.getElementById('wallet_uri_btn').href = payment.monero_uri; - } - - if (payment.invoice_ids && payment.invoice_ids.length > 0) { - const container = document.getElementById('invoice_download_container'); - container.innerHTML = ''; - - const dropdown = document.createElement('div'); - dropdown.className = 'dropdown'; - - const button = document.createElement('button'); - button.className = 'btn btn-outline-primary dropdown-toggle'; - button.type = 'button'; - button.id = 'invoiceDropdown'; - button.setAttribute('data-toggle', 'dropdown'); - button.setAttribute('aria-haspopup', 'true'); - button.setAttribute('aria-expanded', 'false'); - button.innerHTML = ' Download Invoice'; - - const menu = document.createElement('div'); - menu.className = 'dropdown-menu'; - menu.setAttribute('aria-labelledby', 'invoiceDropdown'); - - payment.invoice_ids.forEach(invoice_id => { - const link = document.createElement('a'); - link.className = 'dropdown-item'; - link.href = `/my/invoices/${invoice_id}?download=1`; - link.textContent = `Invoice ${invoice_id}`; - menu.appendChild(link); - }); - - dropdown.appendChild(button); - dropdown.appendChild(menu); - container.appendChild(dropdown); - - const disabledBtn = container.querySelector('.disabled'); - if (disabledBtn) { - disabledBtn.remove(); - } - } - }, - - _setupEventListeners: async function() { - const checkStatusBtn = this.moneroPaymentContainer.querySelector('#check_status_btn'); - if (checkStatusBtn) { - checkStatusBtn.addEventListener('click', (ev) => { - ev.preventDefault(); - console.debug(`${DEBUG_TAG} Manual status check triggered`); - this._manualCheckStatus(); - }); - } - - if (typeof ClipboardJS !== 'undefined') { - console.debug(`${DEBUG_TAG} Initializing clipboard`); - this.clipboard = new ClipboardJS('.copy-btn'); - this.clipboard.on('success', (e) => { - console.debug(`${DEBUG_TAG} Copied to clipboard:`, e.text); - const btn = e.trigger; - btn.setAttribute('title', _t("Copied!")); - const icon = btn.querySelector('i'); - if (icon) icon.className = 'fa fa-check'; - setTimeout(() => { - btn.setAttribute('title', _t("Copy to clipboard")); - if (icon) icon.className = 'fa fa-copy'; - }, 2000); - }); - } - }, - - _startStatusChecking: function(paymentId) { - console.debug(`${DEBUG_TAG} Configuring status check interval`); - this._stopStatusChecking(); - - const checkInterval = this.moneroPaymentContainer.querySelector('.alert-warning') ? 30000 : 60000; - console.debug(`${DEBUG_TAG} Setting check interval to ${checkInterval}ms`); - this.statusCheckInterval = setInterval( - () => this._checkPaymentStatus(paymentId), - checkInterval - ); - }, - - _stopStatusChecking: function() { - if (this.statusCheckInterval) { - console.debug(`${DEBUG_TAG} Stopping status checks`); - clearInterval(this.statusCheckInterval); - this.statusCheckInterval = null; - } - }, - - _manualCheckStatus: function() { - const paymentId = this.currentPaymentId; - if (paymentId) { - console.debug(`${DEBUG_TAG} Manual status check for payment:`, paymentId); - this._checkPaymentStatus(paymentId); - } - }, - - _checkPaymentStatus: async function(paymentId) { - console.debug(`${DEBUG_TAG} Checking payment status for:`, paymentId); - try { - const status = await rpc("/shop/payment/monero/status/" + paymentId, { - // No need for additional params since payment_id is in the URL - }, { - shadow: true, - timeout: 10000 - }); - - console.debug(`${DEBUG_TAG} Status check response:`, status); - - // Force status to 'confirmed' in case it is not in sync with confirmations count - if (status.status === 'confirmed' || status.confirmations >= 2) { - console.debug(`${DEBUG_TAG} Payment confirmed, clearing cart and redirecting`); - this._updateStatusDisplay({ - status: 'confirmed', - status_message: "Payment confirmed! Thank you for your purchase.", - status_alert_class: "success", - status_icon: "fa-check-circle" - }); - this._stopStatusChecking(); - - try { - // Clear the cart - await rpc("/shop/cart/clear", {}, { - shadow: true, - timeout: 10000 - }); - } catch (clearError) { - console.warn(`${DEBUG_TAG} Could not clear cart:`, clearError); - } - - // Redirect after a short delay to allow UI updates - setTimeout(() => { - if (this.el.dataset.returnUrl) { - window.location.href = this.el.dataset.returnUrl; - } - }, 1500); - return; - } - if (status.error) { - throw new Error(status.error); - } - if (status.status === 'paid_unconfirmed') { - console.debug(`${DEBUG_TAG} Payment unconfirmed, updating display`); - this._updateStatusDisplay({ - ...status, - status_message: "Payment received - awaiting confirmation", - status_alert_class: "warning", - confirmation: "We've received your payment but it's awaiting network confirmation. This may take a few minutes." - }); - this._startStatusChecking(paymentId); - } else if (status.status === 'pending') { - console.debug(`${DEBUG_TAG} Payment still pending`); - this._updateStatusDisplay({ - ...status, - status_message: "Payment pending - please complete the transaction", - status_alert_class: "info", - confirmation: "Your payment is currently pending. Please complete the transaction process." - }); - } else if (status.status === 'expired') { - console.debug(`${DEBUG_TAG} Payment expired`); - this._updateStatusDisplay({ - ...status, - status_message: "Payment expired - please restart the payment process", - status_alert_class: "danger", - confirmation: "The payment session has expired. Please initiate a new payment if you wish to complete your purchase." - }); - this._stopStatusChecking(); - } - - } catch (error) { - console.error(`${DEBUG_TAG} Status check failed:`, error); - this._updateStatusDisplay({ - status_message: "Error checking payment status: " + error.message, - status_alert_class: "danger" - }); - } - }, - - _updateStatusDisplay: function(status) { - console.debug(`${DEBUG_TAG} Update screen data with - `, status); - - // Update elements that might be in the template - const confirmationsEl = this.moneroPaymentContainer.querySelector('#confirmations'); - const requiredConfirmationsEl = this.moneroPaymentContainer.querySelector('#required_confirmations'); - const requiredConfirmationsEl2 = this.moneroPaymentContainer.querySelector('#instructions_required_confirmations'); - const statusMessageEl = this.moneroPaymentContainer.querySelector('#status_message'); - const statusIconEl = this.moneroPaymentContainer.querySelector('#status_icon'); - const statusAlertEl = this.moneroPaymentContainer.querySelector('#payment_status_message'); - const checkStatusBtn = this.moneroPaymentContainer.querySelector('#check_status_btn'); - const walletUriContainer = this.moneroPaymentContainer.querySelector('#wallet_uri_container'); - - if (confirmationsEl && status.confirmations !== undefined) { - confirmationsEl.textContent = status.confirmations; - } - - if (requiredConfirmationsEl && status.required_confirmations) { - requiredConfirmationsEl.textContent = status.required_confirmations; - requiredConfirmationsEl2.textContent = status.required_confirmations; - } - - if (statusMessageEl && status.status_message) { - statusMessageEl.textContent = status.status_message; - } - - if (statusIconEl && status.status_icon_class) { - statusIconEl.className = `fa ${status.status_icon_class}`; - } - - if (statusAlertEl && status.status_alert_class) { - statusAlertEl.className = `alert alert-${status.status_alert_class}`; - } - - if (checkStatusBtn && status.payment_complete) { - checkStatusBtn.style.display = 'none'; - } - - if (walletUriContainer && status.payment_complete) { - walletUriContainer.style.display = 'none'; - } - }, - - _cleanupPaymentContainer: function() { - console.debug(`${DEBUG_TAG} Cleaning up payment container`); - this._stopStatusChecking(); - - if (this.clipboard) { - this.clipboard.destroy(); - this.clipboard = null; - } - - if (this.moneroPaymentContainer) { - this.moneroPaymentContainer.remove(); - this.moneroPaymentContainer = null; - } - - this.el.style.display = ''; - }, - - _updatePayButtonText: function(text) { - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Updating pay button text to:`, text); - this.submitButton.textContent = text; - } - }, - - _disablePaymentForm: function() { - console.debug(`${DEBUG_TAG} Disabling payment form`); - if (this.submitButton) { - this.submitButton.disabled = true; - } - this.el.querySelectorAll('input').forEach(el => el.disabled = true); - this.call('ui', 'block'); - }, - - _enablePaymentForm: function() { - console.debug(`${DEBUG_TAG} Enabling payment form`); - if (this.submitButton) { - this.submitButton.disabled = false; - } - this.el.querySelectorAll('input').forEach(el => el.disabled = false); - this.call('ui', 'unblock'); - }, - - _displayError: function(title, message) { - console.debug(`${DEBUG_TAG} Displaying error dialog:`, title, message); - this.call('dialog', 'add', ConfirmationDialog, { - title: title, - body: message, - confirmLabel: _t("OK"), - }); - }, - - _getProviderCode: function(radio) { - return radio.dataset.providerCode; - }, - - _getProviderId: function(radio) { - return parseInt(radio.dataset.providerId); - }, - - destroy: function() { - console.debug(`${DEBUG_TAG} Destroying widget`); - if (this.submitButton) { - this.submitButton.removeEventListener('click', this._boundOnSubmitPayment); - } - this._cleanupPaymentContainer(); - this._super.apply(this, arguments); - } -}); - -export default publicWidget.registry.PaymentForm; diff --git a/payment_monero_rpc/static/src/js/payment_form_monero_update.js b/payment_monero_rpc/static/src/js/payment_form_monero_update.js deleted file mode 100644 index fcd57825..00000000 --- a/payment_monero_rpc/static/src/js/payment_form_monero_update.js +++ /dev/null @@ -1,622 +0,0 @@ -/** @odoo-module **/ - -//TODO this is the future OWL-3 incarnation still in progress. - -import { Component, onMounted, onWillUnmount, useState } from "@odoo/owl"; -import { useService } from "@web/core/utils/hooks"; -import { renderToString } from "@web/core/utils/render"; -import { _t } from "@web/core/l10n/translation"; -import { ConfirmationDialog } from "@web/core/confirmation_dialog/confirmation_dialog"; -import { loadJS } from "@web/core/assets"; -import publicWidget from '@web/legacy/js/public/public_widget'; - -const DEBUG_TAG = "[MoneroPayment]"; - -export class MoneroPaymentForm extends Component { - static template = "payment_monero_rpc.MoneroPaymentForm"; - - setup() { - console.debug(`${DEBUG_TAG} Initializing component setup`); - this.rpc = useService("rpc"); - this.dialog = useService("dialog"); - this.ui = useService("ui"); - this.state = useState({ - paymentData: null, - currentPaymentId: null, - moneroSelected: false, - statusCheckInterval: null, - }); - - this.submitButton = null; - this.clipboard = null; - this.moneroPaymentContainer = null; - - console.debug(`${DEBUG_TAG} Setting up lifecycle hooks`); - onMounted(() => { - console.debug(`${DEBUG_TAG} Component mounted`); - this.onMounted(); - }); - onWillUnmount(() => { - console.debug(`${DEBUG_TAG} Component will unmount`); - this.onWillUnmount(); - }); - } - - onMounted() { - console.debug(`${DEBUG_TAG} Starting onMounted`); - console.debug(`${DEBUG_TAG} Searching for submit button`); - this.submitButton = document.querySelector('button[name="o_payment_submit_button"]'); - - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Found submit button:`, this.submitButton); - console.debug(`${DEBUG_TAG} Current button text:`, this.submitButton.textContent); - console.debug(`${DEBUG_TAG} Adding click event listener`); - this.submitButton.addEventListener("click", this.onSubmitPayment.bind(this)); - } else { - console.error(`${DEBUG_TAG} Could not find submit button in DOM!`); - console.debug(`${DEBUG_TAG} Available buttons:`, document.querySelectorAll('button')); - } - - console.debug(`${DEBUG_TAG} Checking initial payment selection`); - this.handleInitialSelection(); - } - - onWillUnmount() { - console.debug(`${DEBUG_TAG} Starting onWillUnmount cleanup`); - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Removing event listener from submit button`); - this.submitButton.removeEventListener("click", this.onSubmitPayment.bind(this)); - } - console.debug(`${DEBUG_TAG} Cleaning up payment container`); - this.cleanupPaymentContainer(); - } - - handleInitialSelection() { - console.debug(`${DEBUG_TAG} Checking for initially selected payment method`); - const selectedRadio = document.querySelector('input[name="o_payment_radio"]:checked'); - - if (selectedRadio) { - console.debug(`${DEBUG_TAG} Found default selection:`, { - providerCode: selectedRadio.dataset.providerCode, - element: selectedRadio - }); - this.onPaymentMethodSelected({ currentTarget: selectedRadio }); - } else { - console.debug(`${DEBUG_TAG} No payment method selected by default`); - } - } - - onPaymentMethodSelected(ev) { - if (!ev || !ev.currentTarget) { - console.error(`${DEBUG_TAG} Invalid event object in onPaymentMethodSelected:`, ev); - return; - } - - const providerCode = this.getProviderCode(ev.currentTarget); - console.debug(`${DEBUG_TAG} Payment method changed to:`, providerCode); - - this.state.moneroSelected = (providerCode === 'monero_rpc'); - console.debug(`${DEBUG_TAG} Monero selected state:`, this.state.moneroSelected); - - const newButtonText = this.state.moneroSelected ? _t("Pay with Monero") : _t("Pay Now"); - console.debug(`${DEBUG_TAG} Updating button text to:`, newButtonText); - this.updatePayButtonText(newButtonText); - } - - async onSubmitPayment(ev) { - console.debug(`${DEBUG_TAG} Form submission initiated`); - console.debug(`${DEBUG_TAG} Event details:`, { - type: ev.type, - target: ev.target, - defaultPrevented: ev.defaultPrevented - }); - - ev.preventDefault(); - ev.stopPropagation(); - console.debug(`${DEBUG_TAG} Default form submission prevented`); - - if (!this.state.moneroSelected) { - console.debug(`${DEBUG_TAG} Non-Monero payment selected, skipping Monero processing`); - return; - } - - try { - console.debug(`${DEBUG_TAG} Starting Monero payment processing`); - this.disablePaymentForm(); - - console.debug(`${DEBUG_TAG} Looking for selected payment radio`); - const checkedRadio = document.querySelector('input[name="o_payment_radio"]:checked'); - console.debug(`${DEBUG_TAG} Found radio:`, checkedRadio); - - console.debug(`${DEBUG_TAG} Processing Monero payment...`); - const paymentResponse = await this.processMoneroPayment(checkedRadio); - console.debug(`${DEBUG_TAG} Payment processing complete:`, paymentResponse); - - if (paymentResponse.error) { - console.error(`${DEBUG_TAG} Payment error:`, paymentResponse.error); - throw new Error(paymentResponse.error); - } - - if (!paymentResponse || !paymentResponse.payment_id) { - console.error(`${DEBUG_TAG} Invalid payment data:`, paymentResponse); - throw new Error("Invalid payment data received"); - } - - const paymentData = paymentResponse.payment || {}; - paymentData.payment_id = paymentResponse.payment_id; - this.state.paymentData = paymentData; - this.state.currentPaymentId = paymentResponse.payment_id; - console.debug(`${DEBUG_TAG} Updated component state with payment data`); - - console.debug(`${DEBUG_TAG} Displaying Monero payment page`); - await this.displayMoneroPaymentPage(paymentData); - } catch (error) { - console.error(`${DEBUG_TAG} Payment processing failed:`, { - error: error, - message: error.message, - stack: error.stack - }); - this.displayError( - _t("Payment Error"), - error.message || _t("Failed to process Monero payment. Please try again.") - ); - this.enablePaymentForm(); - } - } - - async processMoneroPayment(radio) { - console.debug(`${DEBUG_TAG} Starting Monero payment processing`); - console.debug(`${DEBUG_TAG} Radio element:`, radio); - - const amountTotal = document.getElementById('amount_total_summary'); - if (!amountTotal) { - console.error(`${DEBUG_TAG} Missing amount_total_summary element`); - throw new Error("Missing order information"); - } - - const orderId = amountTotal.getAttribute('data-oe-id') || amountTotal.dataset.oeId; - if (!orderId) { - console.error(`${DEBUG_TAG} Missing order ID in amount_total_summary`); - throw new Error("Missing order ID"); - } - - const providerId = this.getProviderId(radio); - const providerCode = this.getProviderCode(radio); - console.debug(`${DEBUG_TAG} Payment details:`, { - providerId, - providerCode, - orderId - }); - - try { - const endpoint = `/shop/payment/monero/process/${orderId}`; - console.debug(`${DEBUG_TAG} Calling endpoint: ${endpoint}`); - - const response = await this.rpc(endpoint, { - provider: providerId, - provider_code: providerCode, - order_sudo: parseInt(orderId), - csrf_token: odoo.csrf_token, - }, { - shadow: true, - timeout: 30000 - }); - - console.debug(`${DEBUG_TAG} Received response:`, response); - - if (!response) { - console.error(`${DEBUG_TAG} Empty response from server`); - throw new Error("Empty response from server"); - } - - if (response.error) { - console.error(`${DEBUG_TAG} Server returned error:`, response.error); - throw new Error(response.error); - } - - if (!response.payment_id) { - console.error(`${DEBUG_TAG} Missing payment_id in response`); - throw new Error("Invalid response format - missing payment_id"); - } - - this.state.currentPaymentId = response.payment_id; - console.debug(`${DEBUG_TAG} Set currentPaymentId:`, this.state.currentPaymentId); - return response; - } catch (error) { - console.error(`${DEBUG_TAG} RPC call failed:`, { - error: error, - message: error.message, - stack: error.stack, - data: error.data || null - }); - - throw new Error("Payment processing failed. Please try again or contact support."); - } - } - - async displayMoneroPaymentPage(payment) { - console.debug(`${DEBUG_TAG} Displaying Monero payment page`); - console.debug(`${DEBUG_TAG} Payment data:`, payment); - this.cleanupPaymentContainer(); - - this.moneroPaymentContainer = document.createElement('div'); - this.moneroPaymentContainer.id = 'monero_payment_container'; - this.moneroPaymentContainer.className = 'monero-payment-container'; - console.debug(`${DEBUG_TAG} Created payment container:`, this.moneroPaymentContainer); - - const paymentForm = document.querySelector('#o_payment_form'); - if (!paymentForm) { - console.error(`${DEBUG_TAG} Could not find payment form`); - throw new Error("Payment form not found"); - } - - paymentForm.parentNode.insertBefore( - this.moneroPaymentContainer, - paymentForm.nextSibling - ); - paymentForm.style.display = 'none'; - console.debug(`${DEBUG_TAG} Updated DOM with payment container`); - - try { - console.debug(`${DEBUG_TAG} Rendering payment template`); - const html = renderToString('payment_monero_rpc.monero_payment_template_page', { - payment_data: payment - }); - - this.moneroPaymentContainer.innerHTML = html; - console.debug(`${DEBUG_TAG} Template rendered successfully`); - - await this.setupEventListeners(); - console.debug(`${DEBUG_TAG} Event listeners setup complete`); - - if (payment.state === 'pending' || payment.state === 'paid_unconfirmed') { - console.debug(`${DEBUG_TAG} Starting status checks for payment state:`, payment.state); - this.startStatusChecking(payment.payment_id); - } - - if (payment.state === 'pending') { - console.debug(`${DEBUG_TAG} Adding refresh script for pending payment`); - const refreshScript = document.createElement('script'); - refreshScript.textContent = ` - setTimeout(function(){ - console.debug('${DEBUG_TAG} Running payment refresh check'); - const form = document.querySelector('#o_payment_form'); - if (form) { - const moneroRadio = form.querySelector('input[data-provider-code="monero_rpc"]'); - if (moneroRadio) { - moneroRadio.checked = true; - const payButton = form.querySelector('button[name="o_payment_submit_button"]'); - if (payButton) { - payButton.click(); - } - } - } - }, 30000); - `; - this.moneroPaymentContainer.appendChild(refreshScript); - } - - this.ui.unblock(); - console.debug(`${DEBUG_TAG} UI unblocked after payment page display`); - } catch (error) { - console.error(`${DEBUG_TAG} Failed to display payment page:`, { - error: error, - message: error.message, - stack: error.stack - }); - this.ui.unblock(); - throw new Error("Failed to display payment page. Please try again."); - } - } - - async setupEventListeners() { - console.debug(`${DEBUG_TAG} Setting up event listeners`); - - const checkStatusBtn = this.moneroPaymentContainer.querySelector('#check_status_btn'); - if (checkStatusBtn) { - console.debug(`${DEBUG_TAG} Found check status button`); - checkStatusBtn.addEventListener('click', (ev) => { - ev.preventDefault(); - console.debug(`${DEBUG_TAG} Manual status check triggered`); - this.manualCheckStatus(); - }); - } else { - console.debug(`${DEBUG_TAG} No check status button found`); - } - - if (typeof ClipboardJS !== 'undefined') { - console.debug(`${DEBUG_TAG} Initializing clipboard`); - this.clipboard = new ClipboardJS('.copy-btn'); - this.clipboard.on('success', (e) => { - console.debug(`${DEBUG_TAG} Copied to clipboard:`, e.text); - const btn = e.trigger; - btn.setAttribute('title', _t("Copied!")); - const icon = btn.querySelector('i'); - if (icon) icon.className = 'fa fa-check'; - setTimeout(() => { - btn.setAttribute('title', _t("Copy to clipboard")); - if (icon) icon.className = 'fa fa-copy'; - }, 2000); - }); - } else { - console.debug(`${DEBUG_TAG} ClipboardJS not available`); - } - } - - startStatusChecking(paymentId) { - console.debug(`${DEBUG_TAG} Starting status checking for payment:`, paymentId); - this.stopStatusChecking(); - - const checkInterval = this.moneroPaymentContainer.querySelector('.alert-warning') ? 30000 : 60000; - console.debug(`${DEBUG_TAG} Setting check interval to ${checkInterval}ms`); - - this.state.statusCheckInterval = setInterval(() => { - console.debug(`${DEBUG_TAG} Running automatic status check`); - this.checkPaymentStatus(paymentId); - }, checkInterval); - } - - stopStatusChecking() { - if (this.state.statusCheckInterval) { - console.debug(`${DEBUG_TAG} Stopping status checks`); - clearInterval(this.state.statusCheckInterval); - this.state.statusCheckInterval = null; - } else { - console.debug(`${DEBUG_TAG} No active status check interval to stop`); - } - } - - manualCheckStatus() { - const paymentId = this.state.currentPaymentId; - if (paymentId) { - console.debug(`${DEBUG_TAG} Manual status check for payment:`, paymentId); - this.checkPaymentStatus(paymentId); - } else { - console.debug(`${DEBUG_TAG} No currentPaymentId for manual check`); - } - } - - async checkPaymentStatus(paymentId) { - console.debug(`${DEBUG_TAG} Checking payment status for:`, paymentId); - try { - const status = await this.rpc("/shop/payment/monero/status/" + paymentId, {}, { - shadow: true, - timeout: 10000 - }); - - console.debug(`${DEBUG_TAG} Status check response:`, status); - - if (status.status === 'confirmed' || status.confirmations >= 10) { - console.debug(`${DEBUG_TAG} Payment confirmed, clearing cart and redirecting`); - status.status = 'confirmed'; - this._updateStatusDisplay({ - ...status, - status_message: "Payment confirmed! Thank you for your purchase.", - status_alert_class: "success", - status_icon: "fa-check-circle" - }); - this.stopStatusChecking(); - - try { - // Clear the cart. Better though should select actual concerned cart item and remove - //TODO Remove actual cart item - await this.rpc("/shop/cart/clear", {}, { - shadow: true, - timeout: 10000 - }); - } catch (clearError) { - console.warn(`${DEBUG_TAG} Could not clear cart:`, clearError); - } - - // Redirect after a short delay to allow UI updates - setTimeout(() => { - const form = document.querySelector('#o_payment_form'); - if (form && form.dataset.returnUrl) { - window.location.href = form.dataset.returnUrl; - } - }, 1500); - return; - } - - if (status.error) { - console.error(`${DEBUG_TAG} Status check error:`, status.error); - throw new Error(status.error); - } - - if (status.status === 'paid_unconfirmed') { - console.debug(`${DEBUG_TAG} Payment received but unconfirmed`); - this.updateStatusDisplay({ - ...status, - status_message: "Payment received - awaiting confirmation", - status_alert_class: "warning", - confirmation: "We've received your payment but it's awaiting network confirmation. This may take a few minutes." - }); - this.startStatusChecking(paymentId); - } else if (status.status === 'pending') { - console.debug(`${DEBUG_TAG} Payment still pending`); - this.updateStatusDisplay({ - ...status, - status_message: "Payment pending - please complete the transaction", - status_alert_class: "info", - confirmation: "Your payment is currently pending. Please complete the transaction process." - }); - } else if (status.status === 'expired') { - console.debug(`${DEBUG_TAG} Payment expired`); - this.updateStatusDisplay({ - ...status, - status_message: "Payment expired - please restart the payment process", - status_alert_class: "danger", - confirmation: "The payment session has expired. Please initiate a new payment if you wish to complete your purchase." - }); - this.stopStatusChecking(); - } - - } catch (error) { - console.error(`${DEBUG_TAG} Status check failed:`, { - error: error, - message: error.message, - stack: error.stack - }); - this.updateStatusDisplay({ - status_message: "Error checking payment status: " + error.message, - status_alert_class: "danger" - }); - } - } - - updateStatusDisplay(status) { - console.debug(`${DEBUG_TAG} Updating status display with:`, status); - - if (!this.moneroPaymentContainer) { - console.debug(`${DEBUG_TAG} No payment container available for update`); - return; - } - - const confirmationsEl = this.moneroPaymentContainer.querySelector('#confirmations'); - const requiredConfirmationsEl = this.moneroPaymentContainer.querySelector('#required_confirmations'); - const statusMessageEl = this.moneroPaymentContainer.querySelector('#status_message'); - const statusIconEl = this.moneroPaymentContainer.querySelector('#status_icon'); - const statusAlertEl = this.moneroPaymentContainer.querySelector('#payment_status_message'); - const checkStatusBtn = this.moneroPaymentContainer.querySelector('#check_status_btn'); - const walletUriContainer = this.moneroPaymentContainer.querySelector('#wallet_uri_container'); - - if (confirmationsEl && status.confirmations !== undefined) { - console.debug(`${DEBUG_TAG} Updating confirmations:`, status.confirmations); - confirmationsEl.textContent = status.confirmations; - } - - if (requiredConfirmationsEl && status.required_confirmations) { - console.debug(`${DEBUG_TAG} Updating required confirmations:`, status.required_confirmations); - requiredConfirmationsEl.textContent = status.required_confirmations; - } - - if (statusMessageEl && status.status_message) { - console.debug(`${DEBUG_TAG} Updating status message:`, status.status_message); - statusMessageEl.textContent = status.status_message; - } - - if (statusIconEl && status.status_icon_class) { - console.debug(`${DEBUG_TAG} Updating status icon:`, status.status_icon_class); - statusIconEl.className = `fa ${status.status_icon_class}`; - } - - if (statusAlertEl && status.status_alert_class) { - console.debug(`${DEBUG_TAG} Updating alert class:`, status.status_alert_class); - statusAlertEl.className = `alert alert-${status.status_alert_class}`; - } - - if (checkStatusBtn && status.payment_complete) { - console.debug(`${DEBUG_TAG} Hiding check status button`); - checkStatusBtn.style.display = 'none'; - } - - if (walletUriContainer && status.payment_complete) { - console.debug(`${DEBUG_TAG} Hiding wallet URI container`); - walletUriContainer.style.display = 'none'; - } - } - - cleanupPaymentContainer() { - console.debug(`${DEBUG_TAG} Cleaning up payment container`); - this.stopStatusChecking(); - - if (this.clipboard) { - console.debug(`${DEBUG_TAG} Destroying clipboard instance`); - this.clipboard.destroy(); - this.clipboard = null; - } - - if (this.moneroPaymentContainer) { - console.debug(`${DEBUG_TAG} Removing payment container from DOM`); - this.moneroPaymentContainer.remove(); - this.moneroPaymentContainer = null; - } - - const paymentForm = document.querySelector('#o_payment_form'); - if (paymentForm) { - console.debug(`${DEBUG_TAG} Restoring payment form visibility`); - paymentForm.style.display = ''; - } - } - - updatePayButtonText(text) { - console.debug(`${DEBUG_TAG} Attempting to update button text to: '${text}'`); - - if (!this.submitButton) { - console.warn(`${DEBUG_TAG} No submitButton reference, re-querying DOM`); - this.submitButton = document.querySelector('button[name="o_payment_submit_button"]'); - - if (!this.submitButton) { - console.error(`${DEBUG_TAG} Could not find submit button in DOM!`); - return; - } - } - - console.debug(`${DEBUG_TAG} Current button text: '${this.submitButton.textContent}'`); - this.submitButton.textContent = text; - console.debug(`${DEBUG_TAG} Button text updated to: '${this.submitButton.textContent}'`); - - // Verify the change was applied - setTimeout(() => { - const currentText = document.querySelector('button[name="o_payment_submit_button"]')?.textContent; - console.debug(`${DEBUG_TAG} DOM verification - current button text: '${currentText}'`); - }, 100); - } - - disablePaymentForm() { - console.debug(`${DEBUG_TAG} Disabling payment form`); - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Disabling submit button`); - this.submitButton.disabled = true; - } - - const inputs = document.querySelectorAll('#o_payment_form input'); - console.debug(`${DEBUG_TAG} Disabling ${inputs.length} form inputs`); - inputs.forEach(el => el.disabled = true); - - console.debug(`${DEBUG_TAG} Blocking UI`); - this.ui.block(); - } - - enablePaymentForm() { - console.debug(`${DEBUG_TAG} Enabling payment form`); - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Enabling submit button`); - this.submitButton.disabled = false; - } - - const inputs = document.querySelectorAll('#o_payment_form input'); - console.debug(`${DEBUG_TAG} Enabling ${inputs.length} form inputs`); - inputs.forEach(el => el.disabled = false); - - console.debug(`${DEBUG_TAG} Unblocking UI`); - this.ui.unblock(); - } - - displayError(title, message) { - console.debug(`${DEBUG_TAG} Displaying error dialog:`, { - title: title, - message: message - }); - this.dialog.add(ConfirmationDialog, { - title: title, - body: message, - confirmLabel: _t("OK"), - }); - } - - getProviderCode(radio) { - const code = radio.dataset.providerCode; - console.debug(`${DEBUG_TAG} Getting provider code:`, code); - return code; - } - - getProviderId(radio) { - const id = parseInt(radio.dataset.providerId); - console.debug(`${DEBUG_TAG} Getting provider ID:`, id); - return id; - } -} - -export default MoneroPaymentForm; -publicWidget.registry.PaymentForm = MoneroPaymentForm; diff --git a/payment_monero_rpc/static/src/js/payment_form_monero_update2.js b/payment_monero_rpc/static/src/js/payment_form_monero_update2.js deleted file mode 100644 index 7e8e2347..00000000 --- a/payment_monero_rpc/static/src/js/payment_form_monero_update2.js +++ /dev/null @@ -1,636 +0,0 @@ -/** @odoo-module **/ - -//TODO this is the future OWL-3 incarnation still in progress - -import { _t } from "@web/core/l10n/translation"; -import { ConfirmationDialog } from "@web/core/confirmation_dialog/confirmation_dialog"; -import { loadJS } from "@web/core/assets"; -import { rpc } from "@web/core/network/rpc"; -import { useService } from "@web/core/utils/hooks"; -import { renderToString } from "@web/core/utils/render"; -import { markup } from "@odoo/owl"; - -const DEBUG_TAG = "[MoneroPayment]"; - -export const PaymentFormMonero = { - dependencies: ['ui', 'dialog'], - - setup() { - this.ui = useService('ui'); - this.dialog = useService('dialog'); - this.action = useService('action'); - this.orm = useService('orm'); - }, - - /** - * Initialize the payment form component - */ - init() { - console.debug(`${DEBUG_TAG} Initializing payment form widget`); - this.moneroPaymentContainer = null; - this.clipboard = null; - this.statusCheckInterval = null; - this.moneroSelected = false; - this.currentPaymentId = null; - this._boundOnSubmitPayment = this._onSubmitPayment.bind(this); - }, - - /** - * Load dependencies before component starts - */ - async willStart() { - console.debug(`${DEBUG_TAG} Loading dependencies`); - try { - await loadJS('/payment_monero_rpc/static/src/js/clipboard.min.js'); - } catch (e) { - console.error(`${DEBUG_TAG} Failed to load clipboard.js:`, e); - } - }, - - /** - * Start the component and set up initial state - */ - start() { - console.debug(`${DEBUG_TAG} Starting payment form widget`); - this.submitButton = document.querySelector('button[name="o_payment_submit_button"]'); - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Found submit button, attaching handler`); - this.submitButton.addEventListener('click', this._boundOnSubmitPayment); - } - this._handleInitialSelection(); - }, - - /** - * Handle the initial payment method selection - */ - _handleInitialSelection() { - const selectedRadio = this.el.querySelector('input[name="o_payment_radio"]:checked'); - if (selectedRadio) { - console.debug(`${DEBUG_TAG} Found default payment selection:`, selectedRadio.dataset.providerCode); - this._onPaymentMethodSelected({ currentTarget: selectedRadio }); - } - }, - - /** - * Handle payment method selection change - * @param {Event} ev - The change event - */ - _onPaymentMethodSelected(ev) { - const providerCode = this._getProviderCode(ev.currentTarget); - console.debug(`${DEBUG_TAG} Payment method changed to:`, providerCode); - - this.moneroSelected = (providerCode === 'monero_rpc'); - this._updatePayButtonText( - this.moneroSelected ? _t("Pay with Monero") : _t("Pay Now") - ); - }, - - /** - * Handle form submission - * @param {Event} ev - The submit event - */ - async _onSubmitPayment(ev) { - console.debug(`${DEBUG_TAG} Form submission initiated`); - ev.preventDefault(); - ev.stopPropagation(); - - if (!this.moneroSelected) { - console.debug(`${DEBUG_TAG} Non-Monero payment selected, using default flow`); - return; - } - - try { - this._disablePaymentForm(); - const checkedRadio = this.el.querySelector('input[name="o_payment_radio"]:checked'); - const paymentResponse = await this._processMoneroPayment(checkedRadio); - - if (paymentResponse.error) { - throw new Error(paymentResponse.error); - } - - if (!paymentResponse || !paymentResponse.payment_id) { - throw new Error("Invalid payment data received"); - } - - const paymentData = paymentResponse.payment || {}; - paymentData.payment_id = paymentResponse.payment_id; - - await this._displayMoneroPaymentPage(paymentData); - } catch (error) { - console.error(`${DEBUG_TAG} Payment processing failed:`, error); - this._displayError( - _t("Payment Error"), - error.message || _t("Failed to process Monero payment. Please try again.") - ); - this._enablePaymentForm(); - } - }, - - /** - * Process Monero payment request - * @param {HTMLElement} radio - The selected payment radio button - * @returns {Promise} - The payment response - */ - async _processMoneroPayment(radio) { - console.debug(`${DEBUG_TAG} Creating Monero transaction request`); - - const amountTotal = document.getElementById('amount_total_summary'); - if (!amountTotal) { - throw new Error("Missing order information"); - } - - const orderId = amountTotal.getAttribute('data-oe-id') || amountTotal.dataset.oeId; - if (!orderId) { - throw new Error("Missing order ID"); - } - - const providerId = this._getProviderId(radio); - const providerCode = this._getProviderCode(radio); - - try { - const endpoint = `/shop/payment/monero/process/${orderId}`; - console.debug(`${DEBUG_TAG} Calling endpoint: ${endpoint}`); - - const response = await rpc(endpoint, { - provider: providerId, - provider_code: providerCode, - order_sudo: parseInt(orderId), - csrf_token: odoo.csrf_token, - }, { - shadow: true, - timeout: 30000 - }); - - console.debug(`${DEBUG_TAG} Received response:`, response); - - if (!response) { - throw new Error("Empty response from server"); - } - - if (response.error) { - throw new Error(response.error); - } - - if (!response.payment_id) { - throw new Error("Invalid response format - missing payment_id"); - } - - this.currentPaymentId = response.payment_id; - return response; - } catch (error) { - console.error(`${DEBUG_TAG} RPC call failed:`, { - error: error, - message: error.message, - stack: error.stack, - data: error.data || null - }); - - throw new Error("Payment processing failed. Please try again or contact support."); - } - }, - - /** - * Display the Monero payment page - * @param {Object} payment - The payment data - */ - async _displayMoneroPaymentPage(payment) { - console.debug(`${DEBUG_TAG} Displaying Monero payment page`); - this._cleanupPaymentContainer(); - - this.moneroPaymentContainer = document.createElement('div'); - this.moneroPaymentContainer.id = 'monero_payment_container'; - this.el.parentNode.insertBefore(this.moneroPaymentContainer, this.el.nextSibling); - this.el.style.display = 'none'; - - // Render the static template (already loaded via assets) - const templateContent = document.createElement('div'); - templateContent.innerHTML = renderToString('payment_monero_rpc.monero_payment_template_page', { - payment_data: payment - }); - console.debug(`${DEBUG_TAG} Rendering payment template`); - - // Append the rendered template - this.moneroPaymentContainer.appendChild(templateContent); - - // Populate dynamic data & setup events - this._populatePaymentData(payment); - await this._setupEventListeners(); - - if (payment.state === 'pending' || payment.state === 'paid_unconfirmed') { - this._startStatusChecking(payment.payment_id); - } - this.ui.unblock(); - }, - /** - * Populate payment data in the template - * @param {Object} payment - The payment data - */ - _populatePaymentData(payment) { - const setTextContent = (id, value) => { - const el = document.getElementById(id); - if (el && value !== undefined) el.textContent = value; - }; - - const setDisplay = (id, show) => { - const el = document.getElementById(id); - if (el) el.style.display = show ? '' : 'none'; - }; - - setTextContent('payment_amount_str', payment.amount_str); - setTextContent('instructions_amount_str', payment.amount_str); - setTextContent('seller_address', payment.address_seller); - setTextContent('order_reference', payment.order_ref || 'N/A'); - setTextContent('required_confirmations', payment.required_confirmations || '10'); - setTextContent('instructions_required_confirmations', payment.required_confirmations || '10'); - setTextContent('confirmations', payment.confirmations || '0'); - - if (payment.id) { - const qrImg = document.getElementById('qr_code_img'); - if (qrImg) qrImg.src = `/shop/payment/monero/qr/${payment.id}`; - } - - if (payment.payment_id) { - setTextContent('payment_id', payment.payment_id); - setDisplay('payment_id_row', true); - } - - if (payment.original_amount_str && payment.original_currency) { - setDisplay('original_amount_container', true); - setTextContent('original_amount_str', payment.original_amount_str); - setTextContent('original_currency', payment.original_currency); - setDisplay('instructions_original_amount', true); - setTextContent('instructions_original_amount_value', payment.original_amount_str); - setTextContent('instructions_original_currency', payment.original_currency); - } - - if (payment.exchange_rate_str && payment.original_currency) { - setDisplay('exchange_rate_container', true); - setTextContent('exchange_rate_str', payment.exchange_rate_str); - setTextContent('exchange_rate_currency', payment.original_currency); - } - - if (payment.expiry_time_str) { - setTextContent('expiry_time_str', payment.expiry_time_str); - setDisplay('expiry_time_row', true); - } - - if (payment.confirmations + payment.required_confirmations < 10) { - setDisplay('confirmations_waiting', true); - setTextContent('confirmations_needed', payment.required_confirmations); - } - - const statusAlertClass = payment.status_alert_class || 'info'; - const statusAlertEl = document.getElementById('payment_status_alert'); - const statusMessageEl = document.getElementById('payment_status_message'); - const statusIconEl = document.getElementById('status_icon'); - - if (statusAlertEl) statusAlertEl.className = `alert alert-${statusAlertClass}`; - if (statusMessageEl) statusMessageEl.className = `alert alert-${statusAlertClass}`; - if (statusIconEl) statusIconEl.className = `fa ${payment.status_icon || 'fa-info-circle'}`; - setTextContent('status_message', payment.status_message || ''); - - setDisplay('status_check_container', payment.state === 'pending'); - setDisplay('payment_proof_btn', payment.state === 'confirmed'); - setDisplay('wallet_uri_container', !!payment.monero_uri); - - if (payment.monero_uri) { - const walletUriBtn = document.getElementById('wallet_uri_btn'); - if (walletUriBtn) walletUriBtn.href = payment.monero_uri; - } - - if (payment.invoice_ids && payment.invoice_ids.length > 0) { - const container = document.getElementById('invoice_download_container'); - if (container) { - container.innerHTML = ''; - - const dropdown = document.createElement('div'); - dropdown.className = 'dropdown'; - - const button = document.createElement('button'); - button.className = 'btn btn-outline-primary dropdown-toggle'; - button.type = 'button'; - button.id = 'invoiceDropdown'; - button.setAttribute('data-toggle', 'dropdown'); - button.setAttribute('aria-haspopup', 'true'); - button.setAttribute('aria-expanded', 'false'); - button.innerHTML = ' Download Invoice'; - - const menu = document.createElement('div'); - menu.className = 'dropdown-menu'; - menu.setAttribute('aria-labelledby', 'invoiceDropdown'); - - payment.invoice_ids.forEach(invoice_id => { - const link = document.createElement('a'); - link.className = 'dropdown-item'; - link.href = `/my/invoices/${invoice_id}?download=1`; - link.textContent = `Invoice ${invoice_id}`; - menu.appendChild(link); - }); - - dropdown.appendChild(button); - dropdown.appendChild(menu); - container.appendChild(dropdown); - - const disabledBtn = container.querySelector('.disabled'); - if (disabledBtn) { - disabledBtn.remove(); - } - } - } - }, - - /** - * Set up event listeners for the payment page - */ - async _setupEventListeners() { - const checkStatusBtn = this.moneroPaymentContainer.querySelector('#check_status_btn'); - if (checkStatusBtn) { - checkStatusBtn.addEventListener('click', (ev) => { - ev.preventDefault(); - console.debug(`${DEBUG_TAG} Manual status check triggered`); - this._manualCheckStatus(); - }); - } - - if (typeof ClipboardJS !== 'undefined') { - console.debug(`${DEBUG_TAG} Initializing clipboard`); - this.clipboard = new ClipboardJS('.copy-btn'); - this.clipboard.on('success', (e) => { - console.debug(`${DEBUG_TAG} Copied to clipboard:`, e.text); - const btn = e.trigger; - btn.setAttribute('title', _t("Copied!")); - const icon = btn.querySelector('i'); - if (icon) icon.className = 'fa fa-check'; - setTimeout(() => { - btn.setAttribute('title', _t("Copy to clipboard")); - if (icon) icon.className = 'fa fa-copy'; - }, 2000); - }); - } - }, - - /** - * Start periodic status checking - * @param {string} paymentId - The payment ID to check - */ - _startStatusChecking(paymentId) { - console.debug(`${DEBUG_TAG} Configuring status check interval`); - this._stopStatusChecking(); - - const checkInterval = this.moneroPaymentContainer.querySelector('.alert-warning') ? 30000 : 60000; - console.debug(`${DEBUG_TAG} Setting check interval to ${checkInterval}ms`); - this.statusCheckInterval = setInterval( - () => this._checkPaymentStatus(paymentId), - checkInterval - ); - }, - - /** - * Stop periodic status checking - */ - _stopStatusChecking() { - if (this.statusCheckInterval) { - console.debug(`${DEBUG_TAG} Stopping status checks`); - clearInterval(this.statusCheckInterval); - this.statusCheckInterval = null; - } - }, - - /** - * Manually trigger a status check - */ - _manualCheckStatus() { - const paymentId = this.currentPaymentId; - if (paymentId) { - console.debug(`${DEBUG_TAG} Manual status check for payment:`, paymentId); - this._checkPaymentStatus(paymentId); - } - }, - - /** - * Check payment status - * @param {string} paymentId - The payment ID to check - */ - async _checkPaymentStatus(paymentId) { - console.debug(`${DEBUG_TAG} Checking payment status for:`, paymentId); - try { - const status = await rpc("/shop/payment/monero/status/" + paymentId, {}, { - shadow: true, - timeout: 10000 - }); - - console.debug(`${DEBUG_TAG} Status check response:`, status); - - if (status.status === 'confirmed' || status.confirmations >= 10) { - console.debug(`${DEBUG_TAG} Payment confirmed, clearing cart and redirecting`); - this._updateStatusDisplay({ - status: 'confirmed', - status_message: "Payment confirmed! Thank you for your purchase.", - status_alert_class: "success", - status_icon: "fa-check-circle" - }); - this._stopStatusChecking(); - - try { - await rpc("/shop/cart/clear", {}, { - shadow: true, - timeout: 10000 - }); - } catch (clearError) { - console.warn(`${DEBUG_TAG} Could not clear cart:`, clearError); - } - - setTimeout(() => { - if (this.el.dataset.returnUrl) { - window.location.href = this.el.dataset.returnUrl; - } - }, 1500); - return; - } - - if (status.error) { - throw new Error(status.error); - } - - if (status.status === 'paid_unconfirmed') { - console.debug(`${DEBUG_TAG} Payment unconfirmed, updating display`); - this._updateStatusDisplay({ - ...status, - status_message: "Payment received - awaiting confirmation", - status_alert_class: "warning", - confirmation: "We've received your payment but it's awaiting network confirmation. This may take a few minutes." - }); - this._startStatusChecking(paymentId); - } else if (status.status === 'pending') { - console.debug(`${DEBUG_TAG} Payment still pending`); - this._updateStatusDisplay({ - ...status, - status_message: "Payment pending - please complete the transaction", - status_alert_class: "info", - confirmation: "Your payment is currently pending. Please complete the transaction process." - }); - } else if (status.status === 'expired') { - console.debug(`${DEBUG_TAG} Payment expired`); - this._updateStatusDisplay({ - ...status, - status_message: "Payment expired - please restart the payment process", - status_alert_class: "danger", - confirmation: "The payment session has expired. Please initiate a new payment if you wish to complete your purchase." - }); - this._stopStatusChecking(); - } - - } catch (error) { - console.error(`${DEBUG_TAG} Status check failed:`, error); - this._updateStatusDisplay({ - status_message: "Error checking payment status: " + error.message, - status_alert_class: "danger" - }); - } - }, - - /** - * Update the status display - * @param {Object} status - The status data to display - */ - _updateStatusDisplay(status) { - console.debug(`${DEBUG_TAG} Update screen data with - `, status); - - const setTextContent = (id, value) => { - const el = this.moneroPaymentContainer.querySelector(`#${id}`); - if (el && value !== undefined) el.textContent = value; - }; - - const setDisplay = (id, show) => { - const el = this.moneroPaymentContainer.querySelector(`#${id}`); - if (el) el.style.display = show ? '' : 'none'; - }; - - if (status.confirmations !== undefined) { - setTextContent('confirmations', status.confirmations); - } - - if (status.required_confirmations) { - setTextContent('required_confirmations', status.required_confirmations); - setTextContent('instructions_required_confirmations', status.required_confirmations); - } - - if (status.status_message) { - setTextContent('status_message', status.status_message); - } - - const statusIconEl = this.moneroPaymentContainer.querySelector('#status_icon'); - if (statusIconEl && status.status_icon_class) { - statusIconEl.className = `fa ${status.status_icon_class}`; - } - - const statusAlertEl = this.moneroPaymentContainer.querySelector('#payment_status_message'); - if (statusAlertEl && status.status_alert_class) { - statusAlertEl.className = `alert alert-${status.status_alert_class}`; - } - - setDisplay('status_check_container', !status.payment_complete); - setDisplay('wallet_uri_container', !status.payment_complete); - }, - - /** - * Clean up the payment container - */ - _cleanupPaymentContainer() { - console.debug(`${DEBUG_TAG} Cleaning up payment container`); - this._stopStatusChecking(); - - if (this.clipboard) { - this.clipboard.destroy(); - this.clipboard = null; - } - - if (this.moneroPaymentContainer) { - this.moneroPaymentContainer.remove(); - this.moneroPaymentContainer = null; - } - - this.el.style.display = ''; - }, - - /** - * Update the pay button text - * @param {string} text - The new button text - */ - _updatePayButtonText(text) { - if (this.submitButton) { - console.debug(`${DEBUG_TAG} Updating pay button text to:`, text); - this.submitButton.textContent = text; - } - }, - - /** - * Disable the payment form - */ - _disablePaymentForm() { - console.debug(`${DEBUG_TAG} Disabling payment form`); - if (this.submitButton) { - this.submitButton.disabled = true; - } - this.el.querySelectorAll('input').forEach(el => el.disabled = true); - this.ui.block(); - }, - - /** - * Enable the payment form - */ - _enablePaymentForm() { - console.debug(`${DEBUG_TAG} Enabling payment form`); - if (this.submitButton) { - this.submitButton.disabled = false; - } - this.el.querySelectorAll('input').forEach(el => el.disabled = false); - this.ui.unblock(); - }, - - /** - * Display an error dialog - * @param {string} title - The dialog title - * @param {string} message - The error message - */ - _displayError(title, message) { - console.debug(`${DEBUG_TAG} Displaying error dialog:`, title, message); - this.dialog.add(ConfirmationDialog, { - title: title, - body: markup(message), - confirmLabel: _t("OK"), - }); - }, - - /** - * Get the provider code from a radio button - * @param {HTMLElement} radio - The radio button element - * @returns {string} - The provider code - */ - _getProviderCode(radio) { - return radio.dataset.providerCode; - }, - - /** - * Get the provider ID from a radio button - * @param {HTMLElement} radio - The radio button element - * @returns {number} - The provider ID - */ - _getProviderId(radio) { - return parseInt(radio.dataset.providerId); - }, - - /** - * Clean up when component is destroyed - */ - destroy() { - console.debug(`${DEBUG_TAG} Destroying widget`); - if (this.submitButton) { - this.submitButton.removeEventListener('click', this._boundOnSubmitPayment); - } - this._cleanupPaymentContainer(); - } -}; - -// Patch the original PaymentForm with our Monero payment functionality -PaymentForm.include(PaymentFormMonero); diff --git a/payment_monero_rpc/static/src/js/payment_monero_checkout.js b/payment_monero_rpc/static/src/js/payment_monero_checkout.js deleted file mode 100644 index 91f00176..00000000 --- a/payment_monero_rpc/static/src/js/payment_monero_checkout.js +++ /dev/null @@ -1,18 +0,0 @@ -/** @odoo-module **/ -import { PublicWidget } from "@web/legacy/js/public/public_widget"; -import { registry } from "@web/core/registry"; - -const MODULE_TAG = "[MoneroCheckout]"; - -class MoneroCheckout extends PublicWidget { - static selector = '.checkout_screen'; // Only targets checkout screen - - start() { - console.debug(`${MODULE_TAG} Checkout screen loaded`); - // No payment method handling here - that's in PaymentForm - return super.start(); - } -} - -registry.category("public_root_widget").add("MoneroCheckout", MoneroCheckout); -export default MoneroCheckout; diff --git a/payment_monero_rpc/static/src/xml/assets.xml b/payment_monero_rpc/static/src/xml/assets.xml deleted file mode 100644 index 12c89b91..00000000 --- a/payment_monero_rpc/static/src/xml/assets.xml +++ /dev/null @@ -1,9 +0,0 @@ - - -