administrator 1 year ago
parent
commit
a93ef0f8c6
  1. 7
      .gitignore
  2. BIN
      __pycache__/setup.cpython-38.pyc
  3. BIN
      smart_service/__pycache__/__init__.cpython-38.pyc
  4. BIN
      smart_service/__pycache__/hooks.cpython-38.pyc
  5. BIN
      smart_service/add_ons/__pycache__/__init__.cpython-38.pyc
  6. BIN
      smart_service/add_ons/doctype/__pycache__/__init__.cpython-38.pyc
  7. BIN
      smart_service/add_ons/doctype/app_dealer/__pycache__/__init__.cpython-38.pyc
  8. BIN
      smart_service/add_ons/doctype/app_dealer/__pycache__/app_dealer.cpython-38.pyc
  9. BIN
      smart_service/add_ons/doctype/app_device/__pycache__/__init__.cpython-38.pyc
  10. BIN
      smart_service/add_ons/doctype/app_device/__pycache__/app_device.cpython-38.pyc
  11. BIN
      smart_service/add_ons/doctype/app_log/__pycache__/__init__.cpython-38.pyc
  12. BIN
      smart_service/add_ons/doctype/app_log/__pycache__/app_log.cpython-38.pyc
  13. BIN
      smart_service/add_ons/doctype/app_preference/__pycache__/__init__.cpython-38.pyc
  14. BIN
      smart_service/add_ons/doctype/app_preference/__pycache__/app_preference.cpython-38.pyc
  15. BIN
      smart_service/add_ons/doctype/app_users/__pycache__/__init__.cpython-38.pyc
  16. BIN
      smart_service/add_ons/doctype/app_users/__pycache__/app_users.cpython-38.pyc
  17. BIN
      smart_service/add_ons/doctype/captcha_validation/__pycache__/__init__.cpython-38.pyc
  18. BIN
      smart_service/add_ons/doctype/captcha_validation/__pycache__/captcha_validation.cpython-38.pyc
  19. 38
      smart_service/add_ons/doctype/circular/circular.js
  20. 5
      smart_service/add_ons/doctype/circular/circular.json
  21. 157
      smart_service/add_ons/doctype/circular/circular.py
  22. 0
      smart_service/add_ons/doctype/refresh_token/__init__.py
  23. 8
      smart_service/add_ons/doctype/refresh_token/refresh_token.js
  24. 77
      smart_service/add_ons/doctype/refresh_token/refresh_token.json
  25. 8
      smart_service/add_ons/doctype/refresh_token/refresh_token.py
  26. 8
      smart_service/add_ons/doctype/refresh_token/test_refresh_token.py
  27. 0
      smart_service/add_ons/doctype/token_settings/__init__.py
  28. 8
      smart_service/add_ons/doctype/token_settings/test_token_settings.py
  29. 8
      smart_service/add_ons/doctype/token_settings/token_settings.js
  30. 48
      smart_service/add_ons/doctype/token_settings/token_settings.json
  31. 15
      smart_service/add_ons/doctype/token_settings/token_settings.py
  32. BIN
      smart_service/add_ons/doctype/user_feedback/__pycache__/__init__.cpython-38.pyc
  33. BIN
      smart_service/add_ons/doctype/user_feedback/__pycache__/user_feedback.cpython-38.pyc
  34. BIN
      smart_service/add_ons/doctype/user_feedback_types/__pycache__/__init__.cpython-38.pyc
  35. BIN
      smart_service/add_ons/doctype/user_feedback_types/__pycache__/user_feedback_types.cpython-38.pyc
  36. 5
      smart_service/add_ons/report/feedback_report/feedback_report.py
  37. 35
      smart_service/add_ons/report/installation_report/installation_report.py
  38. 37
      smart_service/add_ons/report/login_report/login_report.py
  39. 42
      smart_service/add_ons/report/model_download_report/model_download_report.py
  40. 53
      smart_service/add_ons/report/model_hit_report/model_hit_report.py
  41. 658246
      smart_service/apis/THAR-en-full_v12.00.json
  42. BIN
      smart_service/apis/__pycache__/addon_api.cpython-38.pyc
  43. BIN
      smart_service/apis/__pycache__/app_user_login.cpython-38.pyc
  44. BIN
      smart_service/apis/__pycache__/master_api.cpython-38.pyc
  45. BIN
      smart_service/apis/__pycache__/publish_api.cpython-38.pyc
  46. BIN
      smart_service/apis/__pycache__/update_validation.cpython-38.pyc
  47. 99
      smart_service/apis/addon_api.py
  48. 430
      smart_service/apis/app_user_login.py
  49. 126
      smart_service/apis/master_api.py
  50. 909
      smart_service/apis/publish_api.py
  51. 475
      smart_service/apis/support.py
  52. 32
      smart_service/apis/transaction_api.py
  53. 815
      smart_service/apis/update_validation.py
  54. 994
      smart_service/fixtures/custom_docperm.json
  55. 53
      smart_service/fixtures/custom_field.json
  56. 91
      smart_service/fixtures/dashboard_chart.json
  57. 1376
      smart_service/fixtures/property_setter.json
  58. 821
      smart_service/fixtures/report.json
  59. 50
      smart_service/fixtures/role.json
  60. 2714
      smart_service/fixtures/workspace.json
  61. 148
      smart_service/hooks.py
  62. BIN
      smart_service/masters/__pycache__/__init__.cpython-38.pyc
  63. BIN
      smart_service/masters/doctype/__pycache__/__init__.cpython-38.pyc
  64. 14
      smart_service/masters/doctype/app_labels/app_labels.js
  65. 28
      smart_service/masters/doctype/custom_languages/custom_languages.json
  66. 2
      smart_service/masters/doctype/drive/drive.js
  67. 2
      smart_service/masters/doctype/fuel/fuel.js
  68. 2
      smart_service/masters/doctype/procedure_name/procedure_name.js
  69. 2
      smart_service/masters/doctype/service_kilometers/service_kilometers.js
  70. 2
      smart_service/masters/doctype/sub_systems/sub_systems.js
  71. 2
      smart_service/masters/doctype/systems/systems.js
  72. 2
      smart_service/masters/doctype/transmission/transmission.js
  73. BIN
      smart_service/masters/doctype/variant/__pycache__/__init__.cpython-38.pyc
  74. BIN
      smart_service/masters/doctype/variant/__pycache__/variant.cpython-38.pyc
  75. 2
      smart_service/masters/doctype/variant/variant.js
  76. BIN
      smart_service/masters/doctype/vehicle/__pycache__/__init__.cpython-38.pyc
  77. BIN
      smart_service/masters/doctype/vehicle/__pycache__/vehicle.cpython-38.pyc
  78. 33
      smart_service/masters/doctype/vehicle/vehicle.json
  79. 2
      smart_service/masters/doctype/vehicle_segment/vehicle_segment.js
  80. 2
      smart_service/masters/report/_fuel_translation/_fuel_translation.py
  81. 4
      smart_service/public/css/smart_service.css
  82. BIN
      smart_service/public/images/Mahindra Rise2.png
  83. BIN
      smart_service/public/images/Mahindra Rise2_test.png
  84. BIN
      smart_service/reports/__pycache__/__init__.cpython-38.pyc
  85. BIN
      smart_service/transactions/__pycache__/__init__.cpython-38.pyc
  86. BIN
      smart_service/transactions/doctype/__pycache__/__init__.cpython-38.pyc
  87. BIN
      smart_service/transactions/doctype/fish/__pycache__/__init__.cpython-38.pyc
  88. BIN
      smart_service/transactions/doctype/fish/__pycache__/fish.cpython-38.pyc
  89. BIN
      smart_service/transactions/doctype/kilometer_mapping/__pycache__/__init__.cpython-38.pyc
  90. BIN
      smart_service/transactions/doctype/kilometer_mapping/__pycache__/kilometer_mapping.cpython-38.pyc
  91. BIN
      smart_service/transactions/doctype/kilometer_mapping_items/__pycache__/__init__.cpython-38.pyc
  92. BIN
      smart_service/transactions/doctype/kilometer_mapping_items/__pycache__/kilometer_mapping_items.cpython-38.pyc
  93. BIN
      smart_service/transactions/doctype/procedure/__pycache__/__init__.cpython-38.pyc
  94. BIN
      smart_service/transactions/doctype/procedure/__pycache__/procedure.cpython-38.pyc
  95. 36
      smart_service/transactions/doctype/procedure/procedure.js
  96. 335
      smart_service/transactions/doctype/procedure/procedure.py
  97. BIN
      smart_service/transactions/doctype/procedure_details/__pycache__/__init__.cpython-38.pyc
  98. BIN
      smart_service/transactions/doctype/procedure_details/__pycache__/procedure_details.cpython-38.pyc
  99. 3
      smart_service/transactions/doctype/procedure_details/procedure_details.json
  100. BIN
      smart_service/transactions/doctype/publish/__pycache__/__init__.cpython-38.pyc

7
.gitignore

@ -1,2 +1,7 @@
#Ignore all pyc files .DS_Store
*.egg-info
*.swp
tags
smart_service/docs/current
*.pyc *.pyc
__pycache__/

BIN
__pycache__/setup.cpython-38.pyc

Binary file not shown.

BIN
smart_service/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/__pycache__/hooks.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_dealer/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_dealer/__pycache__/app_dealer.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_device/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_device/__pycache__/app_device.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_log/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_log/__pycache__/app_log.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_preference/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_preference/__pycache__/app_preference.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_users/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/app_users/__pycache__/app_users.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/captcha_validation/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/captcha_validation/__pycache__/captcha_validation.cpython-38.pyc

Binary file not shown.

38
smart_service/add_ons/doctype/circular/circular.js

@ -2,10 +2,40 @@
// For license information, please see license.txt // For license information, please see license.txt
frappe.ui.form.on('Circular', { frappe.ui.form.on('Circular', {
validate(frm) { validate(frm) {
if(frm.doc.valid_till < frappe.datetime.nowdate()) { if (frm.doc.valid_till < frappe.datetime.nowdate()) {
msgprint('Valid Till date should be greater than today!'); msgprint('Valid Till date should be equal or greater than today!');
validated = false; validated = false;
} }
} if (frm.doc.description.length > 500) {
frappe.msgprint("<b>Description:</b> Only <b> 500 </b> character's are allowed")
validated = false;
}
if (frm.doc.circular_image) {
console.log("calling")
frappe.call({
method: "smart_service.add_ons.doctype.circular.circular.file_validation",
args: {
image: frm.doc.circular_image,
name: frm.doc.name
},
callback: function (r) {
if (r.message && r.message[0] == false) {
frm.doc.circular_image = ""
frm.refresh_fields("circular_image")
if (r.message[1] == 1) {
frappe.validated = false;
frappe.msgprint("Invalid file type")
}
if (r.message[1] == 2) {
frappe.validated = false;
frappe.msgprint("Invalid file size")
}
}
}
})
}
}
}); });

5
smart_service/add_ons/doctype/circular/circular.json

@ -25,6 +25,7 @@
"reqd": 1 "reqd": 1
}, },
{ {
"description": "Max count (500 character's)",
"fieldname": "description", "fieldname": "description",
"fieldtype": "Small Text", "fieldtype": "Small Text",
"in_list_view": 1, "in_list_view": 1,
@ -65,15 +66,15 @@
"label": "Valid Till" "label": "Valid Till"
}, },
{ {
"description": "Upload *.png,*.jpg,*.pdf",
"fieldname": "circular_image", "fieldname": "circular_image",
"fieldtype": "Attach", "fieldtype": "Attach",
"label": "Circular Image" "label": "Circular Image"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [], "links": [],
"modified": "2022-05-14 12:07:39.981829", "modified": "2023-06-28 16:41:53.914998",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "Add Ons", "module": "Add Ons",
"name": "Circular", "name": "Circular",

157
smart_service/add_ons/doctype/circular/circular.py

@ -1,8 +1,161 @@
# Copyright (c) 2021, Hard n Soft Technologies Pvt Ltd and contributors # Copyright (c) 2021, Hard n Soft Technologies Pvt Ltd and contributors
# For license information, please see license.txt # For license information, please see license.txt
# import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
class Circular(Document): class Circular(Document):
pass def validate(self):
if self.description and len(self.description)>500:
frappe.throw("Description should be less than or equal to 850 characters ")
@frappe.whitelist()
def file_validation(image, name):
if image:
res = check_img_ext(image)
res1 = check_png_ext(image)
res2 = check_pdf_ext(image)
if res == True or res1 == True or res2 == True:
return True
else:
return False, 1
# if res== True:
# pass
# else:
# width, height, size = details_of_image(image)
# if width > 49 or height > 49 or size > 65 and image:
# val = checking_image(image, "Circular","circular_image", name)
# if val:
# return False, 2
# if res2 == True:
# pass
# else:
# width, height, size = details_of_image(image)
# if width > 49 or height > 49 or size > 65 and image:
# val = checking_image(image, "Circular",
# "circular_image", name)
# if val == True:
# return False, 2
# else:
# return True
# else:
# val = checking_image(image, "Circular",
# "circular_image", name)
if res == False:
ret = res
elif res1 == False:
ret = res1
else:
ret = res2
return ret, 1
@frappe.whitelist()
def check_pdf_ext(path):
if path:
ext = path.split()[-1]
if ext.lower().endswith('.pdf'):
return True
else:
return False
else:
return False
@frappe.whitelist()
def check_img_ext(path):
if path:
ext = path.split()[-1]
if ext.lower().endswith('.jpg') or ext.lower().endswith('.jpeg'):
return True
else:
return False
else:
return False
@frappe.whitelist()
def check_png_ext(path):
if path:
ext = path.split()[-1]
if ext.lower().endswith('.png'):
return True
else:
return False
else:
return False
def details_of_image(image_file):
try:
# Image dimension validation
import os
from PIL import Image
if image_file.startswith('/private/'):
filepath = get_absolute_path(image_file, True)
else:
filepath = get_absolute_path(image_file)
img = Image.open(filepath)
width = img.width
height = img.height
size = os.stat(filepath)
size=size[6]/1024
return width, height,size
except Exception as e:
raise e
def get_absolute_path(file_name, is_private=False):
try:
if file_name.startswith('/files/'):
file_name = file_name[7:]
else:
file_name = file_name[15:]
return frappe.utils.get_bench_path() + "/sites/" + frappe.utils.get_path('private' if is_private else 'public',
'files', file_name)[2:]
except Exception as e:
frappe.log_error("get_absolute_path", frappe.get_traceback())
def checking_image(file_url, attached_to_doctype, attached_to_field, docname, is_child=None):
try:
import time
time.sleep(1)
if docname.startswith('new'):
image_name = frappe.db.get_list("File", fields={"name"}, filters={"file_url": file_url,
"attached_to_doctype": attached_to_doctype,
"attached_to_field": attached_to_field,
"attached_to_name": docname})
else:
image_name = frappe.db.get_list("File", fields={"name"}, filters={"file_url": file_url,
"attached_to_doctype": attached_to_doctype,
"attached_to_field": attached_to_field})
image_name = frappe.db.sql(f"""select name from `tabFile` where file_url='{file_url}' and attached_to_doctype='{attached_to_doctype}' and
attached_to_field='{attached_to_field}'""",as_dict=1)
# frappe.msgprint("data-"+str(file_url)+"-"+str(attached_to_doctype)+"-"+str(attached_to_field)+"-"+str(docname))
if not attached_to_doctype == "Symbol Scanner" and is_child != 1:
frappe.db.sql(
'''UPDATE `tab{0}` SET {2} = '' where name = "{1}"'''.format(attached_to_doctype, docname,
attached_to_field))
frappe.db.commit()
if attached_to_doctype == "Symbol Scanner":
frappe.db.set_value(
"Symbol Scanner", "Symbol Scanner", attached_to_field, "")
if len(image_name) > 0:
frappe.delete_doc('File', image_name[0]['name'])
return True
except Exception as e:
frappe.log_error("Checking images", frappe.get_traceback())

0
smart_service/add_ons/doctype/refresh_token/__init__.py

8
smart_service/add_ons/doctype/refresh_token/refresh_token.js

@ -0,0 +1,8 @@
// Copyright (c) 2023, Hard n Soft Technologies Pvt Ltd and contributors
// For license information, please see license.txt
frappe.ui.form.on('Refresh Token', {
// refresh: function(frm) {
// }
});

77
smart_service/add_ons/doctype/refresh_token/refresh_token.json

@ -0,0 +1,77 @@
{
"actions": [],
"allow_rename": 1,
"creation": "2023-02-02 11:54:48.885036",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"access_token",
"refresh_token",
"column_break_3",
"access_expiry_time",
"refresh_expiry_time",
"user",
"device_id"
],
"fields": [
{
"fieldname": "access_token",
"fieldtype": "Small Text",
"label": "Access Token"
},
{
"fieldname": "refresh_token",
"fieldtype": "Small Text",
"label": "Refresh Token"
},
{
"fieldname": "column_break_3",
"fieldtype": "Column Break"
},
{
"fieldname": "access_expiry_time",
"fieldtype": "Datetime",
"label": "Access Expiry Time"
},
{
"fieldname": "refresh_expiry_time",
"fieldtype": "Datetime",
"label": "Refresh Expiry Time"
},
{
"fieldname": "user",
"fieldtype": "Link",
"label": "User",
"options": "User"
},
{
"fieldname": "device_id",
"fieldtype": "Data",
"label": "Device ID"
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2023-06-24 12:22:02.491908",
"modified_by": "Administrator",
"module": "Add Ons",
"name": "Refresh Token",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"export": 1,
"print": 1,
"read": 1,
"report": 1,
"role": "System Manager",
"share": 1,
"write": 1
}
],
"sort_field": "modified",
"sort_order": "DESC"
}

8
smart_service/add_ons/doctype/refresh_token/refresh_token.py

@ -0,0 +1,8 @@
# Copyright (c) 2023, Hard n Soft Technologies Pvt Ltd and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class RefreshToken(Document):
pass

8
smart_service/add_ons/doctype/refresh_token/test_refresh_token.py

@ -0,0 +1,8 @@
# Copyright (c) 2023, Hard n Soft Technologies Pvt Ltd and Contributors
# See license.txt
# import frappe
import unittest
class TestRefreshToken(unittest.TestCase):
pass

0
smart_service/add_ons/doctype/token_settings/__init__.py

8
smart_service/add_ons/doctype/token_settings/test_token_settings.py

@ -0,0 +1,8 @@
# Copyright (c) 2023, Hard n Soft Technologies Pvt Ltd and Contributors
# See license.txt
# import frappe
import unittest
class TestTokenSettings(unittest.TestCase):
pass

8
smart_service/add_ons/doctype/token_settings/token_settings.js

@ -0,0 +1,8 @@
// Copyright (c) 2023, Hard n Soft Technologies Pvt Ltd and contributors
// For license information, please see license.txt
frappe.ui.form.on('Token Settings', {
// refresh: function(frm) {
// }
});

48
smart_service/add_ons/doctype/token_settings/token_settings.json

@ -0,0 +1,48 @@
{
"actions": [],
"allow_rename": 1,
"creation": "2023-02-03 10:17:56.807664",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
"access_expiry_time",
"refresh_expiry_time"
],
"fields": [
{
"description": "Token Expiry in Minutes e.g. 15",
"fieldname": "access_expiry_time",
"fieldtype": "Int",
"label": "Access Expiry Time"
},
{
"description": "Token Expiry in Hours e.g. 1",
"fieldname": "refresh_expiry_time",
"fieldtype": "Int",
"label": "Refresh Expiry Time"
}
],
"index_web_pages_for_search": 1,
"issingle": 1,
"links": [],
"modified": "2023-06-29 09:34:46.212738",
"modified_by": "Administrator",
"module": "Add Ons",
"name": "Token Settings",
"owner": "Administrator",
"permissions": [
{
"create": 1,
"delete": 1,
"email": 1,
"print": 1,
"read": 1,
"role": "System Manager",
"share": 1,
"write": 1
}
],
"sort_field": "modified",
"sort_order": "DESC"
}

15
smart_service/add_ons/doctype/token_settings/token_settings.py

@ -0,0 +1,15 @@
# Copyright (c) 2023, Hard n Soft Technologies Pvt Ltd and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
class TokenSettings(Document):
def validate(self):
if self.access_expiry_time <= 0:
frappe.throw("Access exipry time should be valid minutes")
if self.refresh_expiry_time <= 0:
frappe.throw("Refresh exipry time should be valid hours")

BIN
smart_service/add_ons/doctype/user_feedback/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/user_feedback/__pycache__/user_feedback.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/user_feedback_types/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/add_ons/doctype/user_feedback_types/__pycache__/user_feedback_types.cpython-38.pyc

Binary file not shown.

5
smart_service/add_ons/report/feedback_report/feedback_report.py

@ -28,6 +28,8 @@ def get_data(filters):
def get_columns(): def get_columns():
columns = [ columns = [
{"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype":"Data","width": 100},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 100}, {"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 100},
{"label": _("<b>Feedback ID</b>"), "fieldname": "name", "fieldtype": "Link", "options":"User Feedback","width": 120}, {"label": _("<b>Feedback ID</b>"), "fieldname": "name", "fieldtype": "Link", "options":"User Feedback","width": 120},
{"label": _("<b>Feedback Type</b>"), "fieldname": "feedback_type", "fieldtype": "Data", "width": 120}, {"label": _("<b>Feedback Type</b>"), "fieldname": "feedback_type", "fieldtype": "Data", "width": 120},
@ -35,15 +37,12 @@ def get_columns():
{"label": _("<b>Feedback Description</b>"), "fieldname": "description", "fieldtype": "Text Editor", "width": 250}, {"label": _("<b>Feedback Description</b>"), "fieldname": "description", "fieldtype": "Text Editor", "width": 250},
{"label": _("<b>Attachments</b>"), "fieldname": "attachments", "fieldtype": "Data", "width": 100}, {"label": _("<b>Attachments</b>"), "fieldname": "attachments", "fieldtype": "Data", "width": 100},
{"label": _("<b>Feedback Status</b>"), "fieldname": "status", "fieldtype": "Data", "width": 100}, {"label": _("<b>Feedback Status</b>"), "fieldname": "status", "fieldtype": "Data", "width": 100},
{"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype":"Data","width": 100},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100}, {"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100},
{"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 140}, {"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 140},
{"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 120}, {"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 120},
{"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype": "Data", "width": 150}, {"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Closure Date</b>"), "fieldname": "closure_date", "fieldtype": "Data", "width": 150}, {"label": _("<b>Closure Date</b>"), "fieldname": "closure_date", "fieldtype": "Data", "width": 150},
{"label": _("<b>Closed By</b>"), "fieldname": "closed_by", "fieldtype": "Data", "width": 120} {"label": _("<b>Closed By</b>"), "fieldname": "closed_by", "fieldtype": "Data", "width": 120}
] ]
return columns return columns

35
smart_service/add_ons/report/installation_report/installation_report.py

