diff --git a/payment_wechat/README.rst b/payment_wechat/README.rst new file mode 100644 index 0000000000..01f146ce1e --- /dev/null +++ b/payment_wechat/README.rst @@ -0,0 +1,52 @@ +.. image:: https://img.shields.io/badge/license-LGPL--3-blue.png + :target: https://www.gnu.org/licenses/lgpl + :alt: License: LGPL-3 + +================= + WeChat payments +================= + +Technical module to integrate WeChat payments with odoo POS, eCommerce or backend. As in WeChat QR codes are used, addional modules are required to show QR code in POS or eCommerce. Following methods are supported: + +* TODO User scans QR and authorise payment +* TODO User opens eCommerce website via WeChat's browser, fills the cart and is redirected to WeChat App UI to authorise the payment + +Note, that this module doesn't implement *Quick Pay* method, i.e. the one where buyer shows QR code and vendor scans. + +Credits +======= + +Contributors +------------ +* `Ivan Yelizariev `__ + +Sponsors +-------- +* `IT-Projects LLC `__ + +Maintainers +----------- +* `IT-Projects LLC `__ + + To get a guaranteed support + you are kindly requested to purchase the module + at `odoo apps store `__. + + Thank you for understanding! + + `IT-Projects Team `__ + +Further information +=================== + +Demo: http://runbot.it-projects.info/demo/misc-addons/11.0 + +HTML Description: https://apps.odoo.com/apps/modules/11.0/payment_wechat/ + +Usage instructions: ``_ + +Changelog: ``_ + +Notifications on updates: `via Atom `_, `by Email `_ + +Tested on Odoo 11.0 4d0a1330e05bd688265bea14df4ad12838f9f2d7 diff --git a/payment_wechat/__init__.py b/payment_wechat/__init__.py new file mode 100644 index 0000000000..f7209b1710 --- /dev/null +++ b/payment_wechat/__init__.py @@ -0,0 +1,2 @@ +from . import models +from . import controllers diff --git a/payment_wechat/__manifest__.py b/payment_wechat/__manifest__.py new file mode 100644 index 0000000000..a6d24b56fc --- /dev/null +++ b/payment_wechat/__manifest__.py @@ -0,0 +1,37 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +{ + "name": """WeChat payments""", + "summary": """The most popular Chinese payment method""", + "category": "Accounting", + # "live_test_url": "", + "images": [], + "version": "11.0.1.0.0", + "application": False, + + "author": "IT-Projects LLC, Ivan Yelizariev", + "support": "apps@it-projects.info", + "website": "https://it-projects.info/team/yelizariev", + "license": "LGPL-3", + # "price": 9.00, + # "currency": "EUR", + + "depends": [ + ], + "external_dependencies": {"python": [], "bin": []}, + "data": [ + ], + "demo": [ + "demo/w_p_demo.xml", + ], + "qweb": [ + ], + + "post_load": None, + "pre_init_hook": None, + "post_init_hook": None, + "uninstall_hook": None, + + "auto_install": False, + "installable": True, +} diff --git a/payment_wechat/controllers/__init__.py b/payment_wechat/controllers/__init__.py new file mode 100644 index 0000000000..15a22e1505 --- /dev/null +++ b/payment_wechat/controllers/__init__.py @@ -0,0 +1 @@ +from . import p_w_controllers diff --git a/payment_wechat/controllers/p_w_controllers.py b/payment_wechat/controllers/p_w_controllers.py new file mode 100644 index 0000000000..0191296e26 --- /dev/null +++ b/payment_wechat/controllers/p_w_controllers.py @@ -0,0 +1,146 @@ +from __future__ import unicode_literals +import time +import random +import logging +import requests +import odoo +import json +from odoo.http import request + +_logger = logging.getLogger(__name__) + +try: + from odoo.addons.bus.controllers.main import BusController +except ImportError: + _logger.error('pos_multi_session_sync inconsisten with odoo version') + BusController = object + + +class Controller(BusController): + + @odoo.http.route('/wechat/getsignkey', type="json", auth="public") + def getSignKey(self, message): + data = {} + data['mch_id'] = request.env['ir.config_parameter'].get_param('wechat.mchId') + wcc = request.env['wechat.config'] + data['nonce_str'] = (wcc.getRandomNumberGeneration(message))[:32] + data['sign'] = (str(time.time()).replace('.', '') + + '{0:010}'.format(random.randint(1, 9999999999)) + + '{0:010}'.format(random.randint(1, 9999999999)))[:32] + post = wcc.makeXmlPost(data) + print(post) + url = "https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey" + r1 = requests.post(url, data=post) + print(r1) + print(r1.status_code) + print(r1.headers) + print(r1.headers['content-type']) + print(r1.iter_content) + print(len(r1.text)) + print(len(r1.content)) + # print(r1.mch_id) + # print(r1.sandbox_signkey) + message = {} + message['resp1'] = r1.text + return message + + @odoo.http.route('/wechat/test', type="json", auth="public") + def testAccessToken(self, message): + wcc = request.env['wechat.config'] + if not wcc: + wcc = wcc.create({ + 'token_validity': 7000, + 'access_token': 'test' + }) + wcc.getAccessToken() + + @odoo.http.route('/wechat/payment_commence', type="json", auth="public") + def micropay(self, message): + # data = message['data'] + # data['order_id'] = '{0:06}'.format(message['data']['order_id']) + # data['cashier_id'] = '{0:05}'.format(message['data']['cashier_id']) + # data['session_id'] = '{0:05}'.format(message['data']['session_id']) + data = {} + data['auth_code'] = message['data']['auth_code'] + data['appid'] = request.env['ir.config_parameter'].get_param('wechat.appId') + data['mch_id'] = request.env['ir.config_parameter'].get_param('wechat.mchId') + data['body'] = message['data']['order_short'] + + data['out_trade_no'] = (str(time.time()).replace('.', '') \ + + '{0:010}'.format(random.randint(1, 9999999999)) \ + + '{0:010}'.format(random.randint(1, 9999999999)))[:32] + wcc = request.env['wechat.config'] + if not wcc: + wcc = wcc.create({ + 'token_validity': 1, + 'access_token': '' + }) + data['total_fee'] = message['data']['total_fee'] + data['spbill_create_ip'] = wcc.getIpList()[0] + print(wcc.getIpList()) + # data['auth_code'] = message['data']['auth_code'] + # + # device_info = + # sign_type = + # detail = + # attach = + # fee_type = + # goods_tag = + # limit_pay = + # scene_info = + # + data['nonce_str'] = (wcc.getRandomNumberGeneration(message))[:32] + data['sign'] = (wcc.getRandomNumberGeneration(message))[:32] + + post = wcc.makeXmlPost(data) + print(post) + r1 = requests.post("https://api.mch.weixin.qq.com/sandboxnew/pay/micropay", data=post) + print(r1) + print(r1.status_code) + print(r1.headers) + print(r1.headers['content-type']) + print(r1.encoding) + print(len(r1.text)) + print(len(r1.content)) + message = {} + message['resp1'] = r1 + message['resp_text1'] = r1.text + message['resp_cont1'] = r1.content + # message['encode_text1'] = r1.text.encode('iso-8859-1').decode('utf-8') + # print(r1.text.encode('utf-8')) + time.sleep(5) + # return request.redirect('/wechat/payment_query') + # + # @odoo.http.route('/wechat/payment_query', type="json", auth="public") + # def queryOrderApi(self, message): + data_qa = {} + data_qa['appid'] = data['appid'] + data_qa['mch_id'] = data['mch_id'] + data_qa['out_trade_no'] = data['out_trade_no'] + data_qa['nonce_str'] = data['nonce_str'] + data_qa['sign'] = data['sign'] + if hasattr(data, 'sign_type'): + data_qa['sign_type'] = data['sign_type'] + + post = wcc.makeXmlPost(data_qa) + print(post) + r2 = requests.post("https://api.mch.weixin.qq.com/sandboxnew/pay/orderquery", data=post) + print(r2) + print(r2.status_code) + print(r2.headers) + print(r2.headers['content-type']) + print(r2.encoding) + print(len(r2.text)) + print(len(r2.content)) + message['resp2'] = r2 + message['resp_text2'] = r2.text + message['resp_cont2'] = r2.content + # message['encode_text2'] = r2.text.encode('iso-8859-1').decode('utf-8') + # with open('txt.txt', 'w+') as fil: + # fil.write(r1.text, r2.text) + # print(r2.text.encode('utf-8')) + # for each_unicode_character in r2.text.encode('utf-8').decode('utf-8'): + # print(each_unicode_character) + # print(message['encode_text1']) + # print(message['encode_text2']) + return message diff --git a/payment_wechat/demo/w_p_demo.xml b/payment_wechat/demo/w_p_demo.xml new file mode 100644 index 0000000000..af509e251f --- /dev/null +++ b/payment_wechat/demo/w_p_demo.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/payment_wechat/doc/changelog.rst b/payment_wechat/doc/changelog.rst new file mode 100644 index 0000000000..9ee2b48b8e --- /dev/null +++ b/payment_wechat/doc/changelog.rst @@ -0,0 +1,4 @@ +`1.0.0` +------- + +- Init version diff --git a/payment_wechat/doc/index.rst b/payment_wechat/doc/index.rst new file mode 100644 index 0000000000..85a4a4a079 --- /dev/null +++ b/payment_wechat/doc/index.rst @@ -0,0 +1,12 @@ +================= + WeChat payments +================= + +Follow instructions of `WeChat API `__. + +Usage +===== + +Following instruction covers backend usage only. For POS and eCommerce use instructions of corresponding modules. + +* open menu TODO diff --git a/payment_wechat/models/__init__.py b/payment_wechat/models/__init__.py new file mode 100644 index 0000000000..f84001a85e --- /dev/null +++ b/payment_wechat/models/__init__.py @@ -0,0 +1 @@ +from . import wechat_models diff --git a/payment_wechat/models/wechat_models.py b/payment_wechat/models/wechat_models.py new file mode 100644 index 0000000000..754fb11a8e --- /dev/null +++ b/payment_wechat/models/wechat_models.py @@ -0,0 +1,73 @@ +from __future__ import absolute_import, unicode_literals +from odoo import fields, models, api +from odoo.http import request +import json +import hashlib +import time +import requests + + +class AccountJournal(models.Model): + _inherit = "account.journal" + + wechat_payment = fields.Boolean(string='Allow WeChat payments', default=False, + help="Check this box if this account allows pay via WeChat") + + +# class PosOrder(models.Model): +# _inherit = "pos.order" +# +# auth_code = fields.Integer(string='Code obtained from customers QR or BarCode', default=0) + + +class WechatConfiguration(models.Model): + _name = "wechat.config" + + # auth_code = fields.Integer(string='Code obtained from customers QR or BarCode', default=0) + access_token = fields.Char(string='access_token') + token_validity = fields.Float(string='validity time') + + @api.multi + def getAccessToken(self): + print('inside getAccessToken!!!!!!!!!!!', self.token_validity < time.time()) + if not self.token_validity: + self.createVals() + if self.token_validity < time.time(): + appId = request.env['ir.config_parameter'].get_param('wechat.appId') + appSecret = request.env['ir.config_parameter'].get_param('wechat.appSecret') + url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % ( + appId, appSecret) + response = requests.get(url) + access_token = json.loads(response.text)['access_token'] + self.write({'token_validity': time.time() + 7000, 'access_token': access_token}) + else: + access_token = self.access_token + return access_token + + def getIpList(self): + token = self.getAccessToken() + url = "https://api.wechat.com/cgi-bin/getcallbackip?access_token=%s" % token + response = requests.get(url) + return json.loads(response.text)['ip_list'] + + def sortData(self, message): + arrA = [] + data = message['data'] + for key in data: + if data[key]: + arrA.append(str(key) + '=' + str(data[key])) + arrA.sort() + return arrA + + def getRandomNumberGeneration(self, message): + data = self.sortData(message) + strA = ' & '.join(data) + return hashlib.sha256(strA.encode('utf-8')).hexdigest().upper() + + def makeXmlPost(self, data): + xml_str = [''] + for key in sorted(data): + if data[key]: + xml_str.append('<' + str(key) + '>' + str(data[key]) + '') + xml_str.append('') + return '\n'.join(xml_str) diff --git a/payment_wechat/static/description/icon.png b/payment_wechat/static/description/icon.png new file mode 100644 index 0000000000..b43a0a135f Binary files /dev/null and b/payment_wechat/static/description/icon.png differ diff --git a/payment_wechat/views/views.xml b/payment_wechat/views/views.xml new file mode 100644 index 0000000000..ae8a1f6e24 --- /dev/null +++ b/payment_wechat/views/views.xml @@ -0,0 +1,15 @@ + + + + account.journal.form + account.journal + + + + + + + + + + diff --git a/pos_payment/README.rst b/pos_payment/README.rst new file mode 100644 index 0000000000..21347261bc --- /dev/null +++ b/pos_payment/README.rst @@ -0,0 +1,47 @@ +.. image:: https://img.shields.io/badge/license-LGPL--3-blue.png + :target: https://www.gnu.org/licenses/lgpl + :alt: License: LGPL-3 + +========================== + Payment Acquirers in POS +========================== + +Accept online payments in POS. It works only with invoices created from POS Order. + +Credits +======= + +Contributors +------------ +* `Ivan Yelizariev `__ + +Sponsors +-------- +* `IT-Projects LLC `__ + +Maintainers +----------- +* `IT-Projects LLC `__ + + To get a guaranteed support + you are kindly requested to purchase the module + at `odoo apps store `__. + + Thank you for understanding! + + `IT-Projects Team `__ + +Further information +=================== + +Demo: http://runbot.it-projects.info/demo/pos-addons/11.0 + +HTML Description: https://apps.odoo.com/apps/modules/11.0/payment_wechat/ + +Usage instructions: ``_ + +Changelog: ``_ + +Notifications on updates: `via Atom `_, `by Email `_ + +Tested on Odoo 11.0 4d0a1330e05bd688265bea14df4ad12838f9f2d7 diff --git a/pos_payment/__init__.py b/pos_payment/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pos_payment/__manifest__.py b/pos_payment/__manifest__.py new file mode 100644 index 0000000000..65078dcd53 --- /dev/null +++ b/pos_payment/__manifest__.py @@ -0,0 +1,42 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +{ + "name": """Payment Acquirers in POS""", + "summary": """Accept online payments in POS""", + "category": "Point of Sale", + # "live_test_url": "", + "images": [], + "version": "11.0.1.0.0", + "application": False, + + "author": "IT-Projects LLC, Ivan Yelizariev", + "support": "apps@it-projects.info", + "website": "https://it-projects.info/team/yelizariev", + "license": "LGPL-3", + # "price": 9.00, + # "currency": "EUR", + + "depends": [ + "{DEPENDENCY1}", + "{DEPENDENCY2}", + ], + "external_dependencies": {"python": [], "bin": []}, + "data": [ + "{FILE1}.xml", + "{FILE2}.xml", + ], + "demo": [ + "demo/{DEMOFILE1}.xml", + ], + "qweb": [ + "static/src/xml/{QWEBFILE1}.xml", + ], + + "post_load": None, + "pre_init_hook": None, + "post_init_hook": None, + "uninstall_hook": None, + + "auto_install": False, + "installable": True, +} diff --git a/pos_payment/doc/changelog.rst b/pos_payment/doc/changelog.rst new file mode 100644 index 0000000000..9ee2b48b8e --- /dev/null +++ b/pos_payment/doc/changelog.rst @@ -0,0 +1,4 @@ +`1.0.0` +------- + +- Init version diff --git a/pos_payment/doc/index.rst b/pos_payment/doc/index.rst new file mode 100644 index 0000000000..e444a16d12 --- /dev/null +++ b/pos_payment/doc/index.rst @@ -0,0 +1,30 @@ +========================== + Payment Acquirers in POS +========================== + +Installation +============ +* `Install `__ this module in a usual way +* `Activate longpolling `__ + +Configuration +============= + +TODO + +{Instruction how to configure the module before start to use it} + +* `Activate Developer Mode `__ +* Open menu ``[[ {Menu} ]] >> {Submenu} >> {Subsubmenu}`` +* Click ``[{Button Name}]`` + +Usage +===== + +TODO + +{Instruction for daily usage. It should describe how to check that module works. What shall user do and what would user get.} + +* Open menu ``[[ {Menu} ]]>> {Submenu} >> {Subsubmenu}`` +* Click ``[{Button Name}]`` +* RESULT: {what user gets, how the modules changes default behaviour} diff --git a/pos_payment/static/description/icon.png b/pos_payment/static/description/icon.png new file mode 100644 index 0000000000..8a058284ed Binary files /dev/null and b/pos_payment/static/description/icon.png differ diff --git a/pos_qr_scan/README.rst b/pos_qr_scan/README.rst new file mode 100644 index 0000000000..273259eb08 --- /dev/null +++ b/pos_qr_scan/README.rst @@ -0,0 +1,44 @@ +================== + POS QR Code Scan +================== + +Scans QR codes via device's camera. + +Usage +===== + +To subscribe to scanning event use following code in js:: + + var core = require('web.core'); + core.bus.on('qr_scanned', this, function(value){ + // your handler here + }) + + +Credits +======= + +Contributors +------------ +* `Kolushov Alexandr `__ + +Sponsors +-------- +* `IT-Projects LLC `__ + +Maintainers +----------- +* `IT-Projects LLC `__ + +Further information +=================== + +Demo: http://runbot.it-projects.info/demo/pos-addons/11.0 + +HTML Description: https://apps.odoo.com/apps/modules/11.0/pos_qr_scan/ + +Usage instructions: ``_ + +Changelog: ``_ + +Tested on Odoo 11.0 c7171795f891335e8a8b6d5a6b796c28cea77fea diff --git a/pos_qr_scan/__init__.py b/pos_qr_scan/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pos_qr_scan/__manifest__.py b/pos_qr_scan/__manifest__.py new file mode 100644 index 0000000000..6f15239031 --- /dev/null +++ b/pos_qr_scan/__manifest__.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +{ + "name": """POS QR Code Scan""", + "summary": """Scans QR codes in POS""", + "category": "Point of Sale", + # "live_test_url": "", + "images": [], + "version": "11.0.1.0.0", + "application": False, + + "author": "IT-Projects LLC, KolushovAlexandr", + "support": "apps@it-projects.info", + "website": "https://it-projects.info/team/KolushovAlexandr", + "license": "LGPL-3", + # "price": 9.00, + # "currency": "EUR", + + "depends": [ + "point_of_sale", + ], + "external_dependencies": {"python": [], "bin": []}, + "data": [ + "views/assets.xml", + ], + "qweb": [ + "static/src/xml/templates.xml", + ], + + "auto_install": False, + "installable": True, +} diff --git a/pos_qr_scan/doc/changelog.rst b/pos_qr_scan/doc/changelog.rst new file mode 100644 index 0000000000..9ee2b48b8e --- /dev/null +++ b/pos_qr_scan/doc/changelog.rst @@ -0,0 +1,4 @@ +`1.0.0` +------- + +- Init version diff --git a/pos_qr_scan/doc/index.rst b/pos_qr_scan/doc/index.rst new file mode 100644 index 0000000000..1c047d68c3 --- /dev/null +++ b/pos_qr_scan/doc/index.rst @@ -0,0 +1,45 @@ +================== + POS QR Code Scan +================== + +Installation +============ + +* `Install `__ this module in a usual way + +Configuration +============= + +Browser can get access to camera only on using via ``https`` connection. + +Possible NGINX configurations to support ``https``:: + + server { + listen 443 ssl; + server_name posadd.odoo11.local; + ssl_certificate /etc/nginx/ssl/nginx.crt; + ssl_certificate_key /etc/nginx/ssl/nginx.key; + ssl_protocols TLSv1 TLSv1.1 TLSv1.2; + + if ( $scheme = "http" ) + { + rewrite ^/(.*)$ https://$host/$1 permanent; + } + + proxy_buffers 16 64k; + proxy_buffer_size 128k; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 600s; + client_max_body_size 100m; + + location /longpolling { + proxy_pass http://127.0.0.1:8072; + } + + location / { + proxy_pass http://127.0.0.1:8069; + } + } diff --git a/pos_qr_scan/static/lib/jsqrcode/COPYING b/pos_qr_scan/static/lib/jsqrcode/COPYING new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/COPYING @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/pos_qr_scan/static/lib/jsqrcode/README b/pos_qr_scan/static/lib/jsqrcode/README new file mode 100644 index 0000000000..bf5dd799a1 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/README @@ -0,0 +1,36 @@ +JavaScript QRCode reader for HTML5 enabled browser. +2011 Lazar Laszlo http://lazarsoft.info + +Try it online: http://webqr.com + +This is a port of ZXing qrcode scanner, http://code.google.com/p/zxing. + +Usage: + +Include the scripts in the following order: + + + + + + + + + + + + + + + + + + + +Set qrcode.callback to function "func(data)", where data will get the decoded information. + +Decode image with: qrcode.decode(url or DataURL). +Decode from canvas with "qr-canvas" ID: qrcode.decode() + +[new from 2014.01.09] +For webcam qrcode decoding (included in the test.html) you will need a browser with getUserMedia (WebRTC) capability. diff --git a/pos_qr_scan/static/lib/jsqrcode/alignpat.js b/pos_qr_scan/static/lib/jsqrcode/alignpat.js new file mode 100644 index 0000000000..967473f391 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/alignpat.js @@ -0,0 +1,279 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function AlignmentPattern(posX, posY, estimatedModuleSize) +{ + this.x=posX; + this.y=posY; + this.count = 1; + this.estimatedModuleSize = estimatedModuleSize; + + this.__defineGetter__("EstimatedModuleSize", function() + { + return this.estimatedModuleSize; + }); + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("X", function() + { + return Math.floor(this.x); + }); + this.__defineGetter__("Y", function() + { + return Math.floor(this.y); + }); + this.incrementCount = function() + { + this.count++; + } + this.aboutEquals=function( moduleSize, i, j) + { + if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) + { + var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); + return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; + } + return false; + } + +} + +function AlignmentPatternFinder( image, startX, startY, width, height, moduleSize, resultPointCallback) +{ + this.image = image; + this.possibleCenters = new Array(); + this.startX = startX; + this.startY = startY; + this.width = width; + this.height = height; + this.moduleSize = moduleSize; + this.crossCheckStateCount = new Array(0,0,0); + this.resultPointCallback = resultPointCallback; + + this.centerFromEnd=function(stateCount, end) + { + return (end - stateCount[2]) - stateCount[1] / 2.0; + } + this.foundPatternCross = function(stateCount) + { + var moduleSize = this.moduleSize; + var maxVariance = moduleSize / 2.0; + for (var i = 0; i < 3; i++) + { + if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) + { + return false; + } + } + return true; + } + + this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxI = qrcode.height; + var stateCount = this.crossCheckStateCount; + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + + // Start counting up from center + var i = startI; + while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i--; + } + // If already too many modules in this state or ran off the edge: + if (i < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (i >= 0 && !image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + i--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + // Now also count down from center + i = startI + 1; + while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i++; + } + if (i == maxI || stateCount[1] > maxCount) + { + return NaN; + } + while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[2] <= maxCount) + { + stateCount[2]++; + i++; + } + if (stateCount[2] > maxCount) + { + return NaN; + } + + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; + } + + this.handlePossibleCenter=function( stateCount, i, j) + { + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2]; + var centerJ = this.centerFromEnd(stateCount, j); + var centerI = this.crossCheckVertical(i, Math.floor (centerJ), 2 * stateCount[1], stateCountTotal); + if (!isNaN(centerI)) + { + var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0; + var max = this.possibleCenters.length; + for (var index = 0; index < max; index++) + { + var center = this.possibleCenters[index]; + // Look for about the same center and module size: + if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) + { + return new AlignmentPattern(centerJ, centerI, estimatedModuleSize); + } + } + // Hadn't found this before; save it + var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize); + this.possibleCenters.push(point); + if (this.resultPointCallback != null) + { + this.resultPointCallback.foundPossibleResultPoint(point); + } + } + return null; + } + + this.find = function() + { + var startX = this.startX; + var height = this.height; + var maxJ = startX + width; + var middleI = startY + (height >> 1); + // We are looking for black/white/black modules in 1:1:1 ratio; + // this tracks the number of black/white/black modules seen so far + var stateCount = new Array(0,0,0); + for (var iGen = 0; iGen < height; iGen++) + { + // Search from middle outwards + var i = middleI + ((iGen & 0x01) == 0?((iGen + 1) >> 1):- ((iGen + 1) >> 1)); + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + var j = startX; + // Burn off leading white pixels before anything else; if we start in the middle of + // a white run, it doesn't make sense to count its length, since we don't know if the + // white run continued to the left of the start point + while (j < maxJ && !image[j + qrcode.width* i]) + { + j++; + } + var currentState = 0; + while (j < maxJ) + { + if (image[j + i*qrcode.width]) + { + // Black pixel + if (currentState == 1) + { + // Counting black pixels + stateCount[currentState]++; + } + else + { + // Counting white pixels + if (currentState == 2) + { + // A winner? + if (this.foundPatternCross(stateCount)) + { + // Yes + var confirmed = this.handlePossibleCenter(stateCount, i, j); + if (confirmed != null) + { + return confirmed; + } + } + stateCount[0] = stateCount[2]; + stateCount[1] = 1; + stateCount[2] = 0; + currentState = 1; + } + else + { + stateCount[++currentState]++; + } + } + } + else + { + // White pixel + if (currentState == 1) + { + // Counting black pixels + currentState++; + } + stateCount[currentState]++; + } + j++; + } + if (this.foundPatternCross(stateCount)) + { + var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); + if (confirmed != null) + { + return confirmed; + } + } + } + + // Hmm, nothing we saw was observed and confirmed twice. If we had + // any guess at all, return it. + if (!(this.possibleCenters.length == 0)) + { + return this.possibleCenters[0]; + } + + throw "Couldn't find enough alignment patterns"; + } + +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/bitmat.js b/pos_qr_scan/static/lib/jsqrcode/bitmat.js new file mode 100644 index 0000000000..5b00784296 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/bitmat.js @@ -0,0 +1,111 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function BitMatrix( width, height) +{ + if(!height) + height=width; + if (width < 1 || height < 1) + { + throw "Both dimensions must be greater than 0"; + } + this.width = width; + this.height = height; + var rowSize = width >> 5; + if ((width & 0x1f) != 0) + { + rowSize++; + } + this.rowSize = rowSize; + this.bits = new Array(rowSize * height); + for(var i=0;i> 5); + return ((URShift(this.bits[offset], (x & 0x1f))) & 1) != 0; + } + this.set_Renamed=function( x, y) + { + var offset = y * this.rowSize + (x >> 5); + this.bits[offset] |= 1 << (x & 0x1f); + } + this.flip=function( x, y) + { + var offset = y * this.rowSize + (x >> 5); + this.bits[offset] ^= 1 << (x & 0x1f); + } + this.clear=function() + { + var max = this.bits.length; + for (var i = 0; i < max; i++) + { + this.bits[i] = 0; + } + } + this.setRegion=function( left, top, width, height) + { + if (top < 0 || left < 0) + { + throw "Left and top must be nonnegative"; + } + if (height < 1 || width < 1) + { + throw "Height and width must be at least 1"; + } + var right = left + width; + var bottom = top + height; + if (bottom > this.height || right > this.width) + { + throw "The region must fit inside the matrix"; + } + for (var y = top; y < bottom; y++) + { + var offset = y * this.rowSize; + for (var x = left; x < right; x++) + { + this.bits[offset + (x >> 5)] |= 1 << (x & 0x1f); + } + } + } +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/bmparser.js b/pos_qr_scan/static/lib/jsqrcode/bmparser.js new file mode 100644 index 0000000000..51c6e85ddc --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/bmparser.js @@ -0,0 +1,203 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function BitMatrixParser(bitMatrix) +{ + var dimension = bitMatrix.Dimension; + if (dimension < 21 || (dimension & 0x03) != 1) + { + throw "Error BitMatrixParser"; + } + this.bitMatrix = bitMatrix; + this.parsedVersion = null; + this.parsedFormatInfo = null; + + this.copyBit=function( i, j, versionBits) + { + return this.bitMatrix.get_Renamed(i, j)?(versionBits << 1) | 0x1:versionBits << 1; + } + + this.readFormatInformation=function() + { + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + + // Read top-left format info bits + var formatInfoBits = 0; + for (var i = 0; i < 6; i++) + { + formatInfoBits = this.copyBit(i, 8, formatInfoBits); + } + // .. and skip a bit in the timing pattern ... + formatInfoBits = this.copyBit(7, 8, formatInfoBits); + formatInfoBits = this.copyBit(8, 8, formatInfoBits); + formatInfoBits = this.copyBit(8, 7, formatInfoBits); + // .. and skip a bit in the timing pattern ... + for (var j = 5; j >= 0; j--) + { + formatInfoBits = this.copyBit(8, j, formatInfoBits); + } + + this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + + // Hmm, failed. Try the top-right/bottom-left pattern + var dimension = this.bitMatrix.Dimension; + formatInfoBits = 0; + var iMin = dimension - 8; + for (var i = dimension - 1; i >= iMin; i--) + { + formatInfoBits = this.copyBit(i, 8, formatInfoBits); + } + for (var j = dimension - 7; j < dimension; j++) + { + formatInfoBits = this.copyBit(8, j, formatInfoBits); + } + + this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); + if (this.parsedFormatInfo != null) + { + return this.parsedFormatInfo; + } + throw "Error readFormatInformation"; + } + this.readVersion=function() + { + + if (this.parsedVersion != null) + { + return this.parsedVersion; + } + + var dimension = this.bitMatrix.Dimension; + + var provisionalVersion = (dimension - 17) >> 2; + if (provisionalVersion <= 6) + { + return Version.getVersionForNumber(provisionalVersion); + } + + // Read top-right version info: 3 wide by 6 tall + var versionBits = 0; + var ijMin = dimension - 11; + for (var j = 5; j >= 0; j--) + { + for (var i = dimension - 9; i >= ijMin; i--) + { + versionBits = this.copyBit(i, j, versionBits); + } + } + + this.parsedVersion = Version.decodeVersionInformation(versionBits); + if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) + { + return this.parsedVersion; + } + + // Hmm, failed. Try bottom left: 6 wide by 3 tall + versionBits = 0; + for (var i = 5; i >= 0; i--) + { + for (var j = dimension - 9; j >= ijMin; j--) + { + versionBits = this.copyBit(i, j, versionBits); + } + } + + this.parsedVersion = Version.decodeVersionInformation(versionBits); + if (this.parsedVersion != null && this.parsedVersion.DimensionForVersion == dimension) + { + return this.parsedVersion; + } + throw "Error readVersion"; + } + this.readCodewords=function() + { + + var formatInfo = this.readFormatInformation(); + var version = this.readVersion(); + + // Get the data mask for the format used in this QR Code. This will exclude + // some bits from reading as we wind through the bit matrix. + var dataMask = DataMask.forReference( formatInfo.DataMask); + var dimension = this.bitMatrix.Dimension; + dataMask.unmaskBitMatrix(this.bitMatrix, dimension); + + var functionPattern = version.buildFunctionPattern(); + + var readingUp = true; + var result = new Array(version.TotalCodewords); + var resultOffset = 0; + var currentByte = 0; + var bitsRead = 0; + // Read columns in pairs, from right to left + for (var j = dimension - 1; j > 0; j -= 2) + { + if (j == 6) + { + // Skip whole column with vertical alignment pattern; + // saves time and makes the other code proceed more cleanly + j--; + } + // Read alternatingly from bottom to top then top to bottom + for (var count = 0; count < dimension; count++) + { + var i = readingUp?dimension - 1 - count:count; + for (var col = 0; col < 2; col++) + { + // Ignore bits covered by the function pattern + if (!functionPattern.get_Renamed(j - col, i)) + { + // Read a bit + bitsRead++; + currentByte <<= 1; + if (this.bitMatrix.get_Renamed(j - col, i)) + { + currentByte |= 1; + } + // If we've made a whole byte, save it off + if (bitsRead == 8) + { + result[resultOffset++] = currentByte; + bitsRead = 0; + currentByte = 0; + } + } + } + } + readingUp ^= true; // readingUp = !readingUp; // switch directions + } + if (resultOffset != version.TotalCodewords) + { + throw "Error readCodewords"; + } + return result; + } +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/datablock.js b/pos_qr_scan/static/lib/jsqrcode/datablock.js new file mode 100644 index 0000000000..3cb277a892 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/datablock.js @@ -0,0 +1,117 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function DataBlock(numDataCodewords, codewords) +{ + this.numDataCodewords = numDataCodewords; + this.codewords = codewords; + + this.__defineGetter__("NumDataCodewords", function() + { + return this.numDataCodewords; + }); + this.__defineGetter__("Codewords", function() + { + return this.codewords; + }); +} + +DataBlock.getDataBlocks=function(rawCodewords, version, ecLevel) +{ + + if (rawCodewords.length != version.TotalCodewords) + { + throw "ArgumentException"; + } + + // Figure out the number and size of data blocks used by this version and + // error correction level + var ecBlocks = version.getECBlocksForLevel(ecLevel); + + // First count the total number of data blocks + var totalBlocks = 0; + var ecBlockArray = ecBlocks.getECBlocks(); + for (var i = 0; i < ecBlockArray.length; i++) + { + totalBlocks += ecBlockArray[i].Count; + } + + // Now establish DataBlocks of the appropriate size and number of data codewords + var result = new Array(totalBlocks); + var numResultBlocks = 0; + for (var j = 0; j < ecBlockArray.length; j++) + { + var ecBlock = ecBlockArray[j]; + for (var i = 0; i < ecBlock.Count; i++) + { + var numDataCodewords = ecBlock.DataCodewords; + var numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords; + result[numResultBlocks++] = new DataBlock(numDataCodewords, new Array(numBlockCodewords)); + } + } + + // All blocks have the same amount of data, except that the last n + // (where n may be 0) have 1 more byte. Figure out where these start. + var shorterBlocksTotalCodewords = result[0].codewords.length; + var longerBlocksStartAt = result.length - 1; + while (longerBlocksStartAt >= 0) + { + var numCodewords = result[longerBlocksStartAt].codewords.length; + if (numCodewords == shorterBlocksTotalCodewords) + { + break; + } + longerBlocksStartAt--; + } + longerBlocksStartAt++; + + var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock; + // The last elements of result may be 1 element longer; + // first fill out as many elements as all of them have + var rawCodewordsOffset = 0; + for (var i = 0; i < shorterBlocksNumDataCodewords; i++) + { + for (var j = 0; j < numResultBlocks; j++) + { + result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; + } + } + // Fill out the last data block in the longer ones + for (var j = longerBlocksStartAt; j < numResultBlocks; j++) + { + result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; + } + // Now add in error correction blocks + var max = result[0].codewords.length; + for (var i = shorterBlocksNumDataCodewords; i < max; i++) + { + for (var j = 0; j < numResultBlocks; j++) + { + var iOffset = j < longerBlocksStartAt?i:i + 1; + result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; + } + } + return result; +} diff --git a/pos_qr_scan/static/lib/jsqrcode/databr.js b/pos_qr_scan/static/lib/jsqrcode/databr.js new file mode 100644 index 0000000000..f40257f2e4 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/databr.js @@ -0,0 +1,336 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function QRCodeDataBlockReader(blocks, version, numErrorCorrectionCode) +{ + this.blockPointer = 0; + this.bitPointer = 7; + this.dataLength = 0; + this.blocks = blocks; + this.numErrorCorrectionCode = numErrorCorrectionCode; + if (version <= 9) + this.dataLengthMode = 0; + else if (version >= 10 && version <= 26) + this.dataLengthMode = 1; + else if (version >= 27 && version <= 40) + this.dataLengthMode = 2; + + this.getNextBits = function( numBits) + { + var bits = 0; + if (numBits < this.bitPointer + 1) + { + // next word fits into current data block + var mask = 0; + for (var i = 0; i < numBits; i++) + { + mask += (1 << i); + } + mask <<= (this.bitPointer - numBits + 1); + + bits = (this.blocks[this.blockPointer] & mask) >> (this.bitPointer - numBits + 1); + this.bitPointer -= numBits; + return bits; + } + else if (numBits < this.bitPointer + 1 + 8) + { + // next word crosses 2 data blocks + var mask1 = 0; + for (var i = 0; i < this.bitPointer + 1; i++) + { + mask1 += (1 << i); + } + bits = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); + this.blockPointer++; + bits += ((this.blocks[this.blockPointer]) >> (8 - (numBits - (this.bitPointer + 1)))); + + this.bitPointer = this.bitPointer - numBits % 8; + if (this.bitPointer < 0) + { + this.bitPointer = 8 + this.bitPointer; + } + return bits; + } + else if (numBits < this.bitPointer + 1 + 16) + { + // next word crosses 3 data blocks + var mask1 = 0; // mask of first block + var mask3 = 0; // mask of 3rd block + //bitPointer + 1 : number of bits of the 1st block + //8 : number of the 2nd block (note that use already 8bits because next word uses 3 data blocks) + //numBits - (bitPointer + 1 + 8) : number of bits of the 3rd block + for (var i = 0; i < this.bitPointer + 1; i++) + { + mask1 += (1 << i); + } + var bitsFirstBlock = (this.blocks[this.blockPointer] & mask1) << (numBits - (this.bitPointer + 1)); + this.blockPointer++; + + var bitsSecondBlock = this.blocks[this.blockPointer] << (numBits - (this.bitPointer + 1 + 8)); + this.blockPointer++; + + for (var i = 0; i < numBits - (this.bitPointer + 1 + 8); i++) + { + mask3 += (1 << i); + } + mask3 <<= 8 - (numBits - (this.bitPointer + 1 + 8)); + var bitsThirdBlock = (this.blocks[this.blockPointer] & mask3) >> (8 - (numBits - (this.bitPointer + 1 + 8))); + + bits = bitsFirstBlock + bitsSecondBlock + bitsThirdBlock; + this.bitPointer = this.bitPointer - (numBits - 8) % 8; + if (this.bitPointer < 0) + { + this.bitPointer = 8 + this.bitPointer; + } + return bits; + } + else + { + return 0; + } + } + this.NextMode=function() + { + if ((this.blockPointer > this.blocks.length - this.numErrorCorrectionCode - 2)) + return 0; + else + return this.getNextBits(4); + } + this.getDataLength=function( modeIndicator) + { + var index = 0; + while (true) + { + if ((modeIndicator >> index) == 1) + break; + index++; + } + + return this.getNextBits(qrcode.sizeOfDataLengthInfo[this.dataLengthMode][index]); + } + this.getRomanAndFigureString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var strData = ""; + var tableRomanAndFigure = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':'); + do + { + if (length > 1) + { + intData = this.getNextBits(11); + var firstLetter = Math.floor(intData / 45); + var secondLetter = intData % 45; + strData += tableRomanAndFigure[firstLetter]; + strData += tableRomanAndFigure[secondLetter]; + length -= 2; + } + else if (length == 1) + { + intData = this.getNextBits(6); + strData += tableRomanAndFigure[intData]; + length -= 1; + } + } + while (length > 0); + + return strData; + } + this.getFigureString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var strData = ""; + do + { + if (length >= 3) + { + intData = this.getNextBits(10); + if (intData < 100) + strData += "0"; + if (intData < 10) + strData += "0"; + length -= 3; + } + else if (length == 2) + { + intData = this.getNextBits(7); + if (intData < 10) + strData += "0"; + length -= 2; + } + else if (length == 1) + { + intData = this.getNextBits(4); + length -= 1; + } + strData += intData; + } + while (length > 0); + + return strData; + } + this.get8bitByteArray=function( dataLength) + { + var length = dataLength; + var intData = 0; + var output = new Array(); + + do + { + intData = this.getNextBits(8); + output.push( intData); + length--; + } + while (length > 0); + return output; + } + this.getKanjiString=function( dataLength) + { + var length = dataLength; + var intData = 0; + var unicodeString = ""; + do + { + intData = this.getNextBits(13); + var lowerByte = intData % 0xC0; + var higherByte = intData / 0xC0; + + var tempWord = (higherByte << 8) + lowerByte; + var shiftjisWord = 0; + if (tempWord + 0x8140 <= 0x9FFC) + { + // between 8140 - 9FFC on Shift_JIS character set + shiftjisWord = tempWord + 0x8140; + } + else + { + // between E040 - EBBF on Shift_JIS character set + shiftjisWord = tempWord + 0xC140; + } + + //var tempByte = new Array(0,0); + //tempByte[0] = (sbyte) (shiftjisWord >> 8); + //tempByte[1] = (sbyte) (shiftjisWord & 0xFF); + //unicodeString += new String(SystemUtils.ToCharArray(SystemUtils.ToByteArray(tempByte))); + unicodeString += String.fromCharCode(shiftjisWord); + length--; + } + while (length > 0); + + + return unicodeString; + } + + this.parseECIValue = function () + { + var intData = 0; + var firstByte = this.getNextBits(8); + if ((firstByte & 0x80) == 0) { + intData = firstByte & 0x7F; + } + if ((firstByte & 0xC0) == 0x80) { + // two bytes + var secondByte = this.getNextBits(8); + intData = ((firstByte & 0x3F) << 8) | secondByte; + } + if ((firstByte & 0xE0) == 0xC0) { + // three bytes + var secondThirdBytes = this.getNextBits(8);; + intData = ((firstByte & 0x1F) << 16) | secondThirdBytes; + } + return intData; + } + + this.__defineGetter__("DataByte", function() + { + var output = new Array(); + var MODE_NUMBER = 1; + var MODE_ROMAN_AND_NUMBER = 2; + var MODE_8BIT_BYTE = 4; + var MODE_ECI = 7; + var MODE_KANJI = 8; + do + { + var mode = this.NextMode(); + //canvas.println("mode: " + mode); + if (mode == 0) + { + if (output.length > 0) + break; + else + throw "Empty data block"; + } + if (mode != MODE_NUMBER && mode != MODE_ROMAN_AND_NUMBER && mode != MODE_8BIT_BYTE && mode != MODE_KANJI && mode != MODE_ECI) + { + throw "Invalid mode: " + mode + " in (block:" + this.blockPointer + " bit:" + this.bitPointer + ")"; + } + + if(mode == MODE_ECI) + { + var temp_sbyteArray3 = this.parseECIValue(); + //output.push(temp_sbyteArray3); + } + else + { + + var dataLength = this.getDataLength(mode); + if (dataLength < 1) + throw "Invalid data length: " + dataLength; + switch (mode) + { + + case MODE_NUMBER: + var temp_str = this.getFigureString(dataLength); + var ta = new Array(temp_str.length); + for(var j=0;j 7) + { + throw "System.ArgumentException"; + } + return DataMask.DATA_MASKS[reference]; +} + +function DataMask000() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return ((i + j) & 0x01) == 0; + } +} + +function DataMask001() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (i & 0x01) == 0; + } +} + +function DataMask010() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return j % 3 == 0; + } +} + +function DataMask011() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (i + j) % 3 == 0; + } +} + +function DataMask100() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return (((URShift(i, 1)) + (j / 3)) & 0x01) == 0; + } +} + +function DataMask101() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + var temp = i * j; + return (temp & 0x01) + (temp % 3) == 0; + } +} + +function DataMask110() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + var temp = i * j; + return (((temp & 0x01) + (temp % 3)) & 0x01) == 0; + } +} +function DataMask111() +{ + this.unmaskBitMatrix=function(bits, dimension) + { + for (var i = 0; i < dimension; i++) + { + for (var j = 0; j < dimension; j++) + { + if (this.isMasked(i, j)) + { + bits.flip(j, i); + } + } + } + } + this.isMasked=function( i, j) + { + return ((((i + j) & 0x01) + ((i * j) % 3)) & 0x01) == 0; + } +} + +DataMask.DATA_MASKS = new Array(new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111()); + diff --git a/pos_qr_scan/static/lib/jsqrcode/decoder.js b/pos_qr_scan/static/lib/jsqrcode/decoder.js new file mode 100644 index 0000000000..d0c1ed57cf --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/decoder.js @@ -0,0 +1,95 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +var Decoder={}; +Decoder.rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); + +Decoder.correctErrors=function( codewordBytes, numDataCodewords) +{ + var numCodewords = codewordBytes.length; + // First read into an array of ints + var codewordsInts = new Array(numCodewords); + for (var i = 0; i < numCodewords; i++) + { + codewordsInts[i] = codewordBytes[i] & 0xFF; + } + var numECCodewords = codewordBytes.length - numDataCodewords; + try + { + Decoder.rsDecoder.decode(codewordsInts, numECCodewords); + //var corrector = new ReedSolomon(codewordsInts, numECCodewords); + //corrector.correct(); + } + catch ( rse) + { + throw rse; + } + // Copy back into array of bytes -- only need to worry about the bytes that were data + // We don't care about errors in the error-correction codewords + for (var i = 0; i < numDataCodewords; i++) + { + codewordBytes[i] = codewordsInts[i]; + } +} + +Decoder.decode=function(bits) +{ + var parser = new BitMatrixParser(bits); + var version = parser.readVersion(); + var ecLevel = parser.readFormatInformation().ErrorCorrectionLevel; + + // Read codewords + var codewords = parser.readCodewords(); + + // Separate into data blocks + var dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); + + // Count total number of data bytes + var totalBytes = 0; + for (var i = 0; i < dataBlocks.length; i++) + { + totalBytes += dataBlocks[i].NumDataCodewords; + } + var resultBytes = new Array(totalBytes); + var resultOffset = 0; + + // Error-correct and copy data blocks together into a stream of bytes + for (var j = 0; j < dataBlocks.length; j++) + { + var dataBlock = dataBlocks[j]; + var codewordBytes = dataBlock.Codewords; + var numDataCodewords = dataBlock.NumDataCodewords; + Decoder.correctErrors(codewordBytes, numDataCodewords); + for (var i = 0; i < numDataCodewords; i++) + { + resultBytes[resultOffset++] = codewordBytes[i]; + } + } + + // Decode the contents of that stream of bytes + var reader = new QRCodeDataBlockReader(resultBytes, version.VersionNumber, ecLevel.Bits); + return reader; + //return DecodedBitStreamParser.decode(resultBytes, version, ecLevel); +} diff --git a/pos_qr_scan/static/lib/jsqrcode/detector.js b/pos_qr_scan/static/lib/jsqrcode/detector.js new file mode 100644 index 0000000000..06c214a3a8 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/detector.js @@ -0,0 +1,413 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function PerspectiveTransform( a11, a21, a31, a12, a22, a32, a13, a23, a33) +{ + this.a11 = a11; + this.a12 = a12; + this.a13 = a13; + this.a21 = a21; + this.a22 = a22; + this.a23 = a23; + this.a31 = a31; + this.a32 = a32; + this.a33 = a33; + this.transformPoints1=function( points) + { + var max = points.length; + var a11 = this.a11; + var a12 = this.a12; + var a13 = this.a13; + var a21 = this.a21; + var a22 = this.a22; + var a23 = this.a23; + var a31 = this.a31; + var a32 = this.a32; + var a33 = this.a33; + for (var i = 0; i < max; i += 2) + { + var x = points[i]; + var y = points[i + 1]; + var denominator = a13 * x + a23 * y + a33; + points[i] = (a11 * x + a21 * y + a31) / denominator; + points[i + 1] = (a12 * x + a22 * y + a32) / denominator; + } + } + this. transformPoints2=function(xValues, yValues) + { + var n = xValues.length; + for (var i = 0; i < n; i++) + { + var x = xValues[i]; + var y = yValues[i]; + var denominator = this.a13 * x + this.a23 * y + this.a33; + xValues[i] = (this.a11 * x + this.a21 * y + this.a31) / denominator; + yValues[i] = (this.a12 * x + this.a22 * y + this.a32) / denominator; + } + } + + this.buildAdjoint=function() + { + // Adjoint is the transpose of the cofactor matrix: + return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21); + } + this.times=function( other) + { + return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 +this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33); + } + +} + +PerspectiveTransform.quadrilateralToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3, x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p) +{ + + var qToS = this.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); + var sToQ = this.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); + return sToQ.times(qToS); +} + +PerspectiveTransform.squareToQuadrilateral=function( x0, y0, x1, y1, x2, y2, x3, y3) +{ + var dy2 = y3 - y2; + var dy3 = y0 - y1 + y2 - y3; + if (dy2 == 0.0 && dy3 == 0.0) + { + return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0); + } + else + { + var dx1 = x1 - x2; + var dx2 = x3 - x2; + var dx3 = x0 - x1 + x2 - x3; + var dy1 = y1 - y2; + var denominator = dx1 * dy2 - dx2 * dy1; + var a13 = (dx3 * dy2 - dx2 * dy3) / denominator; + var a23 = (dx1 * dy3 - dx3 * dy1) / denominator; + return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0); + } +} + +PerspectiveTransform.quadrilateralToSquare=function( x0, y0, x1, y1, x2, y2, x3, y3) +{ + // Here, the adjoint serves as the inverse: + return this.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); +} + +function DetectorResult(bits, points) +{ + this.bits = bits; + this.points = points; +} + + +function Detector(image) +{ + this.image=image; + this.resultPointCallback = null; + + this.sizeOfBlackWhiteBlackRun=function( fromX, fromY, toX, toY) + { + // Mild variant of Bresenham's algorithm; + // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm + var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX); + if (steep) + { + var temp = fromX; + fromX = fromY; + fromY = temp; + temp = toX; + toX = toY; + toY = temp; + } + + var dx = Math.abs(toX - fromX); + var dy = Math.abs(toY - fromY); + var error = - dx >> 1; + var ystep = fromY < toY?1:- 1; + var xstep = fromX < toX?1:- 1; + var state = 0; // In black pixels, looking for white, first or second time + for (var x = fromX, y = fromY; x != toX; x += xstep) + { + + var realX = steep?y:x; + var realY = steep?x:y; + if (state == 1) + { + // In white pixels, looking for black + if (this.image[realX + realY*qrcode.width]) + { + state++; + } + } + else + { + if (!this.image[realX + realY*qrcode.width]) + { + state++; + } + } + + if (state == 3) + { + // Found black, white, black, and stumbled back onto white; done + var diffX = x - fromX; + var diffY = y - fromY; + return Math.sqrt( (diffX * diffX + diffY * diffY)); + } + error += dy; + if (error > 0) + { + if (y == toY) + { + break; + } + y += ystep; + error -= dx; + } + } + var diffX2 = toX - fromX; + var diffY2 = toY - fromY; + return Math.sqrt( (diffX2 * diffX2 + diffY2 * diffY2)); + } + + + this.sizeOfBlackWhiteBlackRunBothWays=function( fromX, fromY, toX, toY) + { + + var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); + + // Now count other way -- don't run off image though of course + var scale = 1.0; + var otherToX = fromX - (toX - fromX); + if (otherToX < 0) + { + scale = fromX / (fromX - otherToX); + otherToX = 0; + } + else if (otherToX >= qrcode.width) + { + scale = (qrcode.width - 1 - fromX) / (otherToX - fromX); + otherToX = qrcode.width - 1; + } + var otherToY = Math.floor (fromY - (toY - fromY) * scale); + + scale = 1.0; + if (otherToY < 0) + { + scale = fromY / (fromY - otherToY); + otherToY = 0; + } + else if (otherToY >= qrcode.height) + { + scale = (qrcode.height - 1 - fromY) / (otherToY - fromY); + otherToY = qrcode.height - 1; + } + otherToX = Math.floor (fromX + (otherToX - fromX) * scale); + + result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); + return result - 1.0; // -1 because we counted the middle pixel twice + } + + + + this.calculateModuleSizeOneWay=function( pattern, otherPattern) + { + var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor( pattern.X), Math.floor( pattern.Y), Math.floor( otherPattern.X), Math.floor(otherPattern.Y)); + var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.X), Math.floor(otherPattern.Y), Math.floor( pattern.X), Math.floor(pattern.Y)); + if (isNaN(moduleSizeEst1)) + { + return moduleSizeEst2 / 7.0; + } + if (isNaN(moduleSizeEst2)) + { + return moduleSizeEst1 / 7.0; + } + // Average them, and divide by 7 since we've counted the width of 3 black modules, + // and 1 white and 1 black module on either side. Ergo, divide sum by 14. + return (moduleSizeEst1 + moduleSizeEst2) / 14.0; + } + + + this.calculateModuleSize=function( topLeft, topRight, bottomLeft) + { + // Take the average + return (this.calculateModuleSizeOneWay(topLeft, topRight) + this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0; + } + + this.distance=function( pattern1, pattern2) + { + var xDiff = pattern1.X - pattern2.X; + var yDiff = pattern1.Y - pattern2.Y; + return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); + } + this.computeDimension=function( topLeft, topRight, bottomLeft, moduleSize) + { + + var tltrCentersDimension = Math.round(this.distance(topLeft, topRight) / moduleSize); + var tlblCentersDimension = Math.round(this.distance(topLeft, bottomLeft) / moduleSize); + var dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; + switch (dimension & 0x03) + { + + // mod 4 + case 0: + dimension++; + break; + // 1? do nothing + + case 2: + dimension--; + break; + + case 3: + throw "Error"; + } + return dimension; + } + + this.findAlignmentInRegion=function( overallEstModuleSize, estAlignmentX, estAlignmentY, allowanceFactor) + { + // Look for an alignment pattern (3 modules in size) around where it + // should be + var allowance = Math.floor (allowanceFactor * overallEstModuleSize); + var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance); + var alignmentAreaRightX = Math.min(qrcode.width - 1, estAlignmentX + allowance); + if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) + { + throw "Error"; + } + + var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance); + var alignmentAreaBottomY = Math.min(qrcode.height - 1, estAlignmentY + allowance); + + var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback); + return alignmentFinder.find(); + } + + this.createTransform=function( topLeft, topRight, bottomLeft, alignmentPattern, dimension) + { + var dimMinusThree = dimension - 3.5; + var bottomRightX; + var bottomRightY; + var sourceBottomRightX; + var sourceBottomRightY; + if (alignmentPattern != null) + { + bottomRightX = alignmentPattern.X; + bottomRightY = alignmentPattern.Y; + sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0; + } + else + { + // Don't have an alignment pattern, just make up the bottom-right point + bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; + bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; + sourceBottomRightX = sourceBottomRightY = dimMinusThree; + } + + var transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); + + return transform; + } + + this.sampleGrid=function( image, transform, dimension) + { + + var sampler = GridSampler; + return sampler.sampleGrid3(image, dimension, transform); + } + + this.processFinderPatternInfo = function( info) + { + + var topLeft = info.TopLeft; + var topRight = info.TopRight; + var bottomLeft = info.BottomLeft; + + var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft); + if (moduleSize < 1.0) + { + throw "Error"; + } + var dimension = this.computeDimension(topLeft, topRight, bottomLeft, moduleSize); + var provisionalVersion = Version.getProvisionalVersionForDimension(dimension); + var modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; + + var alignmentPattern = null; + // Anything above version 1 has an alignment pattern + if (provisionalVersion.AlignmentPatternCenters.length > 0) + { + + // Guess where a "bottom right" finder pattern would have been + var bottomRightX = topRight.X - topLeft.X + bottomLeft.X; + var bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; + + // Estimate that alignment pattern is closer by 3 modules + // from "bottom right" to known top left location + var correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters; + var estAlignmentX = Math.floor (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); + var estAlignmentY = Math.floor (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); + + // Kind of arbitrary -- expand search radius before giving up + for (var i = 4; i <= 16; i <<= 1) + { + //try + //{ + alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i); + break; + //} + //catch (re) + //{ + // try next round + //} + } + // If we didn't find alignment pattern... well try anyway without it + } + + var transform = this.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); + + var bits = this.sampleGrid(this.image, transform, dimension); + + var points; + if (alignmentPattern == null) + { + points = new Array(bottomLeft, topLeft, topRight); + } + else + { + points = new Array(bottomLeft, topLeft, topRight, alignmentPattern); + } + return new DetectorResult(bits, points); + } + + + + this.detect=function() + { + var info = new FinderPatternFinder().findFinderPattern(this.image); + + return this.processFinderPatternInfo(info); + } +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/errorlevel.js b/pos_qr_scan/static/lib/jsqrcode/errorlevel.js new file mode 100644 index 0000000000..5ce2a276c6 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/errorlevel.js @@ -0,0 +1,58 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function ErrorCorrectionLevel(ordinal, bits, name) +{ + this.ordinal_Renamed_Field = ordinal; + this.bits = bits; + this.name = name; + this.__defineGetter__("Bits", function() + { + return this.bits; + }); + this.__defineGetter__("Name", function() + { + return this.name; + }); + this.ordinal=function() + { + return this.ordinal_Renamed_Field; + } +} + +ErrorCorrectionLevel.forBits=function( bits) +{ + if (bits < 0 || bits >= FOR_BITS.length) + { + throw "ArgumentException"; + } + return FOR_BITS[bits]; +} + +var L = new ErrorCorrectionLevel(0, 0x01, "L"); +var M = new ErrorCorrectionLevel(1, 0x00, "M"); +var Q = new ErrorCorrectionLevel(2, 0x03, "Q"); +var H = new ErrorCorrectionLevel(3, 0x02, "H"); +var FOR_BITS = new Array( M, L, H, Q); \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/findpat.js b/pos_qr_scan/static/lib/jsqrcode/findpat.js new file mode 100644 index 0000000000..7f6ba89883 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/findpat.js @@ -0,0 +1,651 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +var MIN_SKIP = 3; +var MAX_MODULES = 57; +var INTEGER_MATH_SHIFT = 8; +var CENTER_QUORUM = 2; + +qrcode.orderBestPatterns=function(patterns) + { + + function distance( pattern1, pattern2) + { + var xDiff = pattern1.X - pattern2.X; + var yDiff = pattern1.Y - pattern2.Y; + return Math.sqrt( (xDiff * xDiff + yDiff * yDiff)); + } + + /// Returns the z component of the cross product between vectors BC and BA. + function crossProductZ( pointA, pointB, pointC) + { + var bX = pointB.x; + var bY = pointB.y; + return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); + } + + + // Find distances between pattern centers + var zeroOneDistance = distance(patterns[0], patterns[1]); + var oneTwoDistance = distance(patterns[1], patterns[2]); + var zeroTwoDistance = distance(patterns[0], patterns[2]); + + var pointA, pointB, pointC; + // Assume one closest to other two is B; A and C will just be guesses at first + if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) + { + pointB = patterns[0]; + pointA = patterns[1]; + pointC = patterns[2]; + } + else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) + { + pointB = patterns[1]; + pointA = patterns[0]; + pointC = patterns[2]; + } + else + { + pointB = patterns[2]; + pointA = patterns[0]; + pointC = patterns[1]; + } + + // Use cross product to figure out whether A and C are correct or flipped. + // This asks whether BC x BA has a positive z component, which is the arrangement + // we want for A, B, C. If it's negative, then we've got it flipped around and + // should swap A and C. + if (crossProductZ(pointA, pointB, pointC) < 0.0) + { + var temp = pointA; + pointA = pointC; + pointC = temp; + } + + patterns[0] = pointA; + patterns[1] = pointB; + patterns[2] = pointC; + } + + +function FinderPattern(posX, posY, estimatedModuleSize) +{ + this.x=posX; + this.y=posY; + this.count = 1; + this.estimatedModuleSize = estimatedModuleSize; + + this.__defineGetter__("EstimatedModuleSize", function() + { + return this.estimatedModuleSize; + }); + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("X", function() + { + return this.x; + }); + this.__defineGetter__("Y", function() + { + return this.y; + }); + this.incrementCount = function() + { + this.count++; + } + this.aboutEquals=function( moduleSize, i, j) + { + if (Math.abs(i - this.y) <= moduleSize && Math.abs(j - this.x) <= moduleSize) + { + var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize); + return moduleSizeDiff <= 1.0 || moduleSizeDiff / this.estimatedModuleSize <= 1.0; + } + return false; + } + +} + +function FinderPatternInfo(patternCenters) +{ + this.bottomLeft = patternCenters[0]; + this.topLeft = patternCenters[1]; + this.topRight = patternCenters[2]; + this.__defineGetter__("BottomLeft", function() + { + return this.bottomLeft; + }); + this.__defineGetter__("TopLeft", function() + { + return this.topLeft; + }); + this.__defineGetter__("TopRight", function() + { + return this.topRight; + }); +} + +function FinderPatternFinder() +{ + this.image=null; + this.possibleCenters = []; + this.hasSkipped = false; + this.crossCheckStateCount = new Array(0,0,0,0,0); + this.resultPointCallback = null; + + this.__defineGetter__("CrossCheckStateCount", function() + { + this.crossCheckStateCount[0] = 0; + this.crossCheckStateCount[1] = 0; + this.crossCheckStateCount[2] = 0; + this.crossCheckStateCount[3] = 0; + this.crossCheckStateCount[4] = 0; + return this.crossCheckStateCount; + }); + + this.foundPatternCross=function( stateCount) + { + var totalModuleSize = 0; + for (var i = 0; i < 5; i++) + { + var count = stateCount[i]; + if (count == 0) + { + return false; + } + totalModuleSize += count; + } + if (totalModuleSize < 7) + { + return false; + } + var moduleSize = Math.floor((totalModuleSize << INTEGER_MATH_SHIFT) / 7); + var maxVariance = Math.floor(moduleSize / 2); + // Allow less than 50% variance from 1-1-3-1-1 proportions + return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; + } + this.centerFromEnd=function( stateCount, end) + { + return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0; + } + this.crossCheckVertical=function( startI, centerJ, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxI = qrcode.height; + var stateCount = this.CrossCheckStateCount; + + // Start counting up from center + var i = startI; + while (i >= 0 && image[centerJ + i*qrcode.width]) + { + stateCount[2]++; + i--; + } + if (i < 0) + { + return NaN; + } + while (i >= 0 && !image[centerJ +i*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + i--; + } + // If already too many modules in this state or ran off the edge: + if (i < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (i >= 0 && image[centerJ + i*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + i--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + // Now also count down from center + i = startI + 1; + while (i < maxI && image[centerJ +i*qrcode.width]) + { + stateCount[2]++; + i++; + } + if (i == maxI) + { + return NaN; + } + while (i < maxI && !image[centerJ + i*qrcode.width] && stateCount[3] < maxCount) + { + stateCount[3]++; + i++; + } + if (i == maxI || stateCount[3] >= maxCount) + { + return NaN; + } + while (i < maxI && image[centerJ + i*qrcode.width] && stateCount[4] < maxCount) + { + stateCount[4]++; + i++; + } + if (stateCount[4] >= maxCount) + { + return NaN; + } + + // If we found a finder-pattern-like section, but its size is more than 40% different than + // the original, assume it's a false positive + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, i):NaN; + } + this.crossCheckHorizontal=function( startJ, centerI, maxCount, originalStateCountTotal) + { + var image = this.image; + + var maxJ = qrcode.width; + var stateCount = this.CrossCheckStateCount; + + var j = startJ; + while (j >= 0 && image[j+ centerI*qrcode.width]) + { + stateCount[2]++; + j--; + } + if (j < 0) + { + return NaN; + } + while (j >= 0 && !image[j+ centerI*qrcode.width] && stateCount[1] <= maxCount) + { + stateCount[1]++; + j--; + } + if (j < 0 || stateCount[1] > maxCount) + { + return NaN; + } + while (j >= 0 && image[j+ centerI*qrcode.width] && stateCount[0] <= maxCount) + { + stateCount[0]++; + j--; + } + if (stateCount[0] > maxCount) + { + return NaN; + } + + j = startJ + 1; + while (j < maxJ && image[j+ centerI*qrcode.width]) + { + stateCount[2]++; + j++; + } + if (j == maxJ) + { + return NaN; + } + while (j < maxJ && !image[j+ centerI*qrcode.width] && stateCount[3] < maxCount) + { + stateCount[3]++; + j++; + } + if (j == maxJ || stateCount[3] >= maxCount) + { + return NaN; + } + while (j < maxJ && image[j+ centerI*qrcode.width] && stateCount[4] < maxCount) + { + stateCount[4]++; + j++; + } + if (stateCount[4] >= maxCount) + { + return NaN; + } + + // If we found a finder-pattern-like section, but its size is significantly different than + // the original, assume it's a false positive + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) + { + return NaN; + } + + return this.foundPatternCross(stateCount)?this.centerFromEnd(stateCount, j):NaN; + } + this.handlePossibleCenter=function( stateCount, i, j) + { + var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; + var centerJ = this.centerFromEnd(stateCount, j); //float + var centerI = this.crossCheckVertical(i, Math.floor( centerJ), stateCount[2], stateCountTotal); //float + if (!isNaN(centerI)) + { + // Re-cross check + centerJ = this.crossCheckHorizontal(Math.floor( centerJ), Math.floor( centerI), stateCount[2], stateCountTotal); + if (!isNaN(centerJ)) + { + var estimatedModuleSize = stateCountTotal / 7.0; + var found = false; + var max = this.possibleCenters.length; + for (var index = 0; index < max; index++) + { + var center = this.possibleCenters[index]; + // Look for about the same center and module size: + if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) + { + center.incrementCount(); + found = true; + break; + } + } + if (!found) + { + var point = new FinderPattern(centerJ, centerI, estimatedModuleSize); + this.possibleCenters.push(point); + if (this.resultPointCallback != null) + { + this.resultPointCallback.foundPossibleResultPoint(point); + } + } + return true; + } + } + return false; + } + + this.selectBestPatterns=function() + { + + var startSize = this.possibleCenters.length; + if (startSize < 3) + { + // Couldn't find enough finder patterns + throw "Couldn't find enough finder patterns (found " + startSize + ")" + } + + // Filter outlier possibilities whose module size is too different + if (startSize > 3) + { + // But we can only afford to do so if we have at least 4 possibilities to choose from + var totalModuleSize = 0.0; + var square = 0.0; + for (var i = 0; i < startSize; i++) + { + //totalModuleSize += this.possibleCenters[i].EstimatedModuleSize; + var centerValue=this.possibleCenters[i].EstimatedModuleSize; + totalModuleSize += centerValue; + square += (centerValue * centerValue); + } + var average = totalModuleSize / startSize; + this.possibleCenters.sort(function(center1,center2) { + var dA=Math.abs(center2.EstimatedModuleSize - average); + var dB=Math.abs(center1.EstimatedModuleSize - average); + if (dA < dB) { + return (-1); + } else if (dA == dB) { + return 0; + } else { + return 1; + } + }); + + var stdDev = Math.sqrt(square / startSize - average * average); + var limit = Math.max(0.2 * average, stdDev); + //for (var i = 0; i < this.possibleCenters.length && this.possibleCenters.length > 3; i++) + for (var i = this.possibleCenters.length - 1; i >= 0 ; i--) + { + var pattern = this.possibleCenters[i]; + //if (Math.abs(pattern.EstimatedModuleSize - average) > 0.2 * average) + if (Math.abs(pattern.EstimatedModuleSize - average) > limit) + { + //this.possibleCenters.remove(i); + this.possibleCenters.splice(i,1); + //i--; + } + } + } + + if (this.possibleCenters.length > 3) + { + // Throw away all but those first size candidate points we found. + this.possibleCenters.sort(function(a, b){ + if (a.count > b.count){return -1;} + if (a.count < b.count){return 1;} + return 0; + }); + } + + return new Array( this.possibleCenters[0], this.possibleCenters[1], this.possibleCenters[2]); + } + + this.findRowSkip=function() + { + var max = this.possibleCenters.length; + if (max <= 1) + { + return 0; + } + var firstConfirmedCenter = null; + for (var i = 0; i < max; i++) + { + var center = this.possibleCenters[i]; + if (center.Count >= CENTER_QUORUM) + { + if (firstConfirmedCenter == null) + { + firstConfirmedCenter = center; + } + else + { + // We have two confirmed centers + // How far down can we skip before resuming looking for the next + // pattern? In the worst case, only the difference between the + // difference in the x / y coordinates of the two centers. + // This is the case where you find top left last. + this.hasSkipped = true; + return Math.floor ((Math.abs(firstConfirmedCenter.X - center.X) - Math.abs(firstConfirmedCenter.Y - center.Y)) / 2); + } + } + } + return 0; + } + + this.haveMultiplyConfirmedCenters=function() + { + var confirmedCount = 0; + var totalModuleSize = 0.0; + var max = this.possibleCenters.length; + for (var i = 0; i < max; i++) + { + var pattern = this.possibleCenters[i]; + if (pattern.Count >= CENTER_QUORUM) + { + confirmedCount++; + totalModuleSize += pattern.EstimatedModuleSize; + } + } + if (confirmedCount < 3) + { + return false; + } + // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" + // and that we need to keep looking. We detect this by asking if the estimated module sizes + // vary too much. We arbitrarily say that when the total deviation from average exceeds + // 5% of the total module size estimates, it's too much. + var average = totalModuleSize / max; + var totalDeviation = 0.0; + for (var i = 0; i < max; i++) + { + pattern = this.possibleCenters[i]; + totalDeviation += Math.abs(pattern.EstimatedModuleSize - average); + } + return totalDeviation <= 0.05 * totalModuleSize; + } + + this.findFinderPattern = function(image){ + var tryHarder = false; + this.image=image; + var maxI = qrcode.height; + var maxJ = qrcode.width; + var iSkip = Math.floor((3 * maxI) / (4 * MAX_MODULES)); + if (iSkip < MIN_SKIP || tryHarder) + { + iSkip = MIN_SKIP; + } + + var done = false; + var stateCount = new Array(5); + for (var i = iSkip - 1; i < maxI && !done; i += iSkip) + { + // Get a row of black/white values + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + stateCount[3] = 0; + stateCount[4] = 0; + var currentState = 0; + for (var j = 0; j < maxJ; j++) + { + if (image[j+i*qrcode.width] ) + { + // Black pixel + if ((currentState & 1) == 1) + { + // Counting white pixels + currentState++; + } + stateCount[currentState]++; + } + else + { + // White pixel + if ((currentState & 1) == 0) + { + // Counting black pixels + if (currentState == 4) + { + // A winner? + if (this.foundPatternCross(stateCount)) + { + // Yes + var confirmed = this.handlePossibleCenter(stateCount, i, j); + if (confirmed) + { + // Start examining every other line. Checking each line turned out to be too + // expensive and didn't improve performance. + iSkip = 2; + if (this.hasSkipped) + { + done = this.haveMultiplyConfirmedCenters(); + } + else + { + var rowSkip = this.findRowSkip(); + if (rowSkip > stateCount[2]) + { + // Skip rows between row of lower confirmed center + // and top of presumed third confirmed center + // but back up a bit to get a full chance of detecting + // it, entire width of center of finder pattern + + // Skip by rowSkip, but back off by stateCount[2] (size of last center + // of pattern we saw) to be conservative, and also back off by iSkip which + // is about to be re-added + i += rowSkip - stateCount[2] - iSkip; + j = maxJ - 1; + } + } + } + else + { + // Advance to next black pixel + do + { + j++; + } + while (j < maxJ && !image[j + i*qrcode.width]); + j--; // back up to that last white pixel + } + // Clear state to start looking again + currentState = 0; + stateCount[0] = 0; + stateCount[1] = 0; + stateCount[2] = 0; + stateCount[3] = 0; + stateCount[4] = 0; + } + else + { + // No, shift counts back by two + stateCount[0] = stateCount[2]; + stateCount[1] = stateCount[3]; + stateCount[2] = stateCount[4]; + stateCount[3] = 1; + stateCount[4] = 0; + currentState = 3; + } + } + else + { + stateCount[++currentState]++; + } + } + else + { + // Counting white pixels + stateCount[currentState]++; + } + } + } + if (this.foundPatternCross(stateCount)) + { + var confirmed = this.handlePossibleCenter(stateCount, i, maxJ); + if (confirmed) + { + iSkip = stateCount[0]; + if (this.hasSkipped) + { + // Found a third one + done = this.haveMultiplyConfirmedCenters(); + } + } + } + } + + var patternInfo = this.selectBestPatterns(); + qrcode.orderBestPatterns(patternInfo); + + return new FinderPatternInfo(patternInfo); + }; +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/formatinf.js b/pos_qr_scan/static/lib/jsqrcode/formatinf.js new file mode 100644 index 0000000000..62266a4c66 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/formatinf.js @@ -0,0 +1,104 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +var FORMAT_INFO_MASK_QR = 0x5412; +var FORMAT_INFO_DECODE_LOOKUP = new Array(new Array(0x5412, 0x00), new Array(0x5125, 0x01), new Array(0x5E7C, 0x02), new Array(0x5B4B, 0x03), new Array(0x45F9, 0x04), new Array(0x40CE, 0x05), new Array(0x4F97, 0x06), new Array(0x4AA0, 0x07), new Array(0x77C4, 0x08), new Array(0x72F3, 0x09), new Array(0x7DAA, 0x0A), new Array(0x789D, 0x0B), new Array(0x662F, 0x0C), new Array(0x6318, 0x0D), new Array(0x6C41, 0x0E), new Array(0x6976, 0x0F), new Array(0x1689, 0x10), new Array(0x13BE, 0x11), new Array(0x1CE7, 0x12), new Array(0x19D0, 0x13), new Array(0x0762, 0x14), new Array(0x0255, 0x15), new Array(0x0D0C, 0x16), new Array(0x083B, 0x17), new Array(0x355F, 0x18), new Array(0x3068, 0x19), new Array(0x3F31, 0x1A), new Array(0x3A06, 0x1B), new Array(0x24B4, 0x1C), new Array(0x2183, 0x1D), new Array(0x2EDA, 0x1E), new Array(0x2BED, 0x1F)); +var BITS_SET_IN_HALF_BYTE = new Array(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); + + +function FormatInformation(formatInfo) +{ + this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); + this.dataMask = (formatInfo & 0x07); + + this.__defineGetter__("ErrorCorrectionLevel", function() + { + return this.errorCorrectionLevel; + }); + this.__defineGetter__("DataMask", function() + { + return this.dataMask; + }); + this.GetHashCode=function() + { + return (this.errorCorrectionLevel.ordinal() << 3) | this.dataMask; + } + this.Equals=function( o) + { + var other = o; + return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; + } +} + +FormatInformation.numBitsDiffering=function( a, b) +{ + a ^= b; // a now has a 1 bit exactly where its bit differs with b's + // Count bits set quickly with a series of lookups: + return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(URShift(a, 4) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 8) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 12) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 16) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 20) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 24) & 0x0F)] + BITS_SET_IN_HALF_BYTE[(URShift(a, 28) & 0x0F)]; +} + +FormatInformation.decodeFormatInformation=function( maskedFormatInfo) +{ + var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo); + if (formatInfo != null) + { + return formatInfo; + } + // Should return null, but, some QR codes apparently + // do not mask this info. Try again by actually masking the pattern + // first + return FormatInformation.doDecodeFormatInformation(maskedFormatInfo ^ FORMAT_INFO_MASK_QR); +} +FormatInformation.doDecodeFormatInformation=function( maskedFormatInfo) +{ + // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing + var bestDifference = 0xffffffff; + var bestFormatInfo = 0; + for (var i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) + { + var decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; + var targetInfo = decodeInfo[0]; + if (targetInfo == maskedFormatInfo) + { + // Found an exact match + return new FormatInformation(decodeInfo[1]); + } + var bitsDifference = this.numBitsDiffering(maskedFormatInfo, targetInfo); + if (bitsDifference < bestDifference) + { + bestFormatInfo = decodeInfo[1]; + bestDifference = bitsDifference; + } + } + // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits + // differing means we found a match + if (bestDifference <= 3) + { + return new FormatInformation(bestFormatInfo); + } + return null; +} + + \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/gf256.js b/pos_qr_scan/static/lib/jsqrcode/gf256.js new file mode 100644 index 0000000000..8eb6b61748 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/gf256.js @@ -0,0 +1,117 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function GF256( primitive) +{ + this.expTable = new Array(256); + this.logTable = new Array(256); + var x = 1; + for (var i = 0; i < 256; i++) + { + this.expTable[i] = x; + x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 + if (x >= 0x100) + { + x ^= primitive; + } + } + for (var i = 0; i < 255; i++) + { + this.logTable[this.expTable[i]] = i; + } + // logTable[0] == 0 but this should never be used + var at0=new Array(1);at0[0]=0; + this.zero = new GF256Poly(this, new Array(at0)); + var at1=new Array(1);at1[0]=1; + this.one = new GF256Poly(this, new Array(at1)); + + this.__defineGetter__("Zero", function() + { + return this.zero; + }); + this.__defineGetter__("One", function() + { + return this.one; + }); + this.buildMonomial=function( degree, coefficient) + { + if (degree < 0) + { + throw "System.ArgumentException"; + } + if (coefficient == 0) + { + return this.zero; + } + var coefficients = new Array(degree + 1); + for(var i=0;i 1 && coefficients[0] == 0) + { + // Leading term must be non-zero for anything except the constant polynomial "0" + var firstNonZero = 1; + while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) + { + firstNonZero++; + } + if (firstNonZero == coefficientsLength) + { + this.coefficients = field.Zero.coefficients; + } + else + { + this.coefficients = new Array(coefficientsLength - firstNonZero); + for(var i=0;i largerCoefficients.length) + { + var temp = smallerCoefficients; + smallerCoefficients = largerCoefficients; + largerCoefficients = temp; + } + var sumDiff = new Array(largerCoefficients.length); + var lengthDiff = largerCoefficients.length - smallerCoefficients.length; + // Copy high-order terms only found in higher-degree polynomial's coefficients + //Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff); + for(var ci=0;ci= other.Degree && !remainder.Zero) + { + var degreeDifference = remainder.Degree - other.Degree; + var scale = this.field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm); + var term = other.multiplyByMonomial(degreeDifference, scale); + var iterationQuotient = this.field.buildMonomial(degreeDifference, scale); + quotient = quotient.addOrSubtract(iterationQuotient); + remainder = remainder.addOrSubtract(term); + } + + return new Array(quotient, remainder); + } +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/grid.js b/pos_qr_scan/static/lib/jsqrcode/grid.js new file mode 100644 index 0000000000..3be2ad6049 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/grid.js @@ -0,0 +1,152 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +var GridSampler = {}; + +GridSampler.checkAndNudgePoints=function( image, points) + { + var width = qrcode.width; + var height = qrcode.height; + // Check and nudge points from start until we see some that are OK: + var nudged = true; + for (var offset = 0; offset < points.length && nudged; offset += 2) + { + var x = Math.floor (points[offset]); + var y = Math.floor( points[offset + 1]); + if (x < - 1 || x > width || y < - 1 || y > height) + { + throw "Error.checkAndNudgePoints "; + } + nudged = false; + if (x == - 1) + { + points[offset] = 0.0; + nudged = true; + } + else if (x == width) + { + points[offset] = width - 1; + nudged = true; + } + if (y == - 1) + { + points[offset + 1] = 0.0; + nudged = true; + } + else if (y == height) + { + points[offset + 1] = height - 1; + nudged = true; + } + } + // Check and nudge points from end: + nudged = true; + for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2) + { + var x = Math.floor( points[offset]); + var y = Math.floor( points[offset + 1]); + if (x < - 1 || x > width || y < - 1 || y > height) + { + throw "Error.checkAndNudgePoints "; + } + nudged = false; + if (x == - 1) + { + points[offset] = 0.0; + nudged = true; + } + else if (x == width) + { + points[offset] = width - 1; + nudged = true; + } + if (y == - 1) + { + points[offset + 1] = 0.0; + nudged = true; + } + else if (y == height) + { + points[offset + 1] = height - 1; + nudged = true; + } + } + } + + + +GridSampler.sampleGrid3=function( image, dimension, transform) + { + var bits = new BitMatrix(dimension); + var points = new Array(dimension << 1); + for (var y = 0; y < dimension; y++) + { + var max = points.length; + var iValue = y + 0.5; + for (var x = 0; x < max; x += 2) + { + points[x] = (x >> 1) + 0.5; + points[x + 1] = iValue; + } + transform.transformPoints1(points); + // Quick check to see if points transformed to something inside the image; + // sufficient to check the endpoints + GridSampler.checkAndNudgePoints(image, points); + try + { + for (var x = 0; x < max; x += 2) + { + //var xpoint = (Math.floor( points[x]) * 4) + (Math.floor( points[x + 1]) * qrcode.width * 4); + var bit = image[Math.floor( points[x])+ qrcode.width* Math.floor( points[x + 1])]; + //qrcode.imagedata.data[xpoint] = bit?255:0; + //qrcode.imagedata.data[xpoint+1] = bit?255:0; + //qrcode.imagedata.data[xpoint+2] = 0; + //qrcode.imagedata.data[xpoint+3] = 255; + //bits[x >> 1][ y]=bit; + if(bit) + bits.set_Renamed(x >> 1, y); + } + } + catch ( aioobe) + { + // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting + // transform gets "twisted" such that it maps a straight line of points to a set of points + // whose endpoints are in bounds, but others are not. There is probably some mathematical + // way to detect this about the transformation that I don't know yet. + // This results in an ugly runtime exception despite our clever checks above -- can't have + // that. We could check each point's coordinates but that feels duplicative. We settle for + // catching and wrapping ArrayIndexOutOfBoundsException. + throw "Error.checkAndNudgePoints"; + } + } + return bits; + } + +GridSampler.sampleGridx=function( image, dimension, p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY) +{ + var transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); + + return GridSampler.sampleGrid3(image, dimension, transform); +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/qrcode.js b/pos_qr_scan/static/lib/jsqrcode/qrcode.js new file mode 100644 index 0000000000..a83bddef85 --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/qrcode.js @@ -0,0 +1,455 @@ +/* + Copyright 2011 Lazar Laszlo (lazarsoft@gmail.com, www.lazarsoft.info) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + + +var qrcode = {}; +qrcode.imagedata = null; +qrcode.width = 0; +qrcode.height = 0; +qrcode.qrCodeSymbol = null; +qrcode.debug = false; +qrcode.maxImgSize = 1024*1024; + +qrcode.sizeOfDataLengthInfo = [ [ 10, 9, 8, 8 ], [ 12, 11, 16, 10 ], [ 14, 13, 16, 12 ] ]; + +qrcode.callback = null; + +qrcode.vidSuccess = function (stream) +{ + qrcode.localstream = stream; + if(qrcode.webkit) + qrcode.video.src = window.webkitURL.createObjectURL(stream); + else + if(qrcode.moz) + { + qrcode.video.mozSrcObject = stream; + qrcode.video.play(); + } + else + qrcode.video.src = stream; + + qrcode.gUM=true; + + qrcode.canvas_qr2 = document.createElement('canvas'); + qrcode.canvas_qr2.id = "qr-canvas"; + qrcode.qrcontext2 = qrcode.canvas_qr2.getContext('2d'); + qrcode.canvas_qr2.width = qrcode.video.videoWidth; + qrcode.canvas_qr2.height = qrcode.video.videoHeight; + setTimeout(qrcode.captureToCanvas, 500); +} + +qrcode.vidError = function(error) +{ + qrcode.gUM=false; + return; +} + +qrcode.captureToCanvas = function() +{ + if(qrcode.gUM) + { + try{ + if(qrcode.video.videoWidth == 0) + { + setTimeout(qrcode.captureToCanvas, 500); + return; + } + else + { + qrcode.canvas_qr2.width = qrcode.video.videoWidth; + qrcode.canvas_qr2.height = qrcode.video.videoHeight; + } + qrcode.qrcontext2.drawImage(qrcode.video,0,0); + try{ + qrcode.decode(); + } + catch(e){ + console.log(e); + setTimeout(qrcode.captureToCanvas, 500); + }; + } + catch(e){ + console.log(e); + setTimeout(qrcode.captureToCanvas, 500); + }; + } +} + +qrcode.setWebcam = function(videoId) +{ + var n=navigator; + qrcode.video=document.getElementById(videoId); + + var options = true; + if(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) + { + try{ + navigator.mediaDevices.enumerateDevices() + .then(function(devices) { + devices.forEach(function(device) { + console.log("deb1"); + if (device.kind === 'videoinput') { + if(device.label.toLowerCase().search("back") >-1) + options=[{'sourceId': device.deviceId}] ; + } + console.log(device.kind + ": " + device.label + + " id = " + device.deviceId); + }); + }) + + } + catch(e) + { + console.log(e); + } + } + else{ + console.log("no navigator.mediaDevices.enumerateDevices" ); + } + + if(n.getUserMedia) + n.getUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError); + else + if(n.webkitGetUserMedia) + { + qrcode.webkit=true; + n.webkitGetUserMedia({video:options, audio: false}, qrcode.vidSuccess, qrcode.vidError); + } + else + if(n.mozGetUserMedia) + { + qrcode.moz=true; + n.mozGetUserMedia({video: options, audio: false}, qrcode.vidSuccess, qrcode.vidError); + } +} + +qrcode.decode = function(src){ + + if(arguments.length==0) + { + if(qrcode.canvas_qr2) + { + var canvas_qr = qrcode.canvas_qr2; + var context = qrcode.qrcontext2; + } + else + { + var canvas_qr = document.getElementById("qr-canvas"); + var context = canvas_qr.getContext('2d'); + } + qrcode.width = canvas_qr.width; + qrcode.height = canvas_qr.height; + qrcode.imagedata = context.getImageData(0, 0, qrcode.width, qrcode.height); + qrcode.result = qrcode.process(context); + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + return qrcode.result; + } + else + { + var image = new Image(); + image.crossOrigin = "Anonymous"; + image.onload=function(){ + //var canvas_qr = document.getElementById("qr-canvas"); + var canvas_out = document.getElementById("out-canvas"); + if(canvas_out!=null) + { + var outctx = canvas_out.getContext('2d'); + outctx.clearRect(0, 0, 320, 240); + outctx.drawImage(image, 0, 0, 320, 240); + } + + var canvas_qr = document.createElement('canvas'); + var context = canvas_qr.getContext('2d'); + var nheight = image.height; + var nwidth = image.width; + if(image.width*image.height>qrcode.maxImgSize) + { + var ir = image.width / image.height; + nheight = Math.sqrt(qrcode.maxImgSize/ir); + nwidth=ir*nheight; + } + + canvas_qr.width = nwidth; + canvas_qr.height = nheight; + + context.drawImage(image, 0, 0, canvas_qr.width, canvas_qr.height ); + qrcode.width = canvas_qr.width; + qrcode.height = canvas_qr.height; + try{ + qrcode.imagedata = context.getImageData(0, 0, canvas_qr.width, canvas_qr.height); + }catch(e){ + qrcode.result = "Cross domain image reading not supported in your browser! Save it to your computer then drag and drop the file!"; + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + return; + } + + try + { + qrcode.result = qrcode.process(context); + } + catch(e) + { + console.log(e); + qrcode.result = "error decoding QR Code"; + } + if(qrcode.callback!=null) + qrcode.callback(qrcode.result); + } + image.onerror = function () + { + if(qrcode.callback!=null) + qrcode.callback("Failed to load the image"); + } + image.src = src; + } +} + +qrcode.isUrl = function(s) +{ + var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; + return regexp.test(s); +} + +qrcode.decode_url = function (s) +{ + var escaped = ""; + try{ + escaped = escape( s ); + } + catch(e) + { + console.log(e); + escaped = s; + } + var ret = ""; + try{ + ret = decodeURIComponent( escaped ); + } + catch(e) + { + console.log(e); + ret = escaped; + } + return ret; +} + +qrcode.decode_utf8 = function ( s ) +{ + if(qrcode.isUrl(s)) + return qrcode.decode_url(s); + else + return s; +} + +qrcode.process = function(ctx){ + + var start = new Date().getTime(); + + var image = qrcode.grayScaleToBitmap(qrcode.grayscale()); + //var image = qrcode.binarize(128); + + if(qrcode.debug) + { + for (var y = 0; y < qrcode.height; y++) + { + for (var x = 0; x < qrcode.width; x++) + { + var point = (x * 4) + (y * qrcode.width * 4); + qrcode.imagedata.data[point] = image[x+y*qrcode.width]?0:0; + qrcode.imagedata.data[point+1] = image[x+y*qrcode.width]?0:0; + qrcode.imagedata.data[point+2] = image[x+y*qrcode.width]?255:0; + } + } + ctx.putImageData(qrcode.imagedata, 0, 0); + } + + //var finderPatternInfo = new FinderPatternFinder().findFinderPattern(image); + + var detector = new Detector(image); + + var qRCodeMatrix = detector.detect(); + + if(qrcode.debug) + { + for (var y = 0; y < qRCodeMatrix.bits.Height; y++) + { + for (var x = 0; x < qRCodeMatrix.bits.Width; x++) + { + var point = (x * 4*2) + (y*2 * qrcode.width * 4); + qrcode.imagedata.data[point] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; + qrcode.imagedata.data[point+1] = qRCodeMatrix.bits.get_Renamed(x,y)?0:0; + qrcode.imagedata.data[point+2] = qRCodeMatrix.bits.get_Renamed(x,y)?255:0; + } + } + ctx.putImageData(qrcode.imagedata, 0, 0); + } + + + var reader = Decoder.decode(qRCodeMatrix.bits); + var data = reader.DataByte; + var str=""; + for(var i=0;i minmax[ax][ay][1]) + minmax[ax][ay][1] = target; + } + } + //minmax[ax][ay][0] = (minmax[ax][ay][0] + minmax[ax][ay][1]) / 2; + } + } + var middle = new Array(numSqrtArea); + for (var i3 = 0; i3 < numSqrtArea; i3++) + { + middle[i3] = new Array(numSqrtArea); + } + for (var ay = 0; ay < numSqrtArea; ay++) + { + for (var ax = 0; ax < numSqrtArea; ax++) + { + middle[ax][ay] = Math.floor((minmax[ax][ay][0] + minmax[ax][ay][1]) / 2); + //Console.out.print(middle[ax][ay] + ","); + } + //Console.out.println(""); + } + //Console.out.println(""); + + return middle; +} + +qrcode.grayScaleToBitmap=function(grayScale) +{ + var middle = qrcode.getMiddleBrightnessPerArea(grayScale); + var sqrtNumArea = middle.length; + var areaWidth = Math.floor(qrcode.width / sqrtNumArea); + var areaHeight = Math.floor(qrcode.height / sqrtNumArea); + + var buff = new ArrayBuffer(qrcode.width*qrcode.height); + var bitmap = new Uint8Array(buff); + + //var bitmap = new Array(qrcode.height*qrcode.width); + + for (var ay = 0; ay < sqrtNumArea; ay++) + { + for (var ax = 0; ax < sqrtNumArea; ax++) + { + for (var dy = 0; dy < areaHeight; dy++) + { + for (var dx = 0; dx < areaWidth; dx++) + { + bitmap[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] = (grayScale[areaWidth * ax + dx+ (areaHeight * ay + dy)*qrcode.width] < middle[ax][ay])?true:false; + } + } + } + } + return bitmap; +} + +qrcode.grayscale = function() +{ + var buff = new ArrayBuffer(qrcode.width*qrcode.height); + var ret = new Uint8Array(buff); + //var ret = new Array(qrcode.width*qrcode.height); + + for (var y = 0; y < qrcode.height; y++) + { + for (var x = 0; x < qrcode.width; x++) + { + var gray = qrcode.getPixel(x, y); + + ret[x+y*qrcode.width] = gray; + } + } + return ret; +} + + + + +function URShift( number, bits) +{ + if (number >= 0) + return number >> bits; + else + return (number >> bits) + (2 << ~bits); +} + diff --git a/pos_qr_scan/static/lib/jsqrcode/rsdecoder.js b/pos_qr_scan/static/lib/jsqrcode/rsdecoder.js new file mode 100644 index 0000000000..c110c43c6e --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/rsdecoder.js @@ -0,0 +1,178 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +function ReedSolomonDecoder(field) +{ + this.field = field; + this.decode=function(received, twoS) + { + var poly = new GF256Poly(this.field, received); + var syndromeCoefficients = new Array(twoS); + for(var i=0;i= b's + if (a.Degree < b.Degree) + { + var temp = a; + a = b; + b = temp; + } + + var rLast = a; + var r = b; + var sLast = this.field.One; + var s = this.field.Zero; + var tLast = this.field.Zero; + var t = this.field.One; + + // Run Euclidean algorithm until r's degree is less than R/2 + while (r.Degree >= Math.floor(R / 2)) + { + var rLastLast = rLast; + var sLastLast = sLast; + var tLastLast = tLast; + rLast = r; + sLast = s; + tLast = t; + + // Divide rLastLast by rLast, with quotient in q and remainder in r + if (rLast.Zero) + { + // Oops, Euclidean algorithm already terminated? + throw "r_{i-1} was zero"; + } + r = rLastLast; + var q = this.field.Zero; + var denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); + var dltInverse = this.field.inverse(denominatorLeadingTerm); + while (r.Degree >= rLast.Degree && !r.Zero) + { + var degreeDiff = r.Degree - rLast.Degree; + var scale = this.field.multiply(r.getCoefficient(r.Degree), dltInverse); + q = q.addOrSubtract(this.field.buildMonomial(degreeDiff, scale)); + r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); + //r.EXE(); + } + + s = q.multiply1(sLast).addOrSubtract(sLastLast); + t = q.multiply1(tLast).addOrSubtract(tLastLast); + } + + var sigmaTildeAtZero = t.getCoefficient(0); + if (sigmaTildeAtZero == 0) + { + throw "ReedSolomonException sigmaTilde(0) was zero"; + } + + var inverse = this.field.inverse(sigmaTildeAtZero); + var sigma = t.multiply2(inverse); + var omega = r.multiply2(inverse); + return new Array(sigma, omega); + } + this.findErrorLocations=function( errorLocator) + { + // This is a direct application of Chien's search + var numErrors = errorLocator.Degree; + if (numErrors == 1) + { + // shortcut + return new Array(errorLocator.getCoefficient(1)); + } + var result = new Array(numErrors); + var e = 0; + for (var i = 1; i < 256 && e < numErrors; i++) + { + if (errorLocator.evaluateAt(i) == 0) + { + result[e] = this.field.inverse(i); + e++; + } + } + if (e != numErrors) + { + throw "Error locator degree does not match number of roots"; + } + return result; + } + this.findErrorMagnitudes=function( errorEvaluator, errorLocations, dataMatrix) + { + // This is directly applying Forney's Formula + var s = errorLocations.length; + var result = new Array(s); + for (var i = 0; i < s; i++) + { + var xiInverse = this.field.inverse(errorLocations[i]); + var denominator = 1; + for (var j = 0; j < s; j++) + { + if (i != j) + { + denominator = this.field.multiply(denominator, GF256.addOrSubtract(1, this.field.multiply(errorLocations[j], xiInverse))); + } + } + result[i] = this.field.multiply(errorEvaluator.evaluateAt(xiInverse), this.field.inverse(denominator)); + // Thanks to sanfordsquires for this fix: + if (dataMatrix) + { + result[i] = this.field.multiply(result[i], xiInverse); + } + } + return result; + } +} \ No newline at end of file diff --git a/pos_qr_scan/static/lib/jsqrcode/version.js b/pos_qr_scan/static/lib/jsqrcode/version.js new file mode 100644 index 0000000000..4e19c7f1ae --- /dev/null +++ b/pos_qr_scan/static/lib/jsqrcode/version.js @@ -0,0 +1,261 @@ +/* + Ported to JavaScript by Lazar Laszlo 2011 + + lazarsoft@gmail.com, www.lazarsoft.info + +*/ + +/* +* +* Copyright 2007 ZXing authors +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + + +function ECB(count, dataCodewords) +{ + this.count = count; + this.dataCodewords = dataCodewords; + + this.__defineGetter__("Count", function() + { + return this.count; + }); + this.__defineGetter__("DataCodewords", function() + { + return this.dataCodewords; + }); +} + +function ECBlocks( ecCodewordsPerBlock, ecBlocks1, ecBlocks2) +{ + this.ecCodewordsPerBlock = ecCodewordsPerBlock; + if(ecBlocks2) + this.ecBlocks = new Array(ecBlocks1, ecBlocks2); + else + this.ecBlocks = new Array(ecBlocks1); + + this.__defineGetter__("ECCodewordsPerBlock", function() + { + return this.ecCodewordsPerBlock; + }); + + this.__defineGetter__("TotalECCodewords", function() + { + return this.ecCodewordsPerBlock * this.NumBlocks; + }); + + this.__defineGetter__("NumBlocks", function() + { + var total = 0; + for (var i = 0; i < this.ecBlocks.length; i++) + { + total += this.ecBlocks[i].length; + } + return total; + }); + + this.getECBlocks=function() + { + return this.ecBlocks; + } +} + +function Version( versionNumber, alignmentPatternCenters, ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4) +{ + this.versionNumber = versionNumber; + this.alignmentPatternCenters = alignmentPatternCenters; + this.ecBlocks = new Array(ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4); + + var total = 0; + var ecCodewords = ecBlocks1.ECCodewordsPerBlock; + var ecbArray = ecBlocks1.getECBlocks(); + for (var i = 0; i < ecbArray.length; i++) + { + var ecBlock = ecbArray[i]; + total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); + } + this.totalCodewords = total; + + this.__defineGetter__("VersionNumber", function() + { + return this.versionNumber; + }); + + this.__defineGetter__("AlignmentPatternCenters", function() + { + return this.alignmentPatternCenters; + }); + this.__defineGetter__("TotalCodewords", function() + { + return this.totalCodewords; + }); + this.__defineGetter__("DimensionForVersion", function() + { + return 17 + 4 * this.versionNumber; + }); + + this.buildFunctionPattern=function() + { + var dimension = this.DimensionForVersion; + var bitMatrix = new BitMatrix(dimension); + + // Top left finder pattern + separator + format + bitMatrix.setRegion(0, 0, 9, 9); + // Top right finder pattern + separator + format + bitMatrix.setRegion(dimension - 8, 0, 8, 9); + // Bottom left finder pattern + separator + format + bitMatrix.setRegion(0, dimension - 8, 9, 8); + + // Alignment patterns + var max = this.alignmentPatternCenters.length; + for (var x = 0; x < max; x++) + { + var i = this.alignmentPatternCenters[x] - 2; + for (var y = 0; y < max; y++) + { + if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) + { + // No alignment patterns near the three finder paterns + continue; + } + bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5); + } + } + + // Vertical timing pattern + bitMatrix.setRegion(6, 9, 1, dimension - 17); + // Horizontal timing pattern + bitMatrix.setRegion(9, 6, dimension - 17, 1); + + if (this.versionNumber > 6) + { + // Version info, top right + bitMatrix.setRegion(dimension - 11, 0, 3, 6); + // Version info, bottom left + bitMatrix.setRegion(0, dimension - 11, 6, 3); + } + + return bitMatrix; + } + this.getECBlocksForLevel=function( ecLevel) + { + return this.ecBlocks[ecLevel.ordinal()]; + } +} + +Version.VERSION_DECODE_INFO = new Array(0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69); + +Version.VERSIONS = buildVersions(); + +Version.getVersionForNumber=function( versionNumber) +{ + if (versionNumber < 1 || versionNumber > 40) + { + throw "ArgumentException"; + } + return Version.VERSIONS[versionNumber - 1]; +} + +Version.getProvisionalVersionForDimension=function(dimension) +{ + if (dimension % 4 != 1) + { + throw "Error getProvisionalVersionForDimension"; + } + try + { + return Version.getVersionForNumber((dimension - 17) >> 2); + } + catch ( iae) + { + throw "Error getVersionForNumber"; + } +} + +Version.decodeVersionInformation=function( versionBits) +{ + var bestDifference = 0xffffffff; + var bestVersion = 0; + for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++) + { + var targetVersion = Version.VERSION_DECODE_INFO[i]; + // Do the version info bits match exactly? done. + if (targetVersion == versionBits) + { + return this.getVersionForNumber(i + 7); + } + // Otherwise see if this is the closest to a real version info bit string + // we have seen so far + var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); + if (bitsDifference < bestDifference) + { + bestVersion = i + 7; + bestDifference = bitsDifference; + } + } + // We can tolerate up to 3 bits of error since no two version info codewords will + // differ in less than 4 bits. + if (bestDifference <= 3) + { + return this.getVersionForNumber(bestVersion); + } + // If we didn't find a close enough match, fail + return null; +} + +function buildVersions() +{ + return new Array(new Version(1, new Array(), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), + new Version(2, new Array(6, 18), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), + new Version(3, new Array(6, 22), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), + new Version(4, new Array(6, 26), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), + new Version(5, new Array(6, 30), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), + new Version(6, new Array(6, 34), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), + new Version(7, new Array(6, 22, 38), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), + new Version(8, new Array(6, 24, 42), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), + new Version(9, new Array(6, 26, 46), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), + new Version(10, new Array(6, 28, 50), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), + new Version(11, new Array(6, 30, 54), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), + new Version(12, new Array(6, 32, 58), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), + new Version(13, new Array(6, 34, 62), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), + new Version(14, new Array(6, 26, 46, 66), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), + new Version(15, new Array(6, 26, 48, 70), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), + new Version(16, new Array(6, 26, 50, 74), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), + new Version(17, new Array(6, 30, 54, 78), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), + new Version(18, new Array(6, 30, 56, 82), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), + new Version(19, new Array(6, 30, 58, 86), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), + new Version(20, new Array(6, 34, 62, 90), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), + new Version(21, new Array(6, 28, 50, 72, 94), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), + new Version(22, new Array(6, 26, 50, 74, 98), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), + new Version(23, new Array(6, 30, 54, 74, 102), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), + new Version(24, new Array(6, 28, 54, 80, 106), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), + new Version(25, new Array(6, 32, 58, 84, 110), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), + new Version(26, new Array(6, 30, 58, 86, 114), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), + new Version(27, new Array(6, 34, 62, 90, 118), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))), + new Version(28, new Array(6, 26, 50, 74, 98, 122), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), + new Version(29, new Array(6, 30, 54, 78, 102, 126), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), + new Version(30, new Array(6, 26, 52, 78, 104, 130), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), + new Version(31, new Array(6, 30, 56, 82, 108, 134), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), + new Version(32, new Array(6, 34, 60, 86, 112, 138), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), + new Version(33, new Array(6, 30, 58, 86, 114, 142), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), + new Version(34, new Array(6, 34, 62, 90, 118, 146), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), + new Version(35, new Array(6, 30, 54, 78, 102, 126, 150), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)),new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), + new Version(36, new Array(6, 24, 50, 76, 102, 128, 154), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), + new Version(37, new Array(6, 28, 54, 80, 106, 132, 158), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), + new Version(38, new Array(6, 32, 58, 84, 110, 136, 162), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), + new Version(39, new Array(6, 26, 54, 82, 110, 138, 166), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), + new Version(40, new Array(6, 30, 58, 86, 114, 142, 170), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))); +} \ No newline at end of file diff --git a/pos_qr_scan/static/src/css/pos.css b/pos_qr_scan/static/src/css/pos.css new file mode 100644 index 0000000000..48838baee0 --- /dev/null +++ b/pos_qr_scan/static/src/css/pos.css @@ -0,0 +1,51 @@ +.video_preview { + position: absolute; + height: 100%; + width: 100%; +} +.transparent_sidebar{ + position: absolute; + left: 0; + top: 0; + height: 100%; + width: 250px; +} +.transparent_sidebar .title{ + background: none !important; +} +.popup.popup-qr_scan { + height: 100% !important; + width: 100% !important; + overflow-y: hidden; + display: flex; + align-items: stretch; + justify-content: stretch; + max-width: 100% !important; + max-height: 100% !important; +} +.qr-content { + width: 100% !important; + overflow: hidden; + background: none !important; +} + +.popup.popup-qr_scan .note { + position: absolute; + color: grey; + width: 100%; + top: 15px; +} + +.sidebar { + background: #eceff1; + min-width: 250px; + max-width: 250px; + display: flex; + flex-direction: column; + justify-content: flex-start; + overflow: hidden; +} + +.fa-qrcode:before { + content: "\f029"; +} diff --git a/pos_qr_scan/static/src/description/icon.png b/pos_qr_scan/static/src/description/icon.png new file mode 100644 index 0000000000..8a058284ed Binary files /dev/null and b/pos_qr_scan/static/src/description/icon.png differ diff --git a/pos_qr_scan/static/src/js/qr_scan.js b/pos_qr_scan/static/src/js/qr_scan.js new file mode 100644 index 0000000000..d35e2df09f --- /dev/null +++ b/pos_qr_scan/static/src/js/qr_scan.js @@ -0,0 +1,188 @@ +odoo.define('pos_qr_scan', function(require){ + var exports = {}; + + var core = require('web.core'); + var gui = require('point_of_sale.gui'); + var PopupWidget = require('point_of_sale.popups'); + var screens = require('point_of_sale.screens'); + + var QrButton = screens.ActionButtonWidget.extend({ + template: 'QrButton', + button_click: function(){ + var self = this; + this.gui.show_popup('qr_scan',{ + 'title': 'QR Scanning', + 'value': false, + }); + }, + }); + + screens.define_action_button({ + 'name': 'qr_button', + 'widget': QrButton, + }); + + var QrScanPopupWidget = PopupWidget.extend({ + template: 'QrScanPopupWidget', + show: function (options) { + var self = this; + this.gUM = false; + this._super(options); + this.generate_qr_scanner(); + }, + click_cancel: function() { + this.stop_camera(); + this._super(arguments); + }, + stop_camera: function(camera){ + this.cam_is_on = false; + if (this.stream){ + this.stream.getTracks()[0].stop(); + } + }, + add_button: function(content) { + var button = document.createElement('div'); + button.className = 'button qr-content' + button.innerHTML = content.name; + button.setAttribute('camera-id', content.id); + button = $('.transparent_sidebar > .body').append(button); + return button; + }, + add_button_click: function(e) { + var button = document.createElement('div'); + active_id = e.target.getAttribute('camera-id'); + this.start_webcam({'deviceId': {'exact': active_id}}); + this.pos.db.save('active_camera_id', active_id) + return button; + }, + get_camera_by_id: function(id) { + return _.find(this.video_devices, function(cam){ + return cam.deviceId === id; + }); + }, + generate_qr_scanner: function() { + var options = false; + var self = this; + this.video_element = document.getElementById("preview"); + $(this.video_element).on('click',function(){ + self.click_cancel(); + }); + if(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices){ + this.capture_timeout = 700; + try{ + navigator.mediaDevices.enumerateDevices().then(function(devices) { + self.video_devices = _.filter(devices, function(d) { + return d.kind === 'videoinput'; + }); + _.each(self.video_devices, function(device) { + options = options || {'deviceId': {'exact':device.deviceId}}; + if(device.label.toLowerCase().search("back") > -1) { + options = {'deviceId': {'exact':device.deviceId}, 'facingMode':'environment'} ; + self.active_camera = device; + } + self.add_button({'name': device.label, id: device.deviceId}) + .off() + .on('click', function(e){ + self.add_button_click(e); + }); + }); + var active_camera_id = self.pos.db.load('active_camera_id', false); + if(active_camera_id && self.get_camera_by_id(active_camera_id)){ + options = {'deviceId': {'exact':active_camera_id}} + } + self.start_webcam(options); + }); + } + catch(e){ + alert(e); + } + } + else{ + console.log("no navigator.mediaDevices.enumerateDevices" ); + this.start_webcam(options); + } + }, + + read: function(result){ + // Trigger event on scanning and close camera window + if (this.pos.debug){ + console.log('QR scanned', result); + } + core.bus.trigger('qr_scanned', result); + posmodel.gui.popup_instances.qr_scan.click_cancel(); + }, + + start_webcam: function(options){ + var self = this; + this.initCanvas(800, 600); + qrcode.callback = function(value){ + self.read(value); + } + if(navigator.mediaDevices.getUserMedia){ + navigator.mediaDevices.getUserMedia({video: options, audio: false}). + then(function(stream){ + self.stream = stream; + self.success(stream); + }).catch(function(error){ + error(error); + }); + // dont know for what this is needed + } else if(navigator.getUserMedia){ + webkit = true; + navigator.getUserMedia({video: options, audio: false}, success, error); + } else if(navigator.webkitGetUserMedia){ + webkit = true; + navigator.webkitGetUserMedia({video:options, audio: false}, success, error); + } + + this.cam_is_on = true; + setTimeout(function(){ + self.captureToCanvas(); + }, this.capture_timeout); + }, + + success: function(stream){ + var self = this; + this.video_element.srcObject = stream; + this.video_element.play(); + this.gUM=true; + }, + captureToCanvas: function(){ + if(!this.cam_is_on) + return; + if(this.gUM){ + var self = this; + try{ + gCtx.drawImage(this.video_element,0,0); + try{ + qrcode.decode(); + } + catch(e){ + console.log(e); + setTimeout(function(){ + self.captureToCanvas(); + }, this.capture_timeout); + }; + } + catch(e){ + console.log(e); + setTimeout(function(){ + self.captureToCanvas(); + }, this.capture_timeout); + }; + } + }, + initCanvas: function(w,h){ + gCanvas = document.getElementById("qr-canvas"); + gCanvas.style.width = w + "px"; + gCanvas.style.height = h + "px"; + gCanvas.width = w; + gCanvas.height = h; + gCtx = gCanvas.getContext("2d"); + gCtx.clearRect(0, 0, w, h); + } + + }); + + gui.define_popup({name:'qr_scan', widget: QrScanPopupWidget}); +}); diff --git a/pos_qr_scan/static/src/xml/templates.xml b/pos_qr_scan/static/src/xml/templates.xml new file mode 100644 index 0000000000..3336b43602 --- /dev/null +++ b/pos_qr_scan/static/src/xml/templates.xml @@ -0,0 +1,33 @@ + + + + +
+ QR Scan +
+
+ + + + + +
diff --git a/pos_qr_scan/views/assets.xml b/pos_qr_scan/views/assets.xml new file mode 100644 index 0000000000..7ad161ac78 --- /dev/null +++ b/pos_qr_scan/views/assets.xml @@ -0,0 +1,32 @@ + + + + + + + diff --git a/pos_wechat/README.rst b/pos_wechat/README.rst new file mode 100644 index 0000000000..5f44982674 --- /dev/null +++ b/pos_wechat/README.rst @@ -0,0 +1,51 @@ +======================== + WeChat Payments in POS +======================== + +Payment the workflow is as following: + +* Cashier creates order and scan user's QR in user's WeChat mobile app +* User's receives order information and authorise fund transferring +* Cashier gets payment confirmation in POS + +Debugging +========= + +If you don't have camera, you can executing following code in browser console to simulate scanning:: + + odoo.__DEBUG__.services['web.core'].bus.trigger('qr_scanned', '134579302432164181'); + + +Credits +======= + +Contributors +------------ +* `Kolushov Alexandr `__ + +Sponsors +-------- +* `IT-Projects LLC `__ + +Maintainers +----------- +* `IT-Projects LLC `__ + + To get a guaranteed support you are kindly requested to purchase the module at `odoo apps store `__. + + Thank you for understanding! + + `IT-Projects Team `__ + +Further information +=================== + +Demo: http://runbot.it-projects.info/demo/pos_addons/11.0 + +HTML Description: https://apps.odoo.com/apps/modules/11.0/pos_payment_wechat/ + +Usage instructions: ``_ + +Changelog: ``_ + +Tested on Odoo 11.0 ee2b9fae3519c2494f34dacf15d0a3b5bd8fbd06 diff --git a/pos_wechat/__init__.py b/pos_wechat/__init__.py new file mode 100644 index 0000000000..92325983cf --- /dev/null +++ b/pos_wechat/__init__.py @@ -0,0 +1,2 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from . import models diff --git a/pos_wechat/__manifest__.py b/pos_wechat/__manifest__.py new file mode 100644 index 0000000000..3cc97d8fdb --- /dev/null +++ b/pos_wechat/__manifest__.py @@ -0,0 +1,35 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +{ + "name": """WeChat Payments in POS""", + "summary": """Support payment by scanning user's QR""", + "category": "Point of Sale", + # "live_test_url": "", + "images": [], + "version": "1.0.0", + "application": False, + + "author": "IT-Projects LLC, Kolushov Alexandr", + "support": "apps@it-projects.info", + "website": "https://it-projects.info/team/KolushovAlexandr", + "license": "LGPL-3", + # "price": 9.00, + # "currency": "EUR", + + "depends": [ + "wechat", + "pos_qr_scan", + "pos_longpolling", + ], + "external_dependencies": {"python": [], "bin": []}, + "data": [ + "views/assets.xml", + "data/account_journal_data.xml", + ], + "demo": [ + ], + "qweb": [], + + "auto_install": False, + "installable": True, +} diff --git a/pos_wechat/data/account_journal_data.xml b/pos_wechat/data/account_journal_data.xml new file mode 100644 index 0000000000..2311113834 --- /dev/null +++ b/pos_wechat/data/account_journal_data.xml @@ -0,0 +1,12 @@ + + + + + WeChat Payments + + WECHAT + bank + + + diff --git a/pos_wechat/doc/changelog.rst b/pos_wechat/doc/changelog.rst new file mode 100644 index 0000000000..9ee2b48b8e --- /dev/null +++ b/pos_wechat/doc/changelog.rst @@ -0,0 +1,4 @@ +`1.0.0` +------- + +- Init version diff --git a/pos_wechat/doc/index.rst b/pos_wechat/doc/index.rst new file mode 100644 index 0000000000..a135229384 --- /dev/null +++ b/pos_wechat/doc/index.rst @@ -0,0 +1,27 @@ +======================== + WeChat Payments in POS +======================== + + +Follow instructions of `WeChat API `__ module. + +Installation +============ + +* `Install `__ this module in a usual way + +Configuration +============= + +TODO + +Usage +===== + +* Start POS +* Create some Order +* Click ``[Scan QR Code]`` +* Ask customer to prepare QR in WeChat app +* Scan the QR +* Wait until customer authorise the payment in his WeChat app +* RESULT: Payment is proceeded. Use your WeChat Seller control panel to see balance update. diff --git a/pos_wechat/models/__init__.py b/pos_wechat/models/__init__.py new file mode 100644 index 0000000000..2895ff2d1c --- /dev/null +++ b/pos_wechat/models/__init__.py @@ -0,0 +1,3 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from . import wechat_micropay +from . import account_journal diff --git a/pos_wechat/models/account_journal.py b/pos_wechat/models/account_journal.py new file mode 100644 index 0000000000..fc0672d044 --- /dev/null +++ b/pos_wechat/models/account_journal.py @@ -0,0 +1,9 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from odoo import models, fields + + +class Journal(models.Model): + _inherit = 'account.journal' + + wechat = fields.Boolean('WeChat Payment', help='Register for WeChat payment') diff --git a/pos_wechat/models/wechat_micropay.py b/pos_wechat/models/wechat_micropay.py new file mode 100644 index 0000000000..6bef6b491f --- /dev/null +++ b/pos_wechat/models/wechat_micropay.py @@ -0,0 +1,61 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +import logging +import json + +from odoo import models, fields, api +from odoo.addons.wechat.tools import odoo_async_call + +_logger = logging.getLogger(__name__) +CHANNEL_MICROPAY = 'micropay' + + +class Micropay(models.Model): + + _inherit = 'wechat.micropay' + pos_id = fields.Many2one('pos.config') + + @api.model + def _prepare_pos_create_from_qr(self, **kwargs): + body = self._body(kwargs['terminal_ref']) + create_vals = { + 'pos_id': kwargs['pos_id'], + } + kwargs.update(create_vals=create_vals) + args = (body,) + return args, kwargs + + @api.model + def pos_create_from_qr_sync(self, **kwargs): + args, kwargs = self._prepare_pos_create_from_qr(**kwargs) + record = self.create_from_qr(*args, **kwargs) + return self._process_pos_create_from_qr(record) + + @api.model + def pos_create_from_qr(self, **kwargs): + """Async method. Result is sent via longpolling""" + args, kwargs = self._prepare_pos_create_from_qr(**kwargs) + odoo_async_call(self.create_from_qr, args, kwargs, + callback=self._send_pos_notification) + return 'ok' + + @api.model + def _process_pos_create_from_qr(self, record): + result_json = json.loads(record.result_raw) + msg = { + 'event': 'payment_result', + 'result_code': result_json['result_code'], + 'order_ref': record.order_ref, + 'total_fee': record.total_fee, + } + return msg + + @api.model + def _send_pos_notification(self, record): + msg = self._process_pos_create_from_qr(record) + self.env['pos.config']._send_to_channel_by_id( + self._cr.dbname, + record.pos_id.id, + CHANNEL_MICROPAY, + msg, + ) diff --git a/pos_wechat/static/description/icon.png b/pos_wechat/static/description/icon.png new file mode 100644 index 0000000000..8a058284ed Binary files /dev/null and b/pos_wechat/static/description/icon.png differ diff --git a/pos_wechat/static/src/js/tour.js b/pos_wechat/static/src/js/tour.js new file mode 100644 index 0000000000..4cf7ec3121 --- /dev/null +++ b/pos_wechat/static/src/js/tour.js @@ -0,0 +1,67 @@ +/*- Copyright 2018 Ivan Yelizariev + License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). */ +/* This file is not used until we make a CI tool, that can run it. Normal CI cannot use longpolling. + See https://github.com/odoo/odoo/commit/673f4aa4a77161dc58e0e1bf97e8f713b1e88491 + */ +odoo.define('pos_wechat.tour', function (require) { + "use strict"; + + var DUMMY_AUTH_CODE = '134579302432164181'; + var tour = require("web_tour.tour"); + var core = require('web.core'); + var _t = core._t; + + function open_pos_neworder() { + return [{ + trigger: '.o_app[data-menu-xmlid="point_of_sale.menu_point_root"], .oe_menu_toggler[data-menu-xmlid="point_of_sale.menu_point_root"]', + content: _t("Ready to launch your point of sale? Click here."), + position: 'bottom', + }, { + trigger: ".o_pos_kanban button.oe_kanban_action_button", + content: _t("

Click to start the point of sale interface. It runs on tablets, laptops, or industrial hardware.

Once the session launched, the system continues to run without an internet connection.

"), + position: "bottom" + }, { + content: "Switch to table or make dummy action", + trigger: '.table:not(.oe_invisible .neworder-button), .order-button.selected', + position: "bottom" + }, { + content: 'waiting for loading to finish', + trigger: '.order-button.neworder-button', + }]; + } + + function add_product_to_order(product_name) { + return [{ + content: 'buy ' + product_name, + trigger: '.product-list .product-name:contains("' + product_name + '")', + }, { + content: 'the ' + product_name + ' have been added to the order', + trigger: '.order .product-name:contains("' + product_name + '")', + }]; + } + + var steps = []; + steps = steps.concat(open_pos_neworder()); + steps = steps.concat(add_product_to_order('Miscellaneous')); + // simulate qr scanning + steps = steps.concat([{ + content: "Make dummy action and trigger scanning event", + trigger: '.order-button.selected', + run: function(){ + core.bus.trigger('qr_scanned', DUMMY_AUTH_CODE); + } + }]); + // wait until order is proceeded + steps = steps.concat([{ + content: "Screen is changed to payment screen", + trigger: '.button_next', + run: function(){ + // no need to click on the button + } + },{ + content: "Screen is changed to receipt or products screen (depends on settings)", + trigger: '.button_print,.order-button', + }]); + tour.register('tour_pos_debt_notebook', { test: true, url: '/web' }, steps); + +}); diff --git a/pos_wechat/static/src/js/wechat_pay.js b/pos_wechat/static/src/js/wechat_pay.js new file mode 100644 index 0000000000..6561b6652f --- /dev/null +++ b/pos_wechat/static/src/js/wechat_pay.js @@ -0,0 +1,189 @@ +odoo.define('pos_payment_wechat', function(require){ + "use strict"; + + var rpc = require('web.rpc'); + var core = require('web.core'); + var models = require('point_of_sale.models'); + var screens = require('point_of_sale.screens'); + var gui = require('point_of_sale.gui'); + var session = require('web.session'); + + var _t = core._t; + + models.load_fields('account.journal', ['wechat']); + + gui.Gui.prototype.screen_classes.filter(function(el) { return el.name == 'payment'})[0].widget.include({ + init: function(parent, options) { + this._super(parent, options); + this.pos.bind('validate_order',function(){ + this.validate_order(); + },this); + } + }); + + + + var PosModelSuper = models.PosModel; + models.PosModel = models.PosModel.extend({ + initialize: function(){ + var self = this; + PosModelSuper.prototype.initialize.apply(this, arguments); + this.wechat = new Wechat(this); + + this.bus.add_channel_callback( + "micropay", + this.on_micropay, + this); + this.ready.then(function(){ + // take out wechat cashregister from cashregisters to avoid + // rendering in payment screent + var wechat_journal = _.filter(self.journals, function(r){ + return r.wechat; + }); + if (wechat_journal.length){ + if (wechat_journal.length > 1){ + // TODO warning + console.log('error', 'More than one wechat journals found'); + } + wechat_journal = wechat_journal[0]; + } else { + return; + } + self.wechat_cashregister = _.filter(self.cashregisters, function(r){ + return r.journal_id[0] == wechat_journal.id; + })[0]; + self.cashregisters = _.filter(self.cashregisters, function(r){ + return r.journal_id[0] != wechat_journal.id; + }); + }); + + }, + scan_product: function(parsed_code){ + // TODO: do we need to make this optional? + var value = parsed_code.code; + if (this.wechat.check_auth_code(value)){ + this.wechat.process_qr(value); + return true; + } + return PosModelSuper.prototype.scan_product.apply(this, arguments); + }, + on_micropay: function(msg){ + var order = this.get('orders').find(function(item){ + return item.uid === msg.order_ref; + }); + if (order){ + if (parseInt(100*order.get_total_with_tax()) == msg['total_fee']){ + // order is paid and has to be closed + + // add payment + var newPaymentline = new models.Paymentline({},{ + order: order, + micropay_id: msg['micropay_id'], + cashregister: this.wechat_cashregister, + pos: this}); + newPaymentline.set_amount( msg['total_fee'] / 100.0 ); + order.paymentlines.add(newPaymentline); + + // validate order + this.trigger('validate_order'); + } else { + // order was changed before payment result is recieved + // TODO + } + } else { + consoler.log('error', 'Order is not found'); + } + }, + }); + + + var OrderSuper = models.Order; + models.Order = models.Order.extend({ + }); + + var PaymentlineSuper = models.Paymentline; + models.Paymentline = models.Paymentline.extend({ + initialize: function(attributes, options){ + PaymentlineSuper.prototype.initialize.apply(this, arguments); + this.micropay_id = options.micropay_id; + }, + // TODO: do we need to extend init_from_JSON too ? + export_as_JSON: function(){ + var res = PaymentlineSuper.prototype.export_as_JSON.apply(this, arguments); + res['micropay_id'] = this.micropay_id; + return res; + }, + }); + + var Wechat = Backbone.Model.extend({ + initialize: function(pos){ + var self = this; + this.pos = pos; + core.bus.on('qr_scanned', this, function(value){ + if (self.check_auth_code(value)){ + self.process_qr(value); + } + }); + }, + check_auth_code: function(code) { + // TODO: do we need to integrate this with barcode.nomenclature? + if (code && Number.isInteger(+code) && + code.length === 18 && + +code[0] === 1 && (+code[1] >= 0 && +code[1] <= 5)) { + return true; + } + return false; + }, + process_qr: function(auth_code){ + var order = this.pos.get_order(); + if (!order){ + return; + } + // TODO: block order for editing + this.micropay(auth_code, order); + }, + micropay: function(auth_code, order){ + /* send request asynchronously */ + var self = this; + + // total_fee is amount of cents + var total_fee = parseInt(100 * order.get_total_with_tax()); + + var terminal_ref = 'POS/' + self.pos.config.name; + var pos_id = self.pos.config.id; + + var send_it = function () { + return rpc.query({ + model: 'wechat.micropay', + method: 'pos_create_from_qr', + kwargs: { + 'auth_code': auth_code, + 'total_fee': total_fee, + 'order_ref': order.uid, + 'terminal_ref': terminal_ref, + 'pos_id': pos_id, + }, + }) + }; + + var current_send_number = 0; + return send_it().fail(function (error, e) { + if (self.pos.debug){ + console.log('Wechat', self.pos.config.name, 'failed request #'+current_send_number+':', error.message); + } + self.show_warning(); + }); + }, + warning: function(warning_message){ + console.info('warning', warning_message); + this.pos.chrome.gui.show_popup('error',{ + 'title': _t('Warning'), + 'body': warning_message, + }); + }, + show_warning: function(){ + var warning_message = _t("Some problems have happened. TEST"); + this.warning(warning_message); + } + }); +}); diff --git a/pos_wechat/tests/__init__.py b/pos_wechat/tests/__init__.py new file mode 100644 index 0000000000..e00c3113fa --- /dev/null +++ b/pos_wechat/tests/__init__.py @@ -0,0 +1,2 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from . import test_micropay diff --git a/pos_wechat/tests/test_micropay.py b/pos_wechat/tests/test_micropay.py new file mode 100644 index 0000000000..482b9064cd --- /dev/null +++ b/pos_wechat/tests/test_micropay.py @@ -0,0 +1,91 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +import logging +import json +try: + from unittest.mock import patch +except ImportError: + from mock import patch + +from odoo.tests.common import HttpCase, HOST, PORT, get_db_name +from odoo import api, SUPERUSER_ID +from odoo.addons.bus.models.bus import dispatch + +from ..models.wechat_micropay import CHANNEL_MICROPAY + + +_logger = logging.getLogger(__name__) +DUMMY_AUTH_CODE = '134579302432164181' +DUMMY_POS_ID = 1 + + +# TODO clean this up: no need to use HttpCase. Also some helpers are not used. +class TestMicropay(HttpCase): + at_install = True + post_install = True + + def setUp(self): + super(TestMicropay, self).setUp() + self.phantom_env = api.Environment(self.registry.test_cr, self.uid, {}) + + # patch wechat + patcher = patch('wechatpy.pay.base.BaseWeChatPayAPI._post', wraps=self._post) + patcher.start() + self.addCleanup(patcher.stop) + + def xmlrpc(self, model, method, args, kwargs=None, login=SUPERUSER_ID, password='admin'): + db_name = get_db_name() + return self.xmlrpc_object.execute_kw(db_name, login, password, model, method, args, kwargs) + + def url_open_json(self, url, data=None, timeout=10): + headers = { + 'Content-Type': 'application/json' + } + res = self.url_open_extra(url, data=data, timeout=timeout, headers=headers) + return res.json() + + def url_open_extra(self, url, data=None, timeout=10, headers=None): + if url.startswith('/'): + url = "http://%s:%s%s" % (HOST, PORT, url) + if data: + return self.opener.post(url, data=data, timeout=timeout, headers=headers) + return self.opener.get(url, timeout=timeout, headers=headers) + + def _post(self, url, data): + MICROPAY_URL = 'pay/micropay' + self.assertEqual(url, MICROPAY_URL) + _logger.debug("Request data for %s: %s", MICROPAY_URL, data) + + # see wechatpy/client/base.py::_handle_result for expected result + # format and tricks that are applied on original _post method + result = { + 'return_code': 'SUCCESS', + 'result_code': 'SUCCESS', + 'openid': '123', + 'total_fee': 123, + } + return result + + def test_micropay_backend(self): + """Test payment workflow from server side. + + * Cashier scanned buyer's QR and upload it to odoo server, + odoo server sends information to wechat servers and wait for response with result. + + * Once user authorize the payment, odoo receives result syncroniosly from + previously sent request. + + * Odoo sends result to POS via longpolling. + + Due to limititation of testing framework, we use syncronios call for testing + + """ + + # make request with scanned qr code (auth_code) + msg = self.env['wechat.micropay'].pos_create_from_qr_sync(**{ + 'auth_code': DUMMY_AUTH_CODE, + 'terminal_ref': 'POS/%s' % DUMMY_POS_ID, + 'pos_id': DUMMY_POS_ID, + 'total_fee': 100, + }) + self.assertEqual(msg.get('result_code'), 'SUCCESS', "Wrong result_code. The patch doesn't work?") diff --git a/pos_wechat/views/assets.xml b/pos_wechat/views/assets.xml new file mode 100644 index 0000000000..8294eaeeab --- /dev/null +++ b/pos_wechat/views/assets.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/wechat/README.rst b/wechat/README.rst new file mode 100644 index 0000000000..d6e895deaa --- /dev/null +++ b/wechat/README.rst @@ -0,0 +1,88 @@ +============ + WeChat API +============ + +Basic tools to integrate Odoo and WeChat. + +.. contents:: + :local: + +Payment methods +=============== + +Quick Pay (micropay) +-------------------- + +Buyer presents the pay code, Vendor scans the code to finish the transaction. + +Native Payment (QR Code Payment) +-------------------------------- + +The Vendor gets one-time url and shows it to Buyer as a QR Code, Buyer scans to finish the transaction. + +Official Account Payment +------------------------ + +There are two types of usage: + +* **In-App Web-based Payment** -- The Payer opens the Vendor's HTML5 pages on their WeChat and calls the WeChat payment module via the JSAPI interface to pay their transaction. Client side of this process (i.e. web pages) is not supported. While it could be implemented as additional module, we recommend to develop *Mini programs* instead. +* **Mini program** -- an application as a part of WeChat App is created via *WeChat Developer tools*. + +In-App Payment +-------------- + +This payment way is only for native mobile application. This module provides server part of the process. + +WeChat Documentation & tools +============================ + +Sandbox & Debugging +------------------- + +* API Debug Console https://open.wechat.com/cgi-bin/newreadtemplate?t=overseas_open/docs/oa/basic-info/debug-console +* Creating Test Accounts https://admin.wechat.com/debug/cgi-bin/sandbox?t=sandbox/login + + * Note: it may not work from non-chinese IP addresses + * You will get ``appid`` and ``appsecret`` values + * To work with WeChat payments you also need Merchant ID, which this sandbox + doesn't provide. It seems, that to work with Payments you need a real + account and use *sandbox* mode (*System Parameter ``wechat.sandbox``). + +Payments +-------- + +* https://pay.weixin.qq.com/wechatpay_guide/help_docs.shtml + +Debugging +========= + +To debug UI, create *System Parameter* ``wechat.local_sandbox`` with value ``1``. All requests to wechat will return fake result without making a request. + +Credits +======= + +Contributors +------------ +* `Kolushov Alexandr `__ +* `Ivan Yelizariev `__ + +Sponsors +-------- +* `IT-Projects LLC `__ + +Maintainers +----------- +* `IT-Projects LLC `__ + +Further information +=================== + +Demo: http://runbot.it-projects.info/demo/misc-addons/11.0 + +HTML Description: https://apps.odoo.com/apps/modules/11.0/wechat/ + +Usage instructions: ``_ + +Changelog: ``_ + +Tested on Odoo 11.0 ee2b9fae3519c2494f34dacf15d0a3b5bd8fbd06 diff --git a/wechat/__init__.py b/wechat/__init__.py new file mode 100644 index 0000000000..d24ab0581e --- /dev/null +++ b/wechat/__init__.py @@ -0,0 +1,4 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from . import models +from . import controllers +from . import tools diff --git a/wechat/__manifest__.py b/wechat/__manifest__.py new file mode 100644 index 0000000000..3777cd12f8 --- /dev/null +++ b/wechat/__manifest__.py @@ -0,0 +1,32 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +{ + "name": """WeChat API""", + "summary": """Technical module to intergrate odoo with WeChat""", + "category": "Hidden", + # "live_test_url": "", + "images": [], + "version": "1.0.0", + "application": False, + + "author": "IT-Projects LLC, KolushovAlexandr, Ivan Yelizariev", + "support": "apps@it-projects.info", + "website": "https://it-projects.info/team/KolushovAlexandr", + "license": "LGPL-3", + # "price": 9.00, + # "currency": "EUR", + + "depends": [ + 'product', + ], + "external_dependencies": {"python": [ + 'wechatpy', + ], "bin": []}, + "data": [ + "views/wechat_micropay_views.xml", + ], + "qweb": [], + + "auto_install": False, + "installable": True, +} diff --git a/wechat/controllers/__init__.py b/wechat/controllers/__init__.py new file mode 100644 index 0000000000..2051799182 --- /dev/null +++ b/wechat/controllers/__init__.py @@ -0,0 +1 @@ +from . import wechat_controllers diff --git a/wechat/controllers/wechat_controllers.py b/wechat/controllers/wechat_controllers.py new file mode 100644 index 0000000000..add42d5914 --- /dev/null +++ b/wechat/controllers/wechat_controllers.py @@ -0,0 +1,17 @@ +from __future__ import absolute_import, unicode_literals +import odoo +from odoo import http +from odoo.http import request +from wechatpy import parse_message, create_reply +from wechatpy.utils import check_signature +from wechatpy.exceptions import ( + InvalidSignatureException, + InvalidAppIdException, +) + + +class WechatController(odoo.http.Controller): + + @http.route('/wechat/callback', methods=['POST'], auth='user', type='json') + def micropay(self, **kwargs): + request.env['wechat.order'].on_notification(kwargs) diff --git a/wechat/doc/changelog.rst b/wechat/doc/changelog.rst new file mode 100644 index 0000000000..9ee2b48b8e --- /dev/null +++ b/wechat/doc/changelog.rst @@ -0,0 +1,4 @@ +`1.0.0` +------- + +- Init version diff --git a/wechat/doc/index.rst b/wechat/doc/index.rst new file mode 100644 index 0000000000..a3aebe2f98 --- /dev/null +++ b/wechat/doc/index.rst @@ -0,0 +1,35 @@ +============ + WeChat API +============ + +.. contents:: + :local: + +Installation +============ + +* Install `wechatpy library`__:: + + pip install wechatpy + pip install wechatpy[cryptography] + + # to update existing installation use + pip install -U wechatpy + +WeChat APP +========== + +TODO + +Configuration +============= + +* `Activate Developer Mode `__ +* Open menu ``[[ Settings ]] >> Parameters >> System Parameters`` +* Create following parameters + + * ``wechat.app_id`` + * ``wechat.app_secret`` + * ``wechat.mch_id`` -- *Vendor ID* + * ``wechat.sub_mch_id`` -- *Sub Vendor ID* + * ``wechat.sandbox`` -- set to ``0`` or delete to disable. Any other value to means that sandbox is activated. diff --git a/wechat/models/__init__.py b/wechat/models/__init__.py new file mode 100644 index 0000000000..251404f5a9 --- /dev/null +++ b/wechat/models/__init__.py @@ -0,0 +1,4 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from . import wechat_micropay +from . import wechat_order +from . import ir_config_parameter diff --git a/wechat/models/ir_config_parameter.py b/wechat/models/ir_config_parameter.py new file mode 100644 index 0000000000..476f35142d --- /dev/null +++ b/wechat/models/ir_config_parameter.py @@ -0,0 +1,44 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +import logging +from wechatpy import WeChatPay + +_logger = logging.getLogger(__name__) + +from odoo import models, fields, api + + +class Param(models.Model): + + _inherit = 'ir.config_parameter' + + @api.model + def get_wechat_pay_object(self): + sandbox = self.get_param('wechat.sandbox', '0') != '0', + if sandbox: + _logger.info('Sandbox Mode is used for WeChat API') + + print ('ARGS', ( + self.get_param('wechat.app_id'), + self.get_param('wechat.app_secret'), + self.get_param('wechat.mch_id'), + sandbox, + self.get_param('wechat.sub_mch_id'), + # TODO rest args + # self.sub_mch_id = sub_mch_id + # self.mch_cert = mch_cert + # self.mch_key = mch_key + # self.timeout = timeout + )) + return WeChatPay( + self.get_param('wechat.app_id'), + self.get_param('wechat.app_secret'), + self.get_param('wechat.mch_id'), + sandbox=sandbox, + sub_mch_id=self.get_param('wechat.sub_mch_id'), + # TODO rest args + # self.sub_mch_id = sub_mch_id + # self.mch_cert = mch_cert + # self.mch_key = mch_key + # self.timeout = timeout + ) diff --git a/wechat/models/wechat_micropay.py b/wechat/models/wechat_micropay.py new file mode 100644 index 0000000000..7a86e2c54f --- /dev/null +++ b/wechat/models/wechat_micropay.py @@ -0,0 +1,66 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +import logging +import json + +from odoo import models, fields, api + +_logger = logging.getLogger(__name__) + + +class Micropay(models.Model): + + _name = 'wechat.micropay' + _rec_name = 'order_ref' + + order_ref = fields.Char('Order Reference', readonly=True) + terminal_ref = fields.Char('Terminal Reference', help='e.g. POS Name', readonly=True) + total_fee = fields.Integer('Total Fee', help='Amount in cents', readonly=True) + debug = fields.Boolean('Sandbox', help="Payment was not made. It's only for testing purposes", readonly=True) + result_raw = fields.Text('Raw result', readonly=True) + + @api.model + def _body(self, terminal_ref, **kwargs): + return "%s - Products" % terminal_ref + + @api.model + def create_from_qr(self, body, auth_code, total_fee, terminal_ref=None, create_vals=None, order_ref=None, **kwargs): + """ + :param product_category: is used to prepare "body" + :param total_fee: Specifies the total order amount. The units are expressed in cents as integers. + :param create_vals: extra args to pass on record creation + """ + debug = self.env['ir.config_parameter'].get_param('wechat.local_sandbox') == '1' + if debug: + _logger.info('SANDBOX is activated. Request to wechat servers are not sending') + # Dummy Data. Change it to try different scenarios + result_json = { + 'return_code': 'SUCCESS', + 'result_code': 'SUCCESS', + 'openid': '123', + 'total_fee': total_fee, + 'order_ref': order_ref, + } + if self.env.context.get('debug_micropay_response'): + result_json = self.env.context.get('debug_micropay_response') + else: + wpay = self.env['ir.config_parameter'].get_wechat_pay_object() + result_json = wpay.micropay.create( + body, + total_fee, + auth_code, + ) + + result_raw = json.dumps(result_json) + _logger.debug('result_raw: %s', result_raw) + vals = { + 'terminal_ref': terminal_ref, + 'order_ref': order_ref, + 'result_raw': result_raw, + 'total_fee': result_json['total_fee'], + 'debug': debug, + } + if create_vals: + vals.update(create_vals) + record = self.create(vals) + return record diff --git a/wechat/models/wechat_order.py b/wechat/models/wechat_order.py new file mode 100644 index 0000000000..7c8edf4d7f --- /dev/null +++ b/wechat/models/wechat_order.py @@ -0,0 +1,216 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +import logging +import json + +from odoo import models, fields, api +from odoo.http import request + +_logger = logging.getLogger(__name__) +PAYMENT_RESULT_NOTIFICATION_URL = 'wechat/callback' +SUCCESS = 'SUCCESS' + + +class WeChatOrder(models.Model): + """Records with order information and payment status. + + Can be used for different types of Payments. See description of trade_type field. """ + + _name = 'wechat.order' + _description = 'Unified Order' + _rec_name = 'order_ref' + + trade_type = fields.Selection([ + ('JSAPI', 'Official Account Payment (Mini Program)'), + ('NATIVE', 'Native Payment'), + ('APP', 'In-App Payment'), + ], help=""" +* Official Account Payment -- Mini Program Payment or In-App Web-based Payment +* Native Payment -- Customer scans QR for specific order and confirm payment +* In-App Payment -- payments in native mobile applications + """) + + order_ref = fields.Char('Order Reference', readonly=True) + total_fee = fields.Integer('Total Fee', help='Amount in cents', readonly=True) + state = fields.Selection([ + ('draft', 'Unpaid'), + ('done', 'Paid'), + ('error', 'Error'), + ], string='State', default='draft') + # terminal_ref = fields.Char('Terminal Reference', help='e.g. POS Name', readonly=True) + debug = fields.Boolean('Sandbox', help="Payment was not made. It's only for testing purposes", readonly=True) + order_details_raw = fields.Text('Raw Order', readonly=True) + result_raw = fields.Text('Raw result', readonly=True) + notification_result_raw = fields.Text('Raw Notification result', readonly=True) + currency_id = fields.Many2one('res.currency', default=lambda self: self.env.user.company_id.currency_id) + notification_received = fields.Boolean(help='Set to true on receiving notifcation to avoid repeated processing', default=False) + line_ids = fields.One2many('wechat.order.line', 'order_id') + + def _body(self): + """ Example of result: + + {"goods_detail": [ + { + "goods_id": "iphone6s_16G", + "wxpay_goods_id": "100 1", + "goods_name": "iPhone 6s 16G", + "goods_num": 1, + "price": 100, + "goods_category": "123456", + "body": "苹果手机", + }, + { + "goods_id": "iphone6s_3 2G", + "wxpay_goods_id": "100 2", + "goods_name": "iPhone 6s 32G", + "quantity": 1, + "price": 200, + "goods_category": "123789", + } + ]}""" + self.ensure_one() + rendered_lines = [{ + 'goods_id': str(line.product_id.id), + 'wxpay_goods_id': line.wxpay_goods_ID, + 'goods_name': line.name or line.product_id.name, + 'goods_num': line.quantity, + 'price': line.get_fee(), + 'goods_category': line.category, + } for line in self.line_ids] + body = {'goods_detail': rendered_lines} + + return body + + def _total_fee(self): + self.ensure_one() + total_fee = sum([ + line.get_fee() + for line in self.line_ids]) + return total_fee + + def _notify_url(self): + url = self.env['ir.config_parameter'].get_param('wechat.payment_result_notification_url') + if url: + return url + # Try to compute url automatically + try: + scheme = request.httprequest.scheme + except: + scheme = 'http' + + domain = self.env["ir.config_parameter"].get_param('web.base.url') + return "{scheme}://domain/{path}".format( + scheme=scheme, + domain=domain, + path=PAYMENT_RESULT_NOTIFICATION_URL, + ) + + @api.model + def create_qr(self, lines, total_fee, create_vals=None, **kwargs): + """Native Payment + + :param lines: list of dictionary + :param total_fee: amount in cents + """ + debug = self.env['ir.config_parameter'].get_param('wechat.local_sandbox') == '1' + vals = { + 'trade_type': 'NATIVE', + 'line_ids': [(0, 0, data) for data in lines], + 'debug': debug, + } + if create_vals: + vals.update(create_vals) + order = self.create(vals) + total_fee = order._total_fee() + if debug: + _logger.info('SANDBOX is activated. Request to wechat servers is not sending') + # Dummy Data. Change it to try different scenarios + result_json = { + 'return_code': 'SUCCESS', + 'result_code': 'SUCCESS', + 'openid': '123', + 'total_fee': total_fee, + 'order_ref': order_ref, + } + if self.env.context.get('debug_wechat_order_response'): + result_json = self.env.context.get('debug_wechat_order_response') + else: + body = order._body() + wpay = self.env['ir.config_parameter'].get_wechat_pay_object() + # TODO: we probably have make cr.commit() before making request to + # be sure that we save data before sending request to avoid + # situation when order is sent to wechat server, but was not saved + # in our server for any reason + result_json = wpay.order.create( + 'NATIVE', + total_fee, + body, + total_fee, + self._notify_url(), + out_trade_no=order.id, + # TODO fee_type=record.currency_id.name + ) + + result_raw = json.dumps(result_json) + _logger.debug('result_raw: %s', result_raw) + vals = { + 'result_raw': result_raw, + 'total_fee': total_fee, + } + order.write(vals) + code_url = result_json['code_url'] + return order, code_url + + def on_notification(self, data): + """ + return True if notification changed order + """ + # check signature + wpay = self.env['ir.config_parameter'].get_wechat_pay_object() + if not wpay.check_signature(data): + _logger.warning("Notification Signature is not valid:\n", data) + return False + + order_id = data.get('out_trade_no') + order = None + if order_id: + order = self.browse(order_id) + if not order: + _logger.warning("Order %s from notification is not found", order_id) + return False + + # check for duplicates + if order.notification_received: + _logger.warning("Notifcation duplicate is received: %s", order) + return False + + vals = { + 'notification_result_raw': json.dumps(data), + 'notification_received': True, + } + if not (data['return_code'] == SUCCESS and data['result_code'] == SUCCESS): + vals['state'] = 'error' + + else: + vals['state'] = 'done' + + order.write(vals) + return True + + +class WeChatOrderLine(models.Model): + _name = 'wechat.order.line' + + name = fields.Char('Name', help="When empty, product's name is used") + description = fields.Char('Body') + product_id = fields.Many2one('product.product', required=True) + wxpay_goods_ID = fields.Char('Wechat Good ID') + price = fields.Monetary('Price', required=True, help='Price in currency units (not cents)') + currency_id = fields.Many2one('res.currency', related='order_id') + quantity = fields.Char('Quantity', default=1) + category = fields.Char('Category') + order_id = fields.Many2one('wechat.order') + + def get_fee(self): + self.ensure_one() + return int(100*(self.price or self.product_id.price)) diff --git a/wechat/tests/__init__.py b/wechat/tests/__init__.py new file mode 100644 index 0000000000..e3a260c6aa --- /dev/null +++ b/wechat/tests/__init__.py @@ -0,0 +1,3 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from . import test_wechat_order + diff --git a/wechat/tests/test_wechat_order.py b/wechat/tests/test_wechat_order.py new file mode 100644 index 0000000000..a4a075dbd7 --- /dev/null +++ b/wechat/tests/test_wechat_order.py @@ -0,0 +1,104 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +import logging +try: + from unittest.mock import patch +except ImportError: + from mock import patch +from odoo.tests.common import TransactionCase + + +_logger = logging.getLogger(__name__) + + +class TestWeChatOrder(TransactionCase): + at_install = True + post_install = True + + def setUp(self): + super(TestWeChatOrder, self).setUp() + self.Order = self.env['wechat.order'] + self.product1 = self.env['product.product'].create({ + 'name': 'Product1', + }) + self.product2 = self.env['product.product'].create({ + 'name': 'Product2', + }) + + patcher = patch('wechatpy.WeChatPay.check_signature', wraps=lambda *args: True) + patcher.start() + self.addCleanup(patcher.stop) + + self.lines = [ + { + "product_id": self.product1.id, + "name": "Product 1 Name", + "quantity": 1, + "price": 1, + "category": "123456", + "description": "翻译服务器错误", + }, + { + "product_id": self.product2.id, + "name": "Product 2 Name", + "quantity": 1, + "price": 2, + "category": "123456", + "description": "網路白目哈哈", + } + ] + + + def _patch_post(self, post_result): + + def post(url, data): + self.assertIn(url, post_result) + _logger.debug("Request data for %s: %s", url, data) + return post_result[url] + + # patch wechat + patcher = patch('wechatpy.pay.base.BaseWeChatPayAPI._post', wraps=post) + patcher.start() + self.addCleanup(patcher.stop) + + def _create_order(self): + post_result = { + 'pay/unifiedorder': { + 'code_url': 'weixin://wxpay/s/An4baqw', + 'trade_type': 'NATIVE', + } + } + self._patch_post(post_result) + order, code_url = self.Order.create_qr(self.lines, 300) + self.assertEqual(order.state, 'draft', 'Just created order has wrong state') + return order + + def test_native_payment(self): + + order = self._create_order() + + # simulate notification + notification = { + 'return_code': 'SUCCESS', + 'result_code': 'SUCCESS', + 'out_trade_no': order.id, + } + handled = self.Order.on_notification(notification) + self.assertTrue(handled, 'Notification was not handled (error in checking for duplicates?)') + self.assertEqual(order.state, 'done', "Order's state is not changed after notification about update") + + def test_notification_duplicates(self): + order = self._create_order() + + # simulate notification with failing request + notification = { + 'return_code': 'SUCCESS', + 'result_code': 'FAIL', + 'error_code': 'SYSTEMERR', + # 'transaction_id': '121775250120121775250120', + 'out_trade_no': order.id, + } + handled = self.Order.on_notification(notification) + self.assertTrue(handled, 'Notification was not handled (error in checking for duplicates?)') + handled = self.Order.on_notification(notification) + self.assertFalse(handled, 'Duplicate was not catched and handled as normal notificaiton') diff --git a/wechat/tools/__init__.py b/wechat/tools/__init__.py new file mode 100644 index 0000000000..21e28db949 --- /dev/null +++ b/wechat/tools/__init__.py @@ -0,0 +1,2 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from .async import * diff --git a/wechat/tools/async.py b/wechat/tools/async.py new file mode 100644 index 0000000000..ef2f5fe2cd --- /dev/null +++ b/wechat/tools/async.py @@ -0,0 +1,39 @@ +# Copyright 2018 Ivan Yelizariev +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +import threading + + +from odoo import api, tools + +__all__ = ['odoo_async_call'] + + +def odoo_async_call(target, args, kwargs, callback=None): + t = threading.Thread(target=odoo_wrapper, args=(target, args, kwargs, callback)) + t.start() + return t + + +# TODO: is there more elegant way? +def odoo_wrapper(target, args, kwargs, callback): + self = get_self(target) + with api.Environment.manage(), self.pool.cursor() as cr: + result = call_with_new_cr(cr, target, args, kwargs) + if callback: + call_with_new_cr(cr, callback, (result,)) + + +def get_self(method): + try: + # python 3 + return method.__self__ + except: + # python 2 + return method.im_self + + +def call_with_new_cr(cr, method, args=None, kwargs=None): + method_name = method.__name__ + self = get_self(method) + self = self.with_env(self.env(cr=cr)) + return getattr(self, method_name)(*(args or ()), **(kwargs or {})) diff --git a/wechat/views/wechat_micropay_views.xml b/wechat/views/wechat_micropay_views.xml new file mode 100644 index 0000000000..737d911d2b --- /dev/null +++ b/wechat/views/wechat_micropay_views.xml @@ -0,0 +1,77 @@ + + + + + + + + wechat.micropay.form + wechat.micropay + +
+ +
+

+
+ + + + + + + + + + +
+
+
+
+ + + wechat.micropay.list + wechat.micropay + + + + + + + + + + + wechat.micropay.search + wechat.micropay + + + + + + + + + + + Wechat Micropay + wechat.micropay + form + tree,form + +

+ Click to create a wechat micropay. +

+
+
+ + + +