@resolveio/server-lib 22.2.34 → 22.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (649) hide show
  1. package/ai/assistant-core-heuristics.d.ts +11 -0
  2. package/ai/assistant-core-heuristics.js +531 -0
  3. package/ai/assistant-core-heuristics.js.map +1 -0
  4. package/client-server-app.d.ts +1 -0
  5. package/client-server-app.js +68 -0
  6. package/client-server-app.js.map +1 -0
  7. package/collections/ai-terminal-conversation.collection.d.ts +2 -0
  8. package/collections/ai-terminal-conversation.collection.js +140 -0
  9. package/collections/ai-terminal-conversation.collection.js.map +1 -0
  10. package/collections/ai-terminal-issue-report.collection.d.ts +2 -0
  11. package/collections/ai-terminal-issue-report.collection.js +148 -0
  12. package/collections/ai-terminal-issue-report.collection.js.map +1 -0
  13. package/collections/ai-terminal-message.collection.d.ts +2 -0
  14. package/collections/ai-terminal-message.collection.js +121 -0
  15. package/collections/ai-terminal-message.collection.js.map +1 -0
  16. package/collections/app-setting.collection.d.ts +3 -0
  17. package/collections/app-setting.collection.js +103 -0
  18. package/collections/app-setting.collection.js.map +1 -0
  19. package/collections/app-status.collection.d.ts +3 -0
  20. package/collections/app-status.collection.js +57 -0
  21. package/collections/app-status.collection.js.map +1 -0
  22. package/collections/communication-metric.collection.d.ts +2 -0
  23. package/collections/communication-metric.collection.js +133 -0
  24. package/collections/communication-metric.collection.js.map +1 -0
  25. package/collections/counter.collection.d.ts +3 -0
  26. package/collections/counter.collection.js +56 -0
  27. package/collections/counter.collection.js.map +1 -0
  28. package/collections/cron-job-history.collection.d.ts +3 -0
  29. package/collections/cron-job-history.collection.js +137 -0
  30. package/collections/cron-job-history.collection.js.map +1 -0
  31. package/collections/cron-job.collection.d.ts +3 -0
  32. package/collections/cron-job.collection.js +92 -0
  33. package/collections/cron-job.collection.js.map +1 -0
  34. package/collections/customer-notification.collection.d.ts +3 -0
  35. package/collections/customer-notification.collection.js +130 -0
  36. package/collections/customer-notification.collection.js.map +1 -0
  37. package/collections/customer-portal-password.collection.d.ts +3 -0
  38. package/collections/customer-portal-password.collection.js +75 -0
  39. package/collections/customer-portal-password.collection.js.map +1 -0
  40. package/collections/email-history.collection.d.ts +3 -0
  41. package/collections/email-history.collection.js +121 -0
  42. package/collections/email-history.collection.js.map +1 -0
  43. package/collections/email-verified.collection.d.ts +3 -0
  44. package/collections/email-verified.collection.js +61 -0
  45. package/collections/email-verified.collection.js.map +1 -0
  46. package/collections/file.collection.d.ts +3 -0
  47. package/collections/file.collection.js +74 -0
  48. package/collections/file.collection.js.map +1 -0
  49. package/collections/flag-update.collection.d.ts +3 -0
  50. package/collections/flag-update.collection.js +57 -0
  51. package/collections/flag-update.collection.js.map +1 -0
  52. package/collections/flag.collection.d.ts +3 -0
  53. package/collections/flag.collection.js +57 -0
  54. package/collections/flag.collection.js.map +1 -0
  55. package/collections/log-method-latency.collection.d.ts +3 -0
  56. package/collections/log-method-latency.collection.js +77 -0
  57. package/collections/log-method-latency.collection.js.map +1 -0
  58. package/collections/log-subscription.collection.d.ts +3 -0
  59. package/collections/log-subscription.collection.js +80 -0
  60. package/collections/log-subscription.collection.js.map +1 -0
  61. package/collections/log.collection.d.ts +3 -0
  62. package/collections/log.collection.js +93 -0
  63. package/collections/log.collection.js.map +1 -0
  64. package/collections/logged-in-users.collection.d.ts +3 -0
  65. package/collections/logged-in-users.collection.js +67 -0
  66. package/collections/logged-in-users.collection.js.map +1 -0
  67. package/collections/monitor-cpu.collection.d.ts +3 -0
  68. package/collections/monitor-cpu.collection.js +65 -0
  69. package/collections/monitor-cpu.collection.js.map +1 -0
  70. package/collections/monitor-function.collection.d.ts +3 -0
  71. package/collections/monitor-function.collection.js +74 -0
  72. package/collections/monitor-function.collection.js.map +1 -0
  73. package/collections/monitor-memory.collection.d.ts +3 -0
  74. package/collections/monitor-memory.collection.js +77 -0
  75. package/collections/monitor-memory.collection.js.map +1 -0
  76. package/collections/monitor-mongo.collection.d.ts +3 -0
  77. package/collections/monitor-mongo.collection.js +71 -0
  78. package/collections/monitor-mongo.collection.js.map +1 -0
  79. package/collections/notification.collection.d.ts +3 -0
  80. package/collections/notification.collection.js +57 -0
  81. package/collections/notification.collection.js.map +1 -0
  82. package/collections/openai-usage-ledger.collection.d.ts +2 -0
  83. package/collections/openai-usage-ledger.collection.js +124 -0
  84. package/collections/openai-usage-ledger.collection.js.map +1 -0
  85. package/collections/report-builder-dashboard-builder.collection.d.ts +3 -0
  86. package/collections/report-builder-dashboard-builder.collection.js +109 -0
  87. package/collections/report-builder-dashboard-builder.collection.js.map +1 -0
  88. package/collections/report-builder-library.collection.d.ts +3 -0
  89. package/collections/report-builder-library.collection.js +87 -0
  90. package/collections/report-builder-library.collection.js.map +1 -0
  91. package/collections/report-builder-report.collection.d.ts +4 -0
  92. package/collections/report-builder-report.collection.js +180 -0
  93. package/collections/report-builder-report.collection.js.map +1 -0
  94. package/collections/user-group.collection.d.ts +4 -0
  95. package/collections/user-group.collection.js +89 -0
  96. package/collections/user-group.collection.js.map +1 -0
  97. package/collections/user-guide.collection.d.ts +3 -0
  98. package/collections/user-guide.collection.js +57 -0
  99. package/collections/user-guide.collection.js.map +1 -0
  100. package/collections/user.collection.d.ts +4 -0
  101. package/collections/user.collection.js +180 -0
  102. package/collections/user.collection.js.map +1 -0
  103. package/cron/cron.d.ts +14 -0
  104. package/cron/cron.js +216 -0
  105. package/cron/cron.js.map +1 -0
  106. package/fixtures/cron-jobs.d.ts +1 -0
  107. package/fixtures/cron-jobs.js +150 -0
  108. package/fixtures/cron-jobs.js.map +1 -0
  109. package/fixtures/init.d.ts +1 -0
  110. package/fixtures/init.js +91 -0
  111. package/fixtures/init.js.map +1 -0
  112. package/http/auth.d.ts +2 -0
  113. package/http/auth.js +903 -0
  114. package/http/auth.js.map +1 -0
  115. package/http/health.d.ts +1 -0
  116. package/http/health.js +11 -0
  117. package/http/health.js.map +1 -0
  118. package/http/home.d.ts +1 -0
  119. package/http/home.js +134 -0
  120. package/http/home.js.map +1 -0
  121. package/http/slow-query-publication.d.ts +2 -0
  122. package/http/slow-query-publication.js +99 -0
  123. package/http/slow-query-publication.js.map +1 -0
  124. package/index.d.ts +1 -0
  125. package/index.js +19 -0
  126. package/index.js.map +1 -0
  127. package/managers/communication-metric.manager.d.ts +16 -0
  128. package/managers/communication-metric.manager.js +134 -0
  129. package/managers/communication-metric.manager.js.map +1 -0
  130. package/managers/cron.manager.d.ts +20 -0
  131. package/managers/cron.manager.js +534 -0
  132. package/managers/cron.manager.js.map +1 -0
  133. package/managers/customer-notification-content.manager.d.ts +55 -0
  134. package/managers/customer-notification-content.manager.js +158 -0
  135. package/managers/customer-notification-content.manager.js.map +1 -0
  136. package/managers/diagnostic-manager-bootstrap.d.ts +9 -0
  137. package/managers/diagnostic-manager-bootstrap.js +260 -0
  138. package/managers/diagnostic-manager-bootstrap.js.map +1 -0
  139. package/managers/error-auto-fix.manager.d.ts +149 -0
  140. package/managers/error-auto-fix.manager.js +3064 -0
  141. package/managers/error-auto-fix.manager.js.map +1 -0
  142. package/managers/local-log.manager.d.ts +18 -0
  143. package/managers/local-log.manager.js +88 -0
  144. package/managers/local-log.manager.js.map +1 -0
  145. package/managers/method.manager.d.ts +77 -0
  146. package/managers/method.manager.js +1701 -0
  147. package/managers/method.manager.js.map +1 -0
  148. package/managers/mongo.manager.d.ts +222 -0
  149. package/managers/mongo.manager.js +4984 -0
  150. package/managers/mongo.manager.js.map +1 -0
  151. package/managers/monitor.manager.d.ts +69 -0
  152. package/managers/monitor.manager.js +534 -0
  153. package/managers/monitor.manager.js.map +1 -0
  154. package/managers/openai-usage-ledger.manager.d.ts +15 -0
  155. package/managers/openai-usage-ledger.manager.js +144 -0
  156. package/managers/openai-usage-ledger.manager.js.map +1 -0
  157. package/managers/slow-query-verifier.manager.d.ts +144 -0
  158. package/managers/slow-query-verifier.manager.js +3857 -0
  159. package/managers/slow-query-verifier.manager.js.map +1 -0
  160. package/managers/slow-query.manager.d.ts +28 -0
  161. package/managers/slow-query.manager.js +468 -0
  162. package/managers/slow-query.manager.js.map +1 -0
  163. package/managers/subscription.manager.d.ts +169 -0
  164. package/managers/subscription.manager.js +3422 -0
  165. package/managers/subscription.manager.js.map +1 -0
  166. package/managers/websocket.manager.d.ts +73 -0
  167. package/managers/websocket.manager.js +673 -0
  168. package/managers/websocket.manager.js.map +1 -0
  169. package/managers/worker-dispatcher.manager.d.ts +117 -0
  170. package/managers/worker-dispatcher.manager.js +1210 -0
  171. package/managers/worker-dispatcher.manager.js.map +1 -0
  172. package/managers/worker-server.manager.d.ts +16 -0
  173. package/managers/worker-server.manager.js +530 -0
  174. package/managers/worker-server.manager.js.map +1 -0
  175. package/methods/accounts.d.ts +2 -0
  176. package/methods/accounts.js +624 -0
  177. package/methods/accounts.js.map +1 -0
  178. package/methods/ai-terminal.d.ts +304 -0
  179. package/methods/ai-terminal.js +25096 -0
  180. package/methods/ai-terminal.js.map +1 -0
  181. package/methods/app-settings.d.ts +2 -0
  182. package/methods/app-settings.js +169 -0
  183. package/methods/app-settings.js.map +1 -0
  184. package/methods/aws.d.ts +2 -0
  185. package/methods/aws.js +874 -0
  186. package/methods/aws.js.map +1 -0
  187. package/methods/collections.d.ts +2 -0
  188. package/methods/collections.js +626 -0
  189. package/methods/collections.js.map +1 -0
  190. package/methods/counters.d.ts +2 -0
  191. package/methods/counters.js +111 -0
  192. package/methods/counters.js.map +1 -0
  193. package/methods/cron-jobs.d.ts +2 -0
  194. package/methods/cron-jobs.js +2471 -0
  195. package/methods/cron-jobs.js.map +1 -0
  196. package/methods/customer-notifications.d.ts +2 -0
  197. package/methods/customer-notifications.js +528 -0
  198. package/methods/customer-notifications.js.map +1 -0
  199. package/methods/diagnostics.d.ts +2 -0
  200. package/methods/diagnostics.js +514 -0
  201. package/methods/diagnostics.js.map +1 -0
  202. package/methods/flag-updates.d.ts +2 -0
  203. package/methods/flag-updates.js +8 -0
  204. package/methods/flag-updates.js.map +1 -0
  205. package/methods/flags.d.ts +2 -0
  206. package/methods/flags.js +8 -0
  207. package/methods/flags.js.map +1 -0
  208. package/methods/logs.d.ts +2 -0
  209. package/methods/logs.js +750 -0
  210. package/methods/logs.js.map +1 -0
  211. package/methods/mongo-explorer.d.ts +2 -0
  212. package/methods/mongo-explorer.js +1811 -0
  213. package/methods/mongo-explorer.js.map +1 -0
  214. package/methods/monitor.d.ts +2 -0
  215. package/methods/monitor.js +543 -0
  216. package/methods/monitor.js.map +1 -0
  217. package/methods/pdf.d.ts +2 -0
  218. package/methods/pdf.js +1195 -0
  219. package/methods/pdf.js.map +1 -0
  220. package/methods/publications.d.ts +1 -0
  221. package/methods/publications.js +183 -0
  222. package/methods/publications.js.map +1 -0
  223. package/methods/report-builder.d.ts +2 -0
  224. package/methods/report-builder.js +3099 -0
  225. package/methods/report-builder.js.map +1 -0
  226. package/methods/support.d.ts +2 -0
  227. package/methods/support.js +322 -0
  228. package/methods/support.js.map +1 -0
  229. package/models/ai-terminal-conversation.model.d.ts +17 -0
  230. package/models/ai-terminal-conversation.model.js +4 -0
  231. package/models/ai-terminal-conversation.model.js.map +1 -0
  232. package/models/ai-terminal-issue-report.model.d.ts +19 -0
  233. package/models/ai-terminal-issue-report.model.js +4 -0
  234. package/models/ai-terminal-issue-report.model.js.map +1 -0
  235. package/models/ai-terminal-message.model.d.ts +22 -0
  236. package/models/ai-terminal-message.model.js +4 -0
  237. package/models/ai-terminal-message.model.js.map +1 -0
  238. package/models/app-setting.model.d.ts +16 -0
  239. package/models/app-setting.model.js +4 -0
  240. package/models/app-setting.model.js.map +1 -0
  241. package/{src/models/app-status.model.ts → models/app-status.model.d.ts} +2 -3
  242. package/models/app-status.model.js +4 -0
  243. package/models/app-status.model.js.map +1 -0
  244. package/{src/models/billing-logged-in-users.model.ts → models/billing-logged-in-users.model.d.ts} +4 -5
  245. package/models/billing-logged-in-users.model.js +4 -0
  246. package/models/billing-logged-in-users.model.js.map +1 -0
  247. package/models/collection-document.model.d.ts +21 -0
  248. package/models/collection-document.model.js +4 -0
  249. package/models/collection-document.model.js.map +1 -0
  250. package/models/communication-metric.model.d.ts +20 -0
  251. package/models/communication-metric.model.js +4 -0
  252. package/models/communication-metric.model.js.map +1 -0
  253. package/{src/models/counter.model.ts → models/counter.model.d.ts} +3 -4
  254. package/models/counter.model.js +4 -0
  255. package/models/counter.model.js.map +1 -0
  256. package/models/cron-job-history.model.d.ts +15 -0
  257. package/models/cron-job-history.model.js +4 -0
  258. package/models/cron-job-history.model.js.map +1 -0
  259. package/models/cron-job.model.d.ts +14 -0
  260. package/models/cron-job.model.js +4 -0
  261. package/models/cron-job.model.js.map +1 -0
  262. package/models/customer-notification.model.d.ts +26 -0
  263. package/models/customer-notification.model.js +4 -0
  264. package/models/customer-notification.model.js.map +1 -0
  265. package/models/customer-portal-password.model.d.ts +11 -0
  266. package/models/customer-portal-password.model.js +4 -0
  267. package/models/customer-portal-password.model.js.map +1 -0
  268. package/models/dialog.model.d.ts +23 -0
  269. package/models/dialog.model.js +4 -0
  270. package/models/dialog.model.js.map +1 -0
  271. package/models/email-history.model.d.ts +30 -0
  272. package/{src/models/email-history.model.ts → models/email-history.model.js} +4 -34
  273. package/models/email-history.model.js.map +1 -0
  274. package/{src/models/email-verified.model.ts → models/email-verified.model.d.ts} +5 -6
  275. package/models/email-verified.model.js +4 -0
  276. package/models/email-verified.model.js.map +1 -0
  277. package/{src/models/file.model.ts → models/file.model.d.ts} +7 -8
  278. package/models/file.model.js +4 -0
  279. package/models/file.model.js.map +1 -0
  280. package/{src/models/flag-update.model.ts → models/flag-update.model.d.ts} +3 -4
  281. package/models/flag-update.model.js +4 -0
  282. package/models/flag-update.model.js.map +1 -0
  283. package/{src/models/flag.model.ts → models/flag.model.d.ts} +3 -4
  284. package/models/flag.model.js +4 -0
  285. package/models/flag.model.js.map +1 -0
  286. package/models/log-method-latency.model.d.ts +10 -0
  287. package/models/log-method-latency.model.js +4 -0
  288. package/models/log-method-latency.model.js.map +1 -0
  289. package/{src/models/log-subscription.model.ts → models/log-subscription.model.d.ts} +9 -11
  290. package/models/log-subscription.model.js +4 -0
  291. package/models/log-subscription.model.js.map +1 -0
  292. package/models/log.model.d.ts +17 -0
  293. package/models/log.model.js +4 -0
  294. package/models/log.model.js.map +1 -0
  295. package/{src/models/logged-in-users.model.ts → models/logged-in-users.model.d.ts} +5 -6
  296. package/models/logged-in-users.model.js +4 -0
  297. package/models/logged-in-users.model.js.map +1 -0
  298. package/{src/models/method-response.model.ts → models/method-response.model.d.ts} +6 -7
  299. package/models/method-response.model.js +4 -0
  300. package/models/method-response.model.js.map +1 -0
  301. package/models/method.model.d.ts +24 -0
  302. package/models/method.model.js +4 -0
  303. package/models/method.model.js.map +1 -0
  304. package/{src/models/monitor-cpu.model.ts → models/monitor-cpu.model.d.ts} +7 -9
  305. package/models/monitor-cpu.model.js +4 -0
  306. package/models/monitor-cpu.model.js.map +1 -0
  307. package/models/monitor-function.model.d.ts +14 -0
  308. package/models/monitor-function.model.js +4 -0
  309. package/models/monitor-function.model.js.map +1 -0
  310. package/models/monitor-memory.model.d.ts +15 -0
  311. package/models/monitor-memory.model.js +4 -0
  312. package/models/monitor-memory.model.js.map +1 -0
  313. package/models/monitor-mongo.model.d.ts +13 -0
  314. package/models/monitor-mongo.model.js +4 -0
  315. package/models/monitor-mongo.model.js.map +1 -0
  316. package/{src/models/notification.model.ts → models/notification.model.d.ts} +4 -6
  317. package/models/notification.model.js +4 -0
  318. package/models/notification.model.js.map +1 -0
  319. package/models/openai-usage-ledger.model.d.ts +15 -0
  320. package/models/openai-usage-ledger.model.js +4 -0
  321. package/models/openai-usage-ledger.model.js.map +1 -0
  322. package/models/pagination.model.d.ts +11 -0
  323. package/models/pagination.model.js +28 -0
  324. package/models/pagination.model.js.map +1 -0
  325. package/models/permission.model.d.ts +12 -0
  326. package/models/permission.model.js +4 -0
  327. package/models/permission.model.js.map +1 -0
  328. package/models/report-builder-dashboard-builder.model.d.ts +25 -0
  329. package/models/report-builder-dashboard-builder.model.js +4 -0
  330. package/models/report-builder-dashboard-builder.model.js.map +1 -0
  331. package/models/report-builder-library.model.d.ts +17 -0
  332. package/models/report-builder-library.model.js +4 -0
  333. package/models/report-builder-library.model.js.map +1 -0
  334. package/models/report-builder-report.model.d.ts +120 -0
  335. package/models/report-builder-report.model.js +4 -0
  336. package/models/report-builder-report.model.js.map +1 -0
  337. package/models/report-builder.model.d.ts +61 -0
  338. package/models/report-builder.model.js +4 -0
  339. package/models/report-builder.model.js.map +1 -0
  340. package/models/select-data-label.model.d.ts +9 -0
  341. package/models/select-data-label.model.js +4 -0
  342. package/models/select-data-label.model.js.map +1 -0
  343. package/models/server-message.model.d.ts +32 -0
  344. package/models/server-message.model.js +4 -0
  345. package/models/server-message.model.js.map +1 -0
  346. package/models/slow-query-report.model.d.ts +23 -0
  347. package/models/slow-query-report.model.js +4 -0
  348. package/models/slow-query-report.model.js.map +1 -0
  349. package/models/subscription.model.d.ts +31 -0
  350. package/models/subscription.model.js +4 -0
  351. package/models/subscription.model.js.map +1 -0
  352. package/models/support-ticket.model.d.ts +87 -0
  353. package/models/support-ticket.model.js +4 -0
  354. package/models/support-ticket.model.js.map +1 -0
  355. package/models/user-group.model.d.ts +20 -0
  356. package/models/user-group.model.js +4 -0
  357. package/models/user-group.model.js.map +1 -0
  358. package/{src/models/user-guide.model.ts → models/user-guide.model.d.ts} +4 -5
  359. package/models/user-guide.model.js +4 -0
  360. package/models/user-guide.model.js.map +1 -0
  361. package/models/user.model.d.ts +84 -0
  362. package/models/user.model.js +4 -0
  363. package/models/user.model.js.map +1 -0
  364. package/package.json +1 -1
  365. package/private/images/ResolveIO.png +0 -0
  366. package/public_api.js +107 -0
  367. package/public_api.js.map +1 -0
  368. package/publications/ai-terminal.d.ts +1 -0
  369. package/publications/ai-terminal.js +122 -0
  370. package/publications/ai-terminal.js.map +1 -0
  371. package/publications/app-settings.d.ts +2 -0
  372. package/publications/app-settings.js +28 -0
  373. package/publications/app-settings.js.map +1 -0
  374. package/publications/app-status.d.ts +2 -0
  375. package/publications/app-status.js +16 -0
  376. package/publications/app-status.js.map +1 -0
  377. package/publications/cron-jobs.d.ts +2 -0
  378. package/publications/cron-jobs.js +32 -0
  379. package/publications/cron-jobs.js.map +1 -0
  380. package/publications/customer-notifications.d.ts +2 -0
  381. package/publications/customer-notifications.js +161 -0
  382. package/publications/customer-notifications.js.map +1 -0
  383. package/publications/files.d.ts +2 -0
  384. package/publications/files.js +36 -0
  385. package/publications/files.js.map +1 -0
  386. package/publications/flags-update.d.ts +2 -0
  387. package/publications/flags-update.js +22 -0
  388. package/publications/flags-update.js.map +1 -0
  389. package/publications/flags.d.ts +2 -0
  390. package/publications/flags.js +22 -0
  391. package/publications/flags.js.map +1 -0
  392. package/publications/logs.d.ts +2 -0
  393. package/publications/logs.js +164 -0
  394. package/publications/logs.js.map +1 -0
  395. package/publications/notifications.d.ts +2 -0
  396. package/publications/notifications.js +16 -0
  397. package/publications/notifications.js.map +1 -0
  398. package/publications/report-builder-dashboard-builders.d.ts +2 -0
  399. package/publications/report-builder-dashboard-builders.js +42 -0
  400. package/publications/report-builder-dashboard-builders.js.map +1 -0
  401. package/publications/report-builder-libraries.d.ts +2 -0
  402. package/publications/report-builder-libraries.js +90 -0
  403. package/publications/report-builder-libraries.js.map +1 -0
  404. package/publications/report-builder-reports.d.ts +2 -0
  405. package/publications/report-builder-reports.js +50 -0
  406. package/publications/report-builder-reports.js.map +1 -0
  407. package/publications/super-admin.d.ts +2 -0
  408. package/publications/super-admin.js +16 -0
  409. package/publications/super-admin.js.map +1 -0
  410. package/publications/user-groups.d.ts +1 -0
  411. package/publications/user-groups.js +16 -0
  412. package/publications/user-groups.js.map +1 -0
  413. package/publications/user-guides.d.ts +1 -0
  414. package/publications/user-guides.js +16 -0
  415. package/publications/user-guides.js.map +1 -0
  416. package/resolveio-server-app.d.ts +70 -0
  417. package/resolveio-server-app.js +801 -0
  418. package/resolveio-server-app.js.map +1 -0
  419. package/server-app.d.ts +167 -0
  420. package/server-app.js +2784 -0
  421. package/server-app.js.map +1 -0
  422. package/services/codex-client.d.ts +119 -0
  423. package/services/codex-client.js +1470 -0
  424. package/services/codex-client.js.map +1 -0
  425. package/services/openai-client.d.ts +46 -0
  426. package/services/openai-client.js +318 -0
  427. package/services/openai-client.js.map +1 -0
  428. package/types/error-report.d.ts +25 -0
  429. package/types/error-report.js +4 -0
  430. package/types/error-report.js.map +1 -0
  431. package/types/slow-query-report.d.ts +27 -0
  432. package/types/slow-query-report.js +6 -0
  433. package/types/slow-query-report.js.map +1 -0
  434. package/util/common.d.ts +31 -0
  435. package/util/common.js +683 -0
  436. package/util/common.js.map +1 -0
  437. package/util/customer-portal-password.d.ts +13 -0
  438. package/util/customer-portal-password.js +209 -0
  439. package/util/customer-portal-password.js.map +1 -0
  440. package/util/error-reporter.d.ts +52 -0
  441. package/util/error-reporter.js +326 -0
  442. package/util/error-reporter.js.map +1 -0
  443. package/util/error-tracking.d.ts +13 -0
  444. package/util/error-tracking.js +120 -0
  445. package/util/error-tracking.js.map +1 -0
  446. package/util/report-builder-unwinds.d.ts +15 -0
  447. package/util/report-builder-unwinds.js +156 -0
  448. package/util/report-builder-unwinds.js.map +1 -0
  449. package/util/schema-report-builder.d.ts +6 -0
  450. package/util/schema-report-builder.js +481 -0
  451. package/util/schema-report-builder.js.map +1 -0
  452. package/util/slow-query-reporter.d.ts +28 -0
  453. package/util/slow-query-reporter.js +226 -0
  454. package/util/slow-query-reporter.js.map +1 -0
  455. package/util/subscription-dependency-context.d.ts +34 -0
  456. package/util/subscription-dependency-context.js +1283 -0
  457. package/util/subscription-dependency-context.js.map +1 -0
  458. package/util/tokenizer.d.ts +5 -0
  459. package/util/tokenizer.js +41 -0
  460. package/util/tokenizer.js.map +1 -0
  461. package/workers/codex-runner.worker.d.ts +1 -0
  462. package/workers/codex-runner.worker.js +192 -0
  463. package/workers/codex-runner.worker.js.map +1 -0
  464. package/.github/workflows/ai-assistant-nightly-eval.yml +0 -224
  465. package/.github/workflows/ai-assistant-pr-guardrails.yml +0 -60
  466. package/.nodemon.json +0 -5
  467. package/.vscode/settings.json +0 -21
  468. package/AGENTS.md +0 -179
  469. package/README.md +0 -22
  470. package/build_package.sh +0 -5
  471. package/compileDTS.pl +0 -64
  472. package/docs/ai-assistant-nightly-eval.md +0 -65
  473. package/docs/ai-assistant-preflight-checklist.md +0 -23
  474. package/docs/ai-assistant-report-builder-bridge-playbook.md +0 -115
  475. package/eslint-plugin-custom/index.js +0 -7
  476. package/eslint-plugin-custom/rules/no-filter-zero-index.js +0 -44
  477. package/eslint.config.js +0 -103
  478. package/gulpfile.js +0 -216
  479. package/methodAndPublicationListGenerator.py +0 -319
  480. package/mongodbensurers.js +0 -2
  481. package/mongostop.js +0 -3
  482. package/settings.development.json +0 -25
  483. package/settings.development.redacted.json +0 -25
  484. package/src/.env +0 -12
  485. package/src/ai/assistant-core-heuristics.ts +0 -577
  486. package/src/client-server-app.ts +0 -12
  487. package/src/collections/ai-terminal-conversation.collection.ts +0 -91
  488. package/src/collections/ai-terminal-issue-report.collection.ts +0 -99
  489. package/src/collections/ai-terminal-message.collection.ts +0 -77
  490. package/src/collections/app-setting.collection.ts +0 -104
  491. package/src/collections/app-status.collection.ts +0 -58
  492. package/src/collections/communication-metric.collection.ts +0 -84
  493. package/src/collections/counter.collection.ts +0 -56
  494. package/src/collections/cron-job-history.collection.ts +0 -94
  495. package/src/collections/cron-job.collection.ts +0 -92
  496. package/src/collections/customer-notification.collection.ts +0 -131
  497. package/src/collections/customer-portal-password.collection.ts +0 -76
  498. package/src/collections/email-history.collection.ts +0 -121
  499. package/src/collections/email-verified.collection.ts +0 -61
  500. package/src/collections/file.collection.ts +0 -74
  501. package/src/collections/flag-update.collection.ts +0 -57
  502. package/src/collections/flag.collection.ts +0 -57
  503. package/src/collections/log-method-latency.collection.ts +0 -77
  504. package/src/collections/log-subscription.collection.ts +0 -80
  505. package/src/collections/log.collection.ts +0 -93
  506. package/src/collections/logged-in-users.collection.ts +0 -67
  507. package/src/collections/monitor-cpu.collection.ts +0 -65
  508. package/src/collections/monitor-function.collection.ts +0 -74
  509. package/src/collections/monitor-memory.collection.ts +0 -77
  510. package/src/collections/monitor-mongo.collection.ts +0 -71
  511. package/src/collections/notification.collection.ts +0 -57
  512. package/src/collections/openai-usage-ledger.collection.ts +0 -77
  513. package/src/collections/report-builder-dashboard-builder.collection.ts +0 -109
  514. package/src/collections/report-builder-library.collection.ts +0 -89
  515. package/src/collections/report-builder-report.collection.ts +0 -180
  516. package/src/collections/user-group.collection.ts +0 -89
  517. package/src/collections/user-guide.collection.ts +0 -57
  518. package/src/collections/user.collection.ts +0 -181
  519. package/src/cron/cron.ts +0 -117
  520. package/src/fixtures/cron-jobs.ts +0 -95
  521. package/src/fixtures/init.ts +0 -35
  522. package/src/http/auth.ts +0 -764
  523. package/src/http/health.ts +0 -7
  524. package/src/http/home.ts +0 -90
  525. package/src/http/slow-query-publication.ts +0 -49
  526. package/src/index.ts +0 -1
  527. package/src/managers/communication-metric.manager.ts +0 -82
  528. package/src/managers/cron.manager.ts +0 -333
  529. package/src/managers/customer-notification-content.manager.ts +0 -236
  530. package/src/managers/diagnostic-manager-bootstrap.ts +0 -165
  531. package/src/managers/error-auto-fix.manager.ts +0 -2767
  532. package/src/managers/local-log.manager.ts +0 -113
  533. package/src/managers/method.manager.ts +0 -1557
  534. package/src/managers/mongo.manager.ts +0 -4566
  535. package/src/managers/monitor.manager.ts +0 -489
  536. package/src/managers/openai-usage-ledger.manager.ts +0 -116
  537. package/src/managers/slow-query-verifier.manager.ts +0 -3590
  538. package/src/managers/slow-query.manager.ts +0 -519
  539. package/src/managers/subscription.manager.ts +0 -3120
  540. package/src/managers/websocket.manager.ts +0 -746
  541. package/src/managers/worker-dispatcher.manager.ts +0 -1318
  542. package/src/managers/worker-server.manager.ts +0 -468
  543. package/src/methods/accounts.ts +0 -532
  544. package/src/methods/ai-terminal.ts +0 -25505
  545. package/src/methods/app-settings.ts +0 -114
  546. package/src/methods/aws.ts +0 -646
  547. package/src/methods/collections.ts +0 -544
  548. package/src/methods/counters.ts +0 -67
  549. package/src/methods/cron-jobs.ts +0 -2610
  550. package/src/methods/customer-notifications.ts +0 -458
  551. package/src/methods/diagnostics.ts +0 -447
  552. package/src/methods/flag-updates.ts +0 -7
  553. package/src/methods/flags.ts +0 -7
  554. package/src/methods/logs.ts +0 -656
  555. package/src/methods/mongo-explorer.ts +0 -1883
  556. package/src/methods/monitor.ts +0 -540
  557. package/src/methods/pdf.ts +0 -1210
  558. package/src/methods/publications.ts +0 -128
  559. package/src/methods/report-builder.ts +0 -3305
  560. package/src/methods/support.ts +0 -210
  561. package/src/models/ai-terminal-conversation.model.ts +0 -19
  562. package/src/models/ai-terminal-issue-report.model.ts +0 -21
  563. package/src/models/ai-terminal-message.model.ts +0 -24
  564. package/src/models/app-setting.model.ts +0 -17
  565. package/src/models/collection-document.model.ts +0 -24
  566. package/src/models/communication-metric.model.ts +0 -23
  567. package/src/models/cron-job-history.model.ts +0 -16
  568. package/src/models/cron-job.model.ts +0 -15
  569. package/src/models/customer-notification.model.ts +0 -28
  570. package/src/models/customer-portal-password.model.ts +0 -12
  571. package/src/models/dialog.model.ts +0 -25
  572. package/src/models/log-method-latency.model.ts +0 -11
  573. package/src/models/log.model.ts +0 -19
  574. package/src/models/method.model.ts +0 -23
  575. package/src/models/monitor-function.model.ts +0 -16
  576. package/src/models/monitor-memory.model.ts +0 -17
  577. package/src/models/monitor-mongo.model.ts +0 -15
  578. package/src/models/openai-usage-ledger.model.ts +0 -16
  579. package/src/models/pagination.model.ts +0 -35
  580. package/src/models/permission.model.ts +0 -14
  581. package/src/models/report-builder-dashboard-builder.model.ts +0 -29
  582. package/src/models/report-builder-library.model.ts +0 -20
  583. package/src/models/report-builder-report.model.ts +0 -135
  584. package/src/models/report-builder.model.ts +0 -68
  585. package/src/models/select-data-label.model.ts +0 -9
  586. package/src/models/server-message.model.ts +0 -31
  587. package/src/models/slow-query-report.model.ts +0 -23
  588. package/src/models/subscription.model.ts +0 -73
  589. package/src/models/support-ticket.model.ts +0 -96
  590. package/src/models/user-group.model.ts +0 -24
  591. package/src/models/user.model.ts +0 -96
  592. package/src/private/images/ResolveIO.png +0 -0
  593. package/src/publications/ai-terminal.ts +0 -73
  594. package/src/publications/app-settings.ts +0 -25
  595. package/src/publications/app-status.ts +0 -13
  596. package/src/publications/cron-jobs.ts +0 -29
  597. package/src/publications/customer-notifications.ts +0 -101
  598. package/src/publications/files.ts +0 -33
  599. package/src/publications/flags-update.ts +0 -19
  600. package/src/publications/flags.ts +0 -19
  601. package/src/publications/logs.ts +0 -163
  602. package/src/publications/notifications.ts +0 -13
  603. package/src/publications/report-builder-dashboard-builders.ts +0 -39
  604. package/src/publications/report-builder-libraries.ts +0 -41
  605. package/src/publications/report-builder-reports.ts +0 -47
  606. package/src/publications/super-admin.ts +0 -13
  607. package/src/publications/user-groups.ts +0 -12
  608. package/src/publications/user-guides.ts +0 -12
  609. package/src/resolveio-server-app.ts +0 -617
  610. package/src/server-app.ts +0 -2616
  611. package/src/services/codex-client.ts +0 -1117
  612. package/src/services/openai-client.ts +0 -265
  613. package/src/types/error-report.ts +0 -26
  614. package/src/types/js-tiktoken.d.ts +0 -11
  615. package/src/types/slow-query-report.ts +0 -28
  616. package/src/util/common.ts +0 -649
  617. package/src/util/customer-portal-password.ts +0 -183
  618. package/src/util/error-reporter.ts +0 -332
  619. package/src/util/error-tracking.ts +0 -79
  620. package/src/util/report-builder-unwinds.ts +0 -180
  621. package/src/util/schema-report-builder.ts +0 -448
  622. package/src/util/slow-query-reporter.ts +0 -216
  623. package/src/util/subscription-dependency-context.ts +0 -1096
  624. package/src/util/tokenizer.ts +0 -38
  625. package/src/workers/codex-runner.worker.ts +0 -142
  626. package/start_server.sh +0 -5
  627. package/tests/ai-assistant-corpus-build.ts +0 -484
  628. package/tests/ai-assistant-corpus-replay-e2e.ts +0 -773
  629. package/tests/ai-assistant-data-parity-e2e.ts +0 -2018
  630. package/tests/ai-assistant-eval-triage.ts +0 -831
  631. package/tests/ai-assistant-openai-e2e.ts +0 -1061
  632. package/tests/ai-assistant-openai-git-e2e.ts +0 -155
  633. package/tests/ai-assistant-preflight-matrix.ts +0 -215
  634. package/tests/ai-assistant-routing-eval.test.ts +0 -560
  635. package/tests/ai-assistant-snf-live-eval.ts +0 -921
  636. package/tests/ai-assistant-utils.test.ts +0 -2165
  637. package/tests/error-reporter.test.ts +0 -145
  638. package/tests/report-builder-linking.test.ts +0 -79
  639. package/tests/subscription-connect-race.test.ts +0 -157
  640. package/tests/subscription-dependency-context.test.ts +0 -324
  641. package/tests/subscription-manager-collection-tracking.test.ts +0 -86
  642. package/tests/subscription-manager-invalidation.test.ts +0 -85
  643. package/tsconfig.json +0 -34
  644. /package/{src/private → private}/email-templates/enrollment.html +0 -0
  645. /package/{src/private → private}/email-templates/forgot-password.html +0 -0
  646. /package/{src/private → private}/email-templates/support-ticket-deleted.html +0 -0
  647. /package/{src/private → private}/email-templates/support-ticket-modified.html +0 -0
  648. /package/{src/private → private}/email-templates/support-ticket.html +0 -0
  649. /package/{src/public_api.ts → public_api.d.ts} +0 -0