@ -31,21 +31,36 @@ def get_data(filters):
def get_columns(): def get_columns():
columns = [ columns = [
{"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100}, {"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype": "Data", "width": 100},
{"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype":"Data","width": 150}, {"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 100},
{"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype":"Data","width": 150},
{"label": _("<b>Installation</b>"), "fieldname": "device", "fieldtype": "Data","width": 100}, {"label": _("<b>Installation</b>"), "fieldname": "device", "fieldtype": "Data","width": 100},
{"label": _("<b>App Version No</b>"), "fieldname": "app_current_version", "fieldtype": "Data", "width": 150},
{"label": _("<b>Activity Type</b>"), "fieldname": "type", "fieldtype": "Data","width": 150},
{"label": _("<b>Device</b>"), "fieldname": "device_type", "fieldtype": "Data","width": 100}, {"label": _("<b>Device</b>"), "fieldname": "device_type", "fieldtype": "Data","width": 100},
{"label": _("<b>Device ID</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 100}, {"label": _("<b>Device ID</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device OS</b>"), "fieldname": "os", "fieldtype": "Data", "width": 100}, {"label": _("<b>Device OS</b>"), "fieldname": "os", "fieldtype": "Data", "width": 100},
{"label": _("<b>OS Version</b>"), "fieldname": "os_version", "fieldtype": "Data", "width": 100}, {"label": _("<b>OS Version</b>"), "fieldname": "os_version", "fieldtype": "Data", "width": 100},
{"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype": "Data", "width": 100},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 100},
{"label": _("<b>Activity Type</b>"), "fieldname": "type", "fieldtype": "Data","width": 100},
{"label": _("<b>App Installation Date</b>"), "fieldname": "date_time_stamp", "fieldtype": "DateTime","width": 200}, {"label": _("<b>App Installation Date</b>"), "fieldname": "date_time_stamp", "fieldtype": "DateTime","width": 200},
{"label": _("<b>App Last Accessed Date</b>"), "fieldname": "date", "fieldtype": "DateTime","width": 200}, {"label": _("<b>App Last Accessed Date</b>"), "fieldname": "date", "fieldtype": "DateTime","width": 200}
{"label": _("<b>App Version No</b>"), "fieldname": "app_current_version", "fieldtype": "Data", "width": 150},
] ]
return columns return columns
# def get_columns():
# columns = [
# {"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype":"Data","width": 150},
# {"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype":"Data","width": 150},
# {"label": _("<b>Installation</b>"), "fieldname": "device", "fieldtype": "Data","width": 100},
# {"label": _("<b>Device</b>"), "fieldname": "device_type", "fieldtype": "Data","width": 100},
# {"label": _("<b>Device ID</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Device OS</b>"), "fieldname": "os", "fieldtype": "Data", "width": 100},
# {"label": _("<b>OS Version</b>"), "fieldname": "os_version", "fieldtype": "Data", "width": 100},
# {"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype": "Data", "width": 100},
# {"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Activity Type</b>"), "fieldname": "type", "fieldtype": "Data","width": 100},
# {"label": _("<b>App Installation Date</b>"), "fieldname": "date_time_stamp", "fieldtype": "DateTime","width": 200},
# {"label": _("<b>App Last Accessed Date</b>"), "fieldname": "date", "fieldtype": "DateTime","width": 200},
# {"label": _("<b>App Version No</b>"), "fieldname": "app_current_version", "fieldtype": "Data", "width": 150},
# ]
# return columns

37
smart_service/add_ons/report/login_report/login_report.py

@ -33,7 +33,8 @@ def get_data(filters):
data = frappe.db.sql("""select dealer.zone,au.user_id,concat_ws(' ',au.first_name,au.last_name) as user_name, data = frappe.db.sql("""select dealer.zone,au.user_id,concat_ws(' ',au.first_name,au.last_name) as user_name,
dealer.dealer_code,dealer.dealer_name,dealer.area,ad.os,ad.os_version, dealer.dealer_code,dealer.dealer_name,dealer.area,ad.os,ad.os_version,
ad.device_type,ad.device_id,ad.app_current_version,al.type,date(al.date_time_stamp) as date, ad.device_type,ad.device_id,ad.app_current_version,al.type,date(al.date_time_stamp) as date,
al.latitude, al.longitude, au.name, al.device, time(al.date_time_stamp) as last_login_time, mal.count from {current_db_name}.`tabApp Log` al,{current_db_name}.`tabApp Device` ad, {current_db_name}.`tabApp Users` au,{current_db_name}.`tabApp Dealer` dealer, al.latitude, al.longitude, au.name, al.device, time(al.date_time_stamp) as last_login_time, mal.count from {current_db_name}.`tabApp Log` al,
{current_db_name}.`tabApp Device` ad, {current_db_name}.`tabApp Users` au,{current_db_name}.`tabApp Dealer` dealer,
(select user,Max(date_time_stamp) as date_time_stam, count(date(date_time_stamp)) as count from {current_db_name}.`tabApp Log` (select user,Max(date_time_stamp) as date_time_stam, count(date(date_time_stamp)) as count from {current_db_name}.`tabApp Log`
where date(date_time_stamp) between '{from_date}' and '{to_date}' group by user,date(date_time_stamp)) mal where date(date_time_stamp) between '{from_date}' and '{to_date}' group by user,date(date_time_stamp)) mal
where mal.user=al.user where mal.user=al.user
@ -48,19 +49,33 @@ def get_data(filters):
def get_columns(): def get_columns():
columns = [ columns = [
{"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 100}, {"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 100},
{"label": _("<b>Time</b>"), "fieldname": "last_login_time", "fieldtype": "DateTime", "width": 130}, {"label": _("<b>Time</b>"), "fieldname": "last_login_time", "fieldtype": "DateTime", "width": 130},
{"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100},
{"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 100},
{"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 150},
{"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype":"Data","width": 150},
{"label": _("<b>Device</b>"), "fieldname": "device_type", "fieldtype": "Data", "width": 100},
{"label": _("<b>Device ID</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 100},
{"label": _("<b>Latitude</b>"), "fieldname": "latitude", "fieldtype": "Data", "width": 100},
{"label": _("<b>Longitude</b>"), "fieldname": "longitude", "fieldtype": "Data", "width": 100},
{"label": _("<b>Count</b>"), "fieldname": "count", "fieldtype": "Data", "width": 100}, {"label": _("<b>Count</b>"), "fieldname": "count", "fieldtype": "Data", "width": 100},
{"label": _("<b>Device ID</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 100},
{"label": _("<b>Device</b>"), "fieldname": "device_type", "fieldtype": "Data", "width": 130},
{"label": _("<b>Latitude</b>"), "fieldname": "latitude", "fieldtype": "Data", "width": 100},
{"label": _("<b>Longitude</b>"), "fieldname": "longitude", "fieldtype": "Data", "width": 100}
] ]
return columns return columns
# def get_columns():
# columns = [
# {"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 100},
# {"label": _("<b>Time</b>"), "fieldname": "last_login_time", "fieldtype": "DateTime", "width": 130},
# {"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 150},
# {"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype":"Data","width": 150},
# {"label": _("<b>Device</b>"), "fieldname": "device_type", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Device ID</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 150},
# {"label": _("<b>User ID</b>"), "fieldname": "user_id", "fieldtype": "Data", "width": 150},
# {"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Latitude</b>"), "fieldname": "latitude", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Longitude</b>"), "fieldname": "longitude", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Count</b>"), "fieldname": "count", "fieldtype": "Data", "width": 100},
# ]
# return columns

42
smart_service/add_ons/report/model_download_report/model_download_report.py

@ -21,21 +21,23 @@ def get_data(filters):
from_date=filters['from_date'] from_date=filters['from_date']
to_date=filters['to_date'] to_date=filters['to_date']
modelfilter=filters['model'] modelfilter=filters['model']
# try:
# vId=frappe.db.sql("""SELECT myid FROM _d6463952657fa86c.tabVehicle where vehicle='{0}';""".format(modelfilter), as_dict=1) data = frappe.db.sql("""SELECT date(date) as date, device_id, device_type, app_version, download_vehicle_id, download_vehicle_version,
# vId=vId[-1] download_vehicle_date, download_vehicle_language_id, download_vehicle_current_version, mh.user_id,
# vId=vId['myid'] login_name,concat(first_name,' ',last_name) as user_name
# except: FROM `tabModel Hit` mh
# frappe.msgprint('Vehicle ID Mismatching.') left join `tabApp Users` au on mh.user_id = au.user_id
data = frappe.db.sql("""SELECT date(date) as date, device_id, device_type, app_version, download_vehicle_id, download_vehicle_version, download_vehicle_date, download_vehicle_language_id, download_vehicle_current_version, user_id WHERE download_vehicle_id='{1}' and (date(date) between '{2}' and '{3}') order by download_vehicle_id;""".format(current_db_name,
FROM {0}.`tabModel Hit` WHERE download_vehicle_id='{1}' and (date(date) between '{2}' and '{3}');""".format(current_db_name, modelfilter, from_date, to_date), as_dict=1) modelfilter, from_date, to_date), as_dict=1)
for d in data: for d in data:
d['download_vehicle_id']=modelfilter d['download_vehicle_id']=modelfilter
if d['user_id']: if d['user_id']:
try: try:
dealer_info=frappe.db.sql("""SELECT dealer FROM {0}.`tabApp Users` where user_id='{1}';""".format(current_db_name, d['user_id']), as_dict=1) dealer_info=frappe.db.sql("""SELECT dealer FROM {0}.`tabApp Users` where user_id='{1}';""".format(current_db_name, d['user_id']), as_dict=1)
dealer_info=dealer_info[-1]['dealer'] dealer_info=dealer_info[-1]['dealer']
dealer_details=frappe.db.sql("""SELECT dealer_name,dealer_code,area as location,zone FROM {0}.`tabApp Dealer` where name='{1}';""".format(current_db_name, dealer_info), as_dict=1) dealer_details=frappe.db.sql("""SELECT dealer_name,dealer_code,area as location,zone FROM {0}.`tabApp Dealer`
where name='{1}';""".format(current_db_name, dealer_info), as_dict=1)
dealer_details=dealer_details[-1] dealer_details=dealer_details[-1]
d['dealer_code']=dealer_details['dealer_code'] d['dealer_code']=dealer_details['dealer_code']
d['dealer_name']=dealer_details['dealer_name'] d['dealer_name']=dealer_details['dealer_name']
@ -52,17 +54,19 @@ def get_data(filters):
def get_columns(): def get_columns():
columns = [ columns = [
{"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 100}, {"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 150},
{"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100}, {"label": _("<b>User ID</b>"), "fieldname": "login_name", "fieldtype": "Data", "width": 125},
{"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 150}, {"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 125},
{"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 150}, {"label": _("<b>Downloaded Vehicle</b>"), "fieldname": "download_vehicle_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 100},
{"label": _("<b>Device Type</b>"), "fieldname": "device_type", "fieldtype": "Data", "width": 130},
{"label": _("<b>Downloaded Vehicle</b>"), "fieldname": "download_vehicle_id", "fieldtype": "Data", "width": 170},
{"label": _("<b>Downloaded Version</b>"), "fieldname": "download_vehicle_current_version", "fieldtype": "Data", "width": 150},
{"label": _("<b>Downloaded Language</b>"), "fieldname": "download_vehicle_language_id", "fieldtype": "Data", "width": 150}, {"label": _("<b>Downloaded Language</b>"), "fieldname": "download_vehicle_language_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>App Version</b>"), "fieldname": "app_version", "fieldtype": "Data", "width": 150} {"label": _("<b>Downloaded Version</b>"), "fieldname": "download_vehicle_current_version", "fieldtype": "Data", "width": 150},
{"label": _("<b>App Version</b>"), "fieldname": "app_version", "fieldtype": "Data", "width": 150},
# {"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 100},
# {"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 150},
# {"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 150},
# {"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device Type</b>"), "fieldname": "device_type", "fieldtype": "Data", "width": 150}
] ]
return columns return columns

53
smart_service/add_ons/report/model_hit_report/model_hit_report.py

@ -27,9 +27,12 @@ def get_data(filters):
variantfilter=filters['variant'] variantfilter=filters['variant']
variantfilter=variantfilter.split(".") variantfilter=variantfilter.split(".")
data = frappe.db.sql("""SELECT date as date, device_id, device_type, module_id, vehicle_id, variant_id, system_id, sub_system_id, procedure_id, steps_id, count(*) as count, user_id, language data = frappe.db.sql("""SELECT date as date, device_id, device_type, module_id, vehicle_id, variant_id,variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id,
FROM {0}.`tabModel Usage` WHERE vehicle_id='{1}' and variant_id='{2}' and (date(date) between '{3}' and '{4}') count(*) as count, user_id, language FROM {0}.`tabModel Usage` WHERE vehicle_id='{1}' and variant_id='{2}' and (date(date) between '{3}' and '{4}')
GROUP BY date(date), user_id, module_id, device_id, vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id, language;""".format(current_db_name, modelfilter, variantfilter[1], from_date, to_date), as_dict=1) GROUP BY date(date), user_id, module_id, device_id, vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id,
language
order by module_id,vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id,language;
""".format(current_db_name, modelfilter, variantfilter[1], from_date, to_date), as_dict=1)
for d in data: for d in data:
if d['user_id']: if d['user_id']:
@ -55,9 +58,11 @@ def get_data(filters):
to_date=filters['to_date'] to_date=filters['to_date']
modelfilter=filters['model'] modelfilter=filters['model']
data = frappe.db.sql("""SELECT date(date) as date, device_id, device_type, module_id, vehicle_id, variant_id, system_id, sub_system_id, procedure_id, steps_id, count(*) as count, user_id, language data = frappe.db.sql("""SELECT date(date) as date, device_id, device_type, module_id, vehicle_id, variant_id,variant_mapping_id, system_id, sub_system_id, procedure_id,
FROM {0}.`tabModel Usage` WHERE vehicle_id='{1}' and (date(date) between '{2}' and '{3}') steps_id, count(*) as count, user_id, language FROM {0}.`tabModel Usage` WHERE vehicle_id='{1}' and (date(date) between '{2}' and '{3}')
GROUP BY date(date), user_id, module_id, device_id, vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id, language;""".format(current_db_name, modelfilter, from_date, to_date), as_dict=1) GROUP BY date(date), user_id, module_id, device_id, vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id,language
order by module_id,vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id,language;
;""".format(current_db_name, modelfilter, from_date, to_date), as_dict=1)
for d in data: for d in data:
if d['user_id']: if d['user_id']:
@ -84,9 +89,15 @@ def get_data(filters):
to_date=filters['to_date'] to_date=filters['to_date']
variantfilter=filters['variant'] variantfilter=filters['variant']
variantfilter=variantfilter.split(".") variantfilter=variantfilter.split(".")
data = frappe.db.sql("""SELECT date as date, device_id, device_type, module_id, vehicle_id, variant_id, system_id, sub_system_id, procedure_id, steps_id, count(*) as count, user_id, language data = frappe.db.sql("""SELECT date as date, device_id, device_type, module_id, vehicle_id, variant_id,variant_mapping_id, system_id, sub_system_id,
FROM {0}.`tabModel Usage` WHERE vehicle_id='{1}' and variant_id='{2}' and (date(date) between '{3}' and '{4}') procedure_id, steps_id, count(*) as count, user_id, language,
GROUP BY date(date), user_id, module_id, device_id, vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id, language;""".format(current_db_name, variantfilter[0], variantfilter[1], from_date, to_date), as_dict=1) login_name,concat(first_name,' ',last_name) as user_name
FROM `tabModel Usage` mu left join `tabApp Users` au on mu.user_id = au.user_id
WHERE vehicle_id='{1}' and variant_id='{2}'
and (date(date) between '{3}' and '{4}') GROUP BY date(date), user_id, module_id, device_id, vehicle_id, variant_id, variant_mapping_id,
system_id, sub_system_id, procedure_id, steps_id, language
order by module_id,vehicle_id, variant_id, variant_mapping_id, system_id, sub_system_id, procedure_id, steps_id,language;
;""".format(current_db_name, variantfilter[0], variantfilter[1], from_date, to_date), as_dict=1)
for d in data: for d in data:
if d['user_id']: if d['user_id']:
@ -111,21 +122,25 @@ def get_data(filters):
def get_columns(): def get_columns():
columns = [ columns = [
{"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 150}, {"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 150},
{"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 150}, {"label": _("<b>User ID</b>"), "fieldname": "login_name", "fieldtype": "Data", "width": 125},
{"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 150}, {"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 125},
{"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 150},
{"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device Type</b>"), "fieldname": "device_type", "fieldtype": "Data", "width": 150},
{"label": _("<b>Module</b>"), "fieldname": "module_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Model</b>"), "fieldname": "vehicle_id", "fieldtype": "Data", "width": 150}, {"label": _("<b>Model</b>"), "fieldname": "vehicle_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Variant</b>"), "fieldname": "variant_id", "fieldtype": "Data", "width": 150}, {"label": _("<b>Variant Mapping</b>"), "fieldname": "variant_mapping_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Variant</b>"), "fieldname": "variant_id", "fieldtype": "Data", "width": 80},
{"label": _("<b>Module</b>"), "fieldname": "module_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>System</b>"), "fieldname": "system_id", "fieldtype": "Data", "width": 150}, {"label": _("<b>System</b>"), "fieldname": "system_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Sub System</b>"), "fieldname": "sub_system_id", "fieldtype": "Data", "width": 150}, {"label": _("<b>Sub System</b>"), "fieldname": "sub_system_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Procedure</b>"), "fieldname": "procedure_id", "fieldtype": "Data", "width": 150}, {"label": _("<b>Procedure</b>"), "fieldname": "procedure_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Steps</b>"), "fieldname": "steps_id", "fieldtype": "Data", "width": 150}, {"label": _("<b>Steps</b>"), "fieldname": "steps_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Language</b>"), "fieldname": "language", "fieldtype": "Data", "width": 150}, {"label": _("<b>Language</b>"), "fieldname": "language", "fieldtype": "Data", "width": 80},
{"label": _("<b>Count</b>"), "fieldname": "count", "fieldtype": "Data", "width": 150} {"label": _("<b>Count</b>"), "fieldname": "count", "fieldtype": "Data", "width": 80},
# {"label": _("<b>Zone</b>"), "fieldname": "zone", "fieldtype": "Data", "width": 150},
# {"label": _("<b>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 150},
# {"label": _("<b>Dealer Code</b>"), "fieldname": "dealer_code", "fieldtype": "Data", "width": 150},
# {"label": _("<b>Dealer Name</b>"), "fieldname": "dealer_name", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device</b>"), "fieldname": "device_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>Device Type</b>"), "fieldname": "device_type", "fieldtype": "Data", "width": 150}
] ]
return columns return columns

658246
smart_service/apis/THAR-en-full_v12.00.json

File diff suppressed because it is too large

BIN
smart_service/apis/__pycache__/addon_api.cpython-38.pyc

Binary file not shown.

BIN
smart_service/apis/__pycache__/app_user_login.cpython-38.pyc

Binary file not shown.

BIN
smart_service/apis/__pycache__/master_api.cpython-38.pyc

Binary file not shown.

BIN
smart_service/apis/__pycache__/publish_api.cpython-38.pyc

Binary file not shown.

BIN
smart_service/apis/__pycache__/update_validation.cpython-38.pyc

Binary file not shown.

99
smart_service/apis/addon_api.py

@ -5,22 +5,46 @@ import base64
import os import os
from frappe.utils import cstr from frappe.utils import cstr
from smart_service.apis.app_user_login import input_validation from smart_service.apis.app_user_login import input_validation
site_name = cstr(frappe.local.site)
base_url = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
current_db_name = frappe.conf.get("db_name") current_db_name = frappe.conf.get("db_name")
def custom_rate_limit(limit, seconds):
ip_based = True
ip = frappe.local.request_ip if ip_based is True else None
identity = None
identity = ip
cache_key = f"rl:{frappe.form_dict.cmd}:{identity}"
value = frappe.cache().get(cache_key) or 0
if not value:
frappe.cache().setex(cache_key, seconds, 0)
value = frappe.cache().incrby(cache_key, 1)
if value > limit:
frappe.local.response["http_status_code"] = 429
return "You hit the rate limit because of too many requests. Please try after sometime."
return 1
@frappe.whitelist() @frappe.whitelist()
def addon(args=None): def addon(args=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
# if args == None: # if args == None:
# return {"status": 0, "error": "Parameter missing: args"} # return {"status": 0, "error": "Parameter missing: args"}
val=input_validation(args=args) val = input_validation(args=args)
if val!='': if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val} return {"status": 0, "error": "Input parameter Missing: " + val}
if args: if args:
try: try:
if args == "circular": if args == "circular":
api = frappe.db.sql( api = frappe.db.sql(
'''SELECT name,title,status,description,circular_image as FileUrl,valid_till as validity from {}.tabCircular WHERE valid_till >='{}' '''.format( '''SELECT creation,name,title,status,description,circular_image as FileUrl,valid_till from {}.tabCircular WHERE valid_till >='{}' or valid_till is null '''.format(
current_db_name, frappe.utils.today()), as_dict=True) current_db_name, frappe.utils.today()), as_dict=True)
for i in api: for i in api:
if i["status"] == "Active": if i["status"] == "Active":
@ -51,7 +75,8 @@ def addon(args=None):
elif args == "teknet_module": elif args == "teknet_module":
api = frappe.db.get_list( api = frappe.db.get_list(
"Teknet Module", "Teknet Module",
fields=["name", "teknet_module_name", "active_status", "flvl_id"], fields=["name", "teknet_module_name",
"active_status", "flvl_id"],
) )
for i in api: for i in api:
if i["active_status"] == "Active": if i["active_status"] == "Active":
@ -63,10 +88,11 @@ def addon(args=None):
api = frappe.get_doc('User Manual') api = frappe.get_doc('User Manual')
else: else:
api = {"status": 0, "error": "No such function. Check argument: args"} api = {"status": 0,
"error": "No such function. Check argument: args"}
except Exception as e: except Exception as e:
api = {"status": 0, "error": e} api = {"status": 0, "error": "Module not available"}
else: else:
api = {"status": 0, "error": "Parameter:args is null"} api = {"status": 0, "error": "Parameter:args is null"}
@ -75,8 +101,12 @@ def addon(args=None):
@frappe.whitelist() @frappe.whitelist()
def bookmark(args=None, request=None): def bookmark(args=None, request=None):
val=input_validation(args=args,request=request) rate_res = custom_rate_limit(limit=5, seconds=15)
if val!='': if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val} return {"status": 0, "error": "Input parameter Missing: " + val}
# if args == None and request == None: # if args == None and request == None:
# return {"status": 0, "error": "Parameter's missing: args & request"} # return {"status": 0, "error": "Parameter's missing: args & request"}
@ -134,8 +164,11 @@ def bookmark(args=None, request=None):
@frappe.whitelist() @frappe.whitelist()
def feedback(args=None, request=None): def feedback(args=None, request=None):
val=input_validation(args=args,request=request) rate_res = custom_rate_limit(limit=5, seconds=15)
if val!='': if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val} return {"status": 0, "error": "Input parameter Missing: " + val}
# if args == None and request == None: # if args == None and request == None:
# return {"status": 0, "error": "Parameter's missing: args & request"} # return {"status": 0, "error": "Parameter's missing: args & request"}
@ -150,8 +183,8 @@ def feedback(args=None, request=None):
request = json.loads(request) request = json.loads(request)
api = frappe.db.sql( api = frappe.db.sql(
'''SELECT name,feedback_type,subject,status,concat(DATE(date),"T",time(date)) as date,user_name,attachments,description FROM {0}.`tabUser Feedback` where user_name = '{1}';''' '''SELECT name,feedback_type,subject,status,concat(DATE(date),"T",time(date)) as date,user_name,attachments,description FROM {0}.`tabUser Feedback` where user_name = '{1}';'''
.format(current_db_name, .format(current_db_name,
frappe.db.get_value('App Users', {'user_id': request['UserID']}, ['name'])), frappe.db.get_value('App Users', {'user_id': request['UserID']}, ['name'])),
as_dict=True) as_dict=True)
for i in api: for i in api:
@ -164,7 +197,7 @@ def feedback(args=None, request=None):
i['status'] = False i['status'] = False
except Exception as e: except Exception as e:
api = {"status": 0, "error": e} api = {"status": 0, "error": "Failed to fetch feedback"}
return api return api
elif args == 'post_user_feedback': elif args == 'post_user_feedback':
@ -190,7 +223,8 @@ def feedback(args=None, request=None):
for x in f: for x in f:
file_name = x file_name = x
file_data = f[x] file_data = f[x]
file_url = "/home/ubuntu/frappe-bench/sites/" + site_name + "/public/files/" + file_name
file_url = base_url+"/files/" + file_name
with open(file_url, "wb") as img: with open(file_url, "wb") as img:
img.write(base64.b64decode(file_data)) img.write(base64.b64decode(file_data))
@ -204,9 +238,10 @@ def feedback(args=None, request=None):
ret.is_private = 0 ret.is_private = 0
ret.insert(ignore_permissions=True) ret.insert(ignore_permissions=True)
file_response.append(ret) file_response.append(ret)
api = {"isSuccessful": True, "name": usr_fdbk.name, "files": file_response} api = {"isSuccessful": True,
"name": usr_fdbk.name, "files": file_response}
except Exception as e: except Exception as e:
api = {"status": 0, "error": e} api = {"status": 0, "error": str(frappe.get_traceback())}
else: else:
api = {"status": 0, "error": "Check argument: args"} api = {"status": 0, "error": "Check argument: args"}
else: else:
@ -216,15 +251,14 @@ def feedback(args=None, request=None):
@frappe.whitelist() @frappe.whitelist()
def model_hit(args=None, request=None): def model_hit(args=None, request=None):
val=input_validation(args=args,request=request) rate_res = custom_rate_limit(limit=5, seconds=15)
if val!='': if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val} return {"status": 0, "error": "Input parameter Missing: " + val}
# if args == None and request == None:
# return {"status": 0, "error": "Parameter's missing: args & request"}
# if args == None:
# return {"status": 0, "error": "Parameter missing: args"}
# if request == None:
# return {"status": 0, "error": "Parameter missing: request"}
if args and request: if args and request:
if args == "model_hit": if args == "model_hit":
try: try:
@ -245,11 +279,12 @@ def model_hit(args=None, request=None):
model_hit.download_vehicle_date = i['DownloadVehicleDate'] model_hit.download_vehicle_date = i['DownloadVehicleDate']
model_hit.download_vehicle_language_id = i['DownloadVehicleLanguageID'] model_hit.download_vehicle_language_id = i['DownloadVehicleLanguageID']
model_hit.download_vehicle_current_version = i['DownloadVehicleCurrentVersion'] model_hit.download_vehicle_current_version = i['DownloadVehicleCurrentVersion']
model_hit.insert(ignore_if_duplicate=True, ignore_mandatory=True) model_hit.insert(ignore_if_duplicate=True,
ignore_mandatory=True)
return {"isSuccessful": True} return {"isSuccessful": True}
except Exception as e: except Exception as e:
api = {"status": 0, "error": e} api = {"status": 0, "error": "Failed to fetch Model hit"}
else: else:
api = {"status": 0, "error": "Check argument: args"} api = {"status": 0, "error": "Check argument: args"}
else: else:
@ -259,8 +294,11 @@ def model_hit(args=None, request=None):
@frappe.whitelist() @frappe.whitelist()
def model_usage(args=None, request=None): def model_usage(args=None, request=None):
val=input_validation(args=args,request=request) rate_res = custom_rate_limit(limit=5, seconds=15)
if val!='': if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val} return {"status": 0, "error": "Input parameter Missing: " + val}
# if args == None and request == None: # if args == None and request == None:
# return {"status": 0, "error": "Parameter's missing: args & request"} # return {"status": 0, "error": "Parameter's missing: args & request"}
@ -293,11 +331,12 @@ def model_usage(args=None, request=None):
model_usage.steps_id = i['StepsID'] model_usage.steps_id = i['StepsID']
model_usage.menu_id = i['MenuID'] model_usage.menu_id = i['MenuID']
model_usage.language = i['Language'] model_usage.language = i['Language']
model_usage.insert(ignore_if_duplicate=True, ignore_mandatory=True) model_usage.insert(
ignore_if_duplicate=True, ignore_mandatory=True)
return {"isSuccessful": True} return {"isSuccessful": True}
except Exception as e: except Exception as e:
api = {"status": 0, "error": e} api = {"status": 0, "error": "Failed to fetch Model Usage"}
else: else:
api = {"status": 0, "error": "Check argument: args"} api = {"status": 0, "error": "Check argument: args"}
else: else:

430
smart_service/apis/app_user_login.py

@ -6,11 +6,34 @@ import xml.etree.ElementTree as ET
import frappe import frappe
import requests import requests
from frappe.utils import now from frappe.utils import now
from cryptography.fernet import Fernet, InvalidToken
from frappe.utils import cstr, encode
from datetime import datetime
from datetime import timedelta
current_db_name = frappe.conf.get("db_name") current_db_name = frappe.conf.get("db_name")
def custom_rate_limit(limit, seconds):
ip_based = True
ip = frappe.local.request_ip if ip_based is True else None
identity = None
identity = ip
cache_key = f"rl:{frappe.form_dict.cmd}:{identity}"
value = frappe.cache().get(cache_key) or 0
if not value:
frappe.cache().setex(cache_key, seconds, 0)
value = frappe.cache().incrby(cache_key, 1)
if value > limit:
frappe.local.response["http_status_code"] = 429
return "You hit the rate limit because of too many requests. Please try after sometime."
return 1
# Temporary Login # Temporary Login
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def app_user_validation_test(): def app_user_validation_test():
dicData = {} dicData = {}
@ -25,6 +48,9 @@ def app_user_validation_test():
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def app_user_validation(usr=None, pwd=None): def app_user_validation(usr=None, pwd=None):
# rate_res = custom_custom_rate_limit(limit=5, seconds=15)
# if rate_res != 1:
# return rate_res
val = input_validation(usr=usr, pwd=pwd) val = input_validation(usr=usr, pwd=pwd)
if val != '': if val != '':
return {'status': 0, 'error': "Parameter's missing: " + val} return {'status': 0, 'error': "Parameter's missing: " + val}
@ -169,6 +195,9 @@ def app_user_validation(usr=None, pwd=None):
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def grant_user_access(userdata=None, iid=None): def grant_user_access(userdata=None, iid=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
val = input_validation(userdata=userdata, iid=iid) val = input_validation(userdata=userdata, iid=iid)
if val != '': if val != '':
return {'status': 0, 'error': "Parameter's missing: " + val} return {'status': 0, 'error': "Parameter's missing: " + val}
@ -203,10 +232,20 @@ def grant_user_access(userdata=None, iid=None):
# User validation # User validation
frappe.set_user("Administrator") frappe.set_user("Administrator")
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1) user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(
current_db_name, email), as_dict=1)
# return user_name # return user_name
if user_name: if user_name:
token = generate_keys(user_name[0]['name']) # token = generate_keys(user_name[0]['name'])
try:
""" New Refresh token update """
access_token = generate_access_token(user_name[0]['name'])
refresh_token = generate_refresh_token()
token_details = update_tokens_in_doc(
user_name[0]['name'], access_token, refresh_token)
except:
return {'status': 0, 'error': "Failed to Create token"}
else: else:
user = frappe.new_doc('User') user = frappe.new_doc('User')
user.email = email user.email = email
@ -217,14 +256,23 @@ def grant_user_access(userdata=None, iid=None):
role.role = "_AppUser" role.role = "_AppUser"
user.insert(ignore_permissions=True) user.insert(ignore_permissions=True)
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1) user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(
current_db_name, email), as_dict=1)
if user_name: if user_name:
token = generate_keys(user_name[0]['name']) # token = generate_keys(user_name[0]['name'])
# return token try:
""" New Refresh token update """
access_token = generate_access_token(user_name[0]['name'])
refresh_token = generate_refresh_token()
token_details = update_tokens_in_doc(
user_name[0]['name'], access_token, refresh_token)
except:
return {'status': 0, 'error': "Failed to Create token"}
'''Inserting Dealer Data''' '''Inserting Dealer Data'''
if frappe.db.exists({'doctype': 'App Dealer', 'dealer_code': dealer_code}): if frappe.db.exists({'doctype': 'App Dealer', 'dealer_code': dealer_code}):
dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code}) dealer = frappe.get_doc(
{'doctype': 'App Dealer', 'dealer_code': dealer_code})
else: else:
dealer = frappe.new_doc('App Dealer') dealer = frappe.new_doc('App Dealer')
dealer.dealer_code = dealer_code dealer.dealer_code = dealer_code
@ -233,12 +281,15 @@ def grant_user_access(userdata=None, iid=None):
dealer.area = area_name dealer.area = area_name
dealer.active_status = user_active_status dealer.active_status = user_active_status
dealer.save() dealer.save()
dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code}) dealer = frappe.get_doc(
{'doctype': 'App Dealer', 'dealer_code': dealer_code})
'''Inserting User data''' '''Inserting User data'''
app_dealer1 = frappe.get_last_doc('App Dealer', filters={"dealer_code": dealer_code}) app_dealer1 = frappe.get_last_doc(
'App Dealer', filters={"dealer_code": dealer_code})
if frappe.db.exists({'doctype': 'App Users', 'email_id': email}): if frappe.db.exists({'doctype': 'App Users', 'email_id': email}):
app_user = frappe.get_doc({'doctype': 'App Users', 'email_id': email}) app_user = frappe.get_doc(
{'doctype': 'App Users', 'email_id': email})
else: else:
app_user = frappe.new_doc('App Users') app_user = frappe.new_doc('App Users')
app_user.email_id = email app_user.email_id = email
@ -268,12 +319,14 @@ def grant_user_access(userdata=None, iid=None):
if frappe.db.exists({'doctype': 'App Device', 'device_id': device_id}): if frappe.db.exists({'doctype': 'App Device', 'device_id': device_id}):
frappe.db.sql( frappe.db.sql(
'''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id, '''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id,
"Inactive", "Inactive",
current_db_name)) current_db_name))
frappe.db.commit() frappe.db.commit()
time.sleep(1) time.sleep(1)
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email}) app_user1 = frappe.get_last_doc(
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id}) 'App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc(
'App Device', filters={"device_id": device_id})
app_logs = frappe.new_doc('App Log') app_logs = frappe.new_doc('App Log')
app_logs.user = app_user1.name app_logs.user = app_user1.name
@ -285,7 +338,8 @@ def grant_user_access(userdata=None, iid=None):
app_logs.date_time_stamp = now() app_logs.date_time_stamp = now()
app_logs.insert() app_logs.insert()
app_device_tmp = frappe.get_last_doc('App Device', filters={"device_id": device_id}) app_device_tmp = frappe.get_last_doc(
'App Device', filters={"device_id": device_id})
frappe.db.sql('''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where name = "{0}";'''.format( frappe.db.sql('''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where name = "{0}";'''.format(
app_device_tmp.name, "Active", current_db_name)) app_device_tmp.name, "Active", current_db_name))
frappe.db.commit() frappe.db.commit()
@ -300,8 +354,10 @@ def grant_user_access(userdata=None, iid=None):
app_logs3.insert() app_logs3.insert()
else: else:
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email}) app_user1 = frappe.get_last_doc(
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id}) 'App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc(
'App Device', filters={"device_id": device_id})
app_logs = frappe.new_doc('App Log') app_logs = frappe.new_doc('App Log')
app_logs.user = app_user1.name app_logs.user = app_user1.name
app_logs.device = app_device.name app_logs.device = app_device.name
@ -329,7 +385,8 @@ def grant_user_access(userdata=None, iid=None):
'''UPDATE {3}.`tabApp Device` set last_login= '{0}', device_type = '{2}' where name = "{1}";'''.format( '''UPDATE {3}.`tabApp Device` set last_login= '{0}', device_type = '{2}' where name = "{1}";'''.format(
now(), iid, device_type, current_db_name)) now(), iid, device_type, current_db_name))
frappe.db.commit() frappe.db.commit()
app_user2 = frappe.get_last_doc('App Users', filters={"email_id": email}) app_user2 = frappe.get_last_doc(
'App Users', filters={"email_id": email})
app_logs = frappe.new_doc('App Log') app_logs = frappe.new_doc('App Log')
app_logs.user = app_user2.name app_logs.user = app_user2.name
app_logs.device = iid app_logs.device = iid
@ -340,8 +397,8 @@ def grant_user_access(userdata=None, iid=None):
app_logs.save() app_logs.save()
lst = frappe.db.sql( lst = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format( '''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True) current_db_name, device_id), as_list=True)
lst1 = frappe.db.sql( lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format( '''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format(
current_db_name, email), as_list=True) current_db_name, email), as_list=True)
@ -349,15 +406,21 @@ def grant_user_access(userdata=None, iid=None):
user_details = {} user_details = {}
user_details['Installation ID'] = lst[0][0] user_details['Installation ID'] = lst[0][0]
user_details['User ID'] = lst1[0][0] user_details['User ID'] = lst1[0][0]
user_details['token'] = token # user_details['token'] = token
user_details['status'] = 1
user_details['token_details'] = token_details
return user_details return user_details
except Exception as e1: except Exception as e1:
return {'status': 0, 'error': e1} return {'status': 0, 'error': "Invalid Inputs"}
@frappe.whitelist(allow_guest=True) @frappe.whitelist(allow_guest=True)
def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None): def new_app_user_validation(usr=None, pwd=None, iid=None, device_data=None):
val = input_validation(usr=usr, pwd=pwd,iid=iid,device_data=device_data) rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
val = input_validation(usr=usr, pwd=pwd, iid=iid, device_data=device_data)
if val != '': if val != '':
return {'status': 0, 'error': "Parameter's missing: " + val} return {'status': 0, 'error': "Parameter's missing: " + val}
@ -386,13 +449,13 @@ def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None):
dicData['ID'] = "100" dicData['ID'] = "100"
dicData.update(device_data) dicData.update(device_data)
return new_grant_user_access(dicData,iid) return new_grant_user_access(dicData, iid)
else: else:
return {'status': 0, 'error': 'Invalid Credentials'} return {'status': 0, 'error': 'Invalid Credentials'}
elif technician_login == 0 and mahindra_login == 1: elif technician_login == 0 and mahindra_login == 1:
response1 = requests.post("http://www.mahindramile.com/WindowAuth/Service.asmx/ValidateCredential", response1 = requests.post("http://www.mahindramile.com/WindowAuth/Service.asmx/ValidateCredential",
data=data, headers=headers) data=data, headers=headers)
decoded1 = response1.content.decode('utf-8') decoded1 = response1.content.decode('utf-8')
node = ET.fromstring(decoded1) node = ET.fromstring(decoded1)
dictValue = xml_to_dict(node) dictValue = xml_to_dict(node)
@ -426,7 +489,7 @@ def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None):
msgDic['IsSuccessfull'] = dictValue['children']['IsSuccessfull']['text'] msgDic['IsSuccessfull'] = dictValue['children']['IsSuccessfull']['text']
if dicData['ID'] == "": if dicData['ID'] == "":
dicData['ID'] = "100" dicData['ID'] = "100"
return new_grant_user_access(dicData,iid) return new_grant_user_access(dicData, iid)
except: except:
msgDic['IsSuccessfull'] = node.text msgDic['IsSuccessfull'] = node.text
@ -438,7 +501,7 @@ def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None):
decoded = response.content.decode('utf-8') decoded = response.content.decode('utf-8')
response1 = requests.post("http://www.mahindramile.com/WindowAuth/Service.asmx/ValidateCredential", response1 = requests.post("http://www.mahindramile.com/WindowAuth/Service.asmx/ValidateCredential",
data=data, headers=headers) data=data, headers=headers)
decoded1 = response1.content.decode('utf-8') decoded1 = response1.content.decode('utf-8')
node = ET.fromstring(decoded1) node = ET.fromstring(decoded1)
dictValue = xml_to_dict(node) dictValue = xml_to_dict(node)
@ -476,7 +539,7 @@ def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None):
dicData['ID'] = "100" dicData['ID'] = "100"
dicData.update(device_data) dicData.update(device_data)
return new_grant_user_access(dicData,iid) return new_grant_user_access(dicData, iid)
else: else:
frappe.set_user("Administrator") frappe.set_user("Administrator")
@ -486,7 +549,7 @@ def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None):
dicData['ID'] = "100" dicData['ID'] = "100"
dicData['Code'] = '' dicData['Code'] = ''
dicData.update(device_data) dicData.update(device_data)
return new_grant_user_access(dicData,iid) return new_grant_user_access(dicData, iid)
else: else:
return {'status': 0, 'error': 'Login Blocked'} return {'status': 0, 'error': 'Login Blocked'}
@ -495,6 +558,9 @@ def new_app_user_validation(usr=None, pwd=None,iid=None,device_data=None):
def new_grant_user_access(userdata=None, iid=None): def new_grant_user_access(userdata=None, iid=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
try: try:
user_id = userdata['ID'] user_id = userdata['ID']
email = userdata['EmailId'] email = userdata['EmailId']
@ -524,10 +590,18 @@ def new_grant_user_access(userdata=None, iid=None):
# User validation # User validation
frappe.set_user("Administrator") frappe.set_user("Administrator")
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1) user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(
current_db_name, email), as_dict=1)
if user_name: if user_name:
token = generate_keys(user_name[0]['name']) token = generate_keys(user_name[0]['name'])
""" New Refresh token update """
access_token = generate_access_token(user_name[0]['name'])
refresh_token = generate_refresh_token()
token_details = update_tokens_in_doc(
user_name[0]['name'], access_token, refresh_token)
else: else:
user = frappe.new_doc('User') user = frappe.new_doc('User')
user.email = email user.email = email
@ -538,13 +612,21 @@ def new_grant_user_access(userdata=None, iid=None):
role.role = "_AppUser" role.role = "_AppUser"
user.insert(ignore_permissions=True) user.insert(ignore_permissions=True)
user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(current_db_name,email),as_dict=1) user_name = frappe.db.sql('''SELECT name FROM {0}.tabUser where email='{1}';'''.format(
current_db_name, email), as_dict=1)
if user_name: if user_name:
token = generate_keys(user_name[0]['name']) token = generate_keys(user_name[0]['name'])
""" New Refresh token update """
access_token = generate_access_token(user_name[0]['name'])
refresh_token = generate_refresh_token()
token_details = update_tokens_in_doc(
user_name[0]['name'], access_token, refresh_token)
'''Inserting Dealer Data''' '''Inserting Dealer Data'''
if frappe.db.exists({'doctype': 'App Dealer', 'dealer_code': dealer_code}): if frappe.db.exists({'doctype': 'App Dealer', 'dealer_code': dealer_code}):
dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code}) dealer = frappe.get_doc(
{'doctype': 'App Dealer', 'dealer_code': dealer_code})
else: else:
dealer = frappe.new_doc('App Dealer') dealer = frappe.new_doc('App Dealer')
dealer.dealer_code = dealer_code dealer.dealer_code = dealer_code
@ -553,12 +635,15 @@ def new_grant_user_access(userdata=None, iid=None):
dealer.area = area_name dealer.area = area_name
dealer.active_status = user_active_status dealer.active_status = user_active_status
dealer.save() dealer.save()
dealer = frappe.get_doc({'doctype': 'App Dealer', 'dealer_code': dealer_code}) dealer = frappe.get_doc(
{'doctype': 'App Dealer', 'dealer_code': dealer_code})
'''Inserting User data''' '''Inserting User data'''
app_dealer1 = frappe.get_last_doc('App Dealer', filters={"dealer_code": dealer_code}) app_dealer1 = frappe.get_last_doc(
'App Dealer', filters={"dealer_code": dealer_code})
if frappe.db.exists({'doctype': 'App Users', 'email_id': email}): if frappe.db.exists({'doctype': 'App Users', 'email_id': email}):
app_user = frappe.get_doc({'doctype': 'App Users', 'email_id': email}) app_user = frappe.get_doc(
{'doctype': 'App Users', 'email_id': email})
else: else:
app_user = frappe.new_doc('App Users') app_user = frappe.new_doc('App Users')
app_user.email_id = email app_user.email_id = email
@ -588,12 +673,14 @@ def new_grant_user_access(userdata=None, iid=None):
if frappe.db.exists({'doctype': 'App Device', 'device_id': device_id}): if frappe.db.exists({'doctype': 'App Device', 'device_id': device_id}):
frappe.db.sql( frappe.db.sql(
'''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id, '''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id,
"Inactive", "Inactive",
current_db_name)) current_db_name))
frappe.db.commit() frappe.db.commit()
time.sleep(1) time.sleep(1)
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email}) app_user1 = frappe.get_last_doc(
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id}) 'App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc(
'App Device', filters={"device_id": device_id})
app_logs = frappe.new_doc('App Log') app_logs = frappe.new_doc('App Log')
app_logs.user = app_user1.name app_logs.user = app_user1.name
@ -605,7 +692,8 @@ def new_grant_user_access(userdata=None, iid=None):
app_logs.date_time_stamp = now() app_logs.date_time_stamp = now()
app_logs.insert() app_logs.insert()
app_device_tmp = frappe.get_last_doc('App Device', filters={"device_id": device_id}) app_device_tmp = frappe.get_last_doc(
'App Device', filters={"device_id": device_id})
frappe.db.sql('''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where name = "{0}";'''.format( frappe.db.sql('''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where name = "{0}";'''.format(
app_device_tmp.name, "Active", current_db_name)) app_device_tmp.name, "Active", current_db_name))
frappe.db.commit() frappe.db.commit()
@ -620,8 +708,10 @@ def new_grant_user_access(userdata=None, iid=None):
app_logs3.insert() app_logs3.insert()
else: else:
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email}) app_user1 = frappe.get_last_doc(
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id}) 'App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc(
'App Device', filters={"device_id": device_id})
app_logs = frappe.new_doc('App Log') app_logs = frappe.new_doc('App Log')
app_logs.user = app_user1.name app_logs.user = app_user1.name
app_logs.device = app_device.name app_logs.device = app_device.name
@ -649,7 +739,8 @@ def new_grant_user_access(userdata=None, iid=None):
'''UPDATE {3}.`tabApp Device` set last_login= '{0}', device_type = '{2}' where name = "{1}";'''.format( '''UPDATE {3}.`tabApp Device` set last_login= '{0}', device_type = '{2}' where name = "{1}";'''.format(
now(), iid, device_type, current_db_name)) now(), iid, device_type, current_db_name))
frappe.db.commit() frappe.db.commit()
app_user2 = frappe.get_last_doc('App Users', filters={"email_id": email}) app_user2 = frappe.get_last_doc(
'App Users', filters={"email_id": email})
app_logs = frappe.new_doc('App Log') app_logs = frappe.new_doc('App Log')
app_logs.user = app_user2.name app_logs.user = app_user2.name
app_logs.device = iid app_logs.device = iid
@ -660,8 +751,8 @@ def new_grant_user_access(userdata=None, iid=None):
app_logs.save() app_logs.save()
lst = frappe.db.sql( lst = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format( '''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True) current_db_name, device_id), as_list=True)
lst1 = frappe.db.sql( lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format( '''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format(
current_db_name, email), as_list=True) current_db_name, email), as_list=True)
@ -673,9 +764,16 @@ def new_grant_user_access(userdata=None, iid=None):
return user_details return user_details
except Exception as e1: except Exception as e1:
return {'status': 0, 'error': e1} return {'status': 0, 'error': 'Failed to verify user'}
@frappe.whitelist(allow_guest=1)
def generate_keys(user_name): def generate_keys(user_name):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
frappe.set_user("Administrator")
user_details = frappe.get_doc('User', user_name) user_details = frappe.get_doc('User', user_name)
api_secret = frappe.generate_hash(length=15) api_secret = frappe.generate_hash(length=15)
if not user_details.api_key: if not user_details.api_key:
@ -689,6 +787,9 @@ def generate_keys(user_name):
@frappe.whitelist() @frappe.whitelist()
def login_generate_token(doc=None, method=None): def login_generate_token(doc=None, method=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
new_tok = generate_keys('cms@guidedsmartservice.com') new_tok = generate_keys('cms@guidedsmartservice.com')
water = frappe.get_doc("Fish", None) water = frappe.get_doc("Fish", None)
water.apple = new_tok water.apple = new_tok
@ -711,3 +812,240 @@ def input_validation(**kwargs):
def xml_to_dict(node): def xml_to_dict(node):
return {'tag': node.tag, 'text': node.text, 'attrib': node.attrib, return {'tag': node.tag, 'text': node.text, 'attrib': node.attrib,
'children': {child.tag: xml_to_dict(child) for child in node}} 'children': {child.tag: xml_to_dict(child) for child in node}}
@frappe.whitelist(allow_guest=True)
def generate_user_token(user_email):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
access_token = generate_access_token(user_email)
refresh_token = generate_refresh_token()
token_details = update_tokens_in_doc(
user_email, access_token, refresh_token)
return token_details
@frappe.whitelist(allow_guest=True)
def generate_access_token(user_email):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
frappe.set_user("Administrator")
user_details = frappe.get_doc('User', user_email)
api_secret = frappe.generate_hash(length=15)
if not user_details.api_key:
api_key = frappe.generate_hash(length=15)
user_details.api_key = api_key
user_details.api_secret = api_secret
user_details.save()
token = user_details.api_key + ':' + api_secret
return token
def generate_refresh_token():
frappe.set_user("Administrator")
refresh_api_key = frappe.generate_hash(length=15)
refresh_api_secret = frappe.generate_hash(length=15)
refresh_token = refresh_api_key + ':' + refresh_api_secret
return refresh_token
""" For Refresh API """
@frappe.whitelist(allow_guest=1, methods=['POST'])
def refresh_token():
""" For Refresh API """
# rate_res = custom_rate_limit(limit=5, seconds=15)
# if rate_res != 1:
# return rate_res
frappe.set_user("Administrator")
req = frappe.request.data
req = json.loads(req)
refresh_token= req['refresh_token']
if refresh_token:
device_id= req['DeviceID']
ref_token = refresh_token
doc_details = frappe.db.sql('''
SELECT * FROM `tabRefresh Token`;''', as_dict=1)
try:
for d in doc_details:
if decrypt(d['refresh_token']) == ref_token:
access_token = generate_access_token(d['user'])
refresh_token = generate_refresh_token()
token_details = update_tokens_in_doc(
d['user'], access_token, refresh_token)
# token_details['status'] = 1
return {'status': 1, 'token_details': token_details}
# return token_details
return {'status': 0, "error": 'Invalid token'}
except Exception as e:
return {'status': 0, "error": 'Failed to generate refresh token'}
else:
return {'status': 0, "error": 'Invalid token'}
@frappe.whitelist(allow_guest=1, methods=['POST'])
def invalidate_token(refresh_token):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
if refresh_token:
frappe.set_user("Administrator")
ref_token = refresh_token
doc_details = frappe.db.sql('''
SELECT * FROM `tabRefresh Token`;''', as_dict=1)
try:
for d in doc_details:
if decrypt(d['refresh_token']) == ref_token:
frappe.delete_doc('Refresh Token', d['name'])
access_token = generate_access_token(d['user'])
return {'status': 1, "error": None}
return {'status': 0, "error": 'Failed'}
except Exception as e:
return {'status': 0, "error": 'Failed'}
else:
return {'status': 0, "error": 'Failed'}
@frappe.whitelist(allow_guest=1,methods=['POST'])
def deactivate_account(refresh_token):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
if refresh_token:
frappe.set_user("Administrator")
ref_token = refresh_token
doc_details = frappe.db.sql('''
SELECT * FROM `tabRefresh Token`;''', as_dict=1)
try:
for d in doc_details:
if decrypt(d['refresh_token']) == ref_token:
frappe.delete_doc('Refresh Token', d['name'])
access_token = generate_access_token(d['user'])
return {'status': 1, "error": None}
return {'status': 0, "error": 'Failed'}
except Exception as e:
return {'status': 0, "error": 'Failed'}
else:
return {'status': 0, "error": 'Failed'}
def update_tokens_in_doc(user_email, access, refresh):
# access_exp_hours = 15 * 60
# refresh_exp_hrs = 60 * 60 * 24
token_settings = frappe.get_doc('Token Settings')
access_exp_hours = token_settings.access_expiry_time
refresh_exp_hrs = token_settings.refresh_expiry_time
user_token_details = {}
frappe.set_user("Administrator")
doc_details = frappe.db.sql('''
SELECT name FROM `tabRefresh Token` where user = '{0}';'''.format(user_email), as_dict=1)
if doc_details:
# User Record exists
refresh_doc = frappe.get_doc('Refresh Token', doc_details[0]['name'])
else:
# Create new record
refresh_doc = frappe.new_doc('Refresh Token')
refresh_doc.user = user_email
refresh_doc.access_token = encrypt(access)
refresh_doc.refresh_token = encrypt(refresh)
# access_exp_time = datetime.now() + timedelta(seconds=access_exp_hours)
# refresh_exp_time = datetime.now() + timedelta(seconds=refresh_exp_hrs)
access_exp_time = datetime.now() + timedelta(minutes=access_exp_hours)
refresh_exp_time = datetime.now() + timedelta(hours=refresh_exp_hrs)
refresh_doc.access_expiry_time = access_exp_time
refresh_doc.refresh_expiry_time = refresh_exp_time
refresh_doc.save(ignore_permissions=True)
frappe.db.commit()
user_token_details['access_token'] = access
user_token_details['access_expiry_time'] = access_exp_hours* 60
user_token_details['refresh_token'] = refresh
user_token_details['refresh_expiry_time'] = refresh_exp_hrs* 60 * 60
return user_token_details
def encrypt(txt):
""" Encrypt Tokens """
try:
cipher_suite = Fernet(encode(get_encryption_key()))
except:
frappe.throw(_("Encryption key is in invalid format!"))
cipher_text = cstr(cipher_suite.encrypt(encode(txt)))
return cipher_text
def decrypt(txt):
""" Decrypt Tokens """
try:
cipher_suite = Fernet(encode(get_encryption_key()))
return cstr(cipher_suite.decrypt(encode(txt)))
except:
frappe.throw(_("Encryption key is in invalid format!"))
def get_encryption_key():
""" Get site encryption key """
if "encryption_key" not in frappe.local.conf:
from frappe.installer import update_site_config
encryption_key = Fernet.generate_key().decode()
update_site_config("encryption_key", encryption_key)
frappe.local.conf.encryption_key = encryption_key
return frappe.local.conf.encryption_key
@frappe.whitelist(allow_guest=1)
def deactivate_tokens():
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
token_settings = frappe.get_doc('Token Settings')
access_exp_hours = token_settings.access_expiry_time
access_exp_time = datetime.now() + timedelta(minutes=access_exp_hours)
frappe.set_user("Administrator")
doc_details = frappe.db.sql('''
SELECT * FROM `tabRefresh Token`;''', as_dict=1)
try:
cur_time = datetime.now()
for d in doc_details:
if d['access_expiry_time'] < cur_time:
doc_value = frappe.get_doc('Refresh Token', d['name'])
doc_value.access_token = encrypt(generate_keys(d['user']))
doc_value.access_expiry_time = access_exp_time
doc_value.save()
if d['refresh_expiry_time'] < cur_time:
frappe.delete_doc('Refresh Token', d['name'])
return True
except Exception as e:
return e

126
smart_service/apis/master_api.py

@ -1,27 +1,50 @@
# Copyright (c) 2021, Hard n Soft Technologies Pvt Ltd and contributors # Copyright (c) 2021, Hard n Soft Technologies Pvt Ltd and contributors
# For license information, please see license.txt # For license information, please see license.txt
import frappe import frappe
from frappe.model.document import Document
import json
from frappe.utils import cstr from frappe.utils import cstr
import datetime import datetime
from smart_service.apis.app_user_login import input_validation from smart_service.apis.app_user_login import input_validation
import os
current_db_name = frappe.conf.get("db_name") current_db_name = frappe.conf.get("db_name")
site_name = cstr(frappe.local.site)
base_url = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public/files"
base_path = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
def custom_rate_limit(limit, seconds):
ip_based = True
ip = frappe.local.request_ip if ip_based is True else None
identity = None
identity = ip
cache_key = f"rl:{frappe.form_dict.cmd}:{identity}"
value = frappe.cache().get(cache_key) or 0
if not value:
frappe.cache().setex(cache_key, seconds, 0)
value = frappe.cache().incrby(cache_key, 1)
if value > limit:
frappe.local.response["http_status_code"] = 429
return "You hit the rate limit because of too many requests. Please try after sometime."
return 1
@frappe.whitelist() @frappe.whitelist()
def masters(args=None, LSD=None): def masters(args=None, LSD=None,iid=None):
val=input_validation(args=args) rate = custom_rate_limit(limit=20, seconds=5)
if val!='': if rate != 1:
return {"status": 0, "error": "Parameter's missing:"+val} return rate
# if args == None and LSD == None: val = input_validation(args=args)
# return {"status": 0, "error": "Parameter's missing: args & LSD"} if val != '':
# if args == None: return {"status": 0, "error": "Parameter's missing:"+val}
# return {"status": 0, "error": "Parameter missing: args"}
# if LSD == None:
# return {"status": 0, "error": "Parameter missing: LSD"}
date_format = "%Y-%m-%d %H:%M:%S.%f" date_format = "%Y-%m-%d %H:%M:%S.%f"
@ -33,21 +56,23 @@ def masters(args=None, LSD=None):
try: try:
if args == "vehicle": if args == "vehicle":
api = frappe.db.get_list( val = input_validation(iid=iid)
"Vehicle", if val != '':
fields=[ return {"status": 0, "error": "Parameter's missing:"+val}
"name as vehicle", publish_type = check_pub_type(iid)
"vehicle_segment", api = []
"vehicle_segment_id", if publish_type == 'Global':
"image", api = frappe.db.sql(f'''
"active_status", select name as vehicle,vehicle_segment,vehicle_segment_id,image,active_status,display_order,
"display_order", myid as vechile_id,display_order,modified from tabVehicle
"myid as vechile_id", where modified > '{LSD}' and global_publish = 1;
"display_order", ''',as_dict=1)
"modified", else:
], api = frappe.db.sql(f'''
filters={"modified": [">", LSD]}, select name as vehicle,vehicle_segment,vehicle_segment_id,image,active_status,display_order,
) myid as vechile_id,display_order,modified from tabVehicle
where modified > '{LSD}' and internal_publish = 1;
''',as_dict=1)
for i in api: for i in api:
if i["active_status"] == "Active": if i["active_status"] == "Active":
i["active_status"] = True i["active_status"] = True
@ -113,7 +138,8 @@ def masters(args=None, LSD=None):
elif args == "drive": elif args == "drive":
api = frappe.db.get_list( api = frappe.db.get_list(
"Drive", "Drive",
fields=["name as drive", "active_status", "myid as drive_id", "modified"], fields=["name as drive", "active_status",
"myid as drive_id", "modified"],
filters={"modified": [">", LSD]}, filters={"modified": [">", LSD]},
) )
for i in api: for i in api:
@ -125,7 +151,8 @@ def masters(args=None, LSD=None):
elif args == "fuel": elif args == "fuel":
api = frappe.db.get_list( api = frappe.db.get_list(
"Fuel", "Fuel",
fields=["name as fuel", "active_status", "myid as fuel_id", "modified"], fields=["name as fuel", "active_status",
"myid as fuel_id", "modified"],
filters={"modified": [">", LSD]}, filters={"modified": [">", LSD]},
) )
for i in api: for i in api:
@ -187,17 +214,23 @@ def masters(args=None, LSD=None):
i["active_status"] = False i["active_status"] = False
elif args == "custom_languages": elif args == "custom_languages":
api = frappe.db.get_list( val = input_validation(iid=iid)
"Custom Languages", if val != '':
fields=[ return {"status": 0, "error": "Parameter's missing:"+val}
"lang_name", publish_type = check_pub_type(iid)
"lang_code", api = []
"active_status", if publish_type == 'Global':
"display_order", api = frappe.db.sql('''
"myid as lang_id", SELECT lang_name,lang_code,active_status,display_order,myid as lang_id,modified FROM `tabCustom Languages`
"modified", where modified> 'LSD' and global_publish = 1;
], ''',as_dict=1)
)
else:
api = frappe.db.sql('''
SELECT lang_name,lang_code,active_status,display_order,myid as lang_id,modified FROM `tabCustom Languages`
where modified> 'LSD' and internal_publish = 1;
''',as_dict=1)
for i in api: for i in api:
if i["active_status"] == "Active": if i["active_status"] == "Active":
i["active_status"] = True i["active_status"] = True
@ -252,3 +285,14 @@ def masters(args=None, LSD=None):
api = {"status": 0, "error": e} api = {"status": 0, "error": e}
return api return api
def check_pub_type(iid):
if not iid:
return False
device_pub_type = frappe.db.sql(f'''
select publish_type from `tabApp Device` where name = '{iid}' and active_status = 'Active';''')
if not device_pub_type:
return False
return device_pub_type[0][0]

909
smart_service/apis/publish_api.py

File diff suppressed because it is too large

475
smart_service/apis/support.py

@ -0,0 +1,475 @@
import frappe
import json
import time
import re
import os
from frappe.utils import cstr
site_name = cstr(frappe.local.site)
base_path = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
base_url = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public/files"
base_url1 = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
""" Working """
# @frappe.whitelist(allow_guest=1)
# def delete_all_publish():
# try:
# frappe.db.sql('delete from `tabPublish`;')
# time.sleep(1)
# frappe.db.sql('delete from `tabPublish_Docs`;')
# except Exception as e:
# return str(e)
# return True
""" Working """
# @frappe.whitelist(allow_guest=1)
# def reset_all_publish_assets():
# try:
# frappe.db.sql(
# 'update `tabSystem Mapping_System Assets` set published=0;')
# except Exception as e:
# return str(e)
# return True
def custom_rate_limit(limit, seconds):
ip_based = True
ip = frappe.local.request_ip if ip_based is True else None
identity = None
identity = ip
cache_key = f"rl:{frappe.form_dict.cmd}:{identity}"
value = frappe.cache().get(cache_key) or 0
if not value:
frappe.cache().setex(cache_key, seconds, 0)
value = frappe.cache().incrby(cache_key, 1)
if value > limit:
frappe.local.response["http_status_code"] = 429
return "You hit the rate limit because of too many requests. Please try after sometime."
return 1
@frappe.whitelist(allow_guest=1)
def change_star_data():
count = frappe.db.sql('''
select count(*) from tabProcedure_Details where content like '%**%';
''', as_dict=1)
print(count)
updated_list = []
error_list = []
data = frappe.db.sql('''
select step_name,content_type,content,name,parent,replace(content,'**','abcxyz ') as new_content from tabProcedure_Details where content like '%**%';
''', as_dict=1)
for v in data:
try:
result = re.split(r"abcxyz ", v['new_content'], flags=0)
FLAG = 0
sts = ''
if len(result) > 1:
sts += result[0]
for r in range(1, len(result)):
if FLAG == 0:
sts += '<b>' + result[r] + '</b>'
FLAG = 1
else:
sts += result[r]
FLAG = 0
frappe.db.sql(
f'''update tabProcedure_Details set content = "{sts}" where name = '{v['name']}'; ''')
v['new_content'] = sts
except Exception as e:
error_list.append({v['name']: e})
updated_list.append(v)
content_file = base_path + "/files/json_files/content_update.json"
error_file = base_path + "/files/json_files/content_error.json"
with open(error_file, 'w') as outfile:
try:
outfile.write(json.dumps(error_list))
except:
pass
with open(content_file, 'w') as outfile:
try:
outfile.write(json.dumps(updated_list))
except:
pass
return content_file
def change_file_type():
folder_path = base_url
count = 0
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.split('.')[-1] == 'PNG':
count += 1
f1 = os.path.join(root, file)
f2 = f1[:-3] + 'png'
os.rename(f1, f2)
if file.split('.')[-1] == 'JPG':
count += 1
f1 = os.path.join(root, file)
f2 = f1[:-3] + 'jpg'
os.rename(f1, f2)
return count
def change_procedure_ext():
try:
frappe.db.sql('''
update tabProcedure_Details set file = concat(substring(file,1,length(file)-3),lower(substring(file,length(file)-2)))
where substring(file,length(file)-2) REGEXP BINARY '[A-Z]';
''')
frappe.db.commit()
return True
except:
return False
def change_file_ext():
try:
""" File URL Change """
frappe.db.sql('''
update tabFile set file_url = concat(substring(file_url,1,length(file_url)-3),lower(substring(file_url,length(file_url)-2)))
where substring(file_url,length(file_url)-2) REGEXP BINARY '[A-Z]';
''')
frappe.db.commit()
""" File Name """
frappe.db.sql('''
update tabFile set file_name = concat(substring(file_name,1,length(file_name)-3),lower(substring(file_name,length(file_name)-2)))
where substring(file_name,length(file_name)-2) REGEXP BINARY '[A-Z]';
''')
frappe.db.commit()
except:
return False
return True
def delete_file_ext():
try:
frappe.db.sql('''
Delete from tabFile where substring(file_url,length(file_url)-2) REGEXP BINARY '[A-Z]';
''')
frappe.db.commit()
except:
return False
return True
@frappe.whitelist()
def append_size_file():
try:
data = frappe.db.sql(
""" SELECT * FROM `tabFile` where file_size = 0 and is_folder!=1; """, as_dict=1)
for d in data:
try:
file_path = base_url1 + d.get("file_url")
isExist=os.path.exists(file_path)
if isExist:
file_size = os.path.getsize(file_path)
frappe.db.sql(
f'''UPDATE `tabFile` SET file_size = '{file_size}' WHERE name = '{d['name']}'; ''', as_dict=1)
frappe.db.commit()
else:
pass
except Exception as e:
return str(e)
return data
except Exception as e:
frappe.log_error("FIle size ", str(e))
return e
def asset_to_files_path():
try:
count = frappe.db.sql('''
select count(*) from tabProcedure_Details where content_type = 'File' and file like '%Asset/%';''')
frappe.db.sql('''
update tabProcedure_Details set file =concat('/files/',SUBSTRING_INDEX(file,'/',-1)) where content_type = 'File' and file like '%Asset/%';
''')
frappe.db.commit()
return count
except:
return False
def change_file_dir():
base_path = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
file_data = frappe.db.sql('''
select name,file from tabProcedure_Details where content_type = 'File' ;''', as_dict=1)
changed_file_list = []
for d in file_data:
path = d['file']
isExist = os.path.exists(base_path + path)
if not isExist:
ext = path[-3:]
path = path[:-3]
extension = ''
if ext == 'png':
extension = 'jpg'
if ext == 'jpg':
extension = 'png'
new_full_path = path + extension
new_file_dir = base_path + new_full_path
if os.path.exists(new_file_dir):
changed_file_list.append(str(new_full_path))
frappe.db.sql(f'''
update tabProcedure_Details set file = '{new_full_path}' where content_type = 'File' and name = '{d['name']}';
''')
frappe.db.commit()
frappe.log_error("ALL updated files", str(changed_file_list))
if file_data:
return file_data
else:
return "Done"
@frappe.whitelist(allow_guest=1)
def file_not_exists():
# file_data = frappe.db.sql(
# '''select parent,step_name,file,name from tabProcedure_Details where content_type = 'File' order by parent;''', as_dict=1)
""" Cover Images """
file_data = frappe.db.sql(
'''selectparent,systems,sub_systems,cover_image from `tabSystem Mapping_Sub System` where order by parent;''', as_dict=1)
changed_file_list = []
count = 1
for d in file_data:
path = d['file']
is_exist = os.path.exists(base_path + path)
if not is_exist:
print(d)
d['id'] = count
changed_file_list.append(d)
count += 1
file_path_not_exists = base_path + "/files/json_files/cover_missing.json"
with open(file_path_not_exists, 'w') as outfile:
try:
outfile.write(json.dumps(changed_file_list))
except Exception as e:
pass
@frappe.whitelist(allow_guest=1)
def get_mp4_cover():
file_data = frappe.db.sql(
'''select parent,systems,sub_systems,cover_image from `tabSystem Mapping_Sub System` where cover_image like '.mp4' order by parent;''', as_dict=1)
file_path_not_exists = base_path + "/files/json_files/cover_mp4.json"
with open(file_path_not_exists, 'w') as outfile:
try:
outfile.write(json.dumps(file_data))
except Exception as e:
pass
def remove_extra_spaces_in_file_path():
import re
file_path_not_exists = base_path + "/files/json_files/1.json"
with open(file_path_not_exists, 'r') as outfile:
data = json.load(outfile)
for d in data:
print(d['file'])
res_str = re.sub("/files/ ", "/files/", d['file'])
# res_str = re.sub("/files/ ", "/files/", res_str)
print(res_str)
frappe.db.sql(f'''
update tabProcedure_Details set file = '{res_str}' where name = '{d['name']}';
''')
frappe.db.commit()
def return_star_data():
data = frappe.db.sql('''
select content_type,content,name,parent,replace(content,'*','abcxyz ') as new_content from tabProcedure_Details where content like "%*%";
''', as_dict=1)
return data
def change_star_data():
count = frappe.db.sql('''
select count(*) from tabProcedure_Details where content like '%**%';
''', as_dict=1)
print(count)
updated_list = []
error_list = []
data = frappe.db.sql('''
select step_name,content_type,content,name,parent,replace(content,'**','abcxyz ') as new_content from tabProcedure_Details where content like '%**%';
''', as_dict=1)
for v in data:
try:
result = re.split(r"abcxyz ", v['new_content'], flags=0)
FLAG = 0
sts = ''
if len(result) > 1:
sts += result[0]
for r in range(1, len(result)):
if FLAG == 0:
sts += '<b>' + result[r] + '</b>'
FLAG = 1
else:
sts += result[r]
FLAG = 0
frappe.db.sql(
f'''update tabProcedure_Details set content = "{sts}" where name = '{v['name']}'; ''')
v['new_content'] = sts
except Exception as e:
error_list.append({v['name']: e})
updated_list.append(v)
content_file = base_path + "/files/json_files/content_update.json"
error_file = base_path + "/files/json_files/content_error.json"
with open(error_file, 'w') as outfile:
try:
outfile.write(json.dumps(error_list))
except:
pass
with open(content_file, 'w') as outfile:
try:
outfile.write(json.dumps(updated_list))
except:
pass
return content_file
def change_single_star_data():
count = frappe.db.sql('''
select count(*) from tabProcedure_Details where content like "%* %";''', as_dict=1)
print(count)
updated_list = []
error_list = []
data = frappe.db.sql('''
select name,parent,step_name,content_type,content,replace(content,'* ','abcxyz ') as new_content from tabProcedure_Details where content like "%* %";
''', as_dict=1)
for v in data:
try:
result = re.split(r"abcxyz ", v['new_content'], flags=0)
sts = '<ul>'
if len(result) > 1:
for a in range(1, len(result)):
sts += '<li>' + result[a] + '</li> '
sts += '</ul>'
frappe.db.sql(
f'''update tabProcedure_Details set content = "{sts}" where name = '{v['name']}'; ''')
frappe.db.commit()
v['new_content'] = sts
updated_list.append(v)
except Exception as e:
error_list.append({v['name']: e})
content_file = base_path + "/files/json_files/content_single_star_update.json"
error_file = base_path + "/files/json_files/content_error_single_star.json"
with open(error_file, 'w') as outfile:
try:
outfile.write(json.dumps(error_list))
except:
pass
with open(content_file, 'w') as outfile:
try:
outfile.write(json.dumps(updated_list))
except:
pass
return content_file
def get_single_star_data():
count = frappe.db.sql('''
select count(*) from tabProcedure_Details where content like "%*%";''', as_dict=1)
@frappe.whitelist(allow_guest=1)
def procedure_do(variant,language,system):
data = frappe.db.sql(f'''SELECT min(tmss.idx) as systemdisplayorder,ts.system_name,ts.icon_file,ts.myid,ts.active_status,concat(variant,'-',ts.system_name) FROM
`tabSystem Mapping_Sub System` as tmss inner join `tabSystems` as ts on tmss.systems = ts.system_name
where tmss.parent LIKE "{variant}" and substring(tmss.parent,-5,2) = "{language}" and tmss.systems ="{system}";''',as_dict=1)
return data
@frappe.whitelist()
def set_procedure_false():
try:
frappe.db.sql('''update `tabSystem Mapping_Sub System` set procedure_is_published=0;
''')
frappe.db.commit()
return True
except Exception as e:
return False
# @frappe.whitelist(allow_guest=1)
# def clear_procedures():
# try:
# set_procedure_false()
# frappe.db.sql('''delete FROM `tabPublish`;''')
# frappe.db.sql('''delete FROM `tabPublish_Docs`;''')
# frappe.db.sql('''update `tabVariant Mapping_Assets` set published=0;''')
# frappe.db.sql('''update `tabSystem Mapping_Sub System` set procedure_is_published=0;''')
# frappe.db.sql('''update `tabSystem Mapping_System Assets` set published=0;''')
# frappe.db.commit()
# except Exception as e:
# return e
@frappe.whitelist(allow_guest=1)
def circular_api():
api = frappe.db.sql(
'''SELECT creation,name,title,status,description,circular_image as FileUrl,valid_till from `tabCircular` WHERE valid_till >='{}' '''.format(
frappe.utils.today()), as_dict=True)
for i in api:
if i["status"] == "Active":
i["status"] = True
else:
i["status"] = False
return api
@frappe.whitelist(allow_guest=1)
def get_kms_mapping(sub_system,variant,language):
try:
varKMS = variant + "-" + language + "%"
data = frappe.db.sql(f'''SELECT kilometer as kilometer_name, idx as kilometer_IDX, applicable as kilometers_applicable
FROM `tabKilometer Mapping_Items` where sub_systems="{sub_system}" and parent LIKE "{varKMS}" order by kilometer_IDX;''',as_dict=1)
return data
except Exception as e:
return e
@frappe.whitelist(allow_guest=1)
def remove_html_tags():
try:
frappe.db.sql('''update tabProcedure_Details set content= replace(content,'&gt;','>'); ''')
frappe.db.sql('''update tabProcedure_Details set content= replace(content,'&lt;','<'); ''')
frappe.db.sql('''update tabProcedure_Details set content= replace(content,'<div class="ql-editor read-mode"><p>',''); ''')
frappe.db.sql('''update tabProcedure_Details set content= replace(content,'</p></div>',''); ''')
frappe.db.sql('''update tabProcedure_Details set content= replace(content,'<div class=\"ql-editor read-mode\"><ol><li data-list=\"bullet\"><span class=\"ql-ui\" contenteditable=\"false\"></span>',''); ''')
frappe.db.sql('''update tabProcedure_Details set content= replace(content,'</li></ol></div>',''); ''')
frappe.db.commit()
return True, 'Done'
except Exception as e:
return False,e
@frappe.whitelist()
def clear_tables(table_name):
try:
frappe.db.sql(f'''delete FROM `tab{table_name}`;''')
return 1
except Exception as e:
return e

32
smart_service/apis/transaction_api.py

@ -7,16 +7,37 @@ from smart_service.apis.app_user_login import input_validation
current_db_name = frappe.conf.get("db_name") current_db_name = frappe.conf.get("db_name")
site_name = cstr(frappe.local.site) site_name = cstr(frappe.local.site)
base_url = os.path.expanduser("~") + "/frappe-bench/sites/" + site_name + "/public" base_url = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
def custom_rate_limit(limit, seconds):
ip_based = True
ip = frappe.local.request_ip if ip_based is True else None
identity = None
identity = ip
cache_key = f"rl:{frappe.form_dict.cmd}:{identity}"
value = frappe.cache().get(cache_key) or 0
if not value:
frappe.cache().setex(cache_key, seconds, 0)
value = frappe.cache().incrby(cache_key, 1)
if value > limit:
frappe.local.response["http_status_code"] = 429
return "You hit the rate limit because of too many requests. Please try after sometime."
return 1
@frappe.whitelist() @frappe.whitelist()
def get_technical_manual(args=None): def get_technical_manual(args=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
# if args == None: # if args == None:
# return {'status': 0, 'error': "Parameter missing : args"} # return {'status': 0, 'error': "Parameter missing : args"}
val=input_validation(args=args) val = input_validation(args=args)
if val!='': if val != '':
return {'status': 0, 'error': "Parameter missing :"+val} return {'status': 0, 'error': "Parameter missing :"+val}
try: try:
manual_out = frappe.db.sql('''SELECT parent as variant, language, attach_file as file, active_status,idx as variant_asset_idx FROM {0}.`tabVariant Mapping_Assets` where parent='{1}' and category='Technical Manual' manual_out = frappe.db.sql('''SELECT parent as variant, language, attach_file as file, active_status,idx as variant_asset_idx FROM {0}.`tabVariant Mapping_Assets` where parent='{1}' and category='Technical Manual'
and parentfield = 'assets';'''.format(current_db_name, args), as_dict=True) and parentfield = 'assets';'''.format(current_db_name, args), as_dict=True)
@ -36,5 +57,4 @@ def get_technical_manual(args=None):
return {"status": 1, "error": "Data Not available"} return {"status": 1, "error": "Data Not available"}
except Exception as e: except Exception as e:
return {"status": 0, "error": e} return {"status": 0, "error": "Failed to fetch data"}

815
smart_service/apis/update_validation.py

@ -7,20 +7,56 @@ import time
from smart_service.apis.app_user_login import input_validation from smart_service.apis.app_user_login import input_validation
current_db_name = frappe.conf.get("db_name") current_db_name = frappe.conf.get("db_name")
site_name = cstr(frappe.local.site) site_name = cstr(frappe.local.site)
base_url = os.path.expanduser("~") + "/frappe-bench/sites/" + site_name + "/public" base_url = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
# Constants
JSON_EXT = ".json"
JSON_INT_PATH = "/files/json_files/internal/"
JSON_GLOABL_PATH = "/files/json_files/global/"
JSON_FULL_UPDATE_PATH = "/files/json_files/full_update/"
STATUS = "status"
ERROR = "error"
UPDATE_AVAILABLE = 'IsUpdateAvailable'
UPDATE_FAILED = "Update checking Failed"
PARAM_MISSING = "Parameter missing :"
VERSION = 'Version'
CUR_VERSION = 'CurrentVersion'
FILE_ERROR = 'File failed to load'
LANGUAGE = 'Language'
FILE_SIZE = 'FileSize'
JSON_URL = 'JsonURL'
def custom_rate_limit(limit, seconds):
ip_based = True
ip = frappe.local.request_ip if ip_based is True else None
identity = None
identity = ip
cache_key = f"rl:{frappe.form_dict.cmd}:{identity}"
value = frappe.cache().get(cache_key) or 0
if not value:
frappe.cache().setex(cache_key, seconds, 0)
value = frappe.cache().incrby(cache_key, 1)
if value > limit:
frappe.local.response["http_status_code"] = 429
return "You hit the rate limit because of too many requests. Please try after sometime."
return 1
def get_parent_map(input_list, parameter): def get_parent_map(input_list, parameter):
parentChildMap = {} parent_child_map = {}
for b in input_list: for b in input_list:
parentChildMap.setdefault(b[parameter] or None, []).append(b) parent_child_map.setdefault(b[parameter] or None, []).append(b)
list1 = [] list1 = []
steps_length = 0 steps_length = 0
for p in parentChildMap: for p in parent_child_map:
da = {"procedure_name": p, 'steps': parentChildMap[p]} da = {"procedure_name": p, 'steps': parent_child_map[p]}
list1.append(da) list1.append(da)
steps_length += len(parentChildMap[p]) steps_length += len(parent_child_map[p])
for i in parentChildMap[p]: for i in parent_child_map[p]:
del i['procedure_name'] del i['procedure_name']
del i['idx'] del i['idx']
@ -29,300 +65,358 @@ def get_parent_map(input_list, parameter):
@frappe.whitelist() @frappe.whitelist()
def check_all_vehicle_updates(vehicle_list=None): def check_all_vehicle_updates(vehicle_list=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
# if vehicle_list == None: # if vehicle_list == None:
# return {"status": 0, "error": "Parameter missing: Vehicle List"} # return {STATUS: 0, ERROR: "Parameter missing: Vehicle List"}
val=input_validation(vehicle_list=vehicle_list) val = input_validation(vehicle_list=vehicle_list)
if val!='': if val != '':
return {"status": 0, "error": "Parameter missing:"+val} return {STATUS: 0, ERROR: PARAM_MISSING+val}
if vehicle_list: if vehicle_list:
try: try:
Vehicle_req_list = [] vehicle_req_list = []
response = {} response = {}
v_list = json.loads(vehicle_list) v_list = json.loads(vehicle_list)
lang = v_list['LanguageID'] lang = v_list['LanguageID']
iid = v_list['InstallationId'] iid = v_list['InstallationId']
vehicle_data = v_list['VehicleReqList'] vehicle_data = v_list['VehicleReqList']
publish_type = frappe.db.sql( publish_type = frappe.db.sql(
'''SELECT publish_type FROM {}.`tabApp Device` where name='{}';'''.format(current_db_name, iid), '''SELECT publish_type FROM `tabApp Device` where name='{}';'''.format(iid), as_list=1)
as_list=True)
if publish_type[0][0] is not None: if publish_type[0][0] is not None:
if vehicle_data: if vehicle_data:
for v in vehicle_data: for v in vehicle_data:
v_id = v['Vehicle'] v_id = v['Vehicle']
current_version = float(v['CurrentVersion']) current_version = float(v[CUR_VERSION])
data1_global = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data1_global = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_type='Global' and vehicle_status='Active' order by version ASC;'''.format( and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
current_db_name, v_id, lang), as_dict=True) order by version ASC;'''.format(v_id, lang), as_dict=1)
data1 = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data1 = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_type='{}' and vehicle_status='Active' order by version ASC;'''.format( and publish_status='Published' and publish_type='{}' and vehicle_status='Active'
current_db_name, v_id, lang, publish_type[0][0]), as_dict=True) order by version ASC;'''.format(v_id, lang, publish_type[0][0]), as_dict=1)
if data1[0]['version'] is not None: if data1[0]['version'] is not None:
if current_version == float(data1[0]['version']): if current_version == float(data1[0]['version']):
data1[0]['IsUpdateAvailable'] = "false" data1[0][UPDATE_AVAILABLE] = "false"
Vehicle_req_list.append(data1) vehicle_req_list.append(data1)
else: else:
if current_version < float(data1_global[0]['version']): if current_version < float(data1_global[0]['version']):
data = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_type='Global' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format( and publish_status='Published' and publish_type='Global' and vehicle_status='Active' and version > '{}'
current_db_name, v_id, lang, current_version), as_dict=True) order by version ASC;'''.format(v_id, lang, current_version), as_dict=1)
elif current_version == float(data1_global[0]['version']): elif current_version == float(data1_global[0]['version']):
if current_version < float(data1[0]['version']): if current_version < float(data1[0]['version']):
data = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format( language='{}' and publish_status='Published' and publish_type='{}' and vehicle_status='Active' and version > '{}'
current_db_name, v_id, lang, publish_type[0][0], current_version), as_dict=True) order by version ASC;'''.format(v_id, lang, publish_type[0][0], current_version), as_dict=1)
# return data # return data
data_append = [] data_append = []
try: try:
for d in data: for d in data:
d['IsUpdateAvailable'] = 'true' d[UPDATE_AVAILABLE] = 'true'
d['CurrentVersion'] = float(current_version) d[CUR_VERSION] = float(
current_version)
data_append.append(d) data_append.append(d)
Vehicle_req_list.append(data_append) vehicle_req_list.append(data_append)
except: except:
pass pass
response['LanguageID'] = lang response['LanguageID'] = lang
if len(Vehicle_req_list) != 0: if len(vehicle_req_list) != 0:
response['VehicleReqList'] = Vehicle_req_list[0] response['VehicleReqList'] = vehicle_req_list[0]
return response return response
else: else:
return {"status": 0, "error": "No Vehicles in criteria"} return {STATUS: 0, ERROR: "No Vehicles in criteria"}
else: else:
return {"status": 0, "error": "Invalid Publish Details"} return {STATUS: 0, ERROR: "Invalid Publish Details"}
else: else:
return {"status": 0, "error": "Invalid Publish Details"} return {STATUS: 0, ERROR: "Invalid Publish Details"}
except Exception as e: except Exception as e:
return {"status": 0, "error": e} return {STATUS: 0, ERROR: "Failed to fetch updates"}
else: else:
return {"status": 0, "error": "Check argument: vehicle list"} return {STATUS: 0, ERROR: "Check argument: vehicle list"}
@frappe.whitelist() @frappe.whitelist()
def check_vehicle_update(vehicle_list=None): def check_vehicle_update(vehicle_list=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
# if vehicle_list == None: # if vehicle_list == None:
# return {"status": 0, "error": "Parameter missing: Vehicle List"} # return {STATUS: 0, ERROR: "Parameter missing: Vehicle List"}
val=input_validation(vehicle_list=vehicle_list) val = input_validation(vehicle_list=vehicle_list)
if val!='': if val != '':
return {"status": 0, "error": "Parameter missing:"+val} return {STATUS: 0, ERROR: PARAM_MISSING+val}
if vehicle_list: if vehicle_list:
try: try:
response = {} response = {}
req_list = json.loads(vehicle_list) req_list = json.loads(vehicle_list)
response['Vehicle']=req_list['Vehicle'] response['Vehicle'] = req_list['Vehicle']
vehicle = req_list['Vehicle'] vehicle = req_list['Vehicle']
iid = req_list['InstallationId'] iid = req_list['InstallationId']
vehicle_data = req_list['VehicleReqList'] vehicle_data = req_list['VehicleReqList']
publish_type = frappe.db.get_list('App Device', filters={'name': iid}, fields='publish_type') publish_type = frappe.db.get_list(
'App Device', filters={'name': iid}, fields='publish_type')
if len(publish_type) > 0: if len(publish_type) > 0:
publish_type = publish_type[0]['publish_type'] publish_type = publish_type[0]['publish_type']
Vehicle_req_list = [] vehicle_req_list = []
# Iterate on language # Iterate on language
for v in vehicle_data: for v in vehicle_data:
l_id = v['LanguageID'] l_id = v['LanguageID']
current_version = float(v['CurrentVersion']) current_version = float(v[CUR_VERSION])
data1_global = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data1_global = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_type='Global' and vehicle_status='Active' order by version ASC;'''.format( and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
current_db_name, vehicle, l_id), as_dict=True) order by version ASC;'''.format(vehicle, l_id), as_dict=1)
data1 = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data1 = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}' and
and vehicle_status='Active' order by version ASC;'''.format( publish_status='Published' and vehicle_status='Active'
current_db_name, vehicle, l_id), as_dict=True) order by version ASC;'''.format(vehicle, l_id), as_dict=1)
if data1_global[0]['version']: if data1_global[0]['version']:
if data1[0]['version'] is not None: if data1[0]['version'] is not None:
if current_version == float(data1[0]['version']): if current_version == float(data1[0]['version']):
data1[0]['IsUpdateAvailable'] = "false" data1[0][UPDATE_AVAILABLE] = "false"
data={} data = {}
data['Language']=l_id data[LANGUAGE] = l_id
data['IsUpdateAvailable'] = 'false' data[UPDATE_AVAILABLE] = 'false'
data['CurrentVersion'] = float(current_version) data[CUR_VERSION] = float(current_version)
Vehicle_req_list.append(data) vehicle_req_list.append(data)
else: else:
if current_version < (float(data1_global[0]['version'])-1.00): if current_version < (float(data1_global[0]['version'])-1.00):
data = frappe.db.sql('''SELECT name as Name,max(version) as Version,vehicle_id as Vehicle,language as Language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
and publish_type='Global' and vehicle_status='Active' and Version > '{}' order by version ASC;'''.format( where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='Global' and
current_db_name, vehicle, l_id, current_version), as_dict=True) vehicle_status='Active' and Version > '{}' order by version ASC;'''.format(vehicle, l_id, current_version), as_dict=1)
try: try:
for d in data: for d in data:
try: try:
file_name="/files/json_files/full_update/"+vehicle+"/"+vehicle+"-"+d['Language']+"-"+"full_v"+str(d['Version'])+".json" file_name = JSON_FULL_UPDATE_PATH+vehicle+"/"+vehicle + \
file_size = os.path.getsize(base_url + file_name) "-" + \
d['JsonURL']= file_name d[LANGUAGE]+"-"+"full_v" + \
d['FileSize']= file_size str(d[VERSION])+JSON_EXT
d['Error']= None file_size = os.path.getsize(
base_url + file_name)
except: d[JSON_URL] = file_name
file_name= None d[FILE_SIZE] = file_size
d['Error'] = None
d[UPDATE_AVAILABLE] = 'true'
except Exception as e:
file_name = None
file_size = None file_size = None
d['JsonURL']= file_name d[JSON_URL] = file_name
d['FileSize']= file_size d[FILE_SIZE] = file_size
d['Error']='File failed to load' d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version) d[CUR_VERSION] = float(
Vehicle_req_list.append(d) current_version)
vehicle_req_list.append(d)
except Exception as e: except Exception as e:
Vehicle_req_list.append({"Error":e}) vehicle_req_list.append(
{ERROR: UPDATE_FAILED})
elif current_version == (float(data1_global[0]['version'])-1.00): elif current_version == (float(data1_global[0]['version'])-1.00):
data = frappe.db.sql('''SELECT name as Name,max(version) as Version,vehicle_id as Vehicle,language as Language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
and publish_type='Global' and vehicle_status='Active' and Version > '{}' order by version ASC;'''.format( where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
current_db_name, vehicle, l_id, current_version), as_dict=True) and Version > '{}' order by version ASC;'''.format(vehicle, l_id, current_version), as_dict=1)
try: try:
for d in data: for d in data:
file_name = None file_name = None
try: try:
file_name="/files/json_files/global/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json" file_name = JSON_GLOABL_PATH+vehicle+"/" + \
file_size = os.path.getsize(base_url + file_name) vehicle+"-" + \
d['JsonURL']= file_name d[LANGUAGE]+"_v" + \
d['FileSize']= file_size str(d[VERSION])+JSON_EXT
d['Error']= None file_size = os.path.getsize(
base_url + file_name)
except: d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = None
d[UPDATE_AVAILABLE] = 'true'
except Exception as e:
# file_name= None # file_name= None
file_size = None file_size = None
d['JsonURL']= file_name d[JSON_URL] = file_name
d['FileSize']= file_size d[FILE_SIZE] = file_size
d['Error']='File failed to load' d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version) d[CUR_VERSION] = float(
Vehicle_req_list.append(d) current_version)
vehicle_req_list.append(d)
except Exception as e1: except Exception as e1:
Vehicle_req_list.append({"Error":e1}) vehicle_req_list.append(
{ERROR: UPDATE_FAILED})
elif current_version == float(data1_global[0]['version']): elif current_version == float(data1_global[0]['version']):
if current_version < float(data1[0]['version']): if current_version < float(data1[0]['version']):
data = frappe.db.sql('''SELECT name as Name,max(version) as Version,vehicle_id as Vehicle,language as Language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format( FROM `tabPublish` where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='{}' and
current_db_name, vehicle, l_id, publish_type, current_version), as_dict=True) vehicle_status='Active' and version > '{}' order by version ASC;'''.format(vehicle, l_id, publish_type, current_version), as_dict=1)
try: try:
for d in data: for d in data:
try: try:
file_name="/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json" file_name = JSON_INT_PATH+vehicle+"/" + \
file_size = os.path.getsize(base_url + file_name) vehicle+"-" + \
d['JsonURL']= file_name d[LANGUAGE]+"_v" + \
d['FileSize']= file_size str(d[VERSION]) + \
d['Error']= None JSON_EXT
file_size = os.path.getsize(
except: base_url + file_name)
file_name= None d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = None
d[UPDATE_AVAILABLE] = 'true'
except Exception as e:
file_name = None
file_size = None file_size = None
d['JsonURL']= file_name d[JSON_URL] = file_name
d['FileSize']= file_size d[FILE_SIZE] = file_size
d['Error']='File failed to load' d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version) d[CUR_VERSION] = float(
Vehicle_req_list.append(d) current_version)
vehicle_req_list.append(d)
except Exception as e2: except Exception as e2:
Vehicle_req_list.append({"Error":e2}) vehicle_req_list.append(
{ERROR: UPDATE_FAILED})
elif (float(data1_global[0]['version'])-1.00) < current_version < float(data1_global[0]['version']): elif (float(data1_global[0]['version'])-1.00) < current_version < float(data1_global[0]['version']):
if current_version < float(data1[0]['version']): if current_version < float(data1[0]['version']):
data = frappe.db.sql('''SELECT name as Name,max(version) as Version,vehicle_id as Vehicle,language as Language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
and publish_type='Global' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format( where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
current_db_name, vehicle, l_id, current_version), as_dict=True) and version > '{}' order by version ASC;'''.format(vehicle, l_id, current_version), as_dict=1)
try: try:
for d in data: for d in data:
try: try:
file_name="/files/json_files/global/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json" file_name = JSON_GLOABL_PATH+vehicle+"/" + \
file_size = os.path.getsize(base_url + file_name) vehicle+"-" + \
d['JsonURL']= file_name d[LANGUAGE]+"_v" + \
d['FileSize']= file_size str(d[VERSION]) + \
d['Error']= None JSON_EXT
file_size = os.path.getsize(
except: base_url + file_name)
file_name= "/files/json_files/global/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json" d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = None
d[UPDATE_AVAILABLE] = 'true'
except Exception as e:
file_name = JSON_GLOABL_PATH+vehicle+"/" + \
vehicle+"-" + \
d[LANGUAGE]+"_v" + \
str(d[VERSION]) + \
JSON_EXT
file_size = None file_size = None
d['JsonURL']= file_name d[JSON_URL] = file_name
d['FileSize']= file_size d[FILE_SIZE] = file_size
d['Error']='File failed to load' d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version) d[CUR_VERSION] = float(
Vehicle_req_list.append(d) current_version)
vehicle_req_list.append(d)
except Exception as e2: except Exception as e2:
Vehicle_req_list.append({"Error":e2}) vehicle_req_list.append(
# else: {ERROR: UPDATE_FAILED})
# Vehicle_req_list.append({"error2":"Else"})
elif current_version > float(data1_global[0]['version']): elif current_version > float(data1_global[0]['version']):
if current_version < float(data1[0]['version']): if current_version < float(data1[0]['version']):
data = frappe.db.sql('''SELECT name as Name,max(version) as Version,vehicle_id as Vehicle,language as Language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format( where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='{}' and vehicle_status='Active' and version > '{}'
current_db_name, vehicle, l_id,publish_type, current_version), as_dict=True) order by version ASC;'''.format(vehicle, l_id, publish_type, current_version), as_dict=1)
try: try:
for d in data: for d in data:
try: try:
file_name="/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json" file_name = JSON_INT_PATH+vehicle+"/" + \
file_size = os.path.getsize(base_url + file_name) vehicle+"-" + \
d['JsonURL']= file_name d[LANGUAGE]+"_v" + \
d['FileSize']= file_size str(d[VERSION]) + \
d['Error']= None JSON_EXT
file_size = os.path.getsize(
except: base_url + file_name)
file_name= "/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json" d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = None
d[UPDATE_AVAILABLE] = 'true'
except Exception as e:
file_name = JSON_INT_PATH+vehicle+"/" + \
vehicle+"-" + \
d[LANGUAGE]+"_v" + \
str(d[VERSION]) + \
JSON_EXT
file_size = None file_size = None
d['JsonURL']= file_name d[JSON_URL] = file_name
d['FileSize']= file_size d[FILE_SIZE] = file_size
d['Error']='File failed to load' d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version) d[CUR_VERSION] = float(
Vehicle_req_list.append(d) current_version)
vehicle_req_list.append(d)
except Exception as e3: except Exception as e3:
Vehicle_req_list.append({'Error':e3}) vehicle_req_list.append(
{'Error': UPDATE_FAILED})
# else: # else:
# Vehicle_req_list.append({'Error':"Else 3"}) # vehicle_req_list.append({'Error':"Else 3"})
else: else:
Vehicle_req_list.append( vehicle_req_list.append(
{'Language': l_id, 'IsUpdateAvailable': 'false', 'CurrentVersion': float(current_version)}) {LANGUAGE: l_id, UPDATE_AVAILABLE: 'false', CUR_VERSION: float(current_version)})
else: else:
data = frappe.db.sql('''SELECT name as Name,max(version) as Version,vehicle_id as Vehicle,language as Language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published' data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format( where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='{}' and vehicle_status='Active'
current_db_name, vehicle, l_id, publish_type, current_version), as_dict=True) and version > '{}' order by version ASC;'''.format(vehicle, l_id, publish_type, current_version), as_dict=1)
try: try:
for d in data: for d in data:
try: try:
file_name="/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json" file_name = JSON_INT_PATH+vehicle+"/" + \
file_size = os.path.getsize(base_url + file_name) vehicle+"-"+d[LANGUAGE] + \
d['JsonURL']= file_name "_v"+str(d[VERSION])+JSON_EXT
d['FileSize']= file_size file_size = os.path.getsize(
d['Error']= None base_url + file_name)
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = None
d[UPDATE_AVAILABLE] = 'true'
except: except:
file_name= None file_name = None
file_size = None file_size = None
d['JsonURL']= file_name d[JSON_URL] = file_name
d['FileSize']= file_size d[FILE_SIZE] = file_size
d['Error']='File failed to load' d['Error'] = FILE_ERROR
d[UPDATE_AVAILABLE] = 'false'
d['IsUpdateAvailable'] = 'true' d[CUR_VERSION] = float(current_version)
d['CurrentVersion'] = float(current_version) vehicle_req_list.append(d)
Vehicle_req_list.append(d)
except Exception as e2: except Exception as e2:
Vehicle_req_list.append({"Error":e2}) vehicle_req_list.append(
{ERROR: UPDATE_FAILED})
response['Vehicle'] = vehicle response['Vehicle'] = vehicle
response['VehicleReqList'] = Vehicle_req_list response['VehicleReqList'] = vehicle_req_list
return response return response
else: else:
response['JSON'] = {"status": 0, "Error": "Data Not available"} response['JSON'] = {STATUS: 0, ERROR: "Data Not available"}
return response return response
except Exception as e: except Exception as e:
response['JSON'] = {"status": 0, "error": e} response['JSON'] = {STATUS: 0, ERROR: UPDATE_FAILED}
return response return response
else: else:
return {"status": 0, "error": "Check Parameter: vehicle list"} return {STATUS: 0, ERROR: "Check Parameter: vehicle list"}
def get_step_total_count(json_path): def get_step_total_count(json_path):
with open(json_path) as json_file: with open(json_path) as json_file:
@ -382,370 +476,39 @@ def calculate_step(data):
return data return data
def get_publish_ver(vehicle, l_id):
@frappe.whitelist() return frappe.db.sql('''SELECT format(max(version),2) as version,publish_type as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}' and
def check_vehicle_update11(vehicle_list=None): publish_status='Published' and vehicle_status='Active' ;'''.format(vehicle, l_id), as_dict=1)
val=input_validation(vehicle_list=vehicle_list)
if val!='':
return {"status": 0, "error": "Parameter missing:"+val}
# if vehicle_list == None:
# return {"status": 0, "error": "Parameter missing: Vehicle List"}
Vehicle_req_list = []
if vehicle_list:
response = {}
req_list = json.loads(vehicle_list)
response['Vehicle']=req_list['Vehicle']
vehicle = req_list['Vehicle']
iid = req_list['InstallationId']
vehicle_data = req_list['VehicleReqList']
publish_type = frappe.db.get_list('App Device', filters={'name': iid}, fields='publish_type')
if len(publish_type) > 0:
publish_type = publish_type[0]['publish_type']
# Iterate over language
if publish_type == 'Internal':
for v in vehicle_data:
global_ver = frappe.db.sql('''SELECT max(version) as version,publish_type as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}'
and language='{}' and publish_status='Published' and vehicle_status='Active' and publish_type = 'Global' ;'''.format(
current_db_name, vehicle, l_id), as_dict=True)
if global_ver:
global_pub_ver = global_pub_ver['version']
l_id = v['LanguageID']
cur_ver = v['CurrentVersion']
pub_ver = get_publish_ver(vehicle,l_id)
if cur_ver == pub_ver['version']:
Vehicle_req_list.append({'Language': l_id, 'IsUpdateAvailable': 'false',
'CurrentVersion': float(cur_ver)})
# Global File
else:
for v in vehicle_data:
l_id = v['LanguageID']
cur_ver = v['CurrentVersion']
global_pub = frappe.db.sql('''SELECT max(version) as version,publish_type, vehicle_id,language FROM {}.tabPublish where vehicle='{}'
and language='{}' and publish_status='Published' and vehicle_status='Active' and publish_type = 'Global' ;'''.format(
current_db_name, vehicle, l_id), as_dict=True)
if global_pub:
global_pub_ver1 = float(global_pub[0]['version'])
if global_pub_ver1 == cur_ver:
Vehicle_req_list.append({'Language': l_id, 'IsUpdateAvailable': 'false',
'CurrentVersion': float(cur_ver)})
else:
if cur_ver < global_pub_ver1:
if (global_pub_ver1 - cur_ver) > 1:
file_name="/files/json_files/full_update/"+vehicle+"/"+vehicle+"-"+ l_id +"-" + "full_v" + str(global_pub[0]['version'])+".json"
file_size = os.path.getsize(base_url + file_name)
Vehicle_req_list.append({'Version':global_pub_ver1,'Language': l_id, 'IsUpdateAvailable': 'true','JsonURL':file_name,'FileSize':file_size,
'Error':None,'CurrentVersion': float(cur_ver)})
else:
file_name="/files/json_files/global/"+vehicle+"/"+vehicle+"-"+ l_id + "_v" + str(global_pub[0]['version'])+".json"
file_size = os.path.getsize(base_url + file_name)
Vehicle_req_list.append({'Version':global_pub_ver1,'Language': l_id, 'IsUpdateAvailable': 'true','JsonURL':file_name,'FileSize':file_size,
'Error':None,'CurrentVersion': float(cur_ver)})
else:
Vehicle_req_list.append({'Language': l_id, 'IsUpdateAvailable': 'false',
'CurrentVersion': float(cur_ver)})
return Vehicle_req_list
def get_publish_ver(vehicle,l_id):
return frappe.db.sql('''SELECT max(version) as version,publish_type as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and
publish_status='Published' and vehicle_status='Active' ;'''.format(
current_db_name, vehicle, l_id), as_dict=True)
# @frappe.whitelist()
# def check_vehicle_update(vehicle_list=None):
# if vehicle_list == None:
# return {"status": 0, "error": "Parameter missing: Vehicle List"}
# if vehicle_list:
# try:
# response = {}
# req_list = json.loads(vehicle_list)
# vehicle = req_list['Vehicle']
# iid = req_list['InstallationId']
# vehicle_data = req_list['VehicleReqList']
# publish_type = frappe.db.get_list('App Device', filters={'name': iid}, fields='publish_type')
# if len(publish_type) > 0:
# publish_type = publish_type[0]['publish_type']
# Vehicle_req_list = []
# # Iterate on language
# for v in vehicle_data:
# appendList = []
# appendDict = {}
# variant = set()
# system = {}
# subsystem = {}
# procedure = {}
# list1 = []
# list2 = []
# l_id = v['LanguageID']
# current_version = v['CurrentVersion']
# # Not necessary
# if publish_type == 'Internal':
# publish_data = frappe.db.sql('''select name,CAST(version AS DECIMAL(10,2)) as version from {}.tabPublish where vehicle= '{}'
# and language='{}' and publish_type = '{}' and version > {} and vehicle_status = 'Active';
# '''.format(current_db_name, vehicle, l_id, publish_type, current_version), as_dict=True)
# else:
# publish_data = frappe.db.sql('''select name,version,release_description as description from {}.tabPublish where vehicle= '{}'
# and language='{}' and publish_type = '{}' and version > {} and vehicle_status = 'Active'; '''.format(
# current_db_name, vehicle, l_id, publish_type,
# current_version), as_dict=True)
# if len(publish_data) > 0:
# update_version = publish_data[-1]['version']
# for d in publish_data:
# publish_docs = frappe.db.get_list('Publish_Docs', filters={'parent': d['name']},
# fields=['variant_mapping', 'system', 'sub_system',
# 'procedure_link', 'procedure_status'])
# if publish_docs is not None:
# list1.append(publish_docs)
# for e in list1:
# for f in e:
# list2.append(f)
# # Sort data according to variant, system and sub system
# for d in list2:
# variant.add(d['variant_mapping'])
# for d in variant:
# temp = set()
# for j in list2:
# if j['variant_mapping'] == d:
# temp.add(j['system'])
# system[d] = temp
# for d in variant:
# temp_set = {}
# for j in system[d]:
# temp = set()
# for k in list2:
# if d == k['variant_mapping'] and j == k['system']:
# temp.add(k['sub_system'])
# temp_set[j] = temp
# subsystem[d] = temp_set
# for d in variant:
# temp_set = {}
# for i in system[d]:
# temp_dict = {}
# for j in subsystem[d][i]:
# temp_sub = set()
# for k in list2:
# if k['variant_mapping'] == d and k['system'] == i and k['sub_system'] == j:
# temp_sub.add(k['procedure_link'])
# temp_dict[j] = temp_sub
# temp_set[i] = temp_dict
# procedure[d] = temp_set
# appendList.append(procedure)
# for g in appendList:
# for f in g.keys():
# appendDict[f] = (g[f])
# final = []
# active_status_case = "CASE WHEN active_status = 'Active' THEN 'True' ELSE 'False' END AS active_status"
# for d in appendDict:
# total_count = 0
# # count = 0
# step_count = 0
# variant_out = {}
# # Variant data
# vari = frappe.db.sql('''SELECT name,variant, vehicle,family_code,vehicle_segment,fuel,transmission,drive, active_status
# FROM {}.`tabVariant Mapping` WHERE name ='{}' ; '''.format(current_db_name, d),
# as_dict=True)[0]
# var_asset = frappe.db.sql('''SELECT category, attach_file as file, {},idx as variant_asset_idx FROM {}.`tabVariant Mapping_Assets`
# where category<>'Technical Manual' and parent='{}' and language='{}';'''.format(
# active_status_case, current_db_name, d, l_id), as_dict=True)
# kms_mapping_status = frappe.db.sql(
# '''SELECT active_status FROM {0}.`tabKilometer Mapping` where name LIKE '{1}' and substring(name,-5,2)= '{2}';'''
# .format(current_db_name, vari['name'] + "%", l_id))[0][0]
# if vari['active_status'] == 'Active':
# vari['active_status'] = True
# else:
# vari['active_status'] = False
# if kms_mapping_status == 'Active':
# kms_active_status = True
# else:
# kms_active_status = False
# vari.update({'kms_mapping_active_status': kms_active_status})
# vari['Assets'] = var_asset
# total_count += len(var_asset)
# # -1 Due to NONE value in parent mapping
# total_count += len(appendDict[d]) - 1
# variant_out['Variant'] = vari
# # System data
# system_out = []
# for i in appendDict[d]:
# if i is not None:
# sys = frappe.db.sql(''' SELECT min(tmss.idx) as systemdisplayorder,ts.system_name,ts.icon_file,ts.myid,ts.active_status FROM
# {0}.`tabSystem Mapping_Sub System` as tmss inner join {0}.`tabSystems` as ts on tmss.systems = ts.system_name
# where tmss.parent LIKE '{1}' and substring(tmss.parent,-5,2) = '{2}' and tmss.systems ='{3}';'''
# .format(current_db_name, str(vari['name'] + "%"), l_id, i),
# as_dict=True)[0]
# if sys['active_status'] == 'Active':
# sys['active_status'] = True
# else:
# sys['active_status'] = False
# # System Assets
# sysassets = frappe.db.sql('''SELECT idx as systemdisplayorder, system_asset,active_status FROM {3}.`tabSystem Mapping_System Assets`
# where parent like '{0}%' and language='{1}' and systems='{2}';'''.format(
# d, l_id, i, current_db_name), as_dict=True)
# for sysasset in sysassets:
# if sysasset['active_status'] == 'Active':
# sysasset['active_status'] = True
# else:
# sysasset['active_status'] = False
# sys['Assets'] = sysassets
# total_count += len(sysassets)
# total_count += len(appendDict[d][i])
# # Sub system
# subsystem_out = []
# for j in appendDict[d][i]:
# subsys = frappe.db.sql('''select `tabSystem Mapping_Sub System`.idx as subSystemdisplayorder, systems,sub_systems, symptom,
# component, estimate_time as estimated_time, rts, mat, cover_image, `tabSub Systems`.myid,`tabSystem Mapping_Sub System`.active_status,
# `tabSystem Mapping_Sub System`.cover_image from {4}.`tabSystem Mapping_Sub System` inner join {4}.`tabSub Systems` on
# `tabSystem Mapping_Sub System`.sub_systems = `tabSub Systems`.name where `tabSystem Mapping_Sub System`.parent like '{0}-{3}%' and
# systems='{1}' and sub_systems='{2}' and `tabSystem Mapping_Sub System`.active_status = 'Active';'''.format(
# d, i, j, l_id, current_db_name), as_dict=True)
# if len(subsys) > 0:
# subsys = subsys[0]
# if subsys['active_status'] == 'Active':
# subsys['active_status'] = True
# else:
# subsys['active_status'] = False
# kms = frappe.db.sql('''SELECT kilometer as kilometer_name, idx as kilometer_IDX, applicable as kilometers_applicable
# FROM {}.`tabKilometer Mapping_Items` where sub_systems='{}' and parent Like '{}' and substring(parent,-5,2) = '{}'
# order by kilometer_IDX;'''.format(current_db_name, j, d + "%",
# l_id),
# as_dict=True)
# total_count += len(kms)
# subsys['Config Kilometer'] = kms
# for k in appendDict[d][i][j]:
# proc_details = frappe.db.sql('''select procedure_name, step_name, content_type,
# GROUP_CONCAT(case when content_type='Link' Then system_id else content end) as content,
# GROUP_CONCAT(file) as file,GROUP_CONCAT(DISTINCT idx order by idx) as display_order, idx from {}.tabProcedure_Details
# where parent ='{}' group by procedure_name,step_name,content_type,content order by idx asc; '''
# .format(current_db_name, k), as_dict=True)
# proc_data, step_length = get_parent_map(proc_details, 'procedure_name')
# procedure_status = frappe.db.sql(
# '''SELECT workflow_state FROM {1}.tabProcedure where name='{0}';'''.format(
# k, current_db_name))
# total_count += len(proc_data)
# subsys['procedure_link'] = k
# subsys['procedure_status'] = procedure_status[0][0]
# subsys['Procedure_details'] = proc_data
# step_count += step_length
# subsystem_out.append(subsys)
# sys['Subsystems'] = subsystem_out
# system_out.append(sys)
# variant_out['StepCount'] = step_count
# variant_out['Variant']['Systems'] = system_out
# variant_out['TotalCount'] = total_count + step_count
# final.append(variant_out)
# res = {'Name': '%s-%s_%s' % (iid, vehicle, l_id), 'Language': l_id,
# 'IsUpdateAvailable': 'true',
# 'CurrentVersion': float(current_version), 'Version': float(update_version)}
# try:
# dir1 = "/files/json_files/temp/"
# dir2 = base_url+ dir1
# if not os.path.exists(dir2):
# os.makedirs(dir2)
# file_name = dir1 + "%s-%s_%s.json" % (iid, vehicle, l_id)
# dicfinal = {'JSON': final}
# with open(base_url + file_name, 'w') as outfile:
# outfile.write(json.dumps(dicfinal))
# file_size = os.path.getsize(base_url + file_name)
# res['JsonURL'] = file_name
# res['FileSize'] = file_size
# res['Error'] = None
# except:
# res['JsonURL'] = None
# res['FileSize'] = None
# res['Error'] = 'File failed to save'
# Vehicle_req_list.append(res)
# else:
# Vehicle_req_list.append(
# {'Language': l_id, 'IsUpdateAvailable': 'false', 'CurrentVersion': float(current_version)})
# response['Vehicle'] = vehicle
# response['VehicleReqList'] = Vehicle_req_list
# return response
# else:
# response['JSON'] = {"status": 0, "Error": "Data Not available"}
# return response
# except Exception as e:
# response['JSON'] = {"status": 0, "error": e}
# return response
# else:
# return {"status": 0, "error": "Check Parameter: vehicle list"}
@frappe.whitelist() @frappe.whitelist()
def update_completed(FileName=None): def update_completed(FileName=None):
val=input_validation(vehicle_list=vehicle_list) rate_res = custom_rate_limit(limit=5, seconds=15)
if val!='': if rate_res != 1:
return {"status": 0, "error": "Parameter missing:"+val} return rate_res
# if FileName == None: val = input_validation(FileName=FileName)
# return {'status': 0, 'error': "Parameter missing: FileName"} if val != '':
return {STATUS: 0, ERROR: "Parameter missing:"+val}
if FileName: if FileName:
try: try:
os.remove(base_url + FileName) os.remove(base_url + FileName)
return {'isSuccessful': True} return {'isSuccessful': True}
except Exception as e: except Exception as e:
return {'isSuccessful': False,"status": 0, 'error': e} return {'isSuccessful': False, STATUS: 0, 'ERROR': e}
else: else:
return {"status": 0, "error": "Parameter: FileName is null"} return {STATUS: 0, ERROR: "Parameter: FileName is null"}
@frappe.whitelist() @frappe.whitelist()
def delete_complete(doc=None, method=None): def delete_complete(doc=None, method=None):
base_url1 = os.path.expanduser("~") + "/frappe-bench/sites/" + site_name + "/public" rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
base_url1 = os.path.expanduser(
"~") + "/frappe-bench/sites/" + site_name + "/public"
path = base_url1 + '/files/json_files/temp/' path = base_url1 + '/files/json_files/temp/'
path_file = os.listdir(path) path_file = os.listdir(path)
if path_file: if path_file:
for file in path_file: for file in path_file:
os.remove(str(path) + str(file)) os.remove(str(path) + str(file))

994
smart_service/fixtures/custom_docperm.json

File diff suppressed because it is too large

53
smart_service/fixtures/custom_field.json

@ -51,5 +51,58 @@
"translatable": 0, "translatable": 0,
"unique": 0, "unique": 0,
"width": null "width": null
},
{
"allow_in_quick_entry": 0,
"allow_on_submit": 0,
"bold": 0,
"collapsible": 0,
"collapsible_depends_on": null,
"columns": 0,
"default": null,
"depends_on": null,
"description": null,
"docstatus": 0,
"doctype": "Custom Field",
"dt": "User",
"fetch_from": null,
"fetch_if_empty": 0,
"fieldname": "pwd",
"fieldtype": "Data",
"hidden": 1,
"hide_border": 0,
"hide_days": 0,
"hide_seconds": 0,
"ignore_user_permissions": 0,
"ignore_xss_filter": 0,
"in_global_search": 0,
"in_list_view": 0,
"in_preview": 0,
"in_standard_filter": 0,
"insert_after": "new_password",
"label": "PWD",
"length": 0,
"mandatory_depends_on": null,
"modified": "2022-02-11 19:13:04.645496",
"name": "User-pwd",
"no_copy": 0,
"non_negative": 0,
"options": "",
"parent": null,
"parentfield": null,
"parenttype": null,
"permlevel": 0,
"precision": "",
"print_hide": 0,
"print_hide_if_no_value": 0,
"print_width": null,
"read_only": 0,
"read_only_depends_on": null,
"report_hide": 0,
"reqd": 0,
"search_index": 0,
"translatable": 0,
"unique": 0,
"width": null
} }
] ]

91
smart_service/fixtures/dashboard_chart.json

@ -17,7 +17,7 @@
"heatmap_year": null, "heatmap_year": null,
"is_public": 1, "is_public": 1,
"is_standard": 0, "is_standard": 0,
"last_synced_on": "2022-05-10 12:32:46.535932", "last_synced_on": "2023-02-08 09:55:09.460016",
"modified": "2022-03-28 14:33:10.648848", "modified": "2022-03-28 14:33:10.648848",
"module": null, "module": null,
"name": "Variant mapping", "name": "Variant mapping",
@ -95,11 +95,50 @@
"heatmap_year": null, "heatmap_year": null,
"is_public": 1, "is_public": 1,
"is_standard": 0, "is_standard": 0,
"last_synced_on": "2022-05-11 13:13:51.898783", "last_synced_on": "2022-11-07 15:36:06.864894",
"modified": "2022-04-11 18:20:02.591953", "modified": "2022-04-21 10:00:30.763417",
"module": null, "module": null,
"name": "Publish", "name": "Publish",
"number_of_groups": 10, "number_of_groups": 0,
"parent": null,
"parent_document_type": "",
"parentfield": null,
"parenttype": null,
"report_name": null,
"source": "",
"time_interval": "Yearly",
"timeseries": 0,
"timespan": "Last Year",
"to_date": null,
"type": "Bar",
"use_report_chart": 0,
"value_based_on": "",
"x_field": null,
"y_axis": []
},
{
"aggregate_function_based_on": null,
"based_on": "",
"chart_name": "Publish Status",
"chart_type": "Group By",
"color": "#7cbcf7",
"custom_options": null,
"docstatus": 0,
"doctype": "Dashboard Chart",
"document_type": "Publish",
"dynamic_filters_json": "[]",
"filters_json": "[[\"Publish\",\"publish_status\",\"=\",null,false]]",
"from_date": null,
"group_by_based_on": "vehicle",
"group_by_type": "Count",
"heatmap_year": null,
"is_public": 1,
"is_standard": 0,
"last_synced_on": "2022-11-07 15:36:06.930763",
"modified": "2022-04-11 18:23:00.494268",
"module": null,
"name": "Publish Status",
"number_of_groups": 0,
"parent": null, "parent": null,
"parent_document_type": "", "parent_document_type": "",
"parentfield": null, "parentfield": null,
@ -134,7 +173,7 @@
"heatmap_year": null, "heatmap_year": null,
"is_public": 1, "is_public": 1,
"is_standard": 0, "is_standard": 0,
"last_synced_on": "2022-05-11 13:13:51.477102", "last_synced_on": "2022-11-07 15:36:06.728398",
"modified": "2022-04-12 19:59:36.324953", "modified": "2022-04-12 19:59:36.324953",
"module": null, "module": null,
"name": "Procedure", "name": "Procedure",
@ -157,26 +196,26 @@
}, },
{ {
"aggregate_function_based_on": null, "aggregate_function_based_on": null,
"based_on": "", "based_on": "creation",
"chart_name": "KM Mapping", "chart_name": "Test",
"chart_type": "Group By", "chart_type": "Count",
"color": "#449CF0", "color": "#CB2929",
"custom_options": null, "custom_options": null,
"docstatus": 0, "docstatus": 0,
"doctype": "Dashboard Chart", "doctype": "Dashboard Chart",
"document_type": "Kilometer Mapping", "document_type": "App Device",
"dynamic_filters_json": "[]", "dynamic_filters_json": "[]",
"filters_json": "[[\"Kilometer Mapping\",\"workflow_state\",\"=\",null,false]]", "filters_json": "[]",
"from_date": null, "from_date": null,
"group_by_based_on": "workflow_state", "group_by_based_on": null,
"group_by_type": "Count", "group_by_type": "Count",
"heatmap_year": null, "heatmap_year": null,
"is_public": 1, "is_public": 0,
"is_standard": 0, "is_standard": 0,
"last_synced_on": "2022-05-11 13:13:51.649487", "last_synced_on": null,
"modified": "2022-05-10 13:05:25.011604", "modified": "2022-05-11 11:06:15.280730",
"module": null, "module": null,
"name": "KM Mapping", "name": "Test",
"number_of_groups": 0, "number_of_groups": 0,
"parent": null, "parent": null,
"parent_document_type": "", "parent_document_type": "",
@ -185,10 +224,10 @@
"report_name": null, "report_name": null,
"source": "", "source": "",
"time_interval": "Yearly", "time_interval": "Yearly",
"timeseries": 0, "timeseries": 1,
"timespan": "Last Year", "timespan": "Last Year",
"to_date": null, "to_date": null,
"type": "Bar", "type": "Line",
"use_report_chart": 0, "use_report_chart": 0,
"value_based_on": "", "value_based_on": "",
"x_field": null, "x_field": null,
@ -197,25 +236,25 @@
{ {
"aggregate_function_based_on": null, "aggregate_function_based_on": null,
"based_on": "", "based_on": "",
"chart_name": "Publish Status", "chart_name": "KM Mapping",
"chart_type": "Group By", "chart_type": "Group By",
"color": "#7cbcf7", "color": "#449CF0",
"custom_options": null, "custom_options": null,
"docstatus": 0, "docstatus": 0,
"doctype": "Dashboard Chart", "doctype": "Dashboard Chart",
"document_type": "Publish", "document_type": "Kilometer Mapping",
"dynamic_filters_json": "[]", "dynamic_filters_json": "[]",
"filters_json": "[[\"Publish\",\"publish_status\",\"=\",null,false]]", "filters_json": "[[\"Kilometer Mapping\",\"workflow_state\",\"=\",null,false]]",
"from_date": null, "from_date": null,
"group_by_based_on": "vehicle", "group_by_based_on": "workflow_state",
"group_by_type": "Count", "group_by_type": "Count",
"heatmap_year": null, "heatmap_year": null,
"is_public": 1, "is_public": 1,
"is_standard": 0, "is_standard": 0,
"last_synced_on": "2022-05-11 13:13:51.737960", "last_synced_on": "2022-11-07 15:36:06.500997",
"modified": "2022-04-11 18:23:00.494268", "modified": "2022-05-10 13:05:25.011604",
"module": null, "module": null,
"name": "Publish Status", "name": "KM Mapping",
"number_of_groups": 0, "number_of_groups": 0,
"parent": null, "parent": null,
"parent_document_type": "", "parent_document_type": "",

1376
smart_service/fixtures/property_setter.json

File diff suppressed because it is too large

821
smart_service/fixtures/report.json

File diff suppressed because it is too large

50
smart_service/fixtures/role.json

@ -418,7 +418,7 @@
"home_page": null, "home_page": null,
"is_custom": 0, "is_custom": 0,
"list_sidebar": 1, "list_sidebar": 1,
"modified": "2022-02-07 13:11:48.057238", "modified": "2022-02-22 10:28:00.880225",
"name": "CMS User", "name": "CMS User",
"notifications": 1, "notifications": 1,
"parent": null, "parent": null,
@ -431,6 +431,30 @@
"two_factor_auth": 0, "two_factor_auth": 0,
"view_switcher": 1 "view_switcher": 1
}, },
{
"bulk_actions": 1,
"dashboard": 1,
"desk_access": 1,
"disabled": 0,
"docstatus": 0,
"doctype": "Role",
"form_sidebar": 1,
"home_page": null,
"is_custom": 0,
"list_sidebar": 1,
"modified": "2022-02-25 12:09:33.176233",
"name": "User_Account_Manager",
"notifications": 1,
"parent": null,
"parentfield": null,
"parenttype": null,
"restrict_to_domain": null,
"role_name": "User_Account_Manager",
"search_bar": 1,
"timeline": 1,
"two_factor_auth": 0,
"view_switcher": 1
},
{ {
"bulk_actions": 0, "bulk_actions": 0,
"dashboard": 0, "dashboard": 0,
@ -790,29 +814,5 @@
"timeline": 1, "timeline": 1,
"two_factor_auth": 0, "two_factor_auth": 0,
"view_switcher": 1 "view_switcher": 1
},
{
"bulk_actions": 1,
"dashboard": 1,
"desk_access": 1,
"disabled": 0,
"docstatus": 0,
"doctype": "Role",
"form_sidebar": 1,
"home_page": null,
"is_custom": 0,
"list_sidebar": 1,
"modified": "2022-02-25 10:48:10.932318",
"name": "User_Account_Manager",
"notifications": 1,
"parent": null,
"parentfield": null,
"parenttype": null,
"restrict_to_domain": null,
"role_name": "User_Account_Manager",
"search_bar": 1,
"timeline": 1,
"two_factor_auth": 0,
"view_switcher": 1
} }
] ]

2714
smart_service/fixtures/workspace.json

File diff suppressed because it is too large

148
smart_service/hooks.py

@ -9,7 +9,7 @@ app_color = "#E31A37"
app_email = "siva@hnsonline.com" app_email = "siva@hnsonline.com"
app_license = "MIT" app_license = "MIT"
# app_logo_url = "/assets/smart_service/images/SS Alone.png" # app_logo_url = "/assets/smart_service/images/SS Alone.png"
app_logo_url = "/assets/smart_service/images/SsAndMahindra.png" app_logo_url = "/assets/smart_service/images/Mahindra Rise2.png"
# app_logo_url = "/assets/smart_service/images/ic_app_icon1.png" # app_logo_url = "/assets/smart_service/images/ic_app_icon1.png"
# ic_app_icon.png # ic_app_icon.png
@ -20,10 +20,10 @@ web_include_css = ["/assets/css/smart_service.min.css"]
# Icons # Icons
website_context = { website_context = {
"favicon": "/assets/smart_service/images/Logo Fav Icon.png", "favicon": "/assets/smart_service/images/Logo Fav Icon.png",
"splash_image": "/assets/smart_service/images/SS Alone.png", "splash_image": "/assets/smart_service/images/SS Alone.png",
# "splash_image": "/assets/smart_service/images/ic_app_icon1.png", # "splash_image": "/assets/smart_service/images/ic_app_icon1.png",
"app_name" : "smart service" "app_name": "smart service"
} }
# Includes in <head> # Includes in <head>
# ------------------ # ------------------
@ -51,7 +51,7 @@ website_context = {
# doctype_js = {"doctype" : "public/js/doctype.js"} # doctype_js = {"doctype" : "public/js/doctype.js"}
doctype_js = { doctype_js = {
"Translation": ["custom_scripts/translation.js"], "Translation": ["custom_scripts/translation.js"],
"User": ["custom_scripts/user.js"], "User": ["custom_scripts/user.js"],
} }
# doctype_list_js = {"doctype" : "public/js/doctype_list.js"} # doctype_list_js = {"doctype" : "public/js/doctype_list.js"}
# doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"} # doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"}
@ -65,7 +65,7 @@ doctype_js = {
# website user home page (by Role) # website user home page (by Role)
# role_home_page = { # role_home_page = {
# "Role": "home_page" # "Role": "home_page"
# } # }
# Generators # Generators
@ -102,48 +102,53 @@ doctype_js = {
# --------------- # ---------------
# Override standard doctype classes # Override standard doctype classes
#override_doctype_class = { # override_doctype_class = {
# "ToDo": "custom_app.overrides.CustomToDo" # "ToDo": "custom_app.overrides.CustomToDo"
#} # }
# Document Events # Document Events
# --------------- # ---------------
# Hook on document methods and events # Hook on document methods and events
doc_events = { doc_events = {
"File": { "File": {
"validate": ["smart_service.overrides.overrides.override_file.validate"], "validate": ["smart_service.overrides.overrides.override_file.validate"],
} }
# "*": { # "*": {
# "on_update": "method", # "on_update": "method",
# "on_cancel": "method", # "on_cancel": "method",
# "on_trash": "method" # "on_trash": "method"
# } # }
} }
# Scheduled Tasks # Scheduled Tasks
# --------------- # ---------------
scheduler_events = { scheduler_events = {
# "all": [ # "all": [
# "smart_service.tasks.all" # "smart_service.tasks.all"
# ], # ],
"daily": [ "cron": {
"smart_service.apis.app_user_login.login_generate_token" "0/1 * * * *": [
# "smart_service.tasks.daily" "smart_service.apis.app_user_login.deactivate_tokens"
], ]
# "hourly": [ },
#"smart_service.tasks.hourly" "daily": [
# "smart_service.apis.app_user_login.login_generate_token", "smart_service.apis.app_user_login.login_generate_token"
# ], # "smart_service.tasks.daily"
"weekly": [ ],
# "smart_service.tasks.weekly" # "hourly": [
"smart_service.apis.update_validation.delete_complete" # "smart_service.tasks.hourly"
] # "smart_service.apis.app_user_login.login_generate_token",
# "monthly": [ # ],
# "smart_service.tasks.monthly" "weekly": [
# ] # "smart_service.tasks.weekly"
} "smart_service.apis.update_validation.delete_complete"
]
# "monthly": [
# "smart_service.tasks.monthly"
# ]
}
# Testing # Testing
# ------- # -------
@ -173,24 +178,24 @@ scheduler_events = {
# -------------------- # --------------------
user_data_fields = [ user_data_fields = [
{ {
"doctype": "{doctype_1}", "doctype": "{doctype_1}",
"filter_by": "{filter_by}", "filter_by": "{filter_by}",
"redact_fields": ["{field_1}", "{field_2}"], "redact_fields": ["{field_1}", "{field_2}"],
"partial": 1, "partial": 1,
}, },
{ {
"doctype": "{doctype_2}", "doctype": "{doctype_2}",
"filter_by": "{filter_by}", "filter_by": "{filter_by}",
"partial": 1, "partial": 1,
}, },
{ {
"doctype": "{doctype_3}", "doctype": "{doctype_3}",
"strict": False, "strict": False,
}, },
{ {
"doctype": "{doctype_4}" "doctype": "{doctype_4}"
} }
] ]
# Authentication and authorization # Authentication and authorization
@ -200,23 +205,22 @@ user_data_fields = [
# "smart_service.auth.validate" # "smart_service.auth.validate"
# ] # ]
fixtures = [ fixtures = [
# { # {
# "doctype": "Notification", # "doctype": "Notification",
# "filters": [{"is_standard":0}] # "filters": [{"is_standard":0}]
# } # }
#"Custom Field", # "Custom Field",
#"Property Setter", # "Property Setter",
#"Client Script", # "Client Script",
#"Server Script", # "Server Script",
#"Workflow", # "Workflow",
#"Workflow Action Master", # "Workflow Action Master",
#"Workflow State", # "Workflow State",
#"Role", # "Role",
#"Workspace", # "Workspace",
#"Custom DocPerm", # "Custom DocPerm",
# "Role Profile", # "Role Profile",
#"Report", # "Report",
#"Dashboard Chart" # "Dashboard Chart"
] ]

BIN
smart_service/masters/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/masters/doctype/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

14
smart_service/masters/doctype/app_labels/app_labels.js

@ -23,7 +23,7 @@ frappe.ui.form.on('App Labels', {
}, },
validate: function (frm) { validate: function (frm) {
if (frm.doc.english_label) { if (frm.doc.english_label) {
if (frm.doc.english_label.length > 50) { if (frm.doc.english_label.length > 100) {
frappe.msgprint("<b>English Label :</b> Only <b> 50 </b> characters allowed") frappe.msgprint("<b>English Label :</b> Only <b> 50 </b> characters allowed")
validated = false; validated = false;
} }
@ -36,10 +36,10 @@ frappe.ui.form.on('App Labels', {
frappe.throw(__("Just a <b>.</b> is not prescribed!")); frappe.throw(__("Just a <b>.</b> is not prescribed!"));
frappe.validated = false; frappe.validated = false;
} }
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/; var regex = /[!@#$%^&*()+\=\[\]{};`~':"\\|.<>\/]+/;
if (frm.doc.english_label) { if (frm.doc.english_label) {
if (regex.test(frm.doc.english_label) === true) { if (regex.test(frm.doc.english_label) === true) {
frappe.throw(__("<b>English Label :</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.throw(__("<b>English Label :</b> Only letters, numbers and <b> - , </b> are allowed."));
frappe.validated = false; frappe.validated = false;
} else if (frm.doc.english_label) { } else if (frm.doc.english_label) {
if (frm.doc.english_label.includes("'")) { if (frm.doc.english_label.includes("'")) {
@ -50,7 +50,7 @@ frappe.ui.form.on('App Labels', {
} }
if (frm.doc.page_name) { if (frm.doc.page_name) {
if (frm.doc.page_name.length > 50) { if (frm.doc.page_name.length > 100) {
frappe.msgprint("<b>Page Name :</b> Only <b> 50 </b> characters allowed") frappe.msgprint("<b>Page Name :</b> Only <b> 50 </b> characters allowed")
validated = false; validated = false;
} }
@ -63,7 +63,7 @@ frappe.ui.form.on('App Labels', {
frappe.throw(__("Just a <b>.</b> is not prescribed!")); frappe.throw(__("Just a <b>.</b> is not prescribed!"));
frappe.validated = false; frappe.validated = false;
} }
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/; var regex = /[!@#$%^&*()+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.page_name) { if (frm.doc.page_name) {
if (regex.test(frm.doc.page_name) === true) { if (regex.test(frm.doc.page_name) === true) {
frappe.throw(__("<b>Page Name :</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.throw(__("<b>Page Name :</b> Only letters, numbers and <b> -,</b> are allowed."));
@ -77,7 +77,7 @@ frappe.ui.form.on('App Labels', {
} }
if (frm.doc.label) { if (frm.doc.label) {
if (frm.doc.label.length > 50) { if (frm.doc.label.length > 100) {
frappe.msgprint("<b>Translated Label :</b> Only <b> 50 </b> characters allowed") frappe.msgprint("<b>Translated Label :</b> Only <b> 50 </b> characters allowed")
validated = false; validated = false;
} }
@ -90,7 +90,7 @@ frappe.ui.form.on('App Labels', {
frappe.throw(__("Just a <b>.</b> is not prescribed!")); frappe.throw(__("Just a <b>.</b> is not prescribed!"));
frappe.validated = false; frappe.validated = false;
} }
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/; var regex = /[!@#$%^&*()+\=\[\]{};`~':"\\|.<>\/]+/;
if (frm.doc.label) { if (frm.doc.label) {
if (regex.test(frm.doc.label) === true) { if (regex.test(frm.doc.label) === true) {
frappe.throw(__("<b>Translated Label :</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.throw(__("<b>Translated Label :</b> Only letters, numbers and <b> -,</b> are allowed."));

28
smart_service/masters/doctype/custom_languages/custom_languages.json

@ -6,6 +6,10 @@
"editable_grid": 1, "editable_grid": 1,
"engine": "InnoDB", "engine": "InnoDB",
"field_order": [ "field_order": [
"internal_publish",
"column_break_10",
"global_publish",
"section_break_3",
"lang_code", "lang_code",
"active_status", "active_status",
"column_break_2", "column_break_2",
@ -60,11 +64,33 @@
"label": "myID", "label": "myID",
"read_only": 1, "read_only": 1,
"set_only_once": 1 "set_only_once": 1
},
{
"default": "0",
"fieldname": "internal_publish",
"fieldtype": "Check",
"label": "Internal Publish",
"read_only": 1
},
{
"default": "0",
"fieldname": "global_publish",
"fieldtype": "Check",
"label": "Global Publish",
"read_only": 1
},
{
"fieldname": "section_break_3",
"fieldtype": "Section Break"
},
{
"fieldname": "column_break_10",
"fieldtype": "Column Break"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2022-02-11 12:41:29.369497", "modified": "2023-07-11 15:55:25.503377",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "Masters", "module": "Masters",
"name": "Custom Languages", "name": "Custom Languages",

2
smart_service/masters/doctype/drive/drive.js

@ -20,7 +20,7 @@ frappe.ui.form.on('Drive', {
} }
var regex = /[!@#$%^&*()_+\=\[\]{};'`~:"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};'`~:"\\|.<>\/?]+/;
if (regex.test(frm.doc.drive) === true) { if (regex.test(frm.doc.drive) === true) {
frappe.msgprint(__("<b>Variant:</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.msgprint(__("<b>Variant:</b> Only letters, numbers and <b> - , </b> are allowed."));
frappe.validated = false; frappe.validated = false;
} else if (frm.doc.drive) { } else if (frm.doc.drive) {
if (frm.doc.drive.includes("'")) { if (frm.doc.drive.includes("'")) {

2
smart_service/masters/doctype/fuel/fuel.js

@ -21,7 +21,7 @@ frappe.ui.form.on('Fuel', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.fuel) { if (frm.doc.fuel) {
if (regex.test(frm.doc.fuel) === true) { if (regex.test(frm.doc.fuel) === true) {
frappe.msgprint(__("<b>Fuel:</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.msgprint(__("<b>Fuel:</b> Only letters, numbers and <b> - ,</b> are allowed."));
frappe.validated = false; frappe.validated = false;
} else if (frm.doc.fuel) { } else if (frm.doc.fuel) {
if (frm.doc.fuel.includes("'")) { if (frm.doc.fuel.includes("'")) {

2
smart_service/masters/doctype/procedure_name/procedure_name.js

@ -20,7 +20,7 @@ frappe.ui.form.on('Procedure Name', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.procedure_name) { if (frm.doc.procedure_name) {
if (regex.test(frm.doc.procedure_name) === true) { if (regex.test(frm.doc.procedure_name) === true) {
frappe.msgprint(__("<b>Procedure Name:</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.msgprint(__("<b>Procedure Name:</b> Only letters, numbers and <b> - , </b> are allowed."));
frappe.validated = false; frappe.validated = false;
} else if (frm.doc.procedure_name) { } else if (frm.doc.procedure_name) {
if (frm.doc.procedure_name.includes("'")) { if (frm.doc.procedure_name.includes("'")) {

2
smart_service/masters/doctype/service_kilometers/service_kilometers.js

@ -31,7 +31,7 @@ frappe.ui.form.on('Service Kilometers', {
var regex = /[!@#$%^&*()_+\=\[\]{};~`':"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};~`':"\\|.<>\/?]+/;
if (frm.doc.kilometer) { if (frm.doc.kilometer) {
if (regex.test(frm.doc.kilometer) === true) { if (regex.test(frm.doc.kilometer) === true) {
frappe.throw(__("<b>Service Kilometer:</b> Only letters, numbers and <b> ,</b> are allowed.")); frappe.throw(__("<b>Service Kilometer:</b> Only letters, numbers and <b> - , </b> are allowed."));
frappe.validated = false; frappe.validated = false;
} else if ((frm.doc.kilometer.includes("'"))) { } else if ((frm.doc.kilometer.includes("'"))) {
frappe.throw(__("<b>Service Kilometer:</b> Only letters, numbers and <b> ,</b> are allowed.")); frappe.throw(__("<b>Service Kilometer:</b> Only letters, numbers and <b> ,</b> are allowed."));

2
smart_service/masters/doctype/sub_systems/sub_systems.js

@ -17,7 +17,7 @@ frappe.ui.form.on('Sub Systems', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~:"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};`~:"\\|.<>\/?]+/;
if (frm.doc.sub_system_name) { if (frm.doc.sub_system_name) {
if (regex.test(frm.doc.sub_system_name) === true) { if (regex.test(frm.doc.sub_system_name) === true) {
frappe.msgprint(__("<b>Sub System Name:</b> Only letters, numbers and <b> -,'</b> are allowed.")); frappe.msgprint(__("<b>Sub System Name:</b> Only letters, numbers and <b> - , ' </b> are allowed."));
frappe.validated = false; frappe.validated = false;
} }
} }

2
smart_service/masters/doctype/systems/systems.js

@ -47,7 +47,7 @@ frappe.ui.form.on('Systems', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~:"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};`~:"\\|.<>\/?]+/;
if (frm.doc.system_name) { if (frm.doc.system_name) {
if (regex.test(frm.doc.system_name) === true) { if (regex.test(frm.doc.system_name) === true) {
frappe.msgprint(__("<b>system Name:</b> Only letters, numbers and <b> -,'</b> are allowed.")); frappe.msgprint(__("<b>system Name:</b> Only letters, numbers and <b> - ,' </b> are allowed."));
frappe.validated = false; frappe.validated = false;
} }
} }

2
smart_service/masters/doctype/transmission/transmission.js

@ -21,7 +21,7 @@ frappe.ui.form.on('Transmission', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.transmission) { if (frm.doc.transmission) {
if (regex.test(frm.doc.transmission) === true) { if (regex.test(frm.doc.transmission) === true) {
frappe.msgprint(__("<b>Transmission:</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.msgprint(__("<b>Transmission:</b> Only letters, numbers and <b> - ,</b> are allowed."));
frappe.validated = false; frappe.validated = false;
} else if (frm.doc.transmission) { } else if (frm.doc.transmission) {
if (frm.doc.transmission.includes("'")) { if (frm.doc.transmission.includes("'")) {

BIN
smart_service/masters/doctype/variant/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/masters/doctype/variant/__pycache__/variant.cpython-38.pyc

Binary file not shown.

2
smart_service/masters/doctype/variant/variant.js

@ -27,7 +27,7 @@ frappe.ui.form.on('Variant', {
var regex = /[!@#$%^&*()_+\=\[\]{};'`~:"\\|.<>\/?]+/; var regex = /[!@#$%^&*()_+\=\[\]{};'`~:"\\|.<>\/?]+/;
if(frm.doc.variant){ if(frm.doc.variant){
if (regex.test(frm.doc.variant) === true){ if (regex.test(frm.doc.variant) === true){
frappe.msgprint(__("<b>Variant:</b> Only letters, numbers and <b> -,</b> are allowed.")); frappe.msgprint(__("<b>Variant:</b> Only letters, numbers and <b> - ,</b> are allowed."));
frappe.validated = false; frappe.validated = false;
} else if(frm.doc.variant) { } else if(frm.doc.variant) {
if(frm.doc.variant.includes("'")) { if(frm.doc.variant.includes("'")) {

BIN
smart_service/masters/doctype/vehicle/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/masters/doctype/vehicle/__pycache__/vehicle.cpython-38.pyc

Binary file not shown.

33
smart_service/masters/doctype/vehicle/vehicle.json

@ -9,6 +9,10 @@
"editable_grid": 1, "editable_grid": 1,
"engine": "InnoDB", "engine": "InnoDB",
"field_order": [ "field_order": [
"internal_publish",
"column_break_2",
"global_publish",
"section_break_4",
"vehicle", "vehicle",
"image", "image",
"preview", "preview",
@ -18,9 +22,7 @@
"active_status", "active_status",
"myid", "myid",
"display_order", "display_order",
"service_kilometers", "service_kilometers"
"global_publish_flag",
"internal_publish_flag"
], ],
"fields": [ "fields": [
{ {
@ -103,24 +105,27 @@
}, },
{ {
"default": "0", "default": "0",
"fieldname": "global_publish_flag", "fieldname": "internal_publish",
"fieldtype": "Check", "fieldtype": "Check",
"hidden": 1, "label": "Internal Publish"
"label": "Global Publish Flag",
"read_only": 1
}, },
{ {
"default": "0", "fieldname": "global_publish",
"fieldname": "internal_publish_flag", "fieldtype": "Data",
"fieldtype": "Check", "label": "Global Publish"
"hidden": 1, },
"label": "Internal Publish Flag", {
"read_only": 1 "fieldname": "column_break_2",
"fieldtype": "Column Break"
},
{
"fieldname": "section_break_4",
"fieldtype": "Section Break"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"links": [], "links": [],
"modified": "2022-04-01 17:41:13.606316", "modified": "2023-07-11 15:51:55.396348",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "Masters", "module": "Masters",
"name": "Vehicle", "name": "Vehicle",

2
smart_service/masters/doctype/vehicle_segment/vehicle_segment.js

@ -58,7 +58,7 @@ frappe.ui.form.on('Vehicle Segment', {
var regex = /[!@#$%^&*()_+\-=\[\]{};'`~:"\\|,.<>\/?]+/; var regex = /[!@#$%^&*()_+\-=\[\]{};'`~:"\\|,.<>\/?]+/;
if (frm.doc.vehicle_segment) { if (frm.doc.vehicle_segment) {
if (regex.test(frm.doc.vehicle_segment) === true) { if (regex.test(frm.doc.vehicle_segment) === true) {
frappe.msgprint(__("<b>Vehicle Segment:</b> Only letters and numbers are allowed")); frappe.msgprint(__("<b>Vehicle Segment:</b> Only letters , numbers and <b> - , </b> are allowed"));
frappe.validated = false; frappe.validated = false;
} else if (frm.doc.vehicle_segment) { } else if (frm.doc.vehicle_segment) {
if (frm.doc.vehicle_segment.includes("'")) { if (frm.doc.vehicle_segment.includes("'")) {

2
smart_service/masters/report/_fuel_translation/_fuel_translation.py

@ -1,7 +1,7 @@
# Copyright (c) 2013, Hard n Soft Technologies Pvt Ltd and contributors # Copyright (c) 2013, Hard n Soft Technologies Pvt Ltd and contributors
# For license information, please see license.txt # For license information, please see license.txt
# import frappe import frappe
def execute(filters=None): def execute(filters=None):
columns, data = [], [] columns, data = [], []

4
smart_service/public/css/smart_service.css

@ -26,8 +26,8 @@
} }
.app-logo { .app-logo {
width: 400px !important; /* width: 400px !important;
height: 50px !important; height: 50px !important; */
image-rendering: -webkit-optimize-contrast !important; image-rendering: -webkit-optimize-contrast !important;
filter: none !important; filter: none !important;
} }

BIN
smart_service/public/images/Mahindra Rise2.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
smart_service/public/images/Mahindra Rise2_test.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

BIN
smart_service/reports/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/fish/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/fish/__pycache__/fish.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/kilometer_mapping/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/kilometer_mapping/__pycache__/kilometer_mapping.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/kilometer_mapping_items/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/kilometer_mapping_items/__pycache__/kilometer_mapping_items.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/procedure/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/procedure/__pycache__/procedure.cpython-38.pyc

Binary file not shown.

36
smart_service/transactions/doctype/procedure/procedure.js

@ -35,14 +35,15 @@ frappe.ui.form.on('Procedure', {
}, },
validate: function (frm) { validate: function (frm) {
var regex = /[@#$%^*+\\[\]{}`~:\\|\?]+/; // var regex = /[@#$%^*\\[\]{}`~\\|\?]/;
var regex = /[@#$^\\[\]{}`\\|\?]/;
if (frm.doc.procedure_details) { if (frm.doc.procedure_details) {
for (var i = 0; i < frm.doc.procedure_details.length; i++) { for (var i = 0; i < frm.doc.procedure_details.length; i++) {
if (regex.test(frm.doc.procedure_details[i].content) === true) { if (regex.test(frm.doc.procedure_details[i].content) === true) {
if (frm.doc.procedure_details[i].content_type != "Link") { if (frm.doc.procedure_details[i].content_type != "Link") {
frm.doc.procedure_details[i].content_type = '' frm.doc.procedure_details[i].content_type = ''
frm.refresh_fields(); frm.refresh_fields();
frappe.msgprint(__("<b>Content:</b> Only letters, numbers and <b> - ,'<>_()!=/;</b> are allowed.")); frappe.msgprint(__("<b>Content:</b> Only letters, numbers and <b> - ,'<>_()!=/:+;</b> are allowed."));
} }
} }
} }
@ -68,19 +69,28 @@ frappe.ui.form.on('Procedure', {
callback: function (r) { callback: function (r) {
} }
}) })
if(frm.doc.procedure_details){
frappe.call({
"method": "smart_service.transactions.doctype.procedure.procedure.get_path",
"args": {
"name": frm.doc.name,
},
callback: function (r) {
var url = window.location.host;
var url = window.location.host; var regex = /[://]+/;
var regex = /[://]+/; // frappe.db.get_value('Fish', { name: "Fish" }, 'path', (r) => {
frappe.db.get_value('Fish', { name: "Fish" }, 'path', (r) => { for (var i = 0; i < frm.doc.procedure_details.length; i++) {
for (var i = 0; i < frm.doc.procedure_details.length; i++) { if (frm.doc.procedure_details[i].content && r.message && frm.doc.procedure_details[i].content_type == "Link"){// && !(frm.doc.procedure_details[i].content).includes('</a>')){
if (frm.doc.procedure_details[i].content && r.path && frm.doc.procedure_details[i].content_type == "Link"){// && !(frm.doc.procedure_details[i].content).includes('</a>')){ var x = "<a href=" + '"' + r.message + "://" + url + "/app/procedure/" + frm.doc.procedure_details[i].temp_cnt+ '"' + 'target="_blank"' + ' role="link"' +' onclick="window.open('+r.message + "://" + url + "/app/procedure/" + frm.doc.procedure_details[i].temp_cnt+')"'+'>' + frm.doc.procedure_details[i].temp_cnt + '</a>';
var x = "<a href=" + '"' + r.path + "://" + url + "/app/procedure/" + frm.doc.procedure_details[i].temp_cnt+ '"' + 'target="_blank"' + ' role="link"' +' onclick="window.open('+r.path + "://" + url + "/app/procedure/" + frm.doc.procedure_details[i].temp_cnt+')"'+'>' + frm.doc.procedure_details[i].temp_cnt + '</a>'; frm.doc.procedure_details[i].content = x
frm.doc.procedure_details[i].content = x }
} }
cur_frm.refresh_fields('procedure_details');
// })
} }
cur_frm.refresh_fields('procedure_details'); })
}) }
} }
// select_row(frm); // select_row(frm);
// if (frm.doc.procedure_filter == "All") { // if (frm.doc.procedure_filter == "All") {

335
smart_service/transactions/doctype/procedure/procedure.py

@ -1,195 +1,252 @@
# Copyright (c) 2021, Hard n Soft Technologies Pvt Ltd and contributors # Copyright (c) 2021, Hard n Soft Technologies Pvt Ltd and contributors
# For license information, please see license.txt # For license information, please see license.txt
import re
import sys
import frappe import frappe
from frappe.model.document import Document from frappe.model.document import Document
import frappe,json import frappe
import json
current_db_name = frappe.conf.get("db_name") current_db_name = frappe.conf.get("db_name")
import sys sys.tracebacklimit = 0
sys.tracebacklimit=0
class Procedure(Document): class Procedure(Document):
def validate(self): def validate(self):
if self.procedure_details: if self.procedure_details:
for x in self.get("procedure_details"): for x in self.get("procedure_details"):
if x.content_type == "File": if x.content:
if not x.file:
frappe.throw("Please choose the file in row no " + str(x.idx)) res_str = re.sub("–", "", x.content)
if x.content_type != "File": res_str = re.sub("—", "", res_str)
if not x.content: res_str = re.sub("‘", "", res_str)
frappe.throw("Please enter the content in row no " + str(x.idx)) res_str = re.sub("’", "", res_str)
res_str = re.sub("“", "", res_str)
res_str = re.sub("”", "", res_str)
res_str = re.sub("Â", "", res_str)
x.content = res_str
if x.content_type == "File":
if not x.file:
frappe.throw(
"Please choose the file in row no " + str(x.idx))
if x.content_type != "File":
if not x.content:
frappe.throw(
"Please enter the content in row no " + str(x.idx))
if not self.is_new():
frappe.db.sql(
f"""UPDATE `tabSystem Mapping_Sub System` set procedure_is_published=0,procedure_status='{self.workflow_state}',active_status='{self.active_status}' where `procedure`='{self.name}';""")
frappe.db.commit()
@frappe.whitelist() @frappe.whitelist()
def get_doc_status(docname): def get_doc_status(docname):
self = frappe.get_doc("Procedure",docname) self = frappe.get_doc("Procedure", docname)
return self.workflow_state return self.workflow_state
@frappe.whitelist() @frappe.whitelist()
def get_publish_details(procedure_name,status): def get_publish_details(procedure_name, status):
data=frappe.db.sql('''select pd.parent from {0}.`tabPublish_Docs` pd, {0}.`tabPublish` p where pd.procedure_link='{1}' and p.publish_status != '{2}' and pd.parent=p.name'''.format(current_db_name,procedure_name,status), as_list=True) data = frappe.db.sql('''select pd.parent from {0}.`tabPublish_Docs` pd, {0}.`tabPublish` p where pd.procedure_link='{1}' and p.publish_status != '{2}' and pd.parent=p.name'''.format(
return data current_db_name, procedure_name, status), as_list=True)
return data
@frappe.whitelist() @frappe.whitelist()
def sub_systems(doctype, txt, searchfield, start, page_len, filters): def sub_systems(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql(""" select name return frappe.db.sql(""" select name
FROM {0}.`tabSub Systems` where FROM {0}.`tabSub Systems` where
(name like "%%%(txt)s%%") order by creation desc limit %(start)s, %(page_len)s """.format(current_db_name)%{'txt': txt, 'start': start, 'page_len': page_len}) (name like "%%%(txt)s%%") order by creation desc limit %(start)s, %(page_len)s """.format(current_db_name) % {'txt': txt, 'start': start, 'page_len': page_len})
@frappe.whitelist() @frappe.whitelist()
def variant(doctype, txt, searchfield, start, page_len, filters): def variant(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql(""" select name,family_code,fuel,transmission,vehicle_segment,active_status return frappe.db.sql(""" select name,family_code,fuel,transmission,vehicle_segment,active_status
FROM {0}.`tabVariant Mapping` where FROM {0}.`tabVariant Mapping` where
(active_status like "%%%(txt)s%%" or vehicle_segment like "%%%(txt)s%%" or name like "%%%(txt)s%%" or variant like "%%%(txt)s%%" or family_code like "%%%(txt)s%%" or fuel like "%%%(txt)s%%" or transmission like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name)%{'txt': txt, 'start': start, 'page_len': page_len}) (active_status like "%%%(txt)s%%" or vehicle_segment like "%%%(txt)s%%" or name like "%%%(txt)s%%" or variant like "%%%(txt)s%%" or family_code like "%%%(txt)s%%" or fuel like "%%%(txt)s%%" or transmission like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name) % {'txt': txt, 'start': start, 'page_len': page_len})
@frappe.whitelist() @frappe.whitelist()
def fuel(doctype, txt, searchfield, start, page_len, filters): def fuel(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql(""" select name FROM {0}.tabFuel where return frappe.db.sql(""" select name FROM {0}.tabFuel where
(name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name)%{'txt': txt, 'start': start, 'page_len': page_len}) (name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name) % {'txt': txt, 'start': start, 'page_len': page_len})
@frappe.whitelist() @frappe.whitelist()
def transmission(doctype, txt, searchfield, start, page_len, filters): def transmission(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql(""" select name FROM {0}.tabTransmission where return frappe.db.sql(""" select name FROM {0}.tabTransmission where
(name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name)%{'txt': txt, 'start': start, 'page_len': page_len}) (name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name) % {'txt': txt, 'start': start, 'page_len': page_len})
@frappe.whitelist() @frappe.whitelist()
def drive(doctype, txt, searchfield, start, page_len, filters): def drive(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql(""" select name FROM {0}.tabDrive where return frappe.db.sql(""" select name FROM {0}.tabDrive where
(name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name)%{'txt': txt, 'start': start, 'page_len': page_len}) (name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name) % {'txt': txt, 'start': start, 'page_len': page_len})
@frappe.whitelist() @frappe.whitelist()
def get_variant(doctype, txt, searchfield, start, page_len, filters): def get_variant(doctype, txt, searchfield, start, page_len, filters):
if not filters: if not filters:
return [] return []
filters = frappe._dict(filters) filters = frappe._dict(filters)
vm = filters.get('variant_mapping') vm = filters.get('variant_mapping')
lang = filters.get('language') lang = filters.get('language')
if vm: if vm:
vehicle = frappe.db.get_value('Variant Mapping', vm, 'vehicle') vehicle = frappe.db.get_value('Variant Mapping', vm, 'vehicle')
variant = frappe.db.sql("""select name,family_code,fuel,transmission,drive,active_status FROM {0}.`tabVariant Mapping` where vehicle = '{1}' and variant = frappe.db.sql("""select name,family_code,fuel,transmission,drive,active_status FROM {0}.`tabVariant Mapping` where vehicle = '{1}' and
(name like "%%%(txt)s%%" or active_status like "%%%(txt)s%%" or drive like "%%%(txt)s%%" or family_code like "%%%(txt)s%%" or fuel like "%%%(txt)s%%" or transmission like "%%%(txt)s%%") group by name limit %(start)s, %(page_len)s """.format(current_db_name,vehicle)%{'txt': txt, 'start': start, 'page_len': page_len}) (name like "%%%(txt)s%%" or active_status like "%%%(txt)s%%" or drive like "%%%(txt)s%%" or family_code like "%%%(txt)s%%" or fuel like "%%%(txt)s%%" or transmission like "%%%(txt)s%%") group by name limit %(start)s, %(page_len)s """.format(current_db_name, vehicle) % {'txt': txt, 'start': start, 'page_len': page_len})
if variant: if variant:
return variant return variant
else: else:
return [] return []
else: else:
return [] return []
@frappe.whitelist() @frappe.whitelist()
def get_systems(doctype, txt, searchfield, start, page_len, filters): def get_systems(doctype, txt, searchfield, start, page_len, filters):
if not filters: if not filters:
return [] return []
filters = frappe._dict(filters) filters = frappe._dict(filters)
vm = filters.get('variant_mapping') vm = filters.get('variant_mapping')
lang = filters.get('language') lang = filters.get('language')
if vm: if vm:
sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language ='{2}'""".format(current_db_name,vm,lang),as_dict=True) sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language ='{2}'""".format(
if sys_mapping: current_db_name, vm, lang), as_dict=True)
for x in sys_mapping: if sys_mapping:
doc = frappe.get_doc('System Mapping', x.name) for x in sys_mapping:
systems = frappe.db.sql(""" select systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and doc = frappe.get_doc('System Mapping', x.name)
(systems like "%%%(txt)s%%") group by systems limit %(start)s, %(page_len)s """.format(current_db_name,doc.name)%{'txt': txt, 'start': start, 'page_len': page_len},as_list=True) systems = frappe.db.sql(""" select systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and
if systems: (systems like "%%%(txt)s%%") group by systems limit %(start)s, %(page_len)s """.format(current_db_name, doc.name) % {'txt': txt, 'start': start, 'page_len': page_len}, as_list=True)
return systems if systems:
else: return systems
return [] else:
else: return []
return [] else:
else: return []
return [] else:
return []
@frappe.whitelist() @frappe.whitelist()
def get_subsystems(doctype, txt, searchfield, start, page_len, filters): def get_subsystems(doctype, txt, searchfield, start, page_len, filters):
if not filters: if not filters:
return [] return []
filters = frappe._dict(filters) filters = frappe._dict(filters)
vm = filters.get('variant_mapping') vm = filters.get('variant_mapping')
systems = filters.get('systems') systems = filters.get('systems')
lang = filters.get('language') lang = filters.get('language')
if vm: if vm:
sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(current_db_name,vm,lang),as_dict=True) sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(
if sys_mapping: current_db_name, vm, lang), as_dict=True)
for x in sys_mapping: if sys_mapping:
doc = frappe.get_doc('System Mapping', x.name) for x in sys_mapping:
systems = frappe.db.sql(""" select sub_systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and doc = frappe.get_doc('System Mapping', x.name)
(sub_systems like "%%%(txt)s%%") group by sub_systems limit %(start)s, %(page_len)s """.format(current_db_name,doc.name,systems)%{'txt': txt, 'start': start, 'page_len': page_len}) systems = frappe.db.sql(""" select sub_systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and
if systems: (sub_systems like "%%%(txt)s%%") group by sub_systems limit %(start)s, %(page_len)s """.format(current_db_name, doc.name, systems) % {'txt': txt, 'start': start, 'page_len': page_len})
return systems if systems:
else: return systems
return [] else:
else: return []
return [] else:
else: return []
return [] else:
return []
@frappe.whitelist() @frappe.whitelist()
def get_procedure(doctype, txt, searchfield, start, page_len, filters): def get_procedure(doctype, txt, searchfield, start, page_len, filters):
if not filters: if not filters:
return [] return []
filters = frappe._dict(filters) filters = frappe._dict(filters)
vm = filters.get('variant_mapping') vm = filters.get('variant_mapping')
systems = filters.get('systems') systems = filters.get('systems')
sub_systems = filters.get('sub_systems') sub_systems = filters.get('sub_systems')
lang = filters.get('language') lang = filters.get('language')
if vm: if vm:
sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(current_db_name,vm,lang),as_dict=True) sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(
if sys_mapping: current_db_name, vm, lang), as_dict=True)
for x in sys_mapping: if sys_mapping:
doc = frappe.get_doc('System Mapping', x.name) for x in sys_mapping:
procedure = frappe.db.sql(""" select `procedure` FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and sub_systems = '{3}' and doc = frappe.get_doc('System Mapping', x.name)
(`procedure` like "%%%(txt)s%%") group by `procedure` limit %(start)s, %(page_len)s """.format(current_db_name,doc.name,systems,sub_systems)%{'txt': txt, 'start': start, 'page_len': page_len}) procedure = frappe.db.sql(""" select `procedure` FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and sub_systems = '{3}' and
if procedure: (`procedure` like "%%%(txt)s%%") group by `procedure` limit %(start)s, %(page_len)s """.format(current_db_name, doc.name, systems, sub_systems) % {'txt': txt, 'start': start, 'page_len': page_len})
return procedure if procedure:
else: return procedure
return [] else:
else: return []
return [] else:
else: return []
return [] else:
return []
@frappe.whitelist()
def get_procedures(variant_mapping,systems,sub_systems,language):
sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(current_db_name,variant_mapping,language),as_dict=True) @frappe.whitelist()
if sys_mapping: def get_procedures(variant_mapping, systems, sub_systems, language):
for x in sys_mapping: sys_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(
doc = frappe.get_doc('System Mapping', x.name) current_db_name, variant_mapping, language), as_dict=True)
procedure = frappe.db.sql(""" select `procedure` FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and sub_systems = '{3}'""".format(current_db_name,doc.name,systems,sub_systems)) if sys_mapping:
return procedure for x in sys_mapping:
doc = frappe.get_doc('System Mapping', x.name)
procedure = frappe.db.sql(""" select `procedure` FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and sub_systems = '{3}'""".format(
current_db_name, doc.name, systems, sub_systems))
return procedure
@frappe.whitelist() @frappe.whitelist()
def get_systemid(systems): def get_systemid(systems):
system = frappe.db.sql(""" select myid FROM {0}.`tabSystems` where name = '{1}'""".format(current_db_name,systems)) system = frappe.db.sql(""" select myid FROM {0}.`tabSystems` where name = '{1}'""".format(
if system: current_db_name, systems))
return system if system:
return system
@frappe.whitelist() @frappe.whitelist()
def get_subsystemid(systems): def get_subsystemid(systems):
system = frappe.db.sql(""" select myid FROM {0}.`tabSub Systems` where name = '{1}'""".format(current_db_name,systems)) system = frappe.db.sql(""" select myid FROM {0}.`tabSub Systems` where name = '{1}'""".format(
if system: current_db_name, systems))
return system if system:
return system
@frappe.whitelist() @frappe.whitelist()
def procedure_name(doctype, txt, searchfield, start, page_len, filters): def procedure_name(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql(""" select name FROM {0}.`tabProcedure Name` where return frappe.db.sql(""" select name FROM {0}.`tabProcedure Name` where
(name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name)%{'txt': txt, 'start': start, 'page_len': page_len}) (name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name) % {'txt': txt, 'start': start, 'page_len': page_len})
@frappe.whitelist() @frappe.whitelist()
def procedure_step_name(doctype, txt, searchfield, start, page_len, filters): def procedure_step_name(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql(""" select name FROM {0}.`tabProcedure Step Name` where return frappe.db.sql(""" select name FROM {0}.`tabProcedure Step Name` where
(name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name)%{'txt': txt, 'start': start, 'page_len': page_len}) (name like "%%%(txt)s%%") order by modified desc limit %(start)s, %(page_len)s """.format(current_db_name) % {'txt': txt, 'start': start, 'page_len': page_len})
@frappe.whitelist() @frappe.whitelist()
def update_system_id(name): def update_system_id(name):
doc = frappe.get_doc("Procedure",name) doc = frappe.get_doc("Procedure", name)
for table in doc.get("procedure_details"): for table in doc.get("procedure_details"):
if table.content_type == "Link": if table.content_type == "Link":
procedure = table.temp_cnt procedure = table.temp_cnt
system_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(current_db_name,doc.variant_mapping,doc.language),as_dict=True) system_mapping = frappe.db.sql("""select name from {0}.`tabSystem Mapping` where variant_mapping = '{1}' and language = '{2}'""".format(
if system_mapping: current_db_name, doc.variant_mapping, doc.language), as_dict=True)
sm = system_mapping[0]['name'] if system_mapping:
sys_procedure = frappe.db.sql("""select systems,sub_systems,system_id,sub_system_id,`procedure` from {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and `procedure` = '{2}'""".format(current_db_name,sm,table.temp_cnt),as_dict=True) sm = system_mapping[0]['name']
if sys_procedure: sys_procedure = frappe.db.sql("""select systems,sub_systems,system_id,sub_system_id,`procedure` from {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and `procedure` = '{2}'""".format(
if table.temp_cnt == sys_procedure[0]['procedure']: current_db_name, sm, table.temp_cnt), as_dict=True)
sys_id = doc.variant_mapping + ',' + str(sys_procedure[0]['system_id']) + ',' + str(sys_procedure[0]['sub_system_id']) if sys_procedure:
table.system_id = sys_id if str(table.temp_cnt) == str(sys_procedure[0]['procedure']):
frappe.db.sql("""update {0}.`tabProcedure_Details` set system_id = '{1}' where parent = '{2}' and temp_cnt = '{3}'""".format(current_db_name,sys_id,doc.name,table.temp_cnt) )
frappe.db.commit() sys_id = doc.variant_mapping + ',' + \
str(sys_procedure[0]['system_id']) + ',' + \
str(sys_procedure[0]['sub_system_id'])
table.system_id = sys_id
frappe.db.sql("""update {0}.`tabProcedure_Details` set system_id = '{1}' where parent = '{2}' and temp_cnt = '{3}'""".format(
current_db_name, sys_id, doc.name, table.temp_cnt))
frappe.db.commit()
@frappe.whitelist()
def get_path(name):
path = frappe.db.get_single_value("Fish", "path")
if path:
return path

BIN
smart_service/transactions/doctype/procedure_details/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

BIN
smart_service/transactions/doctype/procedure_details/__pycache__/procedure_details.cpython-38.pyc

Binary file not shown.

3
smart_service/transactions/doctype/procedure_details/procedure_details.json

@ -74,14 +74,13 @@
{ {
"fieldname": "system_id", "fieldname": "system_id",
"fieldtype": "Data", "fieldtype": "Data",
"hidden": 1,
"label": "System ID" "label": "System ID"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"istable": 1, "istable": 1,
"links": [], "links": [],
"modified": "2022-04-08 22:21:10.666175", "modified": "2023-06-08 14:41:02.141600",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "Transactions", "module": "Transactions",
"name": "Procedure_Details", "name": "Procedure_Details",

BIN
smart_service/transactions/doctype/publish/__pycache__/__init__.cpython-38.pyc

Binary file not shown.

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save