Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.88 KB | None | 0 0
  1. from django.db import models
  2. from django.db import connection, connections
  3. import json
  4. import datetime
  5. import urllib
  6.  
  7. # Get all Outlets list in the form of dictionary
  8. def GetAllOutlets():
  9. cur = connections['LogisticsEPSMirror'].cursor()
  10. cur.callproc('[dbo].[SP_DepotListWeb]', [])
  11. results = dictfetchall(cur)
  12. cur.close()
  13. return results
  14. # results = cur.fetchall()
  15. # # results = dictfetchall(cur)
  16. # columns = [col[0] for col in cur.description]
  17. # return [
  18. # dict(zip(columns, row))
  19. # for row in results
  20. # ]
  21.  
  22. # Get an array of dictionary as the procedure SP_ChurnAnalysis returns multiple tables
  23. def GetChrunResultset(dateupto, username, depotcode):
  24. cur = connections['LogisticsEPSMirror'].cursor()
  25. cur.callproc('[dbo].[SP_ChurnAnalysis]', [dateupto,username,depotcode])
  26. resultset = []
  27. results = dictfetchall(cur)
  28. resultset.append(results)
  29. while cur.nextset():
  30. results = dictfetchall(cur)
  31. resultset.append(results)
  32.  
  33. cur.close()
  34. return resultset
  35.  
  36. def dictfetchall(cur):
  37. dataset = cur.fetchall()
  38. columns = [col[0] for col in cur.description]
  39. return [
  40. dict(zip(columns, row))
  41. for row in dataset
  42. ]
  43.  
  44. def GetGraphDataForChurn(tables):
  45. resultSet = []
  46. for table in tables:
  47. jsonData = []
  48. for row in table:
  49. date = str(row['InvoicePeriod'])[:4] + "-" + str(row['InvoicePeriod'])[4:6] + "-" + "01"
  50. obj = {'time': date, 'value': float("{0:.2f}".format(row['ChurnRate']))}
  51. jsonData.append(obj)
  52. resultSet.append(json.dumps(jsonData))
  53.  
  54. return resultSet
  55.  
  56. # Check login of a provided username and password
  57. def ValidateLoginDB(user,password):
  58. cur = connections['default'].cursor()
  59. cur.execute("SELECT count(*) FROM [dbo].[UserPanel] where UserId = '" + user + "' and Password = '" + password + "' and IsActive = 1")
  60. total = int(cur.fetchone()[0])
  61. cur.close()
  62. if(total > 0):
  63. return True
  64. else:
  65. return False
  66.  
  67. # Check login of a provided username and password
  68. def GerUsernameFromUserId(userid):
  69. cur = connections['default'].cursor()
  70. cur.execute("SELECT username FROM [dbo].[UserPanel] where UserId = '" + userid + "'")
  71. results = dictfetchall(cur)
  72. cur.close()
  73. return results
  74.  
  75.  
  76.  
  77. def GetDashboards(userid):
  78. cur = connections['default'].cursor()
  79. cur.execute("SELECT A.[DashboardId] \
  80. ,[Title]\
  81. ,[Url]\
  82. ,ReportDescription \
  83. FROM [dbo].[Dashboard] A inner join\
  84. [dbo].[UserPanel] B on A.[DashboardId] = B.[DashboardId]\
  85. and B.UserId = '" + userid + "'")
  86. results = dictfetchall(cur)
  87. cur.close()
  88. return results
  89.  
  90. def GetReportUrl(userid, id):
  91. cur = connections['default'].cursor()
  92. cur.execute("SELECT [Title]\
  93. ,[Url]\
  94. ,ReportDescription \
  95. ,A.DashboardId \
  96. ,A.GroupId \
  97. ,A.ReportId \
  98. FROM [dbo].[Dashboard] A inner join\
  99. [dbo].[UserDashboardMap] B on A.[DashboardId] = B.[DashboardId]\
  100. and B.UserId = '" + userid + "' \
  101. and A.DashboardId = " + id)
  102. result = dictfetchall(cur)
  103. cur.close()
  104. return result
  105.  
  106.  
  107.  
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114.  
  115.  
  116.  
  117. ##All model functions related to manage dashboard page.
  118. class Dashboard():
  119. def GetAllDashboardList(self):
  120. cur = connections['default'].cursor()
  121. cur.execute("SELECT * FROM [dbo].[Dashboard] order by DashboardId")
  122. result = dictfetchall(cur)
  123. cur.close()
  124. return result
  125.  
  126. def InsertDashboardInfo(self,title, description, url,groupId,reportId):
  127. add_dashboard = "INSERT INTO dbo.dashboard \
  128. VALUES('" + title + "', '" + url + "', '" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "', '" + description + "','" + groupId + "', '"+ reportId + "')"
  129.  
  130. #data_dashboard = (title, url, datetime.datetime.strptime(p_date,'%d-%b-%y %H.%M.%S.%f'), description)
  131. print(add_dashboard)
  132. cur = connections['default'].cursor()
  133. cur.execute(add_dashboard)
  134. cur.close()
  135.  
  136.  
  137. def UpdateDashboardInfo(self,dashboardId, title, description, url,groupId,reportId):
  138. update_dashboard = "Update dbo.dashboard \
  139. Set Title = '" + title + "', Url = '" + url + "', ReportDescription = '" + description + "', GroupId = '" + groupId + "' Where DashboardId = " + str(dashboardId)
  140.  
  141. #data_dashboard = (title, url, datetime.datetime.strptime(p_date,'%d-%b-%y %H.%M.%S.%f'), description)
  142. print(update_dashboard)
  143. cur = connections['default'].cursor()
  144. cur.execute(update_dashboard)
  145. cur.close()
  146.  
  147.  
  148. def DeleteDashboardInfo(self,dashboardId):
  149. delete_dashboard = "Delete from dbo.dashboard Where DashboardId = " + str(dashboardId)
  150. cur = connections['default'].cursor()
  151. cur.execute(delete_dashboard)
  152.  
  153. updare_report_order = "update T1 \
  154. set T1.ReportOrder = T2.NewOrder \
  155. from \
  156. ( \
  157. select userid, \
  158. dashboardid, \
  159. ReportOrder, \
  160. row_number() over(PARTITION BY userid order by userid, ReportOrder) as NewOrder \
  161. from [dbo].[UserDashboardMap] \
  162. ) as T2 \
  163. inner join [dbo].[UserDashboardMap] as T1 On T1.userid = T2.userid and T1.dashboardid = T2.dashboardid"
  164. cur.execute(updare_report_order)
  165. cur.close()
  166.  
  167. def GetPBIEmbeddedToken(self, groupId, reportId):
  168. pbitoken = {}
  169. with urllib.request.urlopen(
  170. "http://192.168.100.61:90/pbiembeddedapi/Home/EmbedReport/" + groupId + "/" + reportId) as url:
  171. data = json.loads(url.read().decode())
  172. pbitoken['EmbedToken'] = data['EmbedToken']['Token']
  173. pbitoken['EmbedUrl'] = data['EmbedUrl']
  174. pbitoken['Id'] = data['Id']
  175. return pbitoken
  176.  
  177.  
  178.  
  179.  
  180.  
  181.  
  182.  
  183. class UserPanel():
  184. def GetAllUserList(self):
  185. cur = connections['default'].cursor()
  186. cur.execute("SELECT * FROM [dbo].[UserPanel] where userid != 'admin' order by UserId")
  187. result = dictfetchall(cur)
  188. cur.close()
  189. return result
  190.  
  191. def InsertUserInfo(self, userid, username, password, email, isactive):
  192. ##Check if the usedid is already available in the database
  193. cur = connections['default'].cursor()
  194. cur.execute("SELECT count(*) FROM [dbo].[UserPanel] where UserId = '" + userid + "'")
  195. total = int(cur.fetchone()[0])
  196. if total > 0:
  197. return False
  198. add_user = "INSERT INTO dbo.UserPanel \
  199. VALUES('" + userid + "', '" + password + "', '" + email + "', '" + str(isactive) + "', '" + username + "')"
  200. print(add_user)
  201. cur.execute(add_user)
  202. cur.close()
  203. return True
  204.  
  205. def UpdateUserInfo(self, userid, password, email, isactive):
  206. update_user = "Update dbo.UserPanel \
  207. Set Password = '" + password + "', Email = '" + email + "', IsActive = '" + str(isactive) + "' Where UserId = '" + str(userid) + "'"
  208. print(update_user)
  209. cur = connections['default'].cursor()
  210. cur.execute(update_user)
  211. cur.close()
  212.  
  213. def DeleteUserInfo(self,userid):
  214. # When a user is deleted, all of his data from [dbo].[UserDashboardMap] will be deleted because of cascade delete is ON is database. After deleting, report order should be updated
  215. # Only for
  216. delete_user = "Delete from dbo.UserPanel Where UserId = '" + str(userid) + "'"
  217. print(delete_user)
  218. cur = connections['default'].cursor()
  219. cur.execute(delete_user)
  220.  
  221. # updare_report_order = "update T1 \
  222. # set T1.ReportOrder = T2.NewOrder \
  223. # from \
  224. # ( \
  225. # select userid, \
  226. # dashboardid, \
  227. # ReportOrder, \
  228. # row_number() over(PARTITION BY userid order by userid, ReportOrder) as NewOrder \
  229. # from [dbo].[UserDashboardMap] \
  230. # ) as T2 \
  231. # inner join [dbo].[UserDashboardMap] as T1 On T1.userid = T2.userid and T1.dashboardid = T2.dashboardid \
  232. # where T1.userid = '" + userid + "'"
  233. # cur.execute(updare_report_order)
  234. cur.close()
  235.  
  236.  
  237.  
  238. def GetAllUserWithDashboard(self):
  239. dashboard_list = "SELECT B.UserId , B.Email, B.IsActive, C.Title, C.Url, A.ReportOrder, C.ModifyDate, C.ReportDescription \
  240. FROM [dbo].[UserDashboardMap] A inner join [dbo].[UserPanel] B \
  241. On A.UserId = B.UserId \
  242. inner join [dbo].[Dashboard] C \
  243. On A.DashboardId = C.DashboardId order by B.UserId, A.ReportOrder"
  244. cur = connections['default'].cursor()
  245. cur.execute(dashboard_list)
  246. result = dictfetchall(cur)
  247. cur.close()
  248. return result
  249.  
  250. def GetDistinctUserList(self):
  251. distinct_user = "SELECT distinct UserId from dbo.UserPanel where IsActive = 1"
  252. cur = connections['default'].cursor()
  253. cur.execute(distinct_user)
  254. result = dictfetchall(cur)
  255. cur.close()
  256. return result
  257.  
  258. def GetDistinctDashboardList(self, userid):
  259. #Get all dashboards that are not already assigned to that user, so that user can be assigned
  260. distinct_user = "SELECT distinct DashboardId, title from dbo.Dashboard \
  261. where \
  262. dashboardid not in \
  263. ( \
  264. Select distinct DashboardId from [dbo].[UserDashboardMap] \
  265. Where UserId = '" + userid + "' \
  266. )"
  267. cur = connections['default'].cursor()
  268. cur.execute(distinct_user)
  269. result = dictfetchall(cur)
  270. cur.close()
  271. return result
  272.  
  273. def GetDashboardsByUser(self, userid):
  274. distinct_user = "SELECT B.UserId, C.DashboardId ,C.title ,A.ReportOrder, C.Url, C.ReportDescription \
  275. FROM [dbo].[UserDashboardMap] A inner join [dbo].[UserPanel] B \
  276. On A.UserId = B.UserId \
  277. inner join [dbo].[Dashboard] C \
  278. On A.DashboardId = C.DashboardId \
  279. where B.UserId = '" + userid + "' Order by A.ReportOrder"
  280. cur = connections['default'].cursor()
  281. cur.execute(distinct_user)
  282. result = dictfetchall(cur)
  283. cur.close()
  284. return result
  285.  
  286. def AddNewUserDashboard(self, userid, dashboardId):
  287. cur = connections['default'].cursor()
  288. #Check if the mapping exists already or not
  289. cur.execute("SELECT count(*) FROM [dbo].[UserDashboardMap] where UserId = '" + str(userid) + "' and DashboardId = " + str(dashboardId) )
  290. total = int(cur.fetchone()[0])
  291. if total > 0:
  292. return False
  293.  
  294. add_dashboard = "INSERT INTO dbo.UserDashboardMap( [UserId] ,[DashboardId],[ReportOrder] ) \
  295. SELECT '" + userid + "' as UserId, " + dashboardId + " as DashboardId, ISNULL(MAX(ReportOrder), 0) + 1 as ReportOrder FROM dbo.UserDashboardMap where userid = '" + userid + "'"
  296. cur.execute(add_dashboard)
  297.  
  298.  
  299.  
  300.  
  301. # if reportOrder == 0: #if reportorder is 0, then update all reports order by 1 and insert the newly coming report to order 1
  302. # #update_order = "Update [dbo].[UserDashboardMap] \
  303. # # Set ReportOrder = ReportOrder + 1 Where UserId = '" + str(userid) + "'"
  304. # #cur.execute(update_order)
  305. # add_dashboard = "INSERT INTO [dbo].[UserDashboardMap] \
  306. # VALUES('" + userid + "', " + str(dashboardId) + ", 0)"
  307. # cur.execute(add_dashboard)
  308. # else:
  309. # update_order = "Update [dbo].[UserDashboardMap] \
  310. # Set ReportOrder = ReportOrder + 1 Where ReportOrder > " + str(reportOrder)
  311. # cur.execute(update_order)
  312. # new_order = reportOrder+1
  313. # add_dashboard = "INSERT INTO [dbo].[UserDashboardMap] \
  314. # VALUES('" + userid + "', " + str(dashboardId) + ", " + str(new_order) + ")"
  315. # cur.execute(add_dashboard)
  316. #
  317. # # for safety: adjust all report orders
  318. # updare_report_order = "update T1 \
  319. # set T1.ReportOrder = T2.NewOrder \
  320. # from \
  321. # ( \
  322. # select userid, \
  323. # dashboardid, \
  324. # ReportOrder, \
  325. # row_number() over(PARTITION BY userid order by userid, ReportOrder) as NewOrder \
  326. # from [dbo].[UserDashboardMap] \
  327. # ) as T2 \
  328. # inner join [dbo].[UserDashboardMap] as T1 On T1.userid = T2.userid and T1.dashboardid = T2.dashboardid"
  329. # cur.execute(updare_report_order)
  330.  
  331. cur.close()
  332. return True
  333.  
  334. def DeleteReportMapping(self, userid, dashboardId):
  335. # when a dashboard is deleted, update order of all the remaining dashboards order by order = order - 1
  336. # First: Get the "to be deleted" report order
  337. cur = connections['default'].cursor()
  338. # cur.execute("SELECT reportorder FROM [dbo].[UserDashboardMap] where UserId = '" + userid + "' and DashboardId = " + str(dashboardId) )
  339. # reportOrder = int(cur.fetchone()[0])
  340. delete_mapping = "Delete from [dbo].[UserDashboardMap] Where UserId = '" + str(userid) + "' and DashboardId = "+ str(dashboardId)
  341. print(delete_mapping)
  342. cur.execute(delete_mapping)
  343.  
  344. # Now for the rest of the reports, update their order
  345. updare_report_order = "update T1 \
  346. set T1.ReportOrder = T2.NewOrder \
  347. from \
  348. ( \
  349. select userid, \
  350. dashboardid, \
  351. ReportOrder, \
  352. row_number() over(PARTITION BY userid order by userid, ReportOrder) as NewOrder \
  353. from [dbo].[UserDashboardMap] where userid = '" + userid + "' \
  354. ) as T2 \
  355. inner join [dbo].[UserDashboardMap] as T1 On T1.userid = T2.userid and T1.dashboardid = T2.dashboardid"
  356. cur.execute(updare_report_order)
  357. cur.close()
  358.  
  359. def UpdateReportOrder(self, userid, strNewOrder):
  360. cur = connections['default'].cursor()
  361. print(strNewOrder)
  362. cur.callproc('[dbo].[SP_UpdateReportOrder]', [userid, strNewOrder])
  363. cur.close()
  364.  
  365.  
  366. def UpdateUserPassword(self, userid, password):
  367. cur = connections['default'].cursor()
  368. update_user_password = "Update dbo.UserPanel Set Password = '" + password + "' Where UserId = '" + str(userid) + "'"
  369. cur.execute(update_user_password)
  370. cur.close()
  371.  
  372.  
  373. ##All model functions related to manage dashboard page.
  374. class Feedback():
  375. def AddFeedback(self, userid, rating, comment):
  376. cur = connections['default'].cursor()
  377. add_feedback = "INSERT INTO dbo.feedback \
  378. VALUES('" + userid + "', " + rating + ", '" + comment + "', '" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "')"
  379. cur.execute(add_feedback)
  380. cur.close()
  381.  
  382. def GetAllFeedbacks(self, userid):
  383. cur = connections['default'].cursor()
  384. get_feedback = "Select * from [dbo].[feedback] where UserId = '" + userid + "' order by FeedbackDate desc"
  385. cur.execute(get_feedback)
  386. result = dictfetchall(cur)
  387. cur.close()
  388. return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement