blob: 7d00d8b392834fc45e79aaf52162d8b80a509de9 [file] [log] [blame]
Ahmad8a425702021-09-14 14:45:23 +05001import io
2import os
Ahmadd1746ca2021-11-24 02:54:43 +01003from base64 import b64encode
Ahmad8a425702021-09-14 14:45:23 +05004
Ahmad940db712021-09-17 01:14:41 +05005import frappe
Ahmadd1746ca2021-11-24 02:54:43 +01006from frappe import _
7from frappe.utils.data import add_to_date, get_time, getdate
Ahmad940db712021-09-17 01:14:41 +05008from pyqrcode import create as qr_create
9
10from erpnext import get_region
11
Ahmad8a425702021-09-14 14:45:23 +050012
13def create_qr_code(doc, method):
14 """Create QR Code after inserting Sales Inv
15 """
16
17 region = get_region(doc.company)
18 if region not in ['Saudi Arabia']:
19 return
20
21 # if QR Code field not present, do nothing
22 if not hasattr(doc, 'qr_code'):
23 return
24
25 # Don't create QR Code if it already exists
26 qr_code = doc.get("qr_code")
27 if qr_code and frappe.db.exists({"doctype": "File", "file_url": qr_code}):
28 return
29
Ahmadf1e5a642021-09-17 01:33:32 +050030 meta = frappe.get_meta('Sales Invoice')
Ahmad940db712021-09-17 01:14:41 +050031
Ahmadf1e5a642021-09-17 01:33:32 +050032 for field in meta.get_image_fields():
33 if field.fieldname == 'qr_code':
Ahmadd1746ca2021-11-24 02:54:43 +010034 ''' TLV conversion for
35 1. Seller's Name
36 2. VAT Number
37 3. Time Stamp
38 4. Invoice Amount
39 5. VAT Amount
40 '''
41 tlv_array = []
42 # Sellers Name
Saqib Ansariac273912021-11-20 11:22:19 +053043
Ahmad31b9b842021-11-27 14:28:13 +010044 seller_name = frappe.db.get_value(
45 'Company',
46 doc.company,
47 'company_name_in_arabic')
Ahmad940db712021-09-17 01:14:41 +050048
Ahmad31b9b842021-11-27 14:28:13 +010049 if not seller_name:
Deepesh Gargf3f7ed62021-11-29 13:43:56 +053050 frappe.throw(_('Arabic name missing for {} in the company document').format(doc.company))
Ahmad940db712021-09-17 01:14:41 +050051
Ahmadd1746ca2021-11-24 02:54:43 +010052 tag = bytes([1]).hex()
Ahmad31b9b842021-11-27 14:28:13 +010053 length = bytes([len(seller_name.encode('utf-8'))]).hex()
Ahmadd1746ca2021-11-24 02:54:43 +010054 value = seller_name.encode('utf-8').hex()
55 tlv_array.append(''.join([tag, length, value]))
Saqib Ansariac273912021-11-20 11:22:19 +053056
Ahmadd1746ca2021-11-24 02:54:43 +010057 # VAT Number
58 tax_id = frappe.db.get_value('Company', doc.company, 'tax_id')
59 if not tax_id:
Deepesh Gargf3f7ed62021-11-29 13:43:56 +053060 frappe.throw(_('Tax ID missing for {} in the company document').format(doc.company))
Ahmadd1746ca2021-11-24 02:54:43 +010061
Ahmadd1746ca2021-11-24 02:54:43 +010062 tag = bytes([2]).hex()
63 length = bytes([len(tax_id)]).hex()
64 value = tax_id.encode('utf-8').hex()
65 tlv_array.append(''.join([tag, length, value]))
66
67 # Time Stamp
68 posting_date = getdate(doc.posting_date)
69 time = get_time(doc.posting_time)
70 seconds = time.hour * 60 * 60 + time.minute * 60 + time.second
71 time_stamp = add_to_date(posting_date, seconds=seconds)
72 time_stamp = time_stamp.strftime('%Y-%m-%dT%H:%M:%SZ')
73
Ahmadd1746ca2021-11-24 02:54:43 +010074 tag = bytes([3]).hex()
75 length = bytes([len(time_stamp)]).hex()
76 value = time_stamp.encode('utf-8').hex()
77 tlv_array.append(''.join([tag, length, value]))
78
79 # Invoice Amount
Deepesh Gargf2ffddf2021-12-03 14:32:52 +053080 invoice_amount = str(doc.grand_total)
Ahmadd1746ca2021-11-24 02:54:43 +010081 tag = bytes([4]).hex()
82 length = bytes([len(invoice_amount)]).hex()
83 value = invoice_amount.encode('utf-8').hex()
84 tlv_array.append(''.join([tag, length, value]))
85
86 # VAT Amount
87 vat_amount = str(doc.total_taxes_and_charges)
88
Ahmadd1746ca2021-11-24 02:54:43 +010089 tag = bytes([5]).hex()
90 length = bytes([len(vat_amount)]).hex()
91 value = vat_amount.encode('utf-8').hex()
92 tlv_array.append(''.join([tag, length, value]))
93
94 # Joining bytes into one
95 tlv_buff = ''.join(tlv_array)
96
97 # base64 conversion for QR Code
98 base64_string = b64encode(bytes.fromhex(tlv_buff)).decode()
99
Ahmad8a425702021-09-14 14:45:23 +0500100 qr_image = io.BytesIO()
Ahmadd1746ca2021-11-24 02:54:43 +0100101 url = qr_create(base64_string, error='L')
Ahmad8a425702021-09-14 14:45:23 +0500102 url.png(qr_image, scale=2, quiet_zone=1)
Ahmad940db712021-09-17 01:14:41 +0500103
Saqib7511a9e2021-12-03 16:13:44 +0530104 name = frappe.generate_hash(doc.name, 5)
105
Ahmad8a425702021-09-14 14:45:23 +0500106 # making file
Saqib7511a9e2021-12-03 16:13:44 +0530107 filename = f"QRCode-{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()