blob: 5b8b7c13836f2aa76c4a7619e2155d4c984b65ae [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
27 fields = frappe.get_meta('Sales Invoice').fields
Ahmad940db712021-09-17 01:14:41 +050028
Ahmad8a425702021-09-14 14:45:23 +050029 for field in fields:
30 if field.fieldname == 'qr_code' and field.fieldtype == 'Attach Image':
31 # 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,
49 "content": qr_image.getvalue()
50 })
51
52 _file.save()
53
54 # assigning to document
55 doc.db_set('qr_code', _file.file_url)
56 doc.notify_update()
57
58 break
59
60
61def delete_qr_code_file(doc, method):
62 """Delete QR Code on deleted sales invoice"""
Ahmad940db712021-09-17 01:14:41 +050063
Ahmad8a425702021-09-14 14:45:23 +050064 region = get_region(doc.company)
65 if region not in ['Saudi Arabia']:
66 return
67
68 if hasattr(doc, 'qr_code'):
69 if doc.get('qr_code'):
70 file_doc = frappe.get_list('File', {
Ahmad95b3b9c2021-09-17 01:27:37 +050071 'file_url': doc.get('qr_code')
Ahmad8a425702021-09-14 14:45:23 +050072 })
73 if len(file_doc):
74 frappe.delete_doc('File', file_doc[0].name)