blob: cc6c0af7a56e3e30179f23ccb22299cc60e84fa6 [file] [log] [blame]
Ahmad8a425702021-09-14 14:45:23 +05001import io
2import os
3
Ahmad940db712021-09-17 01:14:41 +05004import frappe
5from pyqrcode import create as qr_create
6
7from erpnext import get_region
8
Ahmad8a425702021-09-14 14:45:23 +05009
10def create_qr_code(doc, method):
11 """Create QR Code after inserting Sales Inv
12 """
13
14 region = get_region(doc.company)
15 if region not in ['Saudi Arabia']:
16 return
17
18 # if QR Code field not present, do nothing
19 if not hasattr(doc, 'qr_code'):
20 return
21
22 # Don't create QR Code if it already exists
23 qr_code = doc.get("qr_code")
24 if qr_code and frappe.db.exists({"doctype": "File", "file_url": qr_code}):
25 return
26
Ahmadf1e5a642021-09-17 01:33:32 +050027 meta = frappe.get_meta('Sales Invoice')
Ahmad940db712021-09-17 01:14:41 +050028
Ahmadf1e5a642021-09-17 01:33:32 +050029 for field in meta.get_image_fields():
30 if field.fieldname == 'qr_code':
Ahmad8a425702021-09-14 14:45:23 +050031 # Creating public url to print format
32 default_print_format = frappe.db.get_value('Property Setter', dict(property='default_print_format', doc_type=doc.doctype), "value")
Ahmad940db712021-09-17 01:14:41 +050033
Ahmad8a425702021-09-14 14:45:23 +050034 # System Language
35 language = frappe.get_system_settings('language')
Ahmad940db712021-09-17 01:14:41 +050036
Ahmad8a425702021-09-14 14:45:23 +050037 # creating qr code for the url
38 url = f"{ frappe.utils.get_url() }/{ doc.doctype }/{ doc.name }?format={ default_print_format or 'Standard' }&_lang={ language }&key={ doc.get_signature() }"
39 qr_image = io.BytesIO()
40 url = qr_create(url, error='L')
41 url.png(qr_image, scale=2, quiet_zone=1)
Ahmad940db712021-09-17 01:14:41 +050042
Ahmad8a425702021-09-14 14:45:23 +050043 # making file
44 filename = f"QR-CODE-{doc.name}.png".replace(os.path.sep, "__")
45 _file = frappe.get_doc({
46 "doctype": "File",
47 "file_name": filename,
48 "is_private": 0,
Ahmad05321d72021-09-17 01:28:52 +050049 "content": qr_image.getvalue(),
50 "attached_to_doctype": doc.get("doctype"),
51 "attached_to_name": doc.get("name"),
52 "attached_to_field": "qr_code"
Ahmad8a425702021-09-14 14:45:23 +050053 })
54
55 _file.save()
56
57 # assigning to document
58 doc.db_set('qr_code', _file.file_url)
59 doc.notify_update()
60
61 break
62
63
64def delete_qr_code_file(doc, method):
65 """Delete QR Code on deleted sales invoice"""
Ahmad940db712021-09-17 01:14:41 +050066
Ahmad8a425702021-09-14 14:45:23 +050067 region = get_region(doc.company)
68 if region not in ['Saudi Arabia']:
69 return
70
71 if hasattr(doc, 'qr_code'):
72 if doc.get('qr_code'):
73 file_doc = frappe.get_list('File', {
Ahmad95b3b9c2021-09-17 01:27:37 +050074 'file_url': doc.get('qr_code')
Ahmad8a425702021-09-14 14:45:23 +050075 })
76 if len(file_doc):
77 frappe.delete_doc('File', file_doc[0].name)