@@ -1,2610 +0,0 @@
1
- import axios from 'axios';
2
- import * as Excel from 'exceljs';
3
- import * as moment from 'moment-timezone';
4
- import SimpleSchema from 'simpl-schema';
5
- import { CronJobs } from '../collections/cron-job.collection';
6
- import { CommunicationMetrics } from '../collections/communication-metric.collection';
7
- import { Files } from '../collections/file.collection';
8
- import { OpenAIUsageLedger } from '../collections/openai-usage-ledger.collection';
9
- import { ReportBuilderReports } from '../collections/report-builder-report.collection';
10
- import { MethodManager } from '../managers/method.manager';
11
- import { PaginationOptions } from '../models/pagination.model';
12
- import { ResolveIOServer } from '../resolveio-server-app';
13
- import { deepCopy, mergeDeep, round, toTitleCase } from '../util/common';
14
-
15
- function getFilterTargets(fieldPath: string, report: any): string[] {
16
- if (!fieldPath) {
17
- return [];
18
- }
19
-
20
- if (fieldPath.startsWith('layout_col_')) {
21
- const normalized = fieldPath.replace(/^layout_col_/, '');
22
- const parts = normalized.split('_');
23
- const idx = parseInt(parts[parts.length - 1], 10);
24
-
25
- if (!isNaN(idx)) {
26
- const layoutTargets = (report?.fields_selected || [])
27
- .filter(f => f && (f.layoutColumnIndex === idx || (f.id || '').includes(`f_layout_${idx}_`)))
28
- .map(f => f.fieldPath);
29
-
30
- if (layoutTargets.length) {
31
- return layoutTargets;
32
- }
33
- }
34
- }
35
-
36
- return [fieldPath];
37
- }
38
-
39
- function buildFilterExpression(filter: any, path: string) {
40
- if (!filter || !filter.condition || (!filter.field && !path)) {
41
- return null;
42
- }
43
-
44
- const hasValue = filter.value !== null && (Array.isArray(filter.value) ? filter.value.length > 0 : true);
45
-
46
- if (!hasValue && filter.condition !== 'null' && filter.condition !== 'nnull') {
47
- return null;
48
- }
49
-
50
- if (filter.condition === 'bw') {
51
- if (filter.fieldType === 'Date' && filter.is_rolling) {
52
- let startDate = null;
53
- let endDate = null;
54
-
55
- if (filter.rolling_interval === 'Q1') {
56
- startDate = moment().startOf('year').toDate();
57
- endDate = moment().startOf('year').quarter(2).subtract(1, 'days').toDate();
58
- }
59
- else if (filter.rolling_interval === 'Q2') {
60
- startDate = moment().startOf('year').quarter(2).toDate();
61
- endDate = moment().startOf('year').quarter(3).subtract(1, 'days').toDate();
62
- }
63
- else if (filter.rolling_interval === 'Q3') {
64
- startDate = moment().startOf('year').quarter(3).toDate();
65
- endDate = moment().startOf('year').quarter(4).subtract(1, 'days').toDate();
66
- }
67
- else if (filter.rolling_interval === 'Q4') {
68
- startDate = moment().startOf('year').quarter(4).toDate();
69
- endDate = moment().endOf('year').toDate();
70
- }
71
- else if (filter.rolling_interval === 'Today') {
72
- startDate = moment().startOf('day').toDate();
73
- endDate = moment().endOf('day').toDate();
74
- }
75
- else if (filter.rolling_interval === 'Yesterday') {
76
- startDate = moment().subtract(1, 'days').startOf('day').toDate();
77
- endDate = moment().subtract(1, 'days').endOf('day').toDate();
78
- }
79
- else if (filter.rolling_interval === 'Week') {
80
- startDate = moment().startOf('isoWeek').toDate();
81
- endDate = moment().endOf('day').toDate();
82
- }
83
- else if (filter.rolling_interval === 'Last Week') {
84
- endDate = moment().startOf('isoWeek').subtract(1, 'days').toDate();
85
- startDate = moment(endDate).startOf('isoWeek').toDate();
86
- }
87
- else if (filter.rolling_interval === 'Month') {
88
- startDate = moment().startOf('month').toDate();
89
- endDate = moment().endOf('day').toDate();
90
- }
91
- else if (filter.rolling_interval === 'Last Month') {
92
- endDate = moment().startOf('month').subtract(1, 'days').endOf('day').toDate();
93
- startDate = moment(endDate).startOf('month').toDate();
94
- }
95
- else if (filter.rolling_interval === 'Last 30 Days') {
96
- endDate = moment().endOf('day').toDate();
97
- startDate = moment().subtract(30, 'days').startOf('day').toDate();
98
- }
99
- else if (filter.rolling_interval === 'Quarter') {
100
- startDate = moment().startOf('year').quarter(moment().quarter()).toDate();
101
- endDate = moment().endOf('day').toDate();
102
- }
103
- else if (filter.rolling_interval === 'Last Quarter') {
104
- endDate = moment().startOf('year').quarter(moment().quarter()).subtract(1, 'days').endOf('day').toDate();
105
- startDate = moment(endDate).startOf('quarter').toDate();
106
- }
107
- else if (filter.rolling_interval === 'Year') {
108
- startDate = moment().startOf('year').toDate();
109
- endDate = moment().endOf('day').toDate();
110
- }
111
- else if (filter.rolling_interval === 'Last Year') {
112
- endDate = moment().startOf('year').subtract(1, 'days').endOf('day').toDate();
113
- startDate = moment(endDate).startOf('year').toDate();
114
- }
115
- else if (filter.rolling_interval === 'All') {
116
- startDate = new Date(2017, 0, 1, 0, 0, 0, 0);
117
- endDate = moment().endOf('day').toDate();
118
- }
119
-
120
- return {$and: [{[path]: {'$gte': startDate}}, {[path]: {'$lte': endDate}}]};
121
- }
122
-
123
- return {$and: [{[path]: {'$gte': filter.value}}, {[path]: {'$lte': filter.highValue}}]};
124
- }
125
- else if (filter.condition === 'nnull') {
126
- let and = [];
127
- and.push({[path]: {'$exists': true}});
128
- and.push({[path]: {'$ne': null}});
129
-
130
- if (filter.fieldType === 'String') {
131
- and.push({[path]: {'$ne': ''}});
132
- }
133
-
134
- return {$and: and};
135
- }
136
- else if (filter.condition === 'null') {
137
- return {[path]: {'$eq': null}};
138
- }
139
- else {
140
- if (Array.isArray(filter.value)) {
141
- if (filter.condition === 'ne') {
142
- let and = [];
143
- filter.value.forEach(filt => {
144
- and.push({[path]: {['$' + filter.condition]: (Array.isArray(filt) ? filt[0] : filt)}});
145
- });
146
-
147
- if (and.length > 1) {
148
- return {$and: and};
149
- }
150
- else {
151
- return and[0];
152
- }
153
- }
154
- else {
155
- let or = [];
156
-
157
- filter.value.forEach(filt => {
158
- or.push({[path]: {['$' + filter.condition]: (Array.isArray(filt) ? filt[0] : filt)}});
159
- });
160
-
161
- if (or.length > 1) {
162
- return {$or: or};
163
- }
164
- else {
165
- return or[0];
166
- }
167
- }
168
- }
169
- else {
170
- return {[path]: {['$' + filter.condition]: filter.value}};
171
- }
172
- }
173
-
174
- return null;
175
- }
176
-
177
- function parseLayoutColIndex(fieldRef: string): number | null {
178
- if (!fieldRef || !fieldRef.startsWith('layout_col_')) {
179
- return null;
180
- }
181
-
182
- const normalized = fieldRef.replace(/^layout_col_/, '');
183
- const parts = normalized.split('_');
184
- const idx = parseInt(parts[parts.length - 1], 10);
185
-
186
- return isNaN(idx) ? null : idx;
187
- }
188
-
189
- function resolveLayoutColumnPrimaryLeafId(fieldRef: string, report: any) {
190
- const idx = parseLayoutColIndex(fieldRef);
191
-
192
- if (idx === null) {
193
- return null;
194
- }
195
-
196
- const candidates = (report?.fields_selected || []).filter(f => f && typeof f.layoutColumnIndex !== 'undefined' && f.layoutColumnIndex === idx);
197
-
198
- if (!candidates.length) {
199
- return null;
200
- }
201
-
202
- const root = report?.collection_root;
203
- const preferred = candidates.find(c => c.collection_name === root || c.layoutCollection === root) || candidates[0];
204
-
205
- return preferred?.id || null;
206
- }
207
-
208
- function resolveFieldRefToLeafId(fieldRef: string, report: any) {
209
- if (!fieldRef) {
210
- return null;
211
- }
212
-
213
- if (fieldRef.startsWith('layout_col_')) {
214
- return resolveLayoutColumnPrimaryLeafId(fieldRef, report);
215
- }
216
-
217
- return fieldRef;
218
- }
219
-
220
- function buildCollectionKeysFromReport(report: any): string[] {
221
- const keys: string[] = [];
222
-
223
- if (report?.collection_root) {
224
- keys.push(report.collection_root);
225
- }
226
-
227
- (report?.collection_joins || []).forEach(join => {
228
- if (!join) {
229
- return;
230
- }
231
-
232
- const alias = (join.alias || '').trim();
233
- if (alias && !keys.includes(alias)) {
234
- keys.push(alias);
235
- }
236
- else if (join.collection && !keys.includes(join.collection)) {
237
- keys.push(join.collection);
238
- }
239
- });
240
-
241
- return keys.length ? keys : ['root'];
242
- }
243
-
244
- function buildLayoutColumnsFromFields(report: any, fields: any[] = []) {
245
- const keys = buildCollectionKeysFromReport(report);
246
-
247
- return (fields || []).map((field, index) => {
248
- const header = field.columnName || field.fieldName || `Column ${index + 1}`;
249
- const isCustom = ((field?.id || field?.fieldPath || '') + '').startsWith('c_') || field?.fieldPathName === 'Custom Field';
250
-
251
- const mappings = keys.map(key => {
252
- const matchesKey = key === report.collection_root
253
- ? (field.collection_name === report.collection_root || isCustom)
254
- : (key === (field.lookup_as || '').trim()) || key === field.collection_name;
255
-
256
- if (matchesKey) {
257
- return {
258
- collection: key,
259
- mode: 'variable',
260
- fieldPath: field.fieldPath || '',
261
- fieldId: field.id || `f_layout_${index}`,
262
- text: '',
263
- leafValueType: field.leafValueType || 'Value',
264
- leafFormatType: field.leafFormatType || ''
265
- };
266
- }
267
-
268
- return {
269
- collection: key,
270
- mode: 'text',
271
- fieldPath: '',
272
- fieldId: '',
273
- text: '',
274
- leafValueType: 'Value',
275
- leafFormatType: ''
276
- };
277
- });
278
-
279
- return {
280
- id: field.id ? `layout_${field.id}` : `layout_${index}`,
281
- header,
282
- mappings
283
- };
284
- });
285
- }
286
-
287
- function ensureLayoutHasCustomField(report: any, layout: any[] = [], customId: string, columnName?: string, leafValueType?: string) {
288
- if (!layout || !customId) {
289
- return;
290
- }
291
-
292
- const hasCustomField = (layout || []).some(col => (col?.mappings || []).some(m =>
293
- m?.mode === 'variable' && (m.fieldId === customId || m.fieldPath === customId)
294
- ));
295
- if (hasCustomField) {
296
- return;
297
- }
298
-
299
- const keys = buildCollectionKeysFromReport(report);
300
- const rootKey = report?.collection_root || '';
301
- const header = columnName || customId;
302
-
303
- const mappings = keys.map(key => {
304
- if (key === rootKey) {
305
- return {
306
- collection: key,
307
- mode: 'variable',
308
- fieldPath: customId,
309
- fieldId: customId,
310
- text: '',
311
- leafValueType: leafValueType || 'Value',
312
- leafFormatType: 'Number'
313
- };
314
- }
315
-
316
- return {
317
- collection: key,
318
- mode: 'text',
319
- fieldPath: '',
320
- fieldId: '',
321
- text: '',
322
- leafValueType: 'Value',
323
- leafFormatType: ''
324
- };
325
- });
326
-
327
- layout.push({
328
- id: `layout_${customId}`,
329
- header,
330
- mappings
331
- });
332
- }
333
-
334
- function ensureLayoutIncludesCustomFields(report: any, layout: any[] = []) {
335
- const fieldsCustom = report?.fields_custom || [];
336
- if (!fieldsCustom.length) {
337
- return layout;
338
- }
339
-
340
- fieldsCustom.forEach(custom => {
341
- ensureLayoutHasCustomField(report, layout, custom?.id, custom?.columnName, custom?.leafValueType);
342
- });
343
-
344
- return layout;
345
- }
346
-
347
- function getLayoutColumnsFromReport(report: any) {
348
- let layout: any[] = [];
349
-
350
- if (report?.fields_layout && report.fields_layout.length) {
351
- layout = deepCopy(report.fields_layout);
352
- }
353
- else {
354
- layout = buildLayoutColumnsFromFields(report, report?.fields_selected || []);
355
- }
356
-
357
- return ensureLayoutIncludesCustomFields(report, layout);
358
- }
359
-
360
- function syncSelectedFieldsFromLayout(report: any, layoutColumns: any[] = []) {
361
- const fields: any[] = [];
362
- const sourceFields = deepCopy(report?.fields_selected || []);
363
- const byId = new Map<string, any>();
364
- const byPath = new Map<string, any>();
365
-
366
- sourceFields.forEach(f => {
367
- if (f?.id) {
368
- byId.set(f.id, f);
369
- }
370
- if (f?.fieldPath) {
371
- byPath.set(f.fieldPath, f);
372
- }
373
- });
374
-
375
- layoutColumns.forEach((col, colIndex) => {
376
- (col.mappings || []).forEach((map, mapIndex) => {
377
- if (map.mode === 'variable' && map.fieldPath) {
378
- const baseField = byId.get(map.fieldId) || byPath.get(map.fieldPath);
379
-
380
- if (!baseField) {
381
- return;
382
- }
383
-
384
- const clone = deepCopy(baseField);
385
- clone.columnName = col.header || baseField.columnName || baseField.fieldPathName || 'Column';
386
- clone.show = (typeof map.show === 'boolean')
387
- ? map.show
388
- : (typeof baseField.show === 'boolean' ? baseField.show : true);
389
- clone.leafValueType = map.leafValueType || clone.leafValueType;
390
- clone.leafFormatType = map.leafFormatType || clone.leafFormatType;
391
- clone.id = map.fieldId || clone.id || `f_layout_${colIndex}_${mapIndex}`;
392
- clone.layoutCollection = map.collection;
393
- clone.layoutColumnIndex = colIndex;
394
-
395
- if (!map.fieldId) {
396
- map.fieldId = clone.id;
397
- }
398
-
399
- fields.push(clone);
400
- }
401
- });
402
- });
403
-
404
- return fields;
405
- }
406
-
407
- function materializeLayoutRow(report: any, layoutColumns: any[], selectedFields: any[], row: any) {
408
- const materialized: any = {_id: row?._id};
409
-
410
- const hasDataForCollection = (collection: string) => {
411
- if (!collection) {
412
- return false;
413
- }
414
-
415
- return (selectedFields || []).some(f =>
416
- f.layoutCollection === collection &&
417
- row &&
418
- Object.prototype.hasOwnProperty.call(row, f.id) &&
419
- row[f.id] !== undefined &&
420
- row[f.id] !== null &&
421
- row[f.id] !== ''
422
- );
423
- };
424
-
425
- (layoutColumns || []).forEach((col, colIndex) => {
426
- const values: any[] = [];
427
-
428
- (col.mappings || []).forEach(map => {
429
- if (map.mode === 'text' && map.text) {
430
- if (hasDataForCollection(map.collection)) {
431
- values.push({collection: map.collection, value: map.text});
432
- }
433
- }
434
- else if (map.mode === 'variable' && map.fieldId && row && Object.prototype.hasOwnProperty.call(row, map.fieldId)) {
435
- values.push({collection: map.collection, value: row[map.fieldId]});
436
- }
437
- });
438
-
439
- materialized[colIndex] = values;
440
- });
441
-
442
- return materialized;
443
- }
444
-
445
- function getLayoutCellExportValue(report: any, layoutRow: any, colIndex: number) {
446
- if (!layoutRow || layoutRow[colIndex] === undefined || layoutRow[colIndex] === null) {
447
- return '';
448
- }
449
-
450
- const cellValues = Array.isArray(layoutRow[colIndex]) ? layoutRow[colIndex] : [layoutRow[colIndex]];
451
- const filtered = cellValues.filter(v => v !== undefined && v !== null && v.value !== undefined && v.value !== null && v.value !== '');
452
-
453
- if (!filtered.length) {
454
- return '';
455
- }
456
-
457
- const rootCollection = report?.collection_root;
458
- const preferred = filtered.find(v => v.collection === rootCollection) || filtered[0];
459
- const value = preferred?.value;
460
-
461
- if (value === undefined || value === null) {
462
- return '';
463
- }
464
-
465
- if (Array.isArray(value)) {
466
- return value;
467
- }
468
-
469
- return typeof value === 'string' ? value.trim().replace(/\t/g, '').replace(/\n/g, '') : value;
470
- }
471
-
472
- function getPrimaryFieldForLayoutColumn(col: any, selectedFields: any[]) {
473
- if (!col?.mappings) {
474
- return null;
475
- }
476
-
477
- const target = col.mappings.find(m => m.mode === 'variable' && m.fieldId);
478
-
479
- if (!target) {
480
- return null;
481
- }
482
-
483
- return (selectedFields || []).find(f => f.id === target.fieldId) || null;
484
- }
485
-
486
- const STRING_DATE_FORMATS = [
487
- moment.ISO_8601,
488
- 'MM/DD/YYYY',
489
- 'M/D/YYYY',
490
- 'MM/DD/YYYY h:mm A',
491
- 'M/D/YYYY h:mm A',
492
- 'MM/DD/YYYY hh:mm A',
493
- 'M/D/YYYY hh:mm A',
494
- 'MM/DD/YYYY h:mm:ss A',
495
- 'M/D/YYYY h:mm:ss A',
496
- 'MM/DD/YYYY hh:mm:ss A',
497
- 'M/D/YYYY hh:mm:ss A',
498
- 'MM/DD/YYYY H:mm',
499
- 'M/D/YYYY H:mm',
500
- 'MM/DD/YYYY HH:mm',
501
- 'M/D/YYYY HH:mm',
502
- 'MM/DD/YYYY H:mm:ss',
503
- 'M/D/YYYY H:mm:ss',
504
- 'MM/DD/YYYY HH:mm:ss',
505
- 'M/D/YYYY HH:mm:ss'
506
- ];
507
-
508
- function parseMoment(value: any) {
509
- if (value === null || value === undefined) {
510
- return null;
511
- }
512
-
513
- if (moment.isMoment(value)) {
514
- return value;
515
- }
516
-
517
- if (value instanceof Date || typeof value === 'number') {
518
- const m = moment(value);
519
- return m.isValid() ? m : null;
520
- }
521
-
522
- if (typeof value === 'string' || value instanceof String) {
523
- const str = `${value}`.trim();
524
- if (!str) {
525
- return null;
526
- }
527
-
528
- const m = moment(str, STRING_DATE_FORMATS, true);
529
- if (m.isValid()) {
530
- return m;
531
- }
532
-
533
- const loose = moment(str, STRING_DATE_FORMATS, false);
534
- if (loose.isValid()) {
535
- return loose;
536
- }
537
-
538
- const jsDateStr = str.replace(/\s*\([^)]*\)\s*$/, '');
539
- const jsDate = moment(jsDateStr, 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ', true);
540
- if (jsDate.isValid()) {
541
- return jsDate;
542
- }
543
-
544
- if (/[T:\\/\\-]/.test(str) || /GMT|UTC/i.test(str)) {
545
- const fallback = moment(str);
546
- return fallback.isValid() ? fallback : null;
547
- }
548
-
549
- return null;
550
- }
551
-
552
- const m = moment(value);
553
- return m.isValid() ? m : null;
554
- }
555
-
556
- function parseExcelNumber(value: unknown): number | null {
557
- if (typeof value === 'number') {
558
- return Number.isFinite(value) ? value : null;
559
- }
560
-
561
- if (typeof value !== 'string') {
562
- return null;
563
- }
564
-
565
- let s = value.trim();
566
- if (!s) {
567
- return null;
568
- }
569
-
570
- let negative = false;
571
- const parenMatch = s.match(/^\((.*)\)$/);
572
- if (parenMatch) {
573
- negative = true;
574
- s = parenMatch[1].trim();
575
- }
576
-
577
- s = s
578
- .replace(/[\t\n\r]/g, '')
579
- .replace(/\$/g, '')
580
- .replace(/,/g, '');
581
-
582
- s = s.trim();
583
- if (!s) {
584
- return null;
585
- }
586
-
587
- const num = Number(s);
588
- if (!Number.isFinite(num)) {
589
- return null;
590
- }
591
-
592
- return negative ? -num : num;
593
- }
594
-
595
- function isExcelNumericField(field: any): boolean {
596
- return !!field && (
597
- field.fieldType === 'Number' ||
598
- field.leafValueType === 'Count' ||
599
- field.leafValueType === 'Sum' ||
600
- field.leafValueType === 'Average'
601
- );
602
- }
603
-
604
- function writeExcelCell(cell: Excel.Cell, value: any, fieldMeta?: any) {
605
- if (value === null || value === undefined) {
606
- cell.value = '';
607
- return;
608
- }
609
-
610
- if (fieldMeta?.fieldType === 'Date') {
611
- const rawValue = Array.isArray(value) ? value.find(v => v !== null && v !== undefined && v !== '') : value;
612
- const m = parseMoment(rawValue);
613
- if (m) {
614
- const timezone = process.env.TZ_CLIENT;
615
- const local = timezone ? moment.tz(m.toDate(), timezone) : m.clone().local();
616
- const leafFormatType = fieldMeta?.leafFormatType;
617
- const excelSerial = (Date.UTC(
618
- local.year(),
619
- local.month(),
620
- local.date(),
621
- local.hour(),
622
- local.minute(),
623
- local.second(),
624
- local.millisecond(),
625
- ) - Date.UTC(1899, 11, 30)) / 86400000;
626
- if (leafFormatType === 'Date' || leafFormatType === 'Date_long') {
627
- cell.value = Math.floor(excelSerial);
628
- }
629
- else if (leafFormatType === 'Time' || leafFormatType === 'DateTime' || leafFormatType === 'DateTime_long') {
630
- cell.value = excelSerial;
631
- }
632
- else {
633
- cell.value = local.toDate();
634
- }
635
-
636
- switch (leafFormatType) {
637
- case 'Time':
638
- cell.numFmt = 'h:mm AM/PM';
639
- break;
640
- case 'DateTime':
641
- case 'DateTime_long':
642
- cell.numFmt = 'mm/dd/yyyy h:mm AM/PM';
643
- break;
644
- case 'Date':
645
- cell.numFmt = 'mm/dd/yyyy';
646
- break;
647
- case 'Date_long':
648
- default:
649
- cell.numFmt = 'mm/dd/yyyy';
650
- break;
651
- }
652
-
653
- return;
654
- }
655
- }
656
-
657
- if (Array.isArray(value)) {
658
- cell.value = value.join(', ');
659
- return;
660
- }
661
-
662
- if (isExcelNumericField(fieldMeta)) {
663
- const parsed = parseExcelNumber(value);
664
- if (parsed !== null) {
665
- cell.value = parsed;
666
-
667
- if (fieldMeta?.leafFormatType === 'Currency') {
668
- cell.numFmt = '"$"#,##0.00;[Red]-"$"#,##0.00';
669
- }
670
- else if (fieldMeta?.leafFormatType === 'Number' || fieldMeta?.leafValueType === 'Count') {
671
- cell.numFmt = '#,##0';
672
- }
673
-
674
- return;
675
- }
676
- }
677
-
678
- if (typeof value === 'string') {
679
- cell.value = value.replace(/\t/g, '').replace(/\n/g, '');
680
- }
681
- else {
682
- cell.value = value;
683
- }
684
- }
685
-
686
- function getMaxRows(row) {
687
- let keys = Object.keys(row || {});
688
- let maxArray = [];
689
-
690
- for (let i = 0; i < keys.length; i++) {
691
- if (Array.isArray(row[keys[i]]) && row[keys[i]].length > maxArray.length) {
692
- maxArray = row[keys[i]];
693
- }
694
- else if (maxArray.length === 0) {
695
- maxArray = [row[keys[i]]];
696
- }
697
- }
698
-
699
- return maxArray;
700
- }
701
-
702
- function applyClientGroupSortToData(results: any[], report: any, sorts: any[] = []) {
703
- if (!Array.isArray(results) || !results.length) {
704
- return;
705
- }
706
-
707
- const groupIds = (report?.groups_row || []).map(g => g.id).filter(Boolean);
708
-
709
- if (!groupIds.length) {
710
- return;
711
- }
712
-
713
- const groupOrderById = {};
714
- const leafSorts = [];
715
-
716
- (sorts || []).forEach(s => {
717
- if (!s?.field) {
718
- return;
719
- }
720
-
721
- if (groupIds.includes(s.field)) {
722
- groupOrderById[s.field] = s.order || 'asc';
723
- }
724
- else {
725
- const leafId = resolveFieldRefToLeafId(s.field, report);
726
- if (leafId) {
727
- leafSorts.push({leafId, order: s.order || 'asc'});
728
- }
729
- }
730
- });
731
-
732
- const compareScalar = (aVal: any, bVal: any, order: string) => {
733
- const dir = order === 'desc' ? -1 : 1;
734
-
735
- const aNull = aVal === null || aVal === undefined || aVal === '';
736
- const bNull = bVal === null || bVal === undefined || bVal === '';
737
- if (aNull && bNull) { return 0; }
738
- if (aNull) { return 1; }
739
- if (bNull) { return -1; }
740
-
741
- const aNum = typeof aVal === 'number' ? aVal : Number(aVal);
742
- const bNum = typeof bVal === 'number' ? bVal : Number(bVal);
743
- if (!isNaN(aNum) && !isNaN(bNum)) {
744
- if (aNum === bNum) { return 0; }
745
- return aNum > bNum ? dir : -dir;
746
- }
747
-
748
- const aStr = ('' + aVal).toLowerCase();
749
- const bStr = ('' + bVal).toLowerCase();
750
- if (aStr === bStr) { return 0; }
751
- return aStr > bStr ? dir : -dir;
752
- };
753
-
754
- const selectedIds = (report?.fields_selected || []).map(f => f.id).filter(Boolean);
755
-
756
- const sortLeafArraysInRow = (row: any) => {
757
- if (!row || !leafSorts.length) {
758
- return;
759
- }
760
-
761
- const arraysToReorder = selectedIds.filter(id => Array.isArray(row[id]));
762
-
763
- if (!arraysToReorder.length) {
764
- return;
765
- }
766
-
767
- let length = 0;
768
- arraysToReorder.forEach(id => {
769
- length = Math.max(length, row[id].length || 0);
770
- });
771
-
772
- if (length <= 1) {
773
- return;
774
- }
775
-
776
- const getArrayVal = (id: string, idx: number) => {
777
- const arr = row[id];
778
- if (!Array.isArray(arr) || !arr.length) {
779
- return null;
780
- }
781
- return arr[idx] !== undefined ? arr[idx] : arr[arr.length - 1];
782
- };
783
-
784
- const indices = Array.from({length}, (_, i) => i);
785
- indices.sort((i, j) => {
786
- for (const s of leafSorts) {
787
- const aVal = Array.isArray(row[s.leafId]) ? getArrayVal(s.leafId, i) : row[s.leafId];
788
- const bVal = Array.isArray(row[s.leafId]) ? getArrayVal(s.leafId, j) : row[s.leafId];
789
- const cmp = compareScalar(aVal, bVal, s.order);
790
- if (cmp !== 0) {
791
- return cmp;
792
- }
793
- }
794
- return 0;
795
- });
796
-
797
- arraysToReorder.forEach(id => {
798
- row[id] = indices.map(idx => getArrayVal(id, idx));
799
- });
800
- };
801
-
802
- const sortGroupLevel = (rows: any[], depth: number) => {
803
- if (!Array.isArray(rows) || !rows.length) {
804
- return;
805
- }
806
-
807
- const groupId = groupIds[depth];
808
- const order = groupOrderById[groupId] || 'asc';
809
- rows.sort((a, b) => compareScalar(a?._id?.[groupId], b?._id?.[groupId], order));
810
-
811
- if (depth < groupIds.length - 1) {
812
- const childId = groupIds[depth + 1];
813
- rows.forEach(r => {
814
- const children = r ? r[childId] : null;
815
- if (Array.isArray(children)) {
816
- sortGroupLevel(children, depth + 1);
817
- }
818
- });
819
- }
820
- else {
821
- rows.forEach(r => sortLeafArraysInRow(r));
822
- }
823
- };
824
-
825
- sortGroupLevel(results, 0);
826
- }
827
-
828
- const OPENAI_USAGE_BILLING_ENDPOINT = 'https://backend.resolveio.com/api/openai-usage/report';
829
- const AI_USAGE_SYNC_JOB_NAME = 'AI Usage Billing Sync';
830
- const LEGACY_AI_USAGE_SYNC_JOB_NAME = 'OpenAI Usage Billing Sync';
831
- const OPENAI_USAGE_DEFAULT_LOOKBACK_DAYS = 30;
832
- const OPENAI_USAGE_DEFAULT_BATCH_SIZE = 500;
833
- const OPENAI_USAGE_DEFAULT_OVERLAP_MINUTES = 10;
834
- const COMMUNICATION_METRICS_ENDPOINT = 'https://backend.resolveio.com/api/communication-metrics/report';
835
- const COMMUNICATION_METRICS_DEFAULT_LOOKBACK_DAYS = 30;
836
- const COMMUNICATION_METRICS_DEFAULT_BATCH_SIZE = 1000;
837
- const COMMUNICATION_METRICS_DEFAULT_OVERLAP_MINUTES = 10;
838
-
839
- const toNumberSetting = (value: any, fallback: number, allowZero = false): number => {
840
- const parsed = Number(value);
841
- if (!Number.isFinite(parsed)) {
842
- return fallback;
843
- }
844
- if (allowZero && parsed === 0) {
845
- return 0;
846
- }
847
- return parsed > 0 ? Math.floor(parsed) : fallback;
848
- };
849
-
850
- const normalizeString = (value: any): string => {
851
- if (typeof value !== 'string') {
852
- return '';
853
- }
854
- return value.trim();
855
- };
856
-
857
- const normalizeIdentifier = (value: any): string => {
858
- if (value === undefined || value === null) {
859
- return '';
860
- }
861
- return String(value).trim();
862
- };
863
-
864
- const normalizeDate = (value: any): Date | null => {
865
- if (!value) {
866
- return null;
867
- }
868
- const date = value instanceof Date ? value : new Date(value);
869
- if (Number.isNaN(date.getTime())) {
870
- return null;
871
- }
872
- return date;
873
- };
874
-
875
- const resolveOpenAIUsageSyncConfig = () => {
876
- const config = ResolveIOServer.getServerConfig?.() || {};
877
- const endpoint = normalizeString(
878
- config['OPENAI_USAGE_BILLING_URL']
879
- || config['OPENAI_USAGE_REPORT_URL']
880
- || process.env.OPENAI_USAGE_BILLING_URL
881
- || process.env.OPENAI_USAGE_REPORT_URL
882
- ) || OPENAI_USAGE_BILLING_ENDPOINT;
883
- const apiKey = normalizeString(
884
- config['OPENAI_USAGE_INGEST_KEY']
885
- || config['OPENAI_USAGE_API_KEY']
886
- || process.env.OPENAI_USAGE_INGEST_KEY
887
- || process.env.OPENAI_USAGE_API_KEY
888
- || process.env.OPENAI_USAGE_REPORT_KEY
889
- );
890
- const batchSize = toNumberSetting(
891
- config['OPENAI_USAGE_SYNC_BATCH_SIZE'] || process.env.OPENAI_USAGE_SYNC_BATCH_SIZE,
892
- OPENAI_USAGE_DEFAULT_BATCH_SIZE
893
- );
894
- const lookbackDays = toNumberSetting(
895
- config['OPENAI_USAGE_SYNC_LOOKBACK_DAYS'] || process.env.OPENAI_USAGE_SYNC_LOOKBACK_DAYS,
896
- OPENAI_USAGE_DEFAULT_LOOKBACK_DAYS
897
- );
898
- const overlapMinutes = toNumberSetting(
899
- config['OPENAI_USAGE_SYNC_OVERLAP_MINUTES'] || process.env.OPENAI_USAGE_SYNC_OVERLAP_MINUTES,
900
- OPENAI_USAGE_DEFAULT_OVERLAP_MINUTES,
901
- true
902
- );
903
- const enabledRaw = config['OPENAI_USAGE_SYNC_ENABLED'] ?? process.env.OPENAI_USAGE_SYNC_ENABLED;
904
- const enabled = typeof enabledRaw === 'string'
905
- ? enabledRaw.trim().toLowerCase() !== 'false' && enabledRaw.trim() !== '0'
906
- : enabledRaw !== false;
907
-
908
- return { config, endpoint, apiKey, batchSize, lookbackDays, overlapMinutes, enabled };
909
- };
910
-
911
- const buildOpenAIUsageQuery = (cursorAt: Date, cursorId: string) => {
912
- const base: any = {
913
- billable: { $ne: false }
914
- };
915
-
916
- if (!cursorId) {
917
- base.timestamp = { $gte: cursorAt };
918
- return base;
919
- }
920
-
921
- base.$or = [
922
- { timestamp: { $gt: cursorAt } },
923
- { timestamp: cursorAt, _id: { $gt: cursorId } }
924
- ];
925
- return base;
926
- };
927
-
928
- const normalizeUsagePayloadEntry = (entry: any) => {
929
- if (!entry) {
930
- return null;
931
- }
932
- const timestamp = normalizeDate(entry.timestamp);
933
- const idClient = normalizeIdentifier(entry.id_client);
934
- if (!timestamp || !idClient) {
935
- return null;
936
- }
937
- const id = normalizeIdentifier(entry._id) || normalizeIdentifier(entry.id) || '';
938
-
939
- return {
940
- _id: id || undefined,
941
- id_client: idClient,
942
- timestamp: timestamp,
943
- model: normalizeString(entry.model) || 'unknown',
944
- input_tokens: Number(entry.input_tokens || 0),
945
- output_tokens: Number(entry.output_tokens || 0),
946
- total_tokens: Number(entry.total_tokens || 0),
947
- cost_estimate: Number(entry.cost_estimate || 0),
948
- billable: entry.billable !== false,
949
- category: normalizeString(entry.category),
950
- id_request: normalizeIdentifier(entry.id_request),
951
- id_conversation: normalizeIdentifier(entry.id_conversation)
952
- };
953
- };
954
-
955
- const resolveCommunicationMetricsSyncConfig = () => {
956
- const config = ResolveIOServer.getServerConfig?.() || {};
957
- const endpoint = normalizeString(
958
- config['COMMUNICATION_METRICS_REPORT_URL']
959
- || config['COMMUNICATION_METRICS_BILLING_URL']
960
- || process.env.COMMUNICATION_METRICS_REPORT_URL
961
- || process.env.COMMUNICATION_METRICS_BILLING_URL
962
- ) || COMMUNICATION_METRICS_ENDPOINT;
963
- const apiKey = normalizeString(
964
- config['COMMUNICATION_METRICS_INGEST_KEY']
965
- || config['COMMUNICATION_METRICS_API_KEY']
966
- || process.env.COMMUNICATION_METRICS_INGEST_KEY
967
- || process.env.COMMUNICATION_METRICS_API_KEY
968
- || config['OPENAI_USAGE_INGEST_KEY']
969
- || config['OPENAI_USAGE_API_KEY']
970
- || process.env.OPENAI_USAGE_INGEST_KEY
971
- || process.env.OPENAI_USAGE_API_KEY
972
- || process.env.OPENAI_USAGE_REPORT_KEY
973
- );
974
- const batchSize = toNumberSetting(
975
- config['COMMUNICATION_METRICS_SYNC_BATCH_SIZE'] || process.env.COMMUNICATION_METRICS_SYNC_BATCH_SIZE,
976
- COMMUNICATION_METRICS_DEFAULT_BATCH_SIZE
977
- );
978
- const lookbackDays = toNumberSetting(
979
- config['COMMUNICATION_METRICS_SYNC_LOOKBACK_DAYS'] || process.env.COMMUNICATION_METRICS_SYNC_LOOKBACK_DAYS,
980
- COMMUNICATION_METRICS_DEFAULT_LOOKBACK_DAYS
981
- );
982
- const overlapMinutes = toNumberSetting(
983
- config['COMMUNICATION_METRICS_SYNC_OVERLAP_MINUTES'] || process.env.COMMUNICATION_METRICS_SYNC_OVERLAP_MINUTES,
984
- COMMUNICATION_METRICS_DEFAULT_OVERLAP_MINUTES,
985
- true
986
- );
987
- const enabledRaw = config['COMMUNICATION_METRICS_SYNC_ENABLED'] ?? process.env.COMMUNICATION_METRICS_SYNC_ENABLED;
988
- const enabled = typeof enabledRaw === 'string'
989
- ? enabledRaw.trim().toLowerCase() !== 'false' && enabledRaw.trim() !== '0'
990
- : enabledRaw !== false;
991
-
992
- return { config, endpoint, apiKey, batchSize, lookbackDays, overlapMinutes, enabled };
993
- };
994
-
995
- const buildCommunicationMetricsQuery = (cursorAt: Date, cursorId: string) => {
996
- if (!cursorId) {
997
- return { date: { $gte: cursorAt } };
998
- }
999
- return {
1000
- $or: [
1001
- { date: { $gt: cursorAt } },
1002
- { date: cursorAt, _id: { $gt: cursorId } }
1003
- ]
1004
- };
1005
- };
1006
-
1007
- const normalizeCommunicationMetricEntry = (entry: any) => {
1008
- if (!entry) {
1009
- return null;
1010
- }
1011
- const date = normalizeDate(entry.date || entry.timestamp);
1012
- const type = normalizeString(entry.type);
1013
- if (!date || !type) {
1014
- return null;
1015
- }
1016
- const value = Number(entry.value ?? entry.count ?? 0);
1017
- if (!Number.isFinite(value) || !value) {
1018
- return null;
1019
- }
1020
- const id = normalizeIdentifier(entry._id) || normalizeIdentifier(entry.id) || '';
1021
- const unit = normalizeString(entry.unit);
1022
- const metadata = entry.metadata && typeof entry.metadata === 'object' ? entry.metadata : undefined;
1023
-
1024
- return {
1025
- _id: id || undefined,
1026
- date,
1027
- type,
1028
- value,
1029
- unit: unit || undefined,
1030
- metadata
1031
- };
1032
- };
1033
-
1034
- export function loadCronJobMethods(methodManager: MethodManager) {
1035
- methodManager.methods({
1036
- cronEmailMergedDocsCleanUp: {
1037
- function: async function() {
1038
- let files = await Files.find({$and: [{type: 'Email Merged Docs'}, {createdAt: {$lte: moment().subtract(1, 'day').toDate()}}]});
1039
-
1040
- if (files.length) {
1041
- await this.callMethod('deleteFiles', files.map(file => file.key));
1042
- await Files.deleteMany({_id: {$in: files.map(a => a._id)}});
1043
- }
1044
-
1045
- return true;
1046
- }
1047
- },
1048
- stuckCronJob: {
1049
- function: async function() {
1050
- let fiveMin = moment().subtract(5, 'minutes').toDate();
1051
- let cronJobs = await CronJobs.find({running: true, updatedAt: {$lte: fiveMin}});
1052
-
1053
- if (cronJobs.length) {
1054
- await CronJobs.updateMany({_id: {$in: cronJobs.map(a => a._id)}}, {$set: {running: false}});
1055
- }
1056
-
1057
- return true;
1058
- }
1059
- },
1060
- cronOpenAIUsageBillingSync: {
1061
- check: new SimpleSchema({
1062
- data: {
1063
- type: Object,
1064
- blackbox: true
1065
- }
1066
- }),
1067
- function: async function() {
1068
- const { config, endpoint, apiKey, batchSize, lookbackDays, overlapMinutes, enabled } = resolveOpenAIUsageSyncConfig();
1069
- if (!enabled) {
1070
- return true;
1071
- }
1072
-
1073
- const rootUrl = normalizeString(config['ROOT_URL']);
1074
- if (rootUrl === 'https://resolveio.com' || rootUrl === 'http://localhost:4200') {
1075
- return true;
1076
- }
1077
-
1078
- if (!endpoint || !apiKey) {
1079
- console.warn('[AI Usage Sync] Missing endpoint or API key.');
1080
- return false;
1081
- }
1082
-
1083
- const jobDoc = await CronJobs.findOne({
1084
- name: {
1085
- $in: [AI_USAGE_SYNC_JOB_NAME, LEGACY_AI_USAGE_SYNC_JOB_NAME]
1086
- }
1087
- });
1088
- const runData = (jobDoc as any)?.method_run_data as any;
1089
- const lastSyncedAt = normalizeDate(runData?.last_synced_at);
1090
- const lastSyncedId = normalizeString(runData?.last_synced_id);
1091
- const lookbackMs = lookbackDays * 24 * 60 * 60 * 1000;
1092
- let cursorAt = lastSyncedAt || new Date(Date.now() - lookbackMs);
1093
-
1094
- if (lastSyncedAt && overlapMinutes > 0) {
1095
- cursorAt = new Date(cursorAt.getTime() - overlapMinutes * 60 * 1000);
1096
- }
1097
-
1098
- let cursorId = lastSyncedId;
1099
- let totalSent = 0;
1100
- let cursorMoved = false;
1101
- const source = {
1102
- clientSlug: ResolveIOServer.getClientName?.(),
1103
- clientName: normalizeString(config['CLIENT_NAME']),
1104
- rootUrl: rootUrl,
1105
- reportedAt: new Date(),
1106
- appVersion: process.env.APP_VERSION
1107
- };
1108
-
1109
- for (let i = 0; i < 1000; i++) {
1110
- const query = buildOpenAIUsageQuery(cursorAt, cursorId);
1111
- const entries = await OpenAIUsageLedger.find(query, {
1112
- sort: { timestamp: 1, _id: 1 },
1113
- limit: batchSize
1114
- });
1115
-
1116
- if (!entries.length) {
1117
- break;
1118
- }
1119
-
1120
- const payloadEntries = entries
1121
- .map(entry => normalizeUsagePayloadEntry(entry))
1122
- .filter(Boolean);
1123
-
1124
- if (payloadEntries.length) {
1125
- await axios.post(endpoint, { entries: payloadEntries, source }, {
1126
- headers: {
1127
- 'Content-Type': 'application/json',
1128
- 'X-ResolveIO-OpenAI-Usage-Key': apiKey,
1129
- 'X-OpenAI-Usage-Key': apiKey,
1130
- 'X-API-Key': apiKey
1131
- },
1132
- timeout: 20000
1133
- });
1134
- totalSent += payloadEntries.length;
1135
- }
1136
-
1137
- const lastEntry = entries[entries.length - 1];
1138
- if (lastEntry) {
1139
- cursorAt = normalizeDate(lastEntry.timestamp) || cursorAt;
1140
- cursorId = normalizeString(lastEntry._id) || cursorId;
1141
- cursorMoved = true;
1142
- }
1143
-
1144
- if (entries.length < batchSize) {
1145
- break;
1146
- }
1147
- }
1148
-
1149
- if (cursorMoved) {
1150
- const jobSelector = (jobDoc as any)?._id
1151
- ? { _id: (jobDoc as any)._id }
1152
- : { name: AI_USAGE_SYNC_JOB_NAME };
1153
- await CronJobs.updateOne(
1154
- jobSelector,
1155
- {
1156
- $set: {
1157
- name: AI_USAGE_SYNC_JOB_NAME,
1158
- 'method_run_data.last_synced_at': cursorAt,
1159
- 'method_run_data.last_synced_id': cursorId,
1160
- 'method_run_data.last_sent_at': new Date(),
1161
- 'method_run_data.last_sent_count': totalSent
1162
- }
1163
- }
1164
- );
1165
- }
1166
-
1167
- return true;
1168
- }
1169
- },
1170
- cronCommunicationMetricsSync: {
1171
- check: new SimpleSchema({
1172
- data: {
1173
- type: Object,
1174
- blackbox: true
1175
- }
1176
- }),
1177
- function: async function() {
1178
- const { config, endpoint, apiKey, batchSize, lookbackDays, overlapMinutes, enabled } = resolveCommunicationMetricsSyncConfig();
1179
- if (!enabled) {
1180
- return true;
1181
- }
1182
-
1183
- const rootUrl = normalizeString(config['ROOT_URL']);
1184
- if (rootUrl === 'https://resolveio.com' || rootUrl === 'http://localhost:4200') {
1185
- return true;
1186
- }
1187
-
1188
- if (!endpoint || !apiKey) {
1189
- console.warn('[Communication Metrics Sync] Missing endpoint or API key.');
1190
- return false;
1191
- }
1192
-
1193
- const jobDoc = await CronJobs.findOne({ name: 'Communication Metrics Sync' });
1194
- const runData = (jobDoc as any)?.method_run_data as any;
1195
- const lastSyncedAt = normalizeDate(runData?.last_synced_at);
1196
- const lastSyncedId = normalizeString(runData?.last_synced_id);
1197
- const lookbackMs = lookbackDays * 24 * 60 * 60 * 1000;
1198
- let cursorAt = lastSyncedAt || new Date(Date.now() - lookbackMs);
1199
-
1200
- if (lastSyncedAt && overlapMinutes > 0) {
1201
- cursorAt = new Date(cursorAt.getTime() - overlapMinutes * 60 * 1000);
1202
- }
1203
-
1204
- let cursorId = lastSyncedId;
1205
- let totalSent = 0;
1206
- let cursorMoved = false;
1207
- const source = {
1208
- clientSlug: ResolveIOServer.getClientName?.(),
1209
- clientName: normalizeString(config['CLIENT_NAME']),
1210
- rootUrl: rootUrl,
1211
- reportedAt: new Date(),
1212
- appVersion: process.env.APP_VERSION
1213
- };
1214
-
1215
- for (let i = 0; i < 1000; i++) {
1216
- const query = buildCommunicationMetricsQuery(cursorAt, cursorId);
1217
- const entries = await CommunicationMetrics.find(query, {
1218
- sort: { date: 1, _id: 1 },
1219
- limit: batchSize
1220
- });
1221
-
1222
- if (!entries.length) {
1223
- break;
1224
- }
1225
-
1226
- const payloadEntries = entries
1227
- .map(entry => normalizeCommunicationMetricEntry(entry))
1228
- .filter(Boolean);
1229
-
1230
- if (payloadEntries.length) {
1231
- await axios.post(endpoint, { entries: payloadEntries, source }, {
1232
- headers: {
1233
- 'Content-Type': 'application/json',
1234
- 'X-ResolveIO-Communication-Metrics-Key': apiKey,
1235
- 'X-ResolveIO-OpenAI-Usage-Key': apiKey,
1236
- 'X-OpenAI-Usage-Key': apiKey,
1237
- 'X-API-Key': apiKey
1238
- },
1239
- timeout: 20000
1240
- });
1241
- totalSent += payloadEntries.length;
1242
- }
1243
-
1244
- const lastEntry = entries[entries.length - 1];
1245
- if (lastEntry) {
1246
- cursorAt = normalizeDate(lastEntry.date) || cursorAt;
1247
- cursorId = normalizeString((lastEntry as any)._id) || cursorId;
1248
- cursorMoved = true;
1249
- }
1250
-
1251
- if (entries.length < batchSize) {
1252
- break;
1253
- }
1254
- }
1255
-
1256
- if (cursorMoved) {
1257
- await CronJobs.updateOne(
1258
- { name: 'Communication Metrics Sync' },
1259
- {
1260
- $set: {
1261
- 'method_run_data.last_synced_at': cursorAt,
1262
- 'method_run_data.last_synced_id': cursorId,
1263
- 'method_run_data.last_sent_at': new Date(),
1264
- 'method_run_data.last_sent_count': totalSent
1265
- }
1266
- }
1267
- );
1268
- }
1269
-
1270
- return true;
1271
- }
1272
- },
1273
- reportbuilderCronJob: {
1274
- check: new SimpleSchema({
1275
- data: {
1276
- type: Object,
1277
- blackbox: true
1278
- }
1279
- }),
1280
- function: async function(data: Object) {
1281
- let report = await ReportBuilderReports.findById(data['id_report']);
1282
-
1283
- try {
1284
- const layoutColumns = getLayoutColumnsFromReport(report);
1285
- const selectedFields = syncSelectedFieldsFromLayout(report, layoutColumns);
1286
- report.fields_selected = selectedFields;
1287
- report.fields_layout = layoutColumns;
1288
-
1289
- (report.fields_selected || []).forEach((field: any, index: number) => {
1290
- if (!field?.id) {
1291
- field.id = `f_${index}`;
1292
- }
1293
- });
1294
-
1295
- (report.fields_custom || []).forEach(custom => {
1296
- if (!custom) {
1297
- return;
1298
- }
1299
-
1300
- if (!custom.selFieldId && custom.id) {
1301
- const match = (report.fields_selected || []).find(field => field.fieldPath === custom.id);
1302
- if (match?.id) {
1303
- custom.selFieldId = match.id;
1304
- }
1305
- }
1306
- });
1307
-
1308
- report.fields_selected.forEach((field: any) => {
1309
- if (!field?.fieldPath) {
1310
- return;
1311
- }
1312
-
1313
- let dotPath = field.fieldPath.replace(/\.\$/g, '');
1314
- let fieldData = dotPath.split('.');
1315
- field.fieldPathObj = null;
1316
- for (let i = fieldData.length - 1; i >= 0; i--) {
1317
- if (!field.fieldPathObj) {
1318
- field.fieldPathObj = {[fieldData[i]]: 1};
1319
- }
1320
- else {
1321
- field.fieldPathObj = {[fieldData[i]]: field.fieldPathObj};
1322
- }
1323
- }
1324
- });
1325
-
1326
- if ((report.fields_selected && report.fields_selected.length) || (report.groups_row && report.groups_row.length)) {
1327
- let fieldsObj = {};
1328
- const selectedFieldsForQuery = (report.fields_selected || []).filter(field => !((field?.fieldPath || '').startsWith('c_')));
1329
-
1330
- report.fields_sort = report.fields_sort || [];
1331
-
1332
- selectedFieldsForQuery.forEach((field: any) => {
1333
- if (field.collection_name === report.collection_root && field.fieldPathObj) {
1334
- fieldsObj = mergeDeep(fieldsObj, field.fieldPathObj);
1335
- }
1336
- });
1337
-
1338
- const groupIds = (report.groups_row || []).map(g => g.id).filter(Boolean);
1339
- const userSorts = (report.fields_sort || []).filter(s => !!s.field);
1340
- const userSortByField = {};
1341
- userSorts.forEach(s => {
1342
- userSortByField[s.field] = s;
1343
- });
1344
-
1345
- const groupSorts = groupIds.map(id => userSortByField[id] || {field: id, order: 'asc'});
1346
- const nonGroupSorts = userSorts.filter(s => !groupIds.includes(s.field));
1347
- const effectiveSorts = groupIds.length ? [...groupSorts, ...nonGroupSorts] : userSorts;
1348
-
1349
- let sortObj = null;
1350
- if (effectiveSorts.length) {
1351
- sortObj = {};
1352
- effectiveSorts.forEach(sortField => {
1353
- let targetField = sortField.field;
1354
-
1355
- if (!targetField) {
1356
- return;
1357
- }
1358
-
1359
- if (targetField.startsWith('layout_col_')) {
1360
- const resolved = resolveFieldRefToLeafId(targetField, report);
1361
- targetField = resolved || targetField;
1362
- }
1363
-
1364
- if (targetField.startsWith('gr_')) {
1365
- sortObj['_id.' + targetField] = (sortField.order === 'asc' ? 1 : -1);
1366
- }
1367
- else {
1368
- sortObj[targetField] = (sortField.order === 'asc' ? 1 : -1);
1369
- }
1370
- });
1371
- }
1372
-
1373
- const totalsForQuery = (report.fields_total || []).map(total => {
1374
- const mappedFields = (total.fields || [])
1375
- .map(ref => {
1376
- if (!ref) {
1377
- return null;
1378
- }
1379
-
1380
- if (ref.startsWith('layout_col_')) {
1381
- return resolveFieldRefToLeafId(ref, report);
1382
- }
1383
-
1384
- return ref;
1385
- })
1386
- .filter(f => !!f);
1387
-
1388
- return {...total, fields: mappedFields};
1389
- }).filter(total => (total.fields || []).length);
1390
-
1391
- report.fields_total = totalsForQuery;
1392
-
1393
- let rootOptions: PaginationOptions = {
1394
- limit: 0,
1395
- skip: 0,
1396
- fields: fieldsObj,
1397
- sort: sortObj
1398
- };
1399
-
1400
- let filters = [];
1401
- let filterArrayFields = [];
1402
- let filterArrays = [];
1403
-
1404
- selectedFieldsForQuery
1405
- .filter(f => (f.fieldPath || '').includes('.$.'))
1406
- .forEach(sel => {
1407
- if (!filterArrayFields.some(f => f?.fieldPath === sel.fieldPath)) {
1408
- filterArrayFields.push(sel);
1409
- }
1410
- });
1411
-
1412
- (report.fields_filter || []).forEach(filterAnd => {
1413
- let ors = [];
1414
- let hasArrayTarget = false;
1415
-
1416
- (filterAnd.ors || []).forEach((filter: any) => {
1417
- const targets = getFilterTargets(filter.field, report);
1418
-
1419
- if (!targets.length) {
1420
- return;
1421
- }
1422
-
1423
- targets.forEach(path => {
1424
- const isArrayTarget = path.includes('.$.');
1425
- const normalizedPath = path.replace(/\.\$/g, '');
1426
- const expr = buildFilterExpression(filter, normalizedPath);
1427
-
1428
- if (expr) {
1429
- ors.push(expr);
1430
- }
1431
-
1432
- if (isArrayTarget) {
1433
- hasArrayTarget = true;
1434
- const leaf = selectedFieldsForQuery.find(a => a.fieldPath === path);
1435
- if (leaf && !filterArrayFields.some(f => f?.fieldPath === leaf.fieldPath)) {
1436
- filterArrayFields.push(leaf);
1437
- }
1438
- }
1439
- });
1440
- });
1441
-
1442
- if (ors.length) {
1443
- const filterObj = {$or: ors};
1444
- if (hasArrayTarget) {
1445
- filterArrays.push(filterObj);
1446
- }
1447
- else {
1448
- filters.push(filterObj);
1449
- }
1450
- }
1451
- });
1452
-
1453
- const res = await this.callMethod('reportBuilderGetResults', report.type, report.collection_root, rootOptions, filters, filterArrays, filterArrayFields, selectedFieldsForQuery, report.fields_custom, report.groups_row, totalsForQuery, report.fields_link, report.id_date_field || null, report.date_interval || null, report.group_type);
1454
-
1455
- if (res && res[0]) {
1456
- let results = res[0].results;
1457
- let reportTotals = res[0].totals;
1458
-
1459
- if (report.type === 'Group') {
1460
- applyClientGroupSortToData(results, report, effectiveSorts);
1461
- }
1462
-
1463
- const customFields = (report.fields_custom || []).map(cust => ({
1464
- ...cust,
1465
- id: cust.selFieldId,
1466
- fieldType: 'Number',
1467
- leafValueType: cust.leafValueType || 'Value',
1468
- leafFormatType: 'Number',
1469
- columnName: cust.columnName || cust.id,
1470
- show: true
1471
- }));
1472
-
1473
- const exportFields = report.fields_selected.filter(a => a.show).concat((<any>customFields));
1474
-
1475
- if (report.type === 'List') {
1476
- exportFields.forEach(field => {
1477
- if ((field.fieldType === 'Number' || field.leafValueType === 'Count') && field.leafFormatType === 'Number') {
1478
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined ).forEach(result => {
1479
- result[field.id] = result[field.id].toLocaleString();
1480
- });
1481
- }
1482
- else if ((field.fieldType === 'Number' || field.leafValueType === 'Count') && field.leafFormatType === 'String') {
1483
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1484
- result[field.id] = result[field.id].toLocaleString('en-US', { style: 'currency', currency: 'USD' });
1485
- });
1486
- }
1487
- else if ((field.fieldType === 'Number' || field.leafValueType === 'Count') && field.leafFormatType === 'Currency') {
1488
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1489
- result[field.id] = round(result[field.id], 2).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
1490
- });
1491
- }
1492
- else if (field.fieldType === 'Boolean' && (!field.leafFormatType || field.leafFormatType === 'Boolean')) {
1493
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1494
- result[field.id] = result[field.id] === true ? 'True' : 'False';
1495
- });
1496
- }
1497
- else if (field.fieldType === 'Boolean' && field.leafFormatType === 'String') {
1498
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1499
- result[field.id] = result[field.id] === true ? 'Yes' : 'No';
1500
- });
1501
- }
1502
- else if (field.fieldType === 'Boolean' && field.leafFormatType === 'Boolean_Number') {
1503
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1504
- result[field.id] = result[field.id] === true ? 1 : 0;
1505
- });
1506
- }
1507
- else if (field.fieldType === 'Date' && (field.leafFormatType === 'Date')) {
1508
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1509
- result[field.id] = moment(result[field.id]).format('L');
1510
- });
1511
- }
1512
- else if (field.fieldType === 'Date' && field.leafFormatType === 'Time') {
1513
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1514
- result[field.id] = moment(result[field.id]).format('LT');
1515
- });
1516
- }
1517
- else if (field.fieldType === 'Date' && field.leafFormatType === 'DateTime') {
1518
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1519
- result[field.id] = moment(result[field.id]).format('MM/DD/YYYY h:mm A');
1520
- });
1521
- }
1522
- else if (field.fieldType === 'Date' && field.leafFormatType === 'Date_long') {
1523
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1524
- result[field.id] = moment(result[field.id]).format('LL');
1525
- });
1526
- }
1527
- else if (field.fieldType === 'Date' && field.leafFormatType === 'DateTime_long') {
1528
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1529
- result[field.id] = moment(result[field.id]).format('LLL');
1530
- });
1531
- }
1532
- else if (field.fieldType === 'Date' && field.leafFormatType === 'Timestamp') {
1533
- results.filter(a => a[field.id] !== null && a[field.id] !== undefined).forEach(result => {
1534
- result[field.id] = moment(result[field.id]).toDate().getTime();
1535
- });
1536
- }
1537
- });
1538
-
1539
- let wb = new Excel.Workbook();
1540
- let ws = wb.addWorksheet('RB_1', {views: [{showGridLines: true}]});
1541
- wb.properties.date1904 = false;
1542
- wb.calcProperties.fullCalcOnLoad = true;
1543
-
1544
- let currentRow = 1;
1545
- let row = ws.getRow(currentRow);
1546
-
1547
- row.getCell(2).font = {
1548
- name: 'Arial',
1549
- bold: true,
1550
- size: 14
1551
- };
1552
- row.getCell(4).font = {
1553
- name: 'Arial',
1554
- size: 14
1555
- };
1556
- row.getCell(2).value = 'Report Name:';
1557
- row.getCell(4).value = report.report_name;
1558
-
1559
- currentRow += 1;
1560
- row = ws.getRow(currentRow);
1561
-
1562
- row.getCell(2).font = {
1563
- name: 'Arial',
1564
- bold: true,
1565
- size: 14
1566
- };
1567
- row.getCell(4).font = {
1568
- name: 'Arial',
1569
- size: 14
1570
- };
1571
- row.getCell(2).value = 'Run Date:';
1572
- row.getCell(4).value = moment().format('LLL');
1573
-
1574
- currentRow += 2;
1575
- row = ws.getRow(currentRow);
1576
-
1577
- const useLayout = (layoutColumns && layoutColumns.length > 0);
1578
- const headers: string[] = [];
1579
-
1580
- report.groups_row.forEach(group => {
1581
- headers.push(group.columnName);
1582
- });
1583
-
1584
- if (useLayout) {
1585
- layoutColumns.forEach((col, idx) => {
1586
- headers.push(col.header || `Column ${idx + 1}`);
1587
- });
1588
- }
1589
- else {
1590
- exportFields.forEach(field => {
1591
- headers.push(field.columnName);
1592
- });
1593
- }
1594
-
1595
- headers.forEach((header, headerIdx) => {
1596
- row.getCell(headerIdx + 1).value = header;
1597
- });
1598
-
1599
- currentRow += 1;
1600
- row = ws.getRow(currentRow);
1601
-
1602
- const exportResults = deepCopy(results || []);
1603
-
1604
- exportResults.forEach(result => {
1605
- let currentCol = 1;
1606
-
1607
- report.groups_row.forEach(group => {
1608
- writeExcelCell(row.getCell(currentCol), result?._id?.[group.id] ?? '', group.treeItem);
1609
- currentCol += 1;
1610
- });
1611
-
1612
- if (useLayout) {
1613
- const layoutRow = materializeLayoutRow(report, layoutColumns, report.fields_selected, result);
1614
- layoutColumns.forEach((col, colIdx) => {
1615
- const cellValue = getLayoutCellExportValue(report, layoutRow, colIdx);
1616
- const primaryFieldMeta = getPrimaryFieldForLayoutColumn(col, report.fields_selected);
1617
- writeExcelCell(row.getCell(currentCol), cellValue === undefined ? '' : cellValue, primaryFieldMeta);
1618
- currentCol += 1;
1619
- });
1620
- }
1621
- else {
1622
- exportFields.forEach(field => {
1623
- writeExcelCell(row.getCell(currentCol), result[field.id] ?? '', field);
1624
- currentCol += 1;
1625
- });
1626
- }
1627
-
1628
- currentRow += 1;
1629
- row = ws.getRow(currentRow);
1630
- });
1631
-
1632
- try {
1633
- let buffer = await wb.xlsx.writeBuffer();
1634
- for (let email of data['emails']) {
1635
- await this.sendEmail(email,
1636
- this.serverConfig['CLIENT_NAME'] + ' Scheduled Report - ' + report.report_name,
1637
- '',
1638
- `
1639
- <b>` + this.serverConfig['CLIENT_NAME'] + ` Automated Report</b><br>
1640
- <b>Report Name: </b>` + report.report_name + `<br>
1641
- <b>Prepared By: </b>` + data['user'] + `<br><br>
1642
- Attached are the results of this automated report.<br><br>
1643
- ResolveIO<br><br>`,
1644
- [
1645
- {
1646
- filename: report.report_name + '-' + moment().format('MM-DD-YYYY-hh-mm-A') + '.xlsx',
1647
- content: buffer
1648
- }
1649
- ],
1650
- this.serverConfig['MAIL_FROM_REPORTS'],
1651
- ''
1652
- );
1653
- }
1654
- }
1655
- catch (err) {
1656
- console.log('Error writing excel export', err);
1657
- }
1658
- }
1659
- else if (report.type === 'Group') {
1660
- exportFields.forEach(field => {
1661
- results.forEach(result => {
1662
- modifyDataTypeField(report, result, field, 1);
1663
- });
1664
- });
1665
-
1666
- let wb = new Excel.Workbook();
1667
- let ws = wb.addWorksheet('RB_1', {views: [{showGridLines: false}]});
1668
- wb.properties.date1904 = false;
1669
- wb.calcProperties.fullCalcOnLoad = true;
1670
-
1671
- let currentRow = 1;
1672
- let row = ws.getRow(currentRow);
1673
-
1674
- row.getCell(2).font = {
1675
- name: 'Arial',
1676
- bold: true,
1677
- size: 14
1678
- };
1679
- row.getCell(4).font = {
1680
- name: 'Arial',
1681
- size: 14
1682
- };
1683
- row.getCell(2).value = 'Report Name:';
1684
- row.getCell(4).value = report.report_name;
1685
-
1686
- currentRow += 1;
1687
- row = ws.getRow(currentRow);
1688
-
1689
- row.getCell(2).font = {
1690
- name: 'Arial',
1691
- bold: true,
1692
- size: 14
1693
- };
1694
- row.getCell(4).font = {
1695
- name: 'Arial',
1696
- size: 14
1697
- };
1698
- row.getCell(2).value = 'Run Date:';
1699
- row.getCell(4).value = moment().format('LLL');
1700
-
1701
- currentRow += 2;
1702
-
1703
- let copy = deepCopy(results);
1704
- let widths = [];
1705
- copy.forEach(res => {
1706
- currentRow = tabGroupExcelRecursive(report, ws, currentRow, 1, res, exportFields);
1707
- tabGroupExcelWidthRecursive(report, 1, res, widths, exportFields);
1708
- });
1709
-
1710
- for (let i = 1; i < ws.columns.length; i++) {
1711
- ws.columns[i].width = widths[i - 1];
1712
- }
1713
-
1714
- let now = new Date();
1715
-
1716
- try {
1717
- let buffer = await wb.xlsx.writeBuffer();
1718
- for (let email of data['emails']) {
1719
- await this.sendEmail(email,
1720
- this.serverConfig['CLIENT_NAME'] + ' Scheduled Report - ' + report.report_name,
1721
- '',
1722
- `
1723
- <b>` + this.serverConfig['CLIENT_NAME'] + ` Automated Report</b><br>
1724
- <b>Report Name: </b>` + report.report_name + `<br>
1725
- <b>Prepared By: </b>` + data['user'] + `<br><br>
1726
- Attached are the results of this automated report.<br><br>
1727
- Have a great day!<br><br>
1728
- ResolveIO<br><br>`,
1729
- [
1730
- {
1731
- filename: 'Group_Report_' + report.report_name + '_' + now.getFullYear() + '_' + (now.getMonth() + 1) + '_' + now.getDate() + '.xlsx',
1732
- content: buffer
1733
- }
1734
- ],
1735
- this.serverConfig['MAIL_FROM_REPORTS'],
1736
- ''
1737
- );
1738
- }
1739
- }
1740
- catch (err) {
1741
- console.log('Error writing excel export', err)
1742
- };
1743
- }
1744
- else if (report.type === 'Dated') {
1745
- let datedUniqueDates = [];
1746
- let datedUniqueGroups = [];
1747
- let datedData = [];
1748
- let reportTotalGroups = [];
1749
- let reportTotalDates = [];
1750
-
1751
- // Step 1: Handle quarterly dates if applicable
1752
- if (report.date_interval === 'Quarterly') {
1753
- results.forEach(dataPt => {
1754
- if (dataPt._id.month < 4) {
1755
- dataPt._id.quarter = 1;
1756
- }
1757
- else if (dataPt._id.month < 7) {
1758
- dataPt._id.quarter = 2;
1759
- }
1760
- else if (dataPt._id.month < 10) {
1761
- dataPt._id.quarter = 3;
1762
- }
1763
- else {
1764
- dataPt._id.quarter = 4;
1765
- }
1766
-
1767
- delete dataPt._id.month;
1768
- });
1769
-
1770
- // Deduplicate quarterly data
1771
- for (let i = results.length - 1; i >= 1; i--) {
1772
- let dataPt = results[i];
1773
- if (results.filter(a => JSON.stringify(a._id) === JSON.stringify(dataPt._id)).length > 1) {
1774
- let tmpData = results.find(a => JSON.stringify(a._id) === JSON.stringify(dataPt._id));
1775
-
1776
- Object.keys(tmpData)
1777
- .filter(a => a !== '_id')
1778
- .forEach(key => {
1779
- tmpData[key] += dataPt[key];
1780
- });
1781
-
1782
- results.splice(i, 1); // Remove the duplicate entry
1783
- }
1784
- }
1785
- }
1786
-
1787
- // Step 2: Prepare unique groups
1788
- let tmpResults = deepCopy(results);
1789
- tmpResults.forEach(result => {
1790
- delete result._id.day;
1791
- delete result._id.week;
1792
- delete result._id.month;
1793
- delete result._id.quarter;
1794
- delete result._id.year;
1795
-
1796
- let tmpGroup = {};
1797
- Object.keys(result._id).forEach(key => {
1798
- tmpGroup[key] = result._id[key];
1799
- });
1800
-
1801
- if (!datedUniqueGroups.find(a => JSON.stringify(a) === JSON.stringify(tmpGroup))) {
1802
- datedUniqueGroups.push(tmpGroup);
1803
- }
1804
- });
1805
-
1806
- // Step 3: Prepare unique dates
1807
- tmpResults = deepCopy(results);
1808
- tmpResults.forEach(result => {
1809
- Object.keys(result._id)
1810
- .filter(a => a !== 'second' && a !== 'hour' && a !== 'minute' && a !== 'day' && a !== 'week' && a !== 'month' && a !== 'quarter' && a !== 'year')
1811
- .forEach(key => {
1812
- delete result._id[key];
1813
- });
1814
-
1815
- let tmpDate = {};
1816
- Object.keys(result._id).forEach(key => {
1817
- tmpDate[key] = result._id[key];
1818
- });
1819
-
1820
- if (!datedUniqueDates.find(a => JSON.stringify(a) === JSON.stringify(tmpDate))) {
1821
- datedUniqueDates.push(tmpDate);
1822
- }
1823
- });
1824
-
1825
- // Build the date strings
1826
- // Ensure moment is using America/Chicago timezone for all date processing
1827
- datedUniqueDates.forEach(result => {
1828
- if (!result.year) {
1829
- result.dateString = 'No Date';
1830
- }
1831
- else {
1832
- if (report.date_interval === 'Seconds') {
1833
- result.date = moment.tz({
1834
- year: result.year,
1835
- month: result.month - 1, // Use `month - 1` since months are zero-indexed in moment as well
1836
- day: result.day,
1837
- hour: result.hour,
1838
- minute: result.minute,
1839
- second: result.second
1840
- }, (process.env.TZ_CLIENT || 'America/Chicago')).toDate();
1841
- result.dateString = moment(result.date).format('MMM DD YYYY HH:mm:ss');
1842
- }
1843
- else if (report.date_interval === 'Minutes') {
1844
- result.date = moment.tz({
1845
- year: result.year,
1846
- month: result.month - 1,
1847
- day: result.day,
1848
- hour: result.hour,
1849
- minute: result.minute
1850
- }, (process.env.TZ_CLIENT || 'America/Chicago')).toDate();
1851
- result.dateString = moment(result.date).format('MMM DD YYYY HH:mm');
1852
- }
1853
- else if (report.date_interval === 'Hours') {
1854
- result.date = moment.tz({
1855
- year: result.year,
1856
- month: result.month - 1,
1857
- day: result.day,
1858
- hour: result.hour
1859
- }, (process.env.TZ_CLIENT || 'America/Chicago')).toDate();
1860
- result.dateString = moment(result.date).format('MMM DD YYYY HH');
1861
- }
1862
- else if (report.date_interval === 'Daily') {
1863
- result.date = moment.tz({
1864
- year: result.year,
1865
- month: result.month - 1,
1866
- day: result.day
1867
- }, (process.env.TZ_CLIENT || 'America/Chicago')).toDate();
1868
- result.dateString = moment(result.date).format('MMM DD YYYY');
1869
- }
1870
- else if (report.date_interval === 'Weekly') {
1871
- result.date = moment.tz({
1872
- year: result.year,
1873
- week: result.week
1874
- }, (process.env.TZ_CLIENT || 'America/Chicago')).day('Monday').toDate();
1875
- result.dateLast = moment.tz({
1876
- year: result.year,
1877
- week: result.week
1878
- }, (process.env.TZ_CLIENT || 'America/Chicago')).day('Sunday').toDate();
1879
- result.dateString = 'Week #' + result.week + ' ' + result.year + ' (' + moment(result.date).format('MM/DD/YY') + ' - ' + moment(result.dateLast).format('MM/DD/YY') + ')';
1880
- }
1881
- else if (report.date_interval === 'Monthly') {
1882
- result.date = moment.tz({
1883
- year: result.year,
1884
- month: result.month - 1, // Months are zero-indexed in moment
1885
- }, (process.env.TZ_CLIENT || 'America/Chicago')).toDate();
1886
- result.dateString = moment(result.date).format('MMM YYYY');
1887
- }
1888
- else if (report.date_interval === 'Quarterly') {
1889
- result.date = moment.tz({
1890
- year: result.year
1891
- }, (process.env.TZ_CLIENT || 'America/Chicago')).quarter(result.quarter).toDate();;
1892
- result.dateString = 'Q' + result.quarter + ' ' + result.year;
1893
- }
1894
- else if (report.date_interval === 'Yearly') {
1895
- result.date = moment.tz({
1896
- year: result.year
1897
- }, (process.env.TZ_CLIENT || 'America/Chicago')).toDate();
1898
- result.dateString = result.year.toString();
1899
- }
1900
- }
1901
- });
1902
-
1903
- datedUniqueDates = datedUniqueDates.filter(a => !a.date)
1904
- .concat(datedUniqueDates.filter(a => a.date).sort((a, b) => a.date.getTime() - b.date.getTime()));
1905
-
1906
- // Step 4: Build datedData and reportTotalGroups
1907
- datedUniqueDates.forEach(date => {
1908
- let tmpData = [];
1909
- let tmpTotalDated = {};
1910
- let tmpTotalCnt = {};
1911
- let tmpTotalType = {};
1912
-
1913
- datedUniqueGroups.forEach(group => {
1914
- let result = results.find(a => {
1915
- let match = true;
1916
-
1917
- // Match the group fields
1918
- Object.keys(group).forEach(key => {
1919
- if (a._id[key] !== group[key]) {
1920
- match = false;
1921
- }
1922
- });
1923
-
1924
- // Match the date fields
1925
- Object.keys(date).filter(key => key !== 'date' && key !== 'dateLast' && key !== 'dateString').forEach(key => {
1926
- if (a._id[key] !== date[key]) {
1927
- match = false;
1928
- }
1929
- });
1930
-
1931
- return match;
1932
- });
1933
-
1934
- if (result) {
1935
- tmpData.push(result);
1936
-
1937
- Object.keys(result._id).filter(a => a).forEach(key => {
1938
- if (report.fields_total.filter(a => a.fields.includes(key)).length) {
1939
- if (!tmpTotalDated[key]) {
1940
- tmpTotalDated[key] = result._id[key];
1941
- }
1942
- else {
1943
- tmpTotalDated[key] += result._id[key];
1944
- }
1945
-
1946
- if (!tmpTotalCnt[key]) {
1947
- tmpTotalCnt[key] = 1;
1948
- }
1949
- else {
1950
- tmpTotalCnt[key] += 1;
1951
- }
1952
-
1953
- tmpTotalType[key] = report.fields_total.find(a => a.fields.includes(key)).type;
1954
- }
1955
- });
1956
-
1957
- Object.keys(result).filter(a => a && a !== '_id').forEach(key => {
1958
- if (report.fields_total.filter(a => a.fields.includes(key)).length) {
1959
- if (!tmpTotalDated[key]) {
1960
- tmpTotalDated[key] = result[key];
1961
- }
1962
- else {
1963
- tmpTotalDated[key] += result[key];
1964
- }
1965
-
1966
- if (!tmpTotalCnt[key]) {
1967
- tmpTotalCnt[key] = 1;
1968
- }
1969
- else {
1970
- tmpTotalCnt[key] += 1;
1971
- }
1972
-
1973
- tmpTotalType[key] = report.fields_total.find(a => a.fields.includes(key)).type;
1974
- }
1975
- });
1976
- }
1977
- else {
1978
- tmpData.push(null);
1979
- }
1980
- });
1981
-
1982
- // Handle averaging for totals
1983
- Object.keys(tmpTotalType).forEach(totalKey => {
1984
- if (tmpTotalType[totalKey] === 'avg') {
1985
- tmpTotalDated[totalKey] = tmpTotalDated[totalKey] / tmpTotalCnt[totalKey];
1986
- }
1987
-
1988
- tmpTotalDated[totalKey] = round(tmpTotalDated[totalKey], 2);
1989
- });
1990
-
1991
- reportTotalDates.push(tmpTotalDated);
1992
- datedData.push(tmpData);
1993
- });
1994
-
1995
- // Calculate group-level totals
1996
- datedUniqueGroups.forEach(group => {
1997
- let tmpTotalGroup = {};
1998
- let filteredData = results.filter(a => {
1999
- let match = (!Object.keys(group).length || group._id === null) ? false : true;
2000
- Object.keys(group).filter(a => a !== 'date' && a !== 'dateLast' && a !== 'dateString' && a !== 'second' && a !== 'minute' && a !== 'hour' && a !== 'day' && a !== 'week' && a !== 'month' && a !== 'quarter' && a !== 'year').forEach(key => {
2001
- if (a._id[key] !== group[key]) {
2002
- match = false;
2003
- }
2004
- });
2005
- return match;
2006
- });
2007
-
2008
- report.fields_total.forEach(total => {
2009
- total.fields.forEach(field => {
2010
- if (filteredData.length) {
2011
- tmpTotalGroup[field] = filteredData.filter(a => a && a[field])
2012
- .map(a => a[field])
2013
- .reduce((a, b) => a + b, 0);
2014
-
2015
- if (total.type === 'avg') {
2016
- tmpTotalGroup[field] = round(tmpTotalGroup[field] / filteredData.length, 2);
2017
- }
2018
- }
2019
- else {
2020
- tmpTotalGroup[field] = 0;
2021
- }
2022
- });
2023
- });
2024
-
2025
- reportTotalGroups.push(tmpTotalGroup);
2026
- });
2027
-
2028
- // Step 5: Proceed with Excel generation using datedData and reportTotalGroups
2029
- let wb = new Excel.Workbook();
2030
- let ws = wb.addWorksheet('Dated_Report', {views: [{showGridLines: true}]});
2031
- wb.properties.date1904 = false;
2032
- wb.calcProperties.fullCalcOnLoad = true;
2033
-
2034
- let currentRow = 1;
2035
- let currentCol = 1;
2036
- let row = ws.getRow(currentRow);
2037
-
2038
- row.getCell(2).font = {
2039
- name: 'Arial',
2040
- bold: true,
2041
- size: 14
2042
- };
2043
- row.getCell(4).font = {
2044
- name: 'Arial',
2045
- size: 14
2046
- };
2047
- row.getCell(2).value = 'Report Name:';
2048
- row.getCell(4).value = report.report_name;
2049
-
2050
- currentRow += 1;
2051
- row = ws.getRow(currentRow);
2052
-
2053
- row.getCell(2).font = {
2054
- name: 'Arial',
2055
- bold: true,
2056
- size: 14
2057
- };
2058
- row.getCell(4).font = {
2059
- name: 'Arial',
2060
- size: 14
2061
- };
2062
- row.getCell(2).value = 'Run Date:';
2063
- row.getCell(4).value = moment().format('LLL');
2064
-
2065
- currentRow += 2;
2066
- row = ws.getRow(currentRow);
2067
-
2068
- // Add group column headers
2069
- report.groups_row.forEach(group => {
2070
- row.getCell(currentCol).value = group.columnName;
2071
- currentCol++;
2072
- });
2073
-
2074
- // Add field headers
2075
- currentCol += report.fields_selected.filter(a => a.show).length;
2076
-
2077
- // Add the date interval headers
2078
- report.fields_selected.filter(a => a.show).forEach(() => {
2079
- datedUniqueDates.forEach(date => {
2080
- row.getCell(currentCol).value = date.dateString;
2081
- currentCol++;
2082
- });
2083
- });
2084
-
2085
- // Add totals headers
2086
- report.fields_total.forEach(total => {
2087
- row.getCell(currentCol).value = 'Totals - ' + toTitleCase(total.type);
2088
- currentCol++;
2089
- });
2090
-
2091
- currentCol = 1;
2092
- currentRow += 1;
2093
- row = ws.getRow(currentRow);
2094
-
2095
- // Populate data for each group and field with date intervals
2096
- for (let i = 0; i < datedUniqueGroups.length; i++) {
2097
- let group = datedUniqueGroups[i];
2098
-
2099
- for (let j = 0; j < report.fields_selected.filter(a => a.show).length; j++) {
2100
- let field = report.fields_selected.filter(a => a.show)[j];
2101
-
2102
- currentCol = 1;
2103
- row = ws.getRow(currentRow);
2104
-
2105
- // Populate group data
2106
- report.groups_row.forEach(groupRow => {
2107
- row.getCell(currentCol).value = (j === 0) ? group[groupRow.id] : '';
2108
- currentCol++;
2109
- });
2110
-
2111
- // Populate field data
2112
- row.getCell(currentCol).value = field.columnName;
2113
- currentCol++;
2114
-
2115
- // Populate date interval data for each field
2116
- for (let k = 0; k < datedUniqueDates.length; k++) {
2117
- let result = datedData[k];
2118
- if (result[i]) {
2119
- row.getCell(currentCol).value = result[i][field.id] ? result[i][field.id] : '';
2120
- }
2121
- else {
2122
- row.getCell(currentCol).value = '';
2123
- }
2124
- currentCol++;
2125
- }
2126
-
2127
- // Add totals for each field in the report
2128
- for (let k = 0; k < report.fields_total.length; k++) {
2129
- row.getCell(currentCol).value = reportTotalGroups[i][field.id] ? reportTotalGroups[i][field.id] : '';
2130
- currentCol++;
2131
- }
2132
-
2133
- currentRow++; // Move to the next row for the next field
2134
- }
2135
- }
2136
-
2137
- // Add report totals at the bottom
2138
- if (reportTotals) {
2139
- for (let i = 0; i < report.fields_total.length; i++) {
2140
- let total = report.fields_total[i];
2141
- row = ws.getRow(currentRow);
2142
- currentCol = 1;
2143
-
2144
- row.getCell(currentCol).value = toTitleCase(total.type) + ' Totals';
2145
- currentCol += report.groups_row.length; // Skip group columns
2146
-
2147
- // Skip the date columns for the totals row
2148
- report.fields_selected.filter(a => a.show).forEach(() => {
2149
- currentCol += 1;
2150
- });
2151
-
2152
- datedUniqueDates.forEach(() => {
2153
- currentCol++;
2154
- });
2155
-
2156
- // Set totals in the correct fields
2157
- for (let j = 0; j < report.fields_selected.filter(a => a.show).length; j++) {
2158
- let field = report.fields_selected.filter(a => a.show)[j];
2159
- row.getCell(currentCol).value = reportTotals[total.id + '_' + field.id] || '';
2160
- currentCol++;
2161
- }
2162
-
2163
- currentRow++; // Move to the next row for the next total
2164
- }
2165
- }
2166
-
2167
- try {
2168
- // Save the Excel file and send it via email
2169
- let buffer = await wb.xlsx.writeBuffer();
2170
- for (let email of data['emails']) {
2171
- await this.sendEmail(
2172
- email,
2173
- this.serverConfig['CLIENT_NAME'] + ' Scheduled Report - ' + report.report_name,
2174
- '',
2175
- `
2176
- <b>${this.serverConfig['CLIENT_NAME']} Automated Report</b><br>
2177
- <b>Report Name: </b>${report.report_name}<br>
2178
- <b>Prepared By: </b>${data['user']}<br><br>
2179
- Attached are the results of this automated report.<br><br>
2180
- ResolveIO<br><br>`,
2181
- [
2182
- {
2183
- filename: report.report_name + '-' + moment().format('MM-DD-YYYY-hh-mm-A') + '.xlsx',
2184
- content: buffer
2185
- }
2186
- ],
2187
- this.serverConfig['MAIL_FROM_REPORTS'],
2188
- ''
2189
- );
2190
- }
2191
- }
2192
- catch (err) {
2193
- console.log('Error writing excel export', err);
2194
- }
2195
-
2196
- return true;
2197
- }
2198
- }
2199
- }
2200
- }
2201
- catch (err) {
2202
- err.message = `Error in Report Builder Cron Job - Report Builder Build Tree: ${err.message}`;
2203
- throw err;
2204
- }
2205
-
2206
- return true;
2207
- }
2208
- }
2209
- });
2210
- }
2211
-
2212
- function modifyDataTypeField(report, result, field, index) {
2213
- const processFieldValue = (value, field) => {
2214
- if (value === undefined || value === null) {
2215
- return '';
2216
- }
2217
-
2218
- if (field.fieldType === 'Boolean') {
2219
- if (!field.leafFormatType || field.leafFormatType === 'Boolean') {
2220
- return value === true ? 'True' : 'False';
2221
- }
2222
- else if (field.leafFormatType === 'String') {
2223
- return value === true ? 'Yes' : 'No';
2224
- }
2225
- else if (field.leafFormatType === 'Boolean_Number') {
2226
- return value === true ? 1 : 0;
2227
- }
2228
- }
2229
- else if (field.fieldType === 'Number' || field.leafValueType === 'Count') {
2230
- if (field.leafFormatType === 'Number') {
2231
- return value.toLocaleString();
2232
- }
2233
- else if (field.leafFormatType === 'String') {
2234
- return value.toString();
2235
- }
2236
- else if (field.leafFormatType === 'Currency') {
2237
- return round(value, 2).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
2238
- }
2239
- }
2240
- else if (field.fieldType === 'Date') {
2241
- switch (field.leafFormatType) {
2242
- case 'Date':
2243
- return moment(value).format('L');
2244
- case 'Time':
2245
- return moment(value).format('LT');
2246
- case 'DateTime':
2247
- return moment(value).format('MM/DD/YYYY h:mm A');
2248
- case 'Date_long':
2249
- return moment(value).format('LL');
2250
- case 'DateTime_long':
2251
- return moment(value).format('LLL');
2252
- case 'Timestamp':
2253
- return moment(value).toDate().getTime();
2254
- default:
2255
- return value;
2256
- }
2257
- }
2258
-
2259
- return value;
2260
- };
2261
-
2262
- const processArrayField = (array, field) => {
2263
- return array.map(value => processFieldValue(value, field));
2264
- };
2265
-
2266
- if (index < report.groups_row.length) {
2267
- // Handle grouped data
2268
- const groupKey = 'gr_' + (index + 1);
2269
- if (result[groupKey]) {
2270
- result[groupKey].forEach(subResult => {
2271
- modifyDataTypeField(report, subResult, field, index + 1);
2272
- });
2273
- }
2274
- }
2275
- else {
2276
- // Process final-level fields
2277
- if (Array.isArray(result[field.id])) {
2278
- result[field.id] = processArrayField(result[field.id], field);
2279
- }
2280
- else {
2281
- result[field.id] = processFieldValue(result[field.id], field);
2282
- }
2283
- }
2284
- }
2285
-
2286
- function tabGroupExcelRecursive(report, ws: Excel.Worksheet, currentRow, level, result, fields) {
2287
- let row = ws.getRow(currentRow);
2288
- const fieldCount = fields.length;
2289
-
2290
- if (level < report.groups_row.length) {
2291
- row.getCell(2).fill = {
2292
- fgColor: {argb: report.groups_row[level - 1].fill_color ? report.groups_row[level - 1].fill_color.replace('#', '') : 'ffffff'},
2293
- type: 'pattern',
2294
- pattern: 'solid'
2295
- };
2296
- row.getCell(2).font = {
2297
- color: {argb: report.groups_row[level - 1].font_color ? report.groups_row[level - 1].font_color.replace('#', '') : '000000'},
2298
- name: 'Arial',
2299
- bold: true,
2300
- size: 14
2301
- };
2302
-
2303
- const currentGroup = report.groups_row[level - 1];
2304
- row.getCell(2).value = currentGroup.columnName + ': ' + (result._id[currentGroup.id] || '');
2305
- ws.mergeCells(row.getCell(2).$col$row + ':' + row.getCell(fieldCount + 1).$col$row);
2306
-
2307
- row.getCell(2).border = {
2308
- top: {style:'thick'},
2309
- left: {style:'thick'},
2310
- right: {style: 'thick'}
2311
- };
2312
-
2313
- if (report.fields_total.length) {
2314
- report.fields_total.forEach(total => {
2315
- currentRow += 1;
2316
- row = ws.getRow(currentRow);
2317
-
2318
- fields.forEach((field, fieldIndex) => {
2319
- if (total.fields.includes(field.id)) {
2320
- row.getCell(fieldIndex + 2).value = field.columnName;
2321
-
2322
- row.getCell(fieldIndex + 2).font = {
2323
- name: 'Arial',
2324
- bold: true,
2325
- size: 10
2326
- };
2327
- }
2328
-
2329
- if (field.leafFormatType === 'Currency') {
2330
- row.getCell(fieldIndex + 2).numFmt = '"$"#,##0.00';
2331
- }
2332
- else if (field.leafFormatType === 'Number') {
2333
- row.getCell(fieldIndex + 2).numFmt = '#,##0';
2334
- }
2335
-
2336
- if (fieldIndex === 0) {
2337
- row.getCell(fieldIndex + 2).border = {
2338
- left: {style:'thick'}
2339
- };
2340
- }
2341
- else if (fieldIndex === fieldCount - 1) {
2342
- row.getCell(fieldIndex + 2).border = {
2343
- right: {style:'thick'}
2344
- };
2345
- }
2346
- });
2347
- });
2348
- }
2349
-
2350
- // Totals
2351
- report.fields_total.forEach(total => {
2352
- currentRow += 1;
2353
- row = ws.getRow(currentRow);
2354
-
2355
- fields.forEach((field, fieldIndex) => {
2356
- if (total.fields.includes(field.id)) {
2357
- row.getCell(fieldIndex + 2).value = result[total.id + '_' + field.id];
2358
-
2359
- row.getCell(fieldIndex + 2).font = {
2360
- name: 'Arial',
2361
- bold: true,
2362
- size: 10
2363
- };
2364
-
2365
- if (field.leafFormatType === 'Currency') {
2366
- row.getCell(fieldIndex + 2).numFmt = '"$"#,##0.00';
2367
- }
2368
- else if (field.leafFormatType === 'Number') {
2369
- row.getCell(fieldIndex + 2).numFmt = '#,##0';
2370
- }
2371
- }
2372
-
2373
- if (fieldIndex === 0) {
2374
- row.getCell(fieldIndex + 2).border = {
2375
- top: {style:'thin'},
2376
- left: {style:'thick'},
2377
- bottom: {style:'thick'}
2378
- };
2379
- }
2380
- else if (fieldIndex === fieldCount - 1) {
2381
- row.getCell(fieldIndex + 2).border = {
2382
- top: {style:'thin'},
2383
- bottom: {style:'thick'},
2384
- right: {style:'thick'}
2385
- };
2386
- }
2387
- else {
2388
- row.getCell(fieldIndex + 2).border = {
2389
- top: {style:'thin'},
2390
- bottom: {style:'thick'}
2391
- };
2392
- }
2393
- });
2394
- });
2395
-
2396
- currentRow += 1;
2397
-
2398
- const nextGroup = report.groups_row[level];
2399
- if (nextGroup) {
2400
- const nextResults = result[nextGroup.id];
2401
- if (Array.isArray(nextResults)) {
2402
- nextResults.forEach(tDataRes => {
2403
- currentRow = tabGroupExcelRecursive(report, ws, currentRow, level + 1, tDataRes, fields);
2404
- });
2405
- }
2406
- }
2407
- }
2408
- else {
2409
- row.getCell(2).fill = {
2410
- fgColor: {argb: report.groups_row[level - 1].fill_color ? report.groups_row[level - 1].fill_color.replace('#', '') : 'ffffff'},
2411
- type: 'pattern',
2412
- pattern: 'solid'
2413
- };
2414
- row.getCell(2).font = {
2415
- color: {argb: report.groups_row[level - 1].font_color ? report.groups_row[level - 1].font_color.replace('#', '') : '000000'},
2416
- name: 'Arial',
2417
- bold: true,
2418
- size: 12
2419
- };
2420
-
2421
- const finalGroup = report.groups_row[level - 1];
2422
- row.getCell(2).value = finalGroup.columnName + ': ' + (result._id[finalGroup.id] || '');
2423
- ws.mergeCells(row.getCell(2).$col$row + ':' + row.getCell(fieldCount + 1).$col$row);
2424
-
2425
- row.getCell(2).border = {
2426
- top: {style:'thick'},
2427
- left: {style:'thick'},
2428
- right: {style: 'thick'}
2429
- };
2430
-
2431
- currentRow += 1;
2432
- row = ws.getRow(currentRow);
2433
- // Headers
2434
- fields.forEach((field, fieldIndex) => {
2435
- row.getCell(fieldIndex + 2).value = field.columnName;
2436
- row.getCell(fieldIndex + 2).font = {
2437
- name: 'Arial',
2438
- bold: true,
2439
- size: 10
2440
- };
2441
-
2442
- if (field.leafFormatType === 'Currency') {
2443
- row.getCell(fieldIndex + 2).numFmt = '"$"#,##0.00';
2444
- }
2445
- else if (field.leafFormatType === 'Number') {
2446
- row.getCell(fieldIndex + 2).numFmt = '#,##0';
2447
- }
2448
-
2449
- if (fieldIndex === 0) {
2450
- row.getCell(fieldIndex + 2).border = {
2451
- left: {style:'thick'}
2452
- };
2453
- }
2454
- else if (fieldIndex === fieldCount - 1) {
2455
- row.getCell(fieldIndex + 2).border = {
2456
- right: {style:'thick'}
2457
- };
2458
- }
2459
- });
2460
-
2461
- // Data
2462
- getMaxRows(result).forEach((res, resIndex) => {
2463
- currentRow += 1;
2464
- row = ws.getRow(currentRow);
2465
-
2466
- fields.forEach((field, fieldIndex) => {
2467
- let value = null;
2468
-
2469
- if (Array.isArray(result[field.id])) {
2470
- value = result[field.id][resIndex] !== undefined ? result[field.id][resIndex] : result[field.id][result[field.id].length - 1];
2471
- }
2472
- else {
2473
- value = result[field.id];
2474
- }
2475
-
2476
- if (field.fieldType === 'Number' && typeof(value) === 'string' && value) {
2477
- row.getCell(fieldIndex + 2).value = parseFloat(value.replace(new RegExp(/\,/g), '').replace(new RegExp(/\$/g), ''));
2478
- }
2479
- else {
2480
- row.getCell(fieldIndex + 2).value = value;
2481
- }
2482
-
2483
- if (field.leafFormatType === 'Currency') {
2484
- row.getCell(fieldIndex + 2).numFmt = '"$"#,##0.00';
2485
- }
2486
- else if (field.leafFormatType === 'Number') {
2487
- row.getCell(fieldIndex + 2).numFmt = '#,##0';
2488
- }
2489
-
2490
- row.getCell(fieldIndex + 2).font = {
2491
- name: 'Arial',
2492
- size: 10
2493
- };
2494
-
2495
- if (fieldIndex === 0) {
2496
- row.getCell(fieldIndex + 2).border = {
2497
- left: {style:'thick'}
2498
- };
2499
- }
2500
- else if (fieldIndex === fieldCount - 1) {
2501
- row.getCell(fieldIndex + 2).border = {
2502
- right: {style:'thick'}
2503
- };
2504
- }
2505
- });
2506
- });
2507
-
2508
- // Totals
2509
- report.fields_total.forEach(total => {
2510
- currentRow += 1;
2511
- row = ws.getRow(currentRow);
2512
-
2513
- fields.forEach((field, fieldIndex) => {
2514
- if (total.fields.includes(field.id)) {
2515
- row.getCell(fieldIndex + 2).value = result[total.id + '_' + field.id];
2516
-
2517
- row.getCell(fieldIndex + 2).font = {
2518
- name: 'Arial',
2519
- bold: true,
2520
- size: 10
2521
- };
2522
-
2523
- if (field.leafFormatType === 'Currency') {
2524
- row.getCell(fieldIndex + 2).numFmt = '"$"#,##0.00';
2525
- }
2526
- else if (field.leafFormatType === 'Number') {
2527
- row.getCell(fieldIndex + 2).numFmt = '#,##0';
2528
- }
2529
- }
2530
-
2531
- if (fieldIndex === 0) {
2532
- row.getCell(fieldIndex + 2).border = {
2533
- top: {style:'thin'},
2534
- left: {style:'thick'},
2535
- bottom: {style:'thick'}
2536
- };
2537
- }
2538
- else if (fieldIndex === fieldCount - 1) {
2539
- row.getCell(fieldIndex + 2).border = {
2540
- top: {style:'thin'},
2541
- bottom: {style:'thick'},
2542
- right: {style:'thick'}
2543
- };
2544
- }
2545
- else {
2546
- row.getCell(fieldIndex + 2).border = {
2547
- top: {style:'thin'},
2548
- bottom: {style:'thick'}
2549
- };
2550
- }
2551
- });
2552
- });
2553
- }
2554
-
2555
- return currentRow + 1;
2556
- }
2557
-
2558
- function tabGroupExcelWidthRecursive(report, level, result, cols, fields) {
2559
- if (level < report.groups_row.length) {
2560
- const nextGroup = report.groups_row[level];
2561
- if (nextGroup) {
2562
- const nextResults = result[nextGroup.id];
2563
- if (Array.isArray(nextResults)) {
2564
- nextResults.forEach(tDataRes => {
2565
- cols = tabGroupExcelWidthRecursive(report, level + 1, tDataRes, cols, fields);
2566
- });
2567
- }
2568
- }
2569
- }
2570
- else {
2571
- fields.forEach((field, fieldIndex) => {
2572
- if (Array.isArray(result[field.id])) {
2573
- result[field.id].forEach(res => {
2574
- let length = 10;
2575
-
2576
- if (res) {
2577
- length = res.length + 3;
2578
- }
2579
-
2580
- if (!cols[fieldIndex]) {
2581
- cols[fieldIndex] = Math.max(10, field.columnName.length);
2582
- }
2583
-
2584
- if (length > cols[fieldIndex]) {
2585
- cols[fieldIndex] = length;
2586
- }
2587
- });
2588
- }
2589
- else {
2590
- let res = result[field.id];
2591
- let length = 10;
2592
-
2593
- if (res !== null && res !== undefined) {
2594
- const resStr = (typeof res === 'string') ? res : `${res}`;
2595
- length = resStr.length + 3;
2596
- }
2597
-
2598
- if (!cols[fieldIndex]) {
2599
- cols[fieldIndex] = Math.max(10, field.columnName.length);
2600
- }
2601
-
2602
- if (length > cols[fieldIndex]) {
2603
- cols[fieldIndex] = length;
2604
- }
2605
- }
2606
- });
2607
- }
2608
-
2609
- return cols;
2610
- }