blob: ba55efc6af748d89d149471b14abb399555917c8 [file] [log] [blame]
Ahmad8a425702021-09-14 14:45:23 +05001import io
2import os
Ahmadd1746ca2021-11-24 02:54:43 +01003from base64 import b64encode
Saqib7314aee2021-12-03 11:29:51 +05304from urllib.parse import quote
Ahmad8a425702021-09-14 14:45:23 +05005
Ahmad940db712021-09-17 01:14:41 +05006import frappe
Ahmadd1746ca2021-11-24 02:54:43 +01007from frappe import _
8from frappe.utils.data import add_to_date, get_time, getdate
Ahmad940db712021-09-17 01:14:41 +05009from pyqrcode import create as qr_create
10
11from erpnext import get_region
12
Ahmad8a425702021-09-14 14:45:23 +050013
14def create_qr_code(doc, method):
15 """Create QR Code after inserting Sales Inv
16 """
17
18 region = get_region(doc.company)
19 if region not in ['Saudi Arabia']:
20 return
21
22 # if QR Code field not present, do nothing
23 if not hasattr(doc, 'qr_code'):
24 return
25
26 # Don't create QR Code if it already exists
27 qr_code = doc.get("qr_code")
28 if qr_code and frappe.db.exists({"doctype": "File", "file_url": qr_code}):
29 return
30
Ahmadf1e5a642021-09-17 01:33:32 +050031 meta = frappe.get_meta('Sales Invoice')
Ahmad940db712021-09-17 01:14:41 +050032
Ahmadf1e5a642021-09-17 01:33:32 +050033 for field in meta.get_image_fields():
34 if field.fieldname == 'qr_code':
Ahmadd1746ca2021-11-24 02:54:43 +010035 ''' TLV conversion for
36 1. Seller's Name
37 2. VAT Number
38 3. Time Stamp
39 4. Invoice Amount
40 5. VAT Amount
41 '''
42 tlv_array = []
43 # Sellers Name
Saqib Ansariac273912021-11-20 11:22:19 +053044
Ahmad31b9b842021-11-27 14:28:13 +010045 seller_name = frappe.db.get_value(
46 'Company',
47 doc.company,
48 'company_name_in_arabic')
Ahmad940db712021-09-17 01:14:41 +050049
Ahmad31b9b842021-11-27 14:28:13 +010050 if not seller_name:
Deepesh Gargf3f7ed62021-11-29 13:43:56 +053051 frappe.throw(_('Arabic name missing for {} in the company document').format(doc.company))
Ahmad940db712021-09-17 01:14:41 +050052
Ahmadd1746ca2021-11-24 02:54:43 +010053 tag = bytes([1]).hex()
Ahmad31b9b842021-11-27 14:28:13 +010054 length = bytes([len(seller_name.encode('utf-8'))]).hex()
Ahmadd1746ca2021-11-24 02:54:43 +010055 value = seller_name.encode('utf-8').hex()
56 tlv_array.append(''.join([tag, length, value]))
Saqib Ansariac273912021-11-20 11:22:19 +053057
Ahmadd1746ca2021-11-24 02:54:43 +010058 # VAT Number
59 tax_id = frappe.db.get_value('Company', doc.company, 'tax_id')
60 if not tax_id:
Deepesh Gargf3f7ed62021-11-29 13:43:56 +053061 frappe.throw(_('Tax ID missing for {} in the company document').format(doc.company))
Ahmadd1746ca2021-11-24 02:54:43 +010062
Ahmadd1746ca2021-11-24 02:54:43 +010063 tag = bytes([2]).hex()
64 length = bytes([len(tax_id)]).hex()
65 value = tax_id.encode('utf-8').hex()
66 tlv_array.append(''.join([tag, length, value]))
67
68 # Time Stamp
69 posting_date = getdate(doc.posting_date)
70 time = get_time(doc.posting_time)
71 seconds = time.hour * 60 * 60 + time.minute * 60 + time.second
72 time_stamp = add_to_date(posting_date, seconds=seconds)
73 time_stamp = time_stamp.strftime('%Y-%m-%dT%H:%M:%SZ')
74
Ahmadd1746ca2021-11-24 02:54:43 +010075 tag = bytes([3]).hex()
76 length = bytes([len(time_stamp)]).hex()
77 value = time_stamp.encode('utf-8').hex()
78 tlv_array.append(''.join([tag, length, value]))
79
80 # Invoice Amount
81 invoice_amount = str(doc.total)
Ahmadd1746ca2021-11-24 02:54:43 +010082 tag = bytes([4]).hex()
83 length = bytes([len(invoice_amount)]).hex()
84 value = invoice_amount.encode('utf-8').hex()
85 tlv_array.append(''.join([tag, length, value]))
86
87 # VAT Amount
88 vat_amount = str(doc.total_taxes_and_charges)
89
Ahmadd1746ca2021-11-24 02:54:43 +010090 tag = bytes([5]).hex()
91 length = bytes([len(vat_amount)]).hex()
92 value = vat_amount.encode('utf-8').hex()
93 tlv_array.append(''.join([tag, length, value]))
94
95 # Joining bytes into one
96 tlv_buff = ''.join(tlv_array)
97
98 # base64 conversion for QR Code
99 base64_string = b64encode(bytes.fromhex(tlv_buff)).decode()
100
Ahmad8a425702021-09-14 14:45:23 +0500101 qr_image = io.BytesIO()
Ahmadd1746ca2021-11-24 02:54:43 +0100102 url = qr_create(base64_string, error='L')
Ahmad8a425702021-09-14 14:45:23 +0500103 url.png(qr_image, scale=2, quiet_zone=1)
Ahmad940db712021-09-17 01:14:41 +0500104
Saqib7314aee2021-12-03 11:29:51 +0530105 urlencoded_name = quote(doc.name)
Ahmad8a425702021-09-14 14:45:23 +0500106 # making file
Saqib7314aee2021-12-03 11:29:51 +0530107 filename = f"QR-CODE-{urlencoded_name}.png".replace(os.path.sep, "__")
Ahmad8a425702021-09-14 14:45:23 +0500108 _file = frappe.get_doc({
109 "doctype": "File",
110 "file_name": filename,
111 "is_private": 0,
Ahmad05321d72021-09-17 01:28:52 +0500112 "content": qr_image.getvalue(),
113 "attached_to_doctype": doc.get("doctype"),
114 "attached_to_name": doc.get("name"),
115 "attached_to_field": "qr_code"
Ahmad8a425702021-09-14 14:45:23 +0500116 })
117
118 _file.save()
119
120 # assigning to document
121 doc.db_set('qr_code', _file.file_url)
122 doc.notify_update()
123
124 break
125
126
127def delete_qr_code_file(doc, method):
128 """Delete QR Code on deleted sales invoice"""
Ahmad940db712021-09-17 01:14:41 +0500129
Ahmad8a425702021-09-14 14:45:23 +0500130 region = get_region(doc.company)
131 if region not in ['Saudi Arabia']:
132 return
133
134 if hasattr(doc, 'qr_code'):
135 if doc.get('qr_code'):
136 file_doc = frappe.get_list('File', {
Ahmad95b3b9c2021-09-17 01:27:37 +0500137 'file_url': doc.get('qr_code')
Ahmad8a425702021-09-14 14:45:23 +0500138 })
139 if len(file_doc):
Deepesh Garg73c56512021-11-22 14:21:53 +0530140 frappe.delete_doc('File', file_doc[0].name)
141
142def delete_vat_settings_for_company(doc, method):
143 if doc.country != 'Saudi Arabia':
144 return
145
146 settings_doc = frappe.get_doc('KSA VAT Setting', {'company': doc.name})
147 settings_doc.delete()