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
__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
frappe.ui.form.on('Circular', {
validate(frm) {
if(frm.doc.valid_till < frappe.datetime.nowdate()) {
msgprint('Valid Till date should be greater than today!');
validate(frm) {
if (frm.doc.valid_till < frappe.datetime.nowdate()) {
msgprint('Valid Till date should be equal or greater than today!');
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
},
{
"description": "Max count (500 character's)",
"fieldname": "description",
"fieldtype": "Small Text",
"in_list_view": 1,
@ -65,15 +66,15 @@
"label": "Valid Till"
},
{
"description": "Upload *.png,*.jpg,*.pdf",
"fieldname": "circular_image",
"fieldtype": "Attach",
"label": "Circular Image"
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
"modified": "2022-05-14 12:07:39.981829",
"modified": "2023-06-28 16:41:53.914998",
"modified_by": "Administrator",
"module": "Add Ons",
"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
# For license information, please see license.txt
# import frappe
import frappe
from frappe.model.document import 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():
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>Feedback ID</b>"), "fieldname": "name", "fieldtype": "Link", "options":"User Feedback","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>Attachments</b>"), "fieldname": "attachments", "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>Area Office</b>"), "fieldname": "area", "fieldtype": "Data", "width": 140},
{"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>Closure Date</b>"), "fieldname": "closure_date", "fieldtype": "Data", "width": 150},
{"label": _("<b>Closed By</b>"), "fieldname": "closed_by", "fieldtype": "Data", "width": 120}
]
return columns

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

@ -31,21 +31,36 @@ def get_data(filters):
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>User ID</b>"), "fieldname": "user_id", "fieldtype": "Data", "width": 100},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 150},
{"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 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>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},
{"label": _("<b>App Last Accessed Date</b>"), "fieldname": "date", "fieldtype": "DateTime","width": 200}
]
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,
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,
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`
where date(date_time_stamp) between '{from_date}' and '{to_date}' group by user,date(date_time_stamp)) mal
where mal.user=al.user
@ -48,19 +49,33 @@ def get_data(filters):
def get_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>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>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
# 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']
to_date=filters['to_date']
modelfilter=filters['model']
# try:
# vId=frappe.db.sql("""SELECT myid FROM _d6463952657fa86c.tabVehicle where vehicle='{0}';""".format(modelfilter), as_dict=1)
# vId=vId[-1]
# vId=vId['myid']
# except:
# frappe.msgprint('Vehicle ID Mismatching.')
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
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)
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, mh.user_id,
login_name,concat(first_name,' ',last_name) as user_name
FROM `tabModel Hit` mh
left join `tabApp Users` au on mh.user_id = au.user_id
WHERE download_vehicle_id='{1}' and (date(date) between '{2}' and '{3}') order by download_vehicle_id;""".format(current_db_name,
modelfilter, from_date, to_date), as_dict=1)
for d in data:
d['download_vehicle_id']=modelfilter
if d['user_id']:
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=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]
d['dealer_code']=dealer_details['dealer_code']
d['dealer_name']=dealer_details['dealer_name']
@ -52,17 +54,19 @@ def get_data(filters):
def get_columns():
columns = [
{"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 100},
{"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": 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>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 150},
{"label": _("<b>User ID</b>"), "fieldname": "login_name", "fieldtype": "Data", "width": 125},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 125},
{"label": _("<b>Downloaded Vehicle</b>"), "fieldname": "download_vehicle_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

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=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
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)
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,
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
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:
if d['user_id']:
@ -55,9 +58,11 @@ def get_data(filters):
to_date=filters['to_date']
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
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)
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,
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
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:
if d['user_id']:
@ -84,9 +89,15 @@ def get_data(filters):
to_date=filters['to_date']
variantfilter=filters['variant']
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
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, variantfilter[0], variantfilter[1], from_date, to_date), as_dict=1)
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, count(*) as count, user_id, language,
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:
if d['user_id']:
@ -111,21 +122,25 @@ def get_data(filters):
def get_columns():
columns = [
{"label": _("<b>Date</b>"), "fieldname": "date", "fieldtype": "Date", "width": 150},
{"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},
{"label": _("<b>Module</b>"), "fieldname": "module_id", "fieldtype": "Data", "width": 150},
{"label": _("<b>User ID</b>"), "fieldname": "login_name", "fieldtype": "Data", "width": 125},
{"label": _("<b>User Name</b>"), "fieldname": "user_name", "fieldtype": "Data", "width": 125},
{"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>Sub System</b>"), "fieldname": "sub_system_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>Language</b>"), "fieldname": "language", "fieldtype": "Data", "width": 150},
{"label": _("<b>Count</b>"), "fieldname": "count", "fieldtype": "Data", "width": 150}
{"label": _("<b>Language</b>"), "fieldname": "language", "fieldtype": "Data", "width": 80},
{"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

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
from frappe.utils import cstr
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")
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()
def addon(args=None):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
# if args == None:
# return {"status": 0, "error": "Parameter missing: args"}
val=input_validation(args=args)
if val!='':
val = input_validation(args=args)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val}
if args:
try:
if args == "circular":
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)
for i in api:
if i["status"] == "Active":
@ -51,7 +75,8 @@ def addon(args=None):
elif args == "teknet_module":
api = frappe.db.get_list(
"Teknet Module",
fields=["name", "teknet_module_name", "active_status", "flvl_id"],
fields=["name", "teknet_module_name",
"active_status", "flvl_id"],
)
for i in api:
if i["active_status"] == "Active":
@ -63,10 +88,11 @@ def addon(args=None):
api = frappe.get_doc('User Manual')
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:
api = {"status": 0, "error": e}
api = {"status": 0, "error": "Module not available"}
else:
api = {"status": 0, "error": "Parameter:args is null"}
@ -75,8 +101,12 @@ def addon(args=None):
@frappe.whitelist()
def bookmark(args=None, request=None):
val=input_validation(args=args,request=request)
if val!='':
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val}
# if args == None and request == None:
# return {"status": 0, "error": "Parameter's missing: args & request"}
@ -134,8 +164,11 @@ def bookmark(args=None, request=None):
@frappe.whitelist()
def feedback(args=None, request=None):
val=input_validation(args=args,request=request)
if val!='':
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val}
# if args == None and request == None:
# return {"status": 0, "error": "Parameter's missing: args & request"}
@ -150,8 +183,8 @@ def feedback(args=None, request=None):
request = json.loads(request)
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}';'''
.format(current_db_name,
frappe.db.get_value('App Users', {'user_id': request['UserID']}, ['name'])),
.format(current_db_name,
frappe.db.get_value('App Users', {'user_id': request['UserID']}, ['name'])),
as_dict=True)
for i in api:
@ -164,7 +197,7 @@ def feedback(args=None, request=None):
i['status'] = False
except Exception as e:
api = {"status": 0, "error": e}
api = {"status": 0, "error": "Failed to fetch feedback"}
return api
elif args == 'post_user_feedback':
@ -190,7 +223,8 @@ def feedback(args=None, request=None):
for x in f:
file_name = 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:
img.write(base64.b64decode(file_data))
@ -204,9 +238,10 @@ def feedback(args=None, request=None):
ret.is_private = 0
ret.insert(ignore_permissions=True)
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:
api = {"status": 0, "error": e}
api = {"status": 0, "error": str(frappe.get_traceback())}
else:
api = {"status": 0, "error": "Check argument: args"}
else:
@ -216,15 +251,14 @@ def feedback(args=None, request=None):
@frappe.whitelist()
def model_hit(args=None, request=None):
val=input_validation(args=args,request=request)
if val!='':
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if 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 == "model_hit":
try:
@ -245,11 +279,12 @@ def model_hit(args=None, request=None):
model_hit.download_vehicle_date = i['DownloadVehicleDate']
model_hit.download_vehicle_language_id = i['DownloadVehicleLanguageID']
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}
except Exception as e:
api = {"status": 0, "error": e}
api = {"status": 0, "error": "Failed to fetch Model hit"}
else:
api = {"status": 0, "error": "Check argument: args"}
else:
@ -259,8 +294,11 @@ def model_hit(args=None, request=None):
@frappe.whitelist()
def model_usage(args=None, request=None):
val=input_validation(args=args,request=request)
if val!='':
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
val = input_validation(args=args, request=request)
if val != '':
return {"status": 0, "error": "Input parameter Missing: " + val}
# if args == None and request == None:
# 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.menu_id = i['MenuID']
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}
except Exception as e:
api = {"status": 0, "error": e}
api = {"status": 0, "error": "Failed to fetch Model Usage"}
else:
api = {"status": 0, "error": "Check argument: args"}
else:

430
smart_service/apis/app_user_login.py

@ -6,11 +6,34 @@ import xml.etree.ElementTree as ET
import frappe
import requests
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")
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
@frappe.whitelist(allow_guest=True)
def app_user_validation_test():
dicData = {}
@ -25,6 +48,9 @@ def app_user_validation_test():
@frappe.whitelist(allow_guest=True)
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)
if 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)
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)
if val != '':
return {'status': 0, 'error': "Parameter's missing: " + val}
@ -203,10 +232,20 @@ def grant_user_access(userdata=None, iid=None):
# User validation
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
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:
user = frappe.new_doc('User')
user.email = email
@ -217,14 +256,23 @@ def grant_user_access(userdata=None, iid=None):
role.role = "_AppUser"
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:
token = generate_keys(user_name[0]['name'])
# return token
# 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"}
'''Inserting Dealer Data'''
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:
dealer = frappe.new_doc('App Dealer')
dealer.dealer_code = dealer_code
@ -233,12 +281,15 @@ def grant_user_access(userdata=None, iid=None):
dealer.area = area_name
dealer.active_status = user_active_status
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'''
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}):
app_user = frappe.get_doc({'doctype': 'App Users', 'email_id': email})
app_user = frappe.get_doc(
{'doctype': 'App Users', 'email_id': email})
else:
app_user = frappe.new_doc('App Users')
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}):
frappe.db.sql(
'''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id,
"Inactive",
current_db_name))
"Inactive",
current_db_name))
frappe.db.commit()
time.sleep(1)
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id})
app_user1 = frappe.get_last_doc(
'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.user = app_user1.name
@ -285,7 +338,8 @@ def grant_user_access(userdata=None, iid=None):
app_logs.date_time_stamp = now()
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(
app_device_tmp.name, "Active", current_db_name))
frappe.db.commit()
@ -300,8 +354,10 @@ def grant_user_access(userdata=None, iid=None):
app_logs3.insert()
else:
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id})
app_user1 = frappe.get_last_doc(
'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.user = app_user1.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(
now(), iid, device_type, current_db_name))
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.user = app_user2.name
app_logs.device = iid
@ -340,8 +397,8 @@ def grant_user_access(userdata=None, iid=None):
app_logs.save()
lst = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True)
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True)
lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format(
current_db_name, email), as_list=True)
@ -349,15 +406,21 @@ def grant_user_access(userdata=None, iid=None):
user_details = {}
user_details['Installation ID'] = lst[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
except Exception as e1:
return {'status': 0, 'error': e1}
return {'status': 0, 'error': "Invalid Inputs"}
@frappe.whitelist(allow_guest=True)
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)
def new_app_user_validation(usr=None, pwd=None, iid=None, device_data=None):
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 != '':
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.update(device_data)
return new_grant_user_access(dicData,iid)
return new_grant_user_access(dicData, iid)
else:
return {'status': 0, 'error': 'Invalid Credentials'}
elif technician_login == 0 and mahindra_login == 1:
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')
node = ET.fromstring(decoded1)
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']
if dicData['ID'] == "":
dicData['ID'] = "100"
return new_grant_user_access(dicData,iid)
return new_grant_user_access(dicData, iid)
except:
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')
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')
node = ET.fromstring(decoded1)
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.update(device_data)
return new_grant_user_access(dicData,iid)
return new_grant_user_access(dicData, iid)
else:
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['Code'] = ''
dicData.update(device_data)
return new_grant_user_access(dicData,iid)
return new_grant_user_access(dicData, iid)
else:
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):
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
try:
user_id = userdata['ID']
email = userdata['EmailId']
@ -524,10 +590,18 @@ def new_grant_user_access(userdata=None, iid=None):
# User validation
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:
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:
user = frappe.new_doc('User')
user.email = email
@ -538,13 +612,21 @@ def new_grant_user_access(userdata=None, iid=None):
role.role = "_AppUser"
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:
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'''
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:
dealer = frappe.new_doc('App Dealer')
dealer.dealer_code = dealer_code
@ -553,12 +635,15 @@ def new_grant_user_access(userdata=None, iid=None):
dealer.area = area_name
dealer.active_status = user_active_status
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'''
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}):
app_user = frappe.get_doc({'doctype': 'App Users', 'email_id': email})
app_user = frappe.get_doc(
{'doctype': 'App Users', 'email_id': email})
else:
app_user = frappe.new_doc('App Users')
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}):
frappe.db.sql(
'''UPDATE {2}.`tabApp Device` SET active_status= "{1}" where device_id = "{0}";'''.format(device_id,
"Inactive",
current_db_name))
"Inactive",
current_db_name))
frappe.db.commit()
time.sleep(1)
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id})
app_user1 = frappe.get_last_doc(
'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.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.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(
app_device_tmp.name, "Active", current_db_name))
frappe.db.commit()
@ -620,8 +708,10 @@ def new_grant_user_access(userdata=None, iid=None):
app_logs3.insert()
else:
app_user1 = frappe.get_last_doc('App Users', filters={"email_id": email})
app_device1 = frappe.get_last_doc('App Device', filters={"device_id": device_id})
app_user1 = frappe.get_last_doc(
'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.user = app_user1.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(
now(), iid, device_type, current_db_name))
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.user = app_user2.name
app_logs.device = iid
@ -660,8 +751,8 @@ def new_grant_user_access(userdata=None, iid=None):
app_logs.save()
lst = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True)
'''SELECT name FROM {}.`tabApp Device` where device_id = "{}" order by name desc limit 1;'''.format(
current_db_name, device_id), as_list=True)
lst1 = frappe.db.sql(
'''SELECT name FROM {}.`tabApp Users` where email_id = "{}" order by name desc limit 1;'''.format(
current_db_name, email), as_list=True)
@ -673,9 +764,16 @@ def new_grant_user_access(userdata=None, iid=None):
return user_details
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):
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)
api_secret = frappe.generate_hash(length=15)
if not user_details.api_key:
@ -689,6 +787,9 @@ def generate_keys(user_name):
@frappe.whitelist()
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')
water = frappe.get_doc("Fish", None)
water.apple = new_tok
@ -711,3 +812,240 @@ def input_validation(**kwargs):
def xml_to_dict(node):
return {'tag': node.tag, 'text': node.text, 'attrib': node.attrib,
'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
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
import json
from frappe.utils import cstr
import datetime
from smart_service.apis.app_user_login import input_validation
import os
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()
def masters(args=None, LSD=None):
val=input_validation(args=args)
if val!='':
return {"status": 0, "error": "Parameter's missing:"+val}
# if args == None and LSD == None:
# return {"status": 0, "error": "Parameter's missing: args & LSD"}
# if args == None:
# return {"status": 0, "error": "Parameter missing: args"}
# if LSD == None:
# return {"status": 0, "error": "Parameter missing: LSD"}
def masters(args=None, LSD=None,iid=None):
rate = custom_rate_limit(limit=20, seconds=5)
if rate != 1:
return rate
val = input_validation(args=args)
if val != '':
return {"status": 0, "error": "Parameter's missing:"+val}
date_format = "%Y-%m-%d %H:%M:%S.%f"
@ -33,21 +56,23 @@ def masters(args=None, LSD=None):
try:
if args == "vehicle":
api = frappe.db.get_list(
"Vehicle",
fields=[
"name as vehicle",
"vehicle_segment",
"vehicle_segment_id",
"image",
"active_status",
"display_order",
"myid as vechile_id",
"display_order",
"modified",
],
filters={"modified": [">", LSD]},
)
val = input_validation(iid=iid)
if val != '':
return {"status": 0, "error": "Parameter's missing:"+val}
publish_type = check_pub_type(iid)
api = []
if publish_type == 'Global':
api = frappe.db.sql(f'''
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 global_publish = 1;
''',as_dict=1)
else:
api = frappe.db.sql(f'''
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:
if i["active_status"] == "Active":
i["active_status"] = True
@ -113,7 +138,8 @@ def masters(args=None, LSD=None):
elif args == "drive":
api = frappe.db.get_list(
"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]},
)
for i in api:
@ -125,7 +151,8 @@ def masters(args=None, LSD=None):
elif args == "fuel":
api = frappe.db.get_list(
"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]},
)
for i in api:
@ -187,17 +214,23 @@ def masters(args=None, LSD=None):
i["active_status"] = False
elif args == "custom_languages":
api = frappe.db.get_list(
"Custom Languages",
fields=[
"lang_name",
"lang_code",
"active_status",
"display_order",
"myid as lang_id",
"modified",
],
)
val = input_validation(iid=iid)
if val != '':
return {"status": 0, "error": "Parameter's missing:"+val}
publish_type = check_pub_type(iid)
api = []
if publish_type == 'Global':
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 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:
if i["active_status"] == "Active":
i["active_status"] = True
@ -252,3 +285,14 @@ def masters(args=None, LSD=None):
api = {"status": 0, "error": e}
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")
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()
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:
# return {'status': 0, 'error': "Parameter missing : args"}
val=input_validation(args=args)
if val!='':
return {'status': 0, 'error': "Parameter missing :"+val}
val = input_validation(args=args)
if val != '':
return {'status': 0, 'error': "Parameter missing :"+val}
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'
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"}
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
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"
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):
parentChildMap = {}
parent_child_map = {}
for b in input_list:
parentChildMap.setdefault(b[parameter] or None, []).append(b)
parent_child_map.setdefault(b[parameter] or None, []).append(b)
list1 = []
steps_length = 0
for p in parentChildMap:
da = {"procedure_name": p, 'steps': parentChildMap[p]}
for p in parent_child_map:
da = {"procedure_name": p, 'steps': parent_child_map[p]}
list1.append(da)
steps_length += len(parentChildMap[p])
for i in parentChildMap[p]:
steps_length += len(parent_child_map[p])
for i in parent_child_map[p]:
del i['procedure_name']
del i['idx']
@ -29,300 +65,358 @@ def get_parent_map(input_list, parameter):
@frappe.whitelist()
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:
# return {"status": 0, "error": "Parameter missing: Vehicle List"}
val=input_validation(vehicle_list=vehicle_list)
if val!='':
return {"status": 0, "error": "Parameter missing:"+val}
# return {STATUS: 0, ERROR: "Parameter missing: Vehicle List"}
val = input_validation(vehicle_list=vehicle_list)
if val != '':
return {STATUS: 0, ERROR: PARAM_MISSING+val}
if vehicle_list:
try:
Vehicle_req_list = []
vehicle_req_list = []
response = {}
v_list = json.loads(vehicle_list)
lang = v_list['LanguageID']
iid = v_list['InstallationId']
vehicle_data = v_list['VehicleReqList']
publish_type = frappe.db.sql(
'''SELECT publish_type FROM {}.`tabApp Device` where name='{}';'''.format(current_db_name, iid),
as_list=True)
'''SELECT publish_type FROM `tabApp Device` where name='{}';'''.format(iid), as_list=1)
if publish_type[0][0] is not None:
if vehicle_data:
for v in vehicle_data:
v_id = v['Vehicle']
current_version = float(v['CurrentVersion'])
data1_global = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published'
and publish_type='Global' and vehicle_status='Active' order by version ASC;'''.format(
current_db_name, v_id, lang), as_dict=True)
data1 = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published'
and publish_type='{}' and vehicle_status='Active' order by version ASC;'''.format(
current_db_name, v_id, lang, publish_type[0][0]), as_dict=True)
current_version = float(v[CUR_VERSION])
data1_global = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
order by version ASC;'''.format(v_id, lang), as_dict=1)
data1 = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_status='Published' and publish_type='{}' and vehicle_status='Active'
order by version ASC;'''.format(v_id, lang, publish_type[0][0]), as_dict=1)
if data1[0]['version'] is not None:
if current_version == float(data1[0]['version']):
data1[0]['IsUpdateAvailable'] = "false"
Vehicle_req_list.append(data1)
data1[0][UPDATE_AVAILABLE] = "false"
vehicle_req_list.append(data1)
else:
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'
and publish_type='Global' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format(
current_db_name, v_id, lang, current_version), as_dict=True)
data = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_status='Published' and publish_type='Global' and vehicle_status='Active' and version > '{}'
order by version ASC;'''.format(v_id, lang, current_version), as_dict=1)
elif current_version == float(data1_global[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'
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format(
current_db_name, v_id, lang, publish_type[0][0], current_version), as_dict=True)
data = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and
language='{}' and publish_status='Published' and publish_type='{}' and vehicle_status='Active' and version > '{}'
order by version ASC;'''.format(v_id, lang, publish_type[0][0], current_version), as_dict=1)
# return data
data_append = []
try:
for d in data:
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version)
d[UPDATE_AVAILABLE] = 'true'
d[CUR_VERSION] = float(
current_version)
data_append.append(d)
Vehicle_req_list.append(data_append)
vehicle_req_list.append(data_append)
except:
pass
response['LanguageID'] = lang
if len(Vehicle_req_list) != 0:
response['VehicleReqList'] = Vehicle_req_list[0]
if len(vehicle_req_list) != 0:
response['VehicleReqList'] = vehicle_req_list[0]
return response
else:
return {"status": 0, "error": "No Vehicles in criteria"}
return {STATUS: 0, ERROR: "No Vehicles in criteria"}
else:
return {"status": 0, "error": "Invalid Publish Details"}
return {STATUS: 0, ERROR: "Invalid Publish Details"}
else:
return {"status": 0, "error": "Invalid Publish Details"}
return {STATUS: 0, ERROR: "Invalid Publish Details"}
except Exception as e:
return {"status": 0, "error": e}
return {STATUS: 0, ERROR: "Failed to fetch updates"}
else:
return {"status": 0, "error": "Check argument: vehicle list"}
return {STATUS: 0, ERROR: "Check argument: vehicle list"}
@frappe.whitelist()
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:
# return {"status": 0, "error": "Parameter missing: Vehicle List"}
val=input_validation(vehicle_list=vehicle_list)
if val!='':
return {"status": 0, "error": "Parameter missing:"+val}
# return {STATUS: 0, ERROR: "Parameter missing: Vehicle List"}
val = input_validation(vehicle_list=vehicle_list)
if val != '':
return {STATUS: 0, ERROR: PARAM_MISSING+val}
if vehicle_list:
try:
response = {}
req_list = json.loads(vehicle_list)
response['Vehicle']=req_list['Vehicle']
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')
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 = []
vehicle_req_list = []
# Iterate on language
for v in vehicle_data:
l_id = v['LanguageID']
current_version = float(v['CurrentVersion'])
data1_global = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published'
and publish_type='Global' and vehicle_status='Active' order by version ASC;'''.format(
current_db_name, vehicle, l_id), as_dict=True)
data1 = frappe.db.sql('''SELECT name,max(version) as version,vehicle_id,language FROM {}.tabPublish where vehicle='{}' and language='{}' and publish_status='Published'
and vehicle_status='Active' order by version ASC;'''.format(
current_db_name, vehicle, l_id), as_dict=True)
current_version = float(v[CUR_VERSION])
data1_global = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}'
and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
order by version ASC;'''.format(vehicle, l_id), as_dict=1)
data1 = frappe.db.sql('''SELECT name,format(max(version),2) as version,vehicle_id,language FROM `tabPublish` where vehicle='{}' and language='{}' and
publish_status='Published' and vehicle_status='Active'
order by version ASC;'''.format(vehicle, l_id), as_dict=1)
if data1_global[0]['version']:
if data1[0]['version'] is not None:
if current_version == float(data1[0]['version']):
data1[0]['IsUpdateAvailable'] = "false"
data={}
data['Language']=l_id
data['IsUpdateAvailable'] = 'false'
data['CurrentVersion'] = float(current_version)
Vehicle_req_list.append(data)
data1[0][UPDATE_AVAILABLE] = "false"
data = {}
data[LANGUAGE] = l_id
data[UPDATE_AVAILABLE] = 'false'
data[CUR_VERSION] = float(current_version)
vehicle_req_list.append(data)
else:
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'
and publish_type='Global' and vehicle_status='Active' and Version > '{}' order by version ASC;'''.format(
current_db_name, vehicle, l_id, current_version), as_dict=True)
data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='Global' and
vehicle_status='Active' and Version > '{}' order by version ASC;'''.format(vehicle, l_id, current_version), as_dict=1)
try:
for d in data:
try:
file_name="/files/json_files/full_update/"+vehicle+"/"+vehicle+"-"+d['Language']+"-"+"full_v"+str(d['Version'])+".json"
file_size = os.path.getsize(base_url + file_name)
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']= None
except:
file_name= None
file_name = JSON_FULL_UPDATE_PATH+vehicle+"/"+vehicle + \
"-" + \
d[LANGUAGE]+"-"+"full_v" + \
str(d[VERSION])+JSON_EXT
file_size = os.path.getsize(
base_url + file_name)
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
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']='File failed to load'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version)
Vehicle_req_list.append(d)
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d[CUR_VERSION] = float(
current_version)
vehicle_req_list.append(d)
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):
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'
and publish_type='Global' and vehicle_status='Active' and Version > '{}' order by version ASC;'''.format(
current_db_name, vehicle, l_id, current_version), as_dict=True)
data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
and Version > '{}' order by version ASC;'''.format(vehicle, l_id, current_version), as_dict=1)
try:
for d in data:
file_name = None
try:
file_name="/files/json_files/global/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json"
file_size = os.path.getsize(base_url + file_name)
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']= None
except:
file_name = JSON_GLOABL_PATH+vehicle+"/" + \
vehicle+"-" + \
d[LANGUAGE]+"_v" + \
str(d[VERSION])+JSON_EXT
file_size = os.path.getsize(
base_url + file_name)
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
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']='File failed to load'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version)
Vehicle_req_list.append(d)
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d[CUR_VERSION] = float(
current_version)
vehicle_req_list.append(d)
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']):
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'
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format(
current_db_name, vehicle, l_id, publish_type, current_version), as_dict=True)
data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language
FROM `tabPublish` where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='{}' and
vehicle_status='Active' and version > '{}' order by version ASC;'''.format(vehicle, l_id, publish_type, current_version), as_dict=1)
try:
for d in data:
try:
file_name="/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json"
file_size = os.path.getsize(base_url + file_name)
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']= None
except:
file_name= None
file_name = JSON_INT_PATH+vehicle+"/" + \
vehicle+"-" + \
d[LANGUAGE]+"_v" + \
str(d[VERSION]) + \
JSON_EXT
file_size = os.path.getsize(
base_url + file_name)
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
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']='File failed to load'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version)
Vehicle_req_list.append(d)
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d[CUR_VERSION] = float(
current_version)
vehicle_req_list.append(d)
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']):
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'
and publish_type='Global' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format(
current_db_name, vehicle, l_id, current_version), as_dict=True)
data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='Global' and vehicle_status='Active'
and version > '{}' order by version ASC;'''.format(vehicle, l_id, current_version), as_dict=1)
try:
for d in data:
try:
file_name="/files/json_files/global/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json"
file_size = os.path.getsize(base_url + file_name)
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']= None
except:
file_name= "/files/json_files/global/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json"
file_name = JSON_GLOABL_PATH+vehicle+"/" + \
vehicle+"-" + \
d[LANGUAGE]+"_v" + \
str(d[VERSION]) + \
JSON_EXT
file_size = os.path.getsize(
base_url + file_name)
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
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']='File failed to load'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version)
Vehicle_req_list.append(d)
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d[CUR_VERSION] = float(
current_version)
vehicle_req_list.append(d)
except Exception as e2:
Vehicle_req_list.append({"Error":e2})
# else:
# Vehicle_req_list.append({"error2":"Else"})
vehicle_req_list.append(
{ERROR: UPDATE_FAILED})
elif current_version > float(data1_global[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'
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format(
current_db_name, vehicle, l_id,publish_type, current_version), as_dict=True)
data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='{}' and vehicle_status='Active' and version > '{}'
order by version ASC;'''.format(vehicle, l_id, publish_type, current_version), as_dict=1)
try:
for d in data:
try:
file_name="/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json"
file_size = os.path.getsize(base_url + file_name)
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']= None
except:
file_name= "/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json"
file_name = JSON_INT_PATH+vehicle+"/" + \
vehicle+"-" + \
d[LANGUAGE]+"_v" + \
str(d[VERSION]) + \
JSON_EXT
file_size = os.path.getsize(
base_url + file_name)
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
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']='File failed to load'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version)
Vehicle_req_list.append(d)
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = e
d[UPDATE_AVAILABLE] = 'false'
d[CUR_VERSION] = float(
current_version)
vehicle_req_list.append(d)
except Exception as e3:
Vehicle_req_list.append({'Error':e3})
vehicle_req_list.append(
{'Error': UPDATE_FAILED})
# else:
# Vehicle_req_list.append({'Error':"Else 3"})
# vehicle_req_list.append({'Error':"Else 3"})
else:
Vehicle_req_list.append(
{'Language': l_id, 'IsUpdateAvailable': 'false', 'CurrentVersion': float(current_version)})
vehicle_req_list.append(
{LANGUAGE: l_id, UPDATE_AVAILABLE: 'false', CUR_VERSION: float(current_version)})
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'
and publish_type='{}' and vehicle_status='Active' and version > '{}' order by version ASC;'''.format(
current_db_name, vehicle, l_id, publish_type, current_version), as_dict=True)
data = frappe.db.sql('''SELECT name as Name,format(max(version),2) as Version,vehicle_id as Vehicle,language as Language FROM `tabPublish`
where vehicle='{}' and language='{}' and publish_status='Published' and publish_type='{}' and vehicle_status='Active'
and version > '{}' order by version ASC;'''.format(vehicle, l_id, publish_type, current_version), as_dict=1)
try:
for d in data:
try:
file_name="/files/json_files/internal/"+vehicle+"/"+vehicle+"-"+d['Language']+"_v"+str(d['Version'])+".json"
file_size = os.path.getsize(base_url + file_name)
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']= None
file_name = JSON_INT_PATH+vehicle+"/" + \
vehicle+"-"+d[LANGUAGE] + \
"_v"+str(d[VERSION])+JSON_EXT
file_size = os.path.getsize(
base_url + file_name)
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = None
d[UPDATE_AVAILABLE] = 'true'
except:
file_name= None
file_name = None
file_size = None
d['JsonURL']= file_name
d['FileSize']= file_size
d['Error']='File failed to load'
d[JSON_URL] = file_name
d[FILE_SIZE] = file_size
d['Error'] = FILE_ERROR
d[UPDATE_AVAILABLE] = 'false'
d['IsUpdateAvailable'] = 'true'
d['CurrentVersion'] = float(current_version)
Vehicle_req_list.append(d)
d[CUR_VERSION] = float(current_version)
vehicle_req_list.append(d)
except Exception as e2:
Vehicle_req_list.append({"Error":e2})
vehicle_req_list.append(
{ERROR: UPDATE_FAILED})
response['Vehicle'] = vehicle
response['VehicleReqList'] = Vehicle_req_list
response['VehicleReqList'] = vehicle_req_list
return response
else:
response['JSON'] = {"status": 0, "Error": "Data Not available"}
response['JSON'] = {STATUS: 0, ERROR: "Data Not available"}
return response
except Exception as e:
response['JSON'] = {"status": 0, "error": e}
response['JSON'] = {STATUS: 0, ERROR: UPDATE_FAILED}
return response
else:
return {"status": 0, "error": "Check Parameter: vehicle list"}
return {STATUS: 0, ERROR: "Check Parameter: vehicle list"}
def get_step_total_count(json_path):
with open(json_path) as json_file:
@ -382,370 +476,39 @@ def calculate_step(data):
return data
@frappe.whitelist()
def check_vehicle_update11(vehicle_list=None):
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"}
def get_publish_ver(vehicle, l_id):
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
publish_status='Published' and vehicle_status='Active' ;'''.format(vehicle, l_id), as_dict=1)
@frappe.whitelist()
def update_completed(FileName=None):
val=input_validation(vehicle_list=vehicle_list)
if val!='':
return {"status": 0, "error": "Parameter missing:"+val}
# if FileName == None:
# return {'status': 0, 'error': "Parameter missing: FileName"}
rate_res = custom_rate_limit(limit=5, seconds=15)
if rate_res != 1:
return rate_res
val = input_validation(FileName=FileName)
if val != '':
return {STATUS: 0, ERROR: "Parameter missing:"+val}
if FileName:
try:
os.remove(base_url + FileName)
return {'isSuccessful': True}
except Exception as e:
return {'isSuccessful': False,"status": 0, 'error': e}
return {'isSuccessful': False, STATUS: 0, 'ERROR': e}
else:
return {"status": 0, "error": "Parameter: FileName is null"}
return {STATUS: 0, ERROR: "Parameter: FileName is null"}
@frappe.whitelist()
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_file = os.listdir(path)
if path_file:
for file in path_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,
"unique": 0,
"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,
"is_public": 1,
"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",
"module": null,
"name": "Variant mapping",
@ -95,11 +95,50 @@
"heatmap_year": null,
"is_public": 1,
"is_standard": 0,
"last_synced_on": "2022-05-11 13:13:51.898783",
"modified": "2022-04-11 18:20:02.591953",
"last_synced_on": "2022-11-07 15:36:06.864894",
"modified": "2022-04-21 10:00:30.763417",
"module": null,
"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_document_type": "",
"parentfield": null,
@ -134,7 +173,7 @@
"heatmap_year": null,
"is_public": 1,
"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",
"module": null,
"name": "Procedure",
@ -157,26 +196,26 @@
},
{
"aggregate_function_based_on": null,
"based_on": "",
"chart_name": "KM Mapping",
"chart_type": "Group By",
"color": "#449CF0",
"based_on": "creation",
"chart_name": "Test",
"chart_type": "Count",
"color": "#CB2929",
"custom_options": null,
"docstatus": 0,
"doctype": "Dashboard Chart",
"document_type": "Kilometer Mapping",
"document_type": "App Device",
"dynamic_filters_json": "[]",
"filters_json": "[[\"Kilometer Mapping\",\"workflow_state\",\"=\",null,false]]",
"filters_json": "[]",
"from_date": null,
"group_by_based_on": "workflow_state",
"group_by_based_on": null,
"group_by_type": "Count",
"heatmap_year": null,
"is_public": 1,
"is_public": 0,
"is_standard": 0,
"last_synced_on": "2022-05-11 13:13:51.649487",
"modified": "2022-05-10 13:05:25.011604",
"last_synced_on": null,
"modified": "2022-05-11 11:06:15.280730",
"module": null,
"name": "KM Mapping",
"name": "Test",
"number_of_groups": 0,
"parent": null,
"parent_document_type": "",
@ -185,10 +224,10 @@
"report_name": null,
"source": "",
"time_interval": "Yearly",
"timeseries": 0,
"timeseries": 1,
"timespan": "Last Year",
"to_date": null,
"type": "Bar",
"type": "Line",
"use_report_chart": 0,
"value_based_on": "",
"x_field": null,
@ -197,25 +236,25 @@
{
"aggregate_function_based_on": null,
"based_on": "",
"chart_name": "Publish Status",
"chart_name": "KM Mapping",
"chart_type": "Group By",
"color": "#7cbcf7",
"color": "#449CF0",
"custom_options": null,
"docstatus": 0,
"doctype": "Dashboard Chart",
"document_type": "Publish",
"document_type": "Kilometer Mapping",
"dynamic_filters_json": "[]",
"filters_json": "[[\"Publish\",\"publish_status\",\"=\",null,false]]",
"filters_json": "[[\"Kilometer Mapping\",\"workflow_state\",\"=\",null,false]]",
"from_date": null,
"group_by_based_on": "vehicle",
"group_by_based_on": "workflow_state",
"group_by_type": "Count",
"heatmap_year": null,
"is_public": 1,
"is_standard": 0,
"last_synced_on": "2022-05-11 13:13:51.737960",
"modified": "2022-04-11 18:23:00.494268",
"last_synced_on": "2022-11-07 15:36:06.500997",
"modified": "2022-05-10 13:05:25.011604",
"module": null,
"name": "Publish Status",
"name": "KM Mapping",
"number_of_groups": 0,
"parent": null,
"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,
"is_custom": 0,
"list_sidebar": 1,
"modified": "2022-02-07 13:11:48.057238",
"modified": "2022-02-22 10:28:00.880225",
"name": "CMS User",
"notifications": 1,
"parent": null,
@ -431,6 +431,30 @@
"two_factor_auth": 0,
"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,
"dashboard": 0,
@ -790,29 +814,5 @@
"timeline": 1,
"two_factor_auth": 0,
"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_license = "MIT"
# 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"
# ic_app_icon.png
@ -20,10 +20,10 @@ web_include_css = ["/assets/css/smart_service.min.css"]
# Icons
website_context = {
"favicon": "/assets/smart_service/images/Logo Fav Icon.png",
"splash_image": "/assets/smart_service/images/SS Alone.png",
# "splash_image": "/assets/smart_service/images/ic_app_icon1.png",
"app_name" : "smart service"
"favicon": "/assets/smart_service/images/Logo Fav Icon.png",
"splash_image": "/assets/smart_service/images/SS Alone.png",
# "splash_image": "/assets/smart_service/images/ic_app_icon1.png",
"app_name": "smart service"
}
# Includes in <head>
# ------------------
@ -51,7 +51,7 @@ website_context = {
# doctype_js = {"doctype" : "public/js/doctype.js"}
doctype_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_tree_js = {"doctype" : "public/js/doctype_tree.js"}
@ -65,7 +65,7 @@ doctype_js = {
# website user home page (by Role)
# role_home_page = {
# "Role": "home_page"
# "Role": "home_page"
# }
# Generators
@ -102,48 +102,53 @@ doctype_js = {
# ---------------
# Override standard doctype classes
#override_doctype_class = {
# override_doctype_class = {
# "ToDo": "custom_app.overrides.CustomToDo"
#}
# }
# Document Events
# ---------------
# Hook on document methods and events
doc_events = {
"File": {
"validate": ["smart_service.overrides.overrides.override_file.validate"],
}
# "*": {
# "on_update": "method",
# "on_cancel": "method",
# "on_trash": "method"
# }
"File": {
"validate": ["smart_service.overrides.overrides.override_file.validate"],
}
# "*": {
# "on_update": "method",
# "on_cancel": "method",
# "on_trash": "method"
# }
}
# Scheduled Tasks
# ---------------
scheduler_events = {
# "all": [
# "smart_service.tasks.all"
# ],
"daily": [
"smart_service.apis.app_user_login.login_generate_token"
# "smart_service.tasks.daily"
],
# "hourly": [
#"smart_service.tasks.hourly"
# "smart_service.apis.app_user_login.login_generate_token",
# ],
"weekly": [
# "smart_service.tasks.weekly"
"smart_service.apis.update_validation.delete_complete"
]
# "monthly": [
# "smart_service.tasks.monthly"
# ]
}
# "all": [
# "smart_service.tasks.all"
# ],
"cron": {
"0/1 * * * *": [
"smart_service.apis.app_user_login.deactivate_tokens"
]
},
"daily": [
"smart_service.apis.app_user_login.login_generate_token"
# "smart_service.tasks.daily"
],
# "hourly": [
# "smart_service.tasks.hourly"
# "smart_service.apis.app_user_login.login_generate_token",
# ],
"weekly": [
# "smart_service.tasks.weekly"
"smart_service.apis.update_validation.delete_complete"
]
# "monthly": [
# "smart_service.tasks.monthly"
# ]
}
# Testing
# -------
@ -173,24 +178,24 @@ scheduler_events = {
# --------------------
user_data_fields = [
{
"doctype": "{doctype_1}",
"filter_by": "{filter_by}",
"redact_fields": ["{field_1}", "{field_2}"],
"partial": 1,
},
{
"doctype": "{doctype_2}",
"filter_by": "{filter_by}",
"partial": 1,
},
{
"doctype": "{doctype_3}",
"strict": False,
},
{
"doctype": "{doctype_4}"
}
{
"doctype": "{doctype_1}",
"filter_by": "{filter_by}",
"redact_fields": ["{field_1}", "{field_2}"],
"partial": 1,
},
{
"doctype": "{doctype_2}",
"filter_by": "{filter_by}",
"partial": 1,
},
{
"doctype": "{doctype_3}",
"strict": False,
},
{
"doctype": "{doctype_4}"
}
]
# Authentication and authorization
@ -200,23 +205,22 @@ user_data_fields = [
# "smart_service.auth.validate"
# ]
fixtures = [
# {
# "doctype": "Notification",
# "filters": [{"is_standard":0}]
# }
#"Custom Field",
#"Property Setter",
#"Client Script",
#"Server Script",
#"Workflow",
#"Workflow Action Master",
#"Workflow State",
#"Role",
#"Workspace",
#"Custom DocPerm",
# "Role Profile",
#"Report",
#"Dashboard Chart"
# {
# "doctype": "Notification",
# "filters": [{"is_standard":0}]
# }
# "Custom Field",
# "Property Setter",
# "Client Script",
# "Server Script",
# "Workflow",
# "Workflow Action Master",
# "Workflow State",
# "Role",
# "Workspace",
# "Custom DocPerm",
# "Role Profile",
# "Report",
# "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) {
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")
validated = false;
}
@ -36,10 +36,10 @@ frappe.ui.form.on('App Labels', {
frappe.throw(__("Just a <b>.</b> is not prescribed!"));
frappe.validated = false;
}
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
var regex = /[!@#$%^&*()+\=\[\]{};`~':"\\|.<>\/]+/;
if (frm.doc.english_label) {
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;
} else if (frm.doc.english_label) {
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.length > 50) {
if (frm.doc.page_name.length > 100) {
frappe.msgprint("<b>Page Name :</b> Only <b> 50 </b> characters allowed")
validated = false;
}
@ -63,7 +63,7 @@ frappe.ui.form.on('App Labels', {
frappe.throw(__("Just a <b>.</b> is not prescribed!"));
frappe.validated = false;
}
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
var regex = /[!@#$%^&*()+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.page_name) {
if (regex.test(frm.doc.page_name) === true) {
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.length > 50) {
if (frm.doc.label.length > 100) {
frappe.msgprint("<b>Translated Label :</b> Only <b> 50 </b> characters allowed")
validated = false;
}
@ -90,7 +90,7 @@ frappe.ui.form.on('App Labels', {
frappe.throw(__("Just a <b>.</b> is not prescribed!"));
frappe.validated = false;
}
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
var regex = /[!@#$%^&*()+\=\[\]{};`~':"\\|.<>\/]+/;
if (frm.doc.label) {
if (regex.test(frm.doc.label) === true) {
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,
"engine": "InnoDB",
"field_order": [
"internal_publish",
"column_break_10",
"global_publish",
"section_break_3",
"lang_code",
"active_status",
"column_break_2",
@ -60,11 +64,33 @@
"label": "myID",
"read_only": 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,
"links": [],
"modified": "2022-02-11 12:41:29.369497",
"modified": "2023-07-11 15:55:25.503377",
"modified_by": "Administrator",
"module": "Masters",
"name": "Custom Languages",

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

@ -20,7 +20,7 @@ frappe.ui.form.on('Drive', {
}
var regex = /[!@#$%^&*()_+\=\[\]{};'`~:"\\|.<>\/?]+/;
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;
} else if (frm.doc.drive) {
if (frm.doc.drive.includes("'")) {

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

@ -21,7 +21,7 @@ frappe.ui.form.on('Fuel', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.fuel) {
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;
} else if (frm.doc.fuel) {
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 = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.procedure_name) {
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;
} else if (frm.doc.procedure_name) {
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 = /[!@#$%^&*()_+\=\[\]{};~`':"\\|.<>\/?]+/;
if (frm.doc.kilometer) {
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;
} else if ((frm.doc.kilometer.includes("'"))) {
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 = /[!@#$%^&*()_+\=\[\]{};`~:"\\|.<>\/?]+/;
if (frm.doc.sub_system_name) {
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;
}
}

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

@ -47,7 +47,7 @@ frappe.ui.form.on('Systems', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~:"\\|.<>\/?]+/;
if (frm.doc.system_name) {
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;
}
}

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

@ -21,7 +21,7 @@ frappe.ui.form.on('Transmission', {
var regex = /[!@#$%^&*()_+\=\[\]{};`~':"\\|.<>\/?]+/;
if (frm.doc.transmission) {
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;
} else if (frm.doc.transmission) {
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 = /[!@#$%^&*()_+\=\[\]{};'`~:"\\|.<>\/?]+/;
if(frm.doc.variant){
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;
} else if(frm.doc.variant) {
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,
"engine": "InnoDB",
"field_order": [
"internal_publish",
"column_break_2",
"global_publish",
"section_break_4",
"vehicle",
"image",
"preview",
@ -18,9 +22,7 @@
"active_status",
"myid",
"display_order",
"service_kilometers",
"global_publish_flag",
"internal_publish_flag"
"service_kilometers"
],
"fields": [
{
@ -103,24 +105,27 @@
},
{
"default": "0",
"fieldname": "global_publish_flag",
"fieldname": "internal_publish",
"fieldtype": "Check",
"hidden": 1,
"label": "Global Publish Flag",
"read_only": 1
"label": "Internal Publish"
},
{
"default": "0",
"fieldname": "internal_publish_flag",
"fieldtype": "Check",
"hidden": 1,
"label": "Internal Publish Flag",
"read_only": 1
"fieldname": "global_publish",
"fieldtype": "Data",
"label": "Global Publish"
},
{
"fieldname": "column_break_2",
"fieldtype": "Column Break"
},
{
"fieldname": "section_break_4",
"fieldtype": "Section Break"
}
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2022-04-01 17:41:13.606316",
"modified": "2023-07-11 15:51:55.396348",
"modified_by": "Administrator",
"module": "Masters",
"name": "Vehicle",

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

@ -58,7 +58,7 @@ frappe.ui.form.on('Vehicle Segment', {
var regex = /[!@#$%^&*()_+\-=\[\]{};'`~:"\\|,.<>\/?]+/;
if (frm.doc.vehicle_segment) {
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;
} else if (frm.doc.vehicle_segment) {
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
# For license information, please see license.txt
# import frappe
import frappe
def execute(filters=None):
columns, data = [], []

4
smart_service/public/css/smart_service.css

@ -26,8 +26,8 @@
}
.app-logo {
width: 400px !important;
height: 50px !important;
/* width: 400px !important;
height: 50px !important; */
image-rendering: -webkit-optimize-contrast !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) {
var regex = /[@#$%^*+\\[\]{}`~:\\|\?]+/;
// var regex = /[@#$%^*\\[\]{}`~\\|\?]/;
var regex = /[@#$^\\[\]{}`\\|\?]/;
if (frm.doc.procedure_details) {
for (var i = 0; i < frm.doc.procedure_details.length; i++) {
if (regex.test(frm.doc.procedure_details[i].content) === true) {
if (frm.doc.procedure_details[i].content_type != "Link") {
frm.doc.procedure_details[i].content_type = ''
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) {
}
})
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 regex = /[://]+/;
frappe.db.get_value('Fish', { name: "Fish" }, 'path', (r) => {
for (var i = 0; i < frm.doc.procedure_details.length; i++) {
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.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
}
var url = window.location.host;
var regex = /[://]+/;
// frappe.db.get_value('Fish', { name: "Fish" }, 'path', (r) => {
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>')){
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>';
frm.doc.procedure_details[i].content = x
}
}
cur_frm.refresh_fields('procedure_details');
// })
}
cur_frm.refresh_fields('procedure_details');
})
})
}
}
// select_row(frm);
// 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
# For license information, please see license.txt
import re
import sys
import frappe
from frappe.model.document import Document
import frappe,json
import frappe
import json
current_db_name = frappe.conf.get("db_name")
import sys
sys.tracebacklimit=0
sys.tracebacklimit = 0
class Procedure(Document):
def validate(self):
if self.procedure_details:
for x in self.get("procedure_details"):
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))
def validate(self):
if self.procedure_details:
for x in self.get("procedure_details"):
if x.content:
res_str = re.sub("–", "", x.content)
res_str = re.sub("—", "", res_str)
res_str = re.sub("‘", "", res_str)
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()
def get_doc_status(docname):
self = frappe.get_doc("Procedure",docname)
return self.workflow_state
self = frappe.get_doc("Procedure", docname)
return self.workflow_state
@frappe.whitelist()
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)
return data
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)
return data
@frappe.whitelist()
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
(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()
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
(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()
def fuel(doctype, txt, searchfield, start, page_len, filters):
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})
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})
@frappe.whitelist()
def transmission(doctype, txt, searchfield, start, page_len, filters):
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})
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})
@frappe.whitelist()
def drive(doctype, txt, searchfield, start, page_len, filters):
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})
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})
@frappe.whitelist()
def get_variant(doctype, txt, searchfield, start, page_len, filters):
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
lang = filters.get('language')
if vm:
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
(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:
return variant
else:
return []
else:
return []
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
lang = filters.get('language')
if vm:
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
(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:
return variant
else:
return []
else:
return []
@frappe.whitelist()
def get_systems(doctype, txt, searchfield, start, page_len, filters):
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
lang = filters.get('language')
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)
if sys_mapping:
for x in sys_mapping:
doc = frappe.get_doc('System Mapping', x.name)
systems = frappe.db.sql(""" select systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and
(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)
if systems:
return systems
else:
return []
else:
return []
else:
return []
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
lang = filters.get('language')
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)
if sys_mapping:
for x in sys_mapping:
doc = frappe.get_doc('System Mapping', x.name)
systems = frappe.db.sql(""" select systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and
(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)
if systems:
return systems
else:
return []
else:
return []
else:
return []
@frappe.whitelist()
def get_subsystems(doctype, txt, searchfield, start, page_len, filters):
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
systems = filters.get('systems')
lang = filters.get('language')
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)
if sys_mapping:
for x in sys_mapping:
doc = frappe.get_doc('System Mapping', x.name)
systems = frappe.db.sql(""" select sub_systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and
(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})
if systems:
return systems
else:
return []
else:
return []
else:
return []
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
systems = filters.get('systems')
lang = filters.get('language')
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)
if sys_mapping:
for x in sys_mapping:
doc = frappe.get_doc('System Mapping', x.name)
systems = frappe.db.sql(""" select sub_systems FROM {0}.`tabSystem Mapping_Sub System` where parent = '{1}' and systems = '{2}' and
(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})
if systems:
return systems
else:
return []
else:
return []
else:
return []
@frappe.whitelist()
def get_procedure(doctype, txt, searchfield, start, page_len, filters):
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
systems = filters.get('systems')
sub_systems = filters.get('sub_systems')
lang = filters.get('language')
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)
if sys_mapping:
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}' and
(`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})
if procedure:
return procedure
else:
return []
else:
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)
if sys_mapping:
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
if not filters:
return []
filters = frappe._dict(filters)
vm = filters.get('variant_mapping')
systems = filters.get('systems')
sub_systems = filters.get('sub_systems')
lang = filters.get('language')
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)
if sys_mapping:
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}' and
(`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})
if procedure:
return procedure
else:
return []
else:
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)
if sys_mapping:
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()
def get_systemid(systems):
system = frappe.db.sql(""" select myid FROM {0}.`tabSystems` where name = '{1}'""".format(current_db_name,systems))
if system:
return system
system = frappe.db.sql(""" select myid FROM {0}.`tabSystems` where name = '{1}'""".format(
current_db_name, systems))
if system:
return system
@frappe.whitelist()
def get_subsystemid(systems):
system = frappe.db.sql(""" select myid FROM {0}.`tabSub Systems` where name = '{1}'""".format(current_db_name,systems))
if system:
return system
system = frappe.db.sql(""" select myid FROM {0}.`tabSub Systems` where name = '{1}'""".format(
current_db_name, systems))
if system:
return system
@frappe.whitelist()
def procedure_name(doctype, txt, searchfield, start, page_len, filters):
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})
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})
@frappe.whitelist()
def procedure_step_name(doctype, txt, searchfield, start, page_len, filters):
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})
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})
@frappe.whitelist()
def update_system_id(name):
doc = frappe.get_doc("Procedure",name)
for table in doc.get("procedure_details"):
if table.content_type == "Link":
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)
if system_mapping:
sm = system_mapping[0]['name']
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)
if sys_procedure:
if table.temp_cnt == sys_procedure[0]['procedure']:
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()
doc = frappe.get_doc("Procedure", name)
for table in doc.get("procedure_details"):
if table.content_type == "Link":
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)
if system_mapping:
sm = system_mapping[0]['name']
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)
if sys_procedure:
if str(table.temp_cnt) == str(sys_procedure[0]['procedure']):
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",
"fieldtype": "Data",
"hidden": 1,
"label": "System ID"
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2022-04-08 22:21:10.666175",
"modified": "2023-06-08 14:41:02.141600",
"modified_by": "Administrator",
"module": "Transactions",
"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