@machinemetrics/mm-erp-sdk 0.1.9-beta.2 → 0.1.9-beta.3

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 (314) hide show
  1. package/dist/index.d.ts +42 -42
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +48 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/knexfile.js +18 -0
  6. package/dist/knexfile.js.map +1 -0
  7. package/dist/migrations/20241015162631_create_cache_table.d.ts +4 -0
  8. package/dist/migrations/20241015162631_create_cache_table.d.ts.map +1 -0
  9. package/dist/migrations/20241015162631_create_cache_table.js +11 -15
  10. package/dist/migrations/20241015162631_create_cache_table.js.map +1 -1
  11. package/dist/migrations/20241015162632_create_sdk_cache_table.d.ts +4 -0
  12. package/dist/migrations/20241015162632_create_sdk_cache_table.d.ts.map +1 -0
  13. package/dist/migrations/20241015162632_create_sdk_cache_table.js +11 -15
  14. package/dist/migrations/20241015162632_create_sdk_cache_table.js.map +1 -1
  15. package/dist/migrations/20250103162631_create_record_tracking_table.d.ts +4 -0
  16. package/dist/migrations/20250103162631_create_record_tracking_table.d.ts.map +1 -0
  17. package/dist/migrations/20250103162631_create_record_tracking_table.js +14 -15
  18. package/dist/migrations/20250103162631_create_record_tracking_table.js.map +1 -1
  19. package/dist/services/caching-service/batch-cache-manager.d.ts +1 -1
  20. package/dist/services/caching-service/batch-cache-manager.d.ts.map +1 -1
  21. package/dist/services/caching-service/batch-cache-manager.js +84 -0
  22. package/dist/services/caching-service/batch-cache-manager.js.map +1 -0
  23. package/dist/services/caching-service/hashed-cache-manager.d.ts +2 -2
  24. package/dist/services/caching-service/hashed-cache-manager.d.ts.map +1 -1
  25. package/dist/services/caching-service/hashed-cache-manager.js +223 -0
  26. package/dist/services/caching-service/hashed-cache-manager.js.map +1 -0
  27. package/dist/services/caching-service/index.d.ts +1 -1
  28. package/dist/services/caching-service/index.d.ts.map +1 -1
  29. package/dist/services/caching-service/index.js +2 -0
  30. package/dist/services/caching-service/index.js.map +1 -0
  31. package/dist/services/caching-service/record-tracking-manager.d.ts +1 -1
  32. package/dist/services/caching-service/record-tracking-manager.d.ts.map +1 -1
  33. package/dist/services/caching-service/record-tracking-manager.js +28 -0
  34. package/dist/services/caching-service/record-tracking-manager.js.map +1 -0
  35. package/dist/services/data-sync-service/configuration-manager.d.ts +1 -1
  36. package/dist/services/data-sync-service/configuration-manager.d.ts.map +1 -1
  37. package/dist/services/data-sync-service/configuration-manager.js +163 -0
  38. package/dist/services/data-sync-service/configuration-manager.js.map +1 -0
  39. package/dist/services/data-sync-service/data-sync-service.d.ts.map +1 -1
  40. package/dist/services/data-sync-service/data-sync-service.js +95 -0
  41. package/dist/services/data-sync-service/data-sync-service.js.map +1 -0
  42. package/dist/services/data-sync-service/index.d.ts +3 -3
  43. package/dist/services/data-sync-service/index.d.ts.map +1 -1
  44. package/dist/services/data-sync-service/index.js +10 -0
  45. package/dist/services/data-sync-service/index.js.map +1 -0
  46. package/dist/services/data-sync-service/jobs/clean-up-expired-cache.js +40 -39
  47. package/dist/services/data-sync-service/jobs/clean-up-expired-cache.js.map +1 -1
  48. package/dist/services/data-sync-service/jobs/from-erp.js +48 -43
  49. package/dist/services/data-sync-service/jobs/from-erp.js.map +1 -1
  50. package/dist/services/data-sync-service/jobs/retry-failed-labor-tickets.js +36 -35
  51. package/dist/services/data-sync-service/jobs/retry-failed-labor-tickets.js.map +1 -1
  52. package/dist/services/data-sync-service/jobs/run-migrations.js +22 -21
  53. package/dist/services/data-sync-service/jobs/run-migrations.js.map +1 -1
  54. package/dist/services/data-sync-service/jobs/to-erp.js +48 -42
  55. package/dist/services/data-sync-service/jobs/to-erp.js.map +1 -1
  56. package/dist/services/erp-api-services/errors.d.ts +1 -1
  57. package/dist/services/erp-api-services/errors.d.ts.map +1 -1
  58. package/dist/services/erp-api-services/errors.js +83 -0
  59. package/dist/services/erp-api-services/errors.js.map +1 -0
  60. package/dist/services/erp-api-services/graphql/graphql-service.d.ts +2 -2
  61. package/dist/services/erp-api-services/graphql/graphql-service.d.ts.map +1 -1
  62. package/dist/services/erp-api-services/graphql/graphql-service.js +102 -0
  63. package/dist/services/erp-api-services/graphql/graphql-service.js.map +1 -0
  64. package/dist/services/erp-api-services/graphql/types.js +6 -0
  65. package/dist/services/erp-api-services/graphql/types.js.map +1 -0
  66. package/dist/services/erp-api-services/index.d.ts +8 -8
  67. package/dist/services/erp-api-services/index.d.ts.map +1 -1
  68. package/dist/services/erp-api-services/index.js +13 -0
  69. package/dist/services/erp-api-services/index.js.map +1 -0
  70. package/dist/services/erp-api-services/oauth-client.js +41 -0
  71. package/dist/services/erp-api-services/oauth-client.js.map +1 -0
  72. package/dist/services/erp-api-services/rest/get-query-params.js +23 -0
  73. package/dist/services/erp-api-services/rest/get-query-params.js.map +1 -0
  74. package/dist/services/erp-api-services/rest/rest-api-service.d.ts +2 -2
  75. package/dist/services/erp-api-services/rest/rest-api-service.d.ts.map +1 -1
  76. package/dist/services/erp-api-services/rest/rest-api-service.js +163 -0
  77. package/dist/services/erp-api-services/rest/rest-api-service.js.map +1 -0
  78. package/dist/services/erp-api-services/types.d.ts +2 -2
  79. package/dist/services/erp-api-services/types.d.ts.map +1 -1
  80. package/dist/services/erp-api-services/types.js +2 -0
  81. package/dist/services/erp-api-services/types.js.map +1 -0
  82. package/dist/services/mm-api-service/index.d.ts +6 -6
  83. package/dist/services/mm-api-service/index.d.ts.map +1 -1
  84. package/dist/services/mm-api-service/index.js +15 -0
  85. package/dist/services/mm-api-service/index.js.map +1 -0
  86. package/dist/services/mm-api-service/mm-api-service.d.ts +7 -7
  87. package/dist/services/mm-api-service/mm-api-service.d.ts.map +1 -1
  88. package/dist/services/mm-api-service/mm-api-service.js +519 -0
  89. package/dist/services/mm-api-service/mm-api-service.js.map +1 -0
  90. package/dist/services/mm-api-service/token-mgr.js +113 -0
  91. package/dist/services/mm-api-service/token-mgr.js.map +1 -0
  92. package/dist/services/mm-api-service/types/checkpoint.js +2 -0
  93. package/dist/services/mm-api-service/types/checkpoint.js.map +1 -0
  94. package/dist/services/mm-api-service/types/entity-transformer.d.ts +2 -2
  95. package/dist/services/mm-api-service/types/entity-transformer.d.ts.map +1 -1
  96. package/dist/services/mm-api-service/types/entity-transformer.js +186 -0
  97. package/dist/services/mm-api-service/types/entity-transformer.js.map +1 -0
  98. package/dist/services/mm-api-service/types/mm-response-interfaces.js +34 -0
  99. package/dist/services/mm-api-service/types/mm-response-interfaces.js.map +1 -0
  100. package/dist/services/mm-api-service/types/receive-types.js +55 -0
  101. package/dist/services/mm-api-service/types/receive-types.js.map +1 -0
  102. package/dist/services/mm-api-service/types/send-types.js +337 -0
  103. package/dist/services/mm-api-service/types/send-types.js.map +1 -0
  104. package/dist/services/psql-erp-service/configuration.js +2 -0
  105. package/dist/services/psql-erp-service/configuration.js.map +1 -0
  106. package/dist/services/psql-erp-service/index.d.ts +3 -3
  107. package/dist/services/psql-erp-service/index.d.ts.map +1 -1
  108. package/dist/services/psql-erp-service/index.js +10 -0
  109. package/dist/services/psql-erp-service/index.js.map +1 -0
  110. package/dist/services/psql-erp-service/internal/types/psql-types.js +5 -0
  111. package/dist/services/psql-erp-service/internal/types/psql-types.js.map +1 -0
  112. package/dist/services/psql-erp-service/psql-helpers.js +99 -0
  113. package/dist/services/psql-erp-service/psql-helpers.js.map +1 -0
  114. package/dist/services/psql-erp-service/psql-service.d.ts +2 -2
  115. package/dist/services/psql-erp-service/psql-service.d.ts.map +1 -1
  116. package/dist/services/psql-erp-service/psql-service.js +187 -0
  117. package/dist/services/psql-erp-service/psql-service.js.map +1 -0
  118. package/dist/services/reporting-service/index.d.ts +1 -1
  119. package/dist/services/reporting-service/index.d.ts.map +1 -1
  120. package/dist/services/reporting-service/index.js +5 -0
  121. package/dist/services/reporting-service/index.js.map +1 -0
  122. package/dist/services/reporting-service/logger.js +217 -0
  123. package/dist/services/reporting-service/logger.js.map +1 -0
  124. package/dist/services/sql-server-erp-service/configuration.js +2 -0
  125. package/dist/services/sql-server-erp-service/configuration.js.map +1 -0
  126. package/dist/services/sql-server-erp-service/index.d.ts +3 -3
  127. package/dist/services/sql-server-erp-service/index.d.ts.map +1 -1
  128. package/dist/services/sql-server-erp-service/index.js +11 -0
  129. package/dist/services/sql-server-erp-service/index.js.map +1 -0
  130. package/dist/services/sql-server-erp-service/internal/sql-labor-ticket-operations.d.ts +2 -2
  131. package/dist/services/sql-server-erp-service/internal/sql-labor-ticket-operations.d.ts.map +1 -1
  132. package/dist/services/sql-server-erp-service/internal/sql-labor-ticket-operations.js +50 -0
  133. package/dist/services/sql-server-erp-service/internal/sql-labor-ticket-operations.js.map +1 -0
  134. package/dist/services/sql-server-erp-service/internal/sql-server-config.js +40 -0
  135. package/dist/services/sql-server-erp-service/internal/sql-server-config.js.map +1 -0
  136. package/dist/services/sql-server-erp-service/internal/sql-transaction-manager.js +36 -0
  137. package/dist/services/sql-server-erp-service/internal/sql-transaction-manager.js.map +1 -0
  138. package/dist/services/sql-server-erp-service/internal/types/sql-server-types.js +2 -0
  139. package/dist/services/sql-server-erp-service/internal/types/sql-server-types.js.map +1 -0
  140. package/dist/services/sql-server-erp-service/sql-server-helpers.d.ts +3 -3
  141. package/dist/services/sql-server-erp-service/sql-server-helpers.d.ts.map +1 -1
  142. package/dist/services/sql-server-erp-service/sql-server-helpers.js +66 -0
  143. package/dist/services/sql-server-erp-service/sql-server-helpers.js.map +1 -0
  144. package/dist/services/sql-server-erp-service/sql-server-service.d.ts +2 -2
  145. package/dist/services/sql-server-erp-service/sql-server-service.d.ts.map +1 -1
  146. package/dist/services/sql-server-erp-service/sql-server-service.js +154 -0
  147. package/dist/services/sql-server-erp-service/sql-server-service.js.map +1 -0
  148. package/dist/services/sql-server-erp-service/types/sql-input-param.js +2 -0
  149. package/dist/services/sql-server-erp-service/types/sql-input-param.js.map +1 -0
  150. package/dist/services/sqlite-service/index.d.ts +1 -1
  151. package/dist/services/sqlite-service/index.d.ts.map +1 -1
  152. package/dist/services/sqlite-service/index.js +2 -0
  153. package/dist/services/sqlite-service/index.js.map +1 -0
  154. package/dist/services/sqlite-service/sqlite-coordinator.js +60 -0
  155. package/dist/services/sqlite-service/sqlite-coordinator.js.map +1 -0
  156. package/dist/types/erp-connector.d.ts +1 -1
  157. package/dist/types/erp-connector.d.ts.map +1 -1
  158. package/dist/types/erp-connector.js +2 -0
  159. package/dist/types/erp-connector.js.map +1 -0
  160. package/dist/types/erp-types.js +13 -0
  161. package/dist/types/erp-types.js.map +1 -0
  162. package/dist/types/index.d.ts +2 -2
  163. package/dist/types/index.d.ts.map +1 -1
  164. package/dist/types/index.js +6 -0
  165. package/dist/types/index.js.map +1 -0
  166. package/dist/utils/application-initializer.js +55 -0
  167. package/dist/utils/application-initializer.js.map +1 -0
  168. package/dist/utils/cleanup-numbers.js +6 -0
  169. package/dist/utils/cleanup-numbers.js.map +1 -0
  170. package/dist/utils/connector-factory.d.ts +1 -1
  171. package/dist/utils/connector-factory.d.ts.map +1 -1
  172. package/dist/utils/connector-factory.js +34 -0
  173. package/dist/utils/connector-factory.js.map +1 -0
  174. package/dist/utils/connector-log/log-deduper.d.ts +1 -1
  175. package/dist/utils/connector-log/log-deduper.d.ts.map +1 -1
  176. package/dist/utils/connector-log/log-deduper.js +240 -0
  177. package/dist/utils/connector-log/log-deduper.js.map +1 -0
  178. package/dist/utils/connector-log/mm-connector-logger-example.d.ts +1 -0
  179. package/dist/utils/connector-log/mm-connector-logger-example.js +88 -0
  180. package/dist/utils/connector-log/mm-connector-logger-example.js.map +1 -0
  181. package/dist/utils/connector-log/mm-connector-logger.d.ts +1 -1
  182. package/dist/utils/connector-log/mm-connector-logger.d.ts.map +1 -1
  183. package/dist/utils/connector-log/mm-connector-logger.js +151 -0
  184. package/dist/utils/connector-log/mm-connector-logger.js.map +1 -0
  185. package/dist/utils/data-transformation.js +38 -0
  186. package/dist/utils/data-transformation.js.map +1 -0
  187. package/dist/utils/erp-type-from-entity.d.ts +1 -1
  188. package/dist/utils/erp-type-from-entity.d.ts.map +1 -1
  189. package/dist/utils/erp-type-from-entity.js +6 -0
  190. package/dist/utils/erp-type-from-entity.js.map +1 -0
  191. package/dist/utils/error-utils.js +21 -0
  192. package/dist/utils/error-utils.js.map +1 -0
  193. package/dist/utils/http-client.js +186 -0
  194. package/dist/utils/http-client.js.map +1 -0
  195. package/dist/utils/index.d.ts +33 -33
  196. package/dist/utils/index.d.ts.map +1 -1
  197. package/dist/utils/index.js +65 -0
  198. package/dist/utils/index.js.map +1 -0
  199. package/dist/utils/local-data-store/database-lock.js +68 -0
  200. package/dist/utils/local-data-store/database-lock.js.map +1 -0
  201. package/dist/utils/local-data-store/jobs-shared-data.js +116 -0
  202. package/dist/utils/local-data-store/jobs-shared-data.js.map +1 -0
  203. package/dist/utils/mm-labor-ticket-helpers.d.ts +1 -1
  204. package/dist/utils/mm-labor-ticket-helpers.d.ts.map +1 -1
  205. package/dist/utils/mm-labor-ticket-helpers.js +23 -0
  206. package/dist/utils/mm-labor-ticket-helpers.js.map +1 -0
  207. package/dist/utils/removeExtraneousFields.d.ts +1 -1
  208. package/dist/utils/removeExtraneousFields.d.ts.map +1 -1
  209. package/dist/utils/removeExtraneousFields.js +16 -0
  210. package/dist/utils/removeExtraneousFields.js.map +1 -0
  211. package/dist/utils/removeIdFieldFromPayload.d.ts +1 -1
  212. package/dist/utils/removeIdFieldFromPayload.d.ts.map +1 -1
  213. package/dist/utils/removeIdFieldFromPayload.js +16 -0
  214. package/dist/utils/removeIdFieldFromPayload.js.map +1 -0
  215. package/dist/utils/resource-group.d.ts +1 -1
  216. package/dist/utils/resource-group.d.ts.map +1 -1
  217. package/dist/utils/resource-group.js +59 -0
  218. package/dist/utils/resource-group.js.map +1 -0
  219. package/dist/utils/standard-process-drivers/error-processor.d.ts +3 -3
  220. package/dist/utils/standard-process-drivers/error-processor.d.ts.map +1 -1
  221. package/dist/utils/standard-process-drivers/error-processor.js +262 -0
  222. package/dist/utils/standard-process-drivers/error-processor.js.map +1 -0
  223. package/dist/utils/standard-process-drivers/index.d.ts +3 -3
  224. package/dist/utils/standard-process-drivers/index.d.ts.map +1 -1
  225. package/dist/utils/standard-process-drivers/index.js +4 -0
  226. package/dist/utils/standard-process-drivers/index.js.map +1 -0
  227. package/dist/utils/standard-process-drivers/labor-ticket-erp-synchronizer.d.ts +1 -1
  228. package/dist/utils/standard-process-drivers/labor-ticket-erp-synchronizer.d.ts.map +1 -1
  229. package/dist/utils/standard-process-drivers/labor-ticket-erp-synchronizer.js +164 -0
  230. package/dist/utils/standard-process-drivers/labor-ticket-erp-synchronizer.js.map +1 -0
  231. package/dist/utils/standard-process-drivers/mm-entity-processor.d.ts +4 -4
  232. package/dist/utils/standard-process-drivers/mm-entity-processor.d.ts.map +1 -1
  233. package/dist/utils/standard-process-drivers/mm-entity-processor.js +168 -0
  234. package/dist/utils/standard-process-drivers/mm-entity-processor.js.map +1 -0
  235. package/dist/utils/standard-process-drivers/standard-process-drivers.d.ts +4 -4
  236. package/dist/utils/standard-process-drivers/standard-process-drivers.d.ts.map +1 -1
  237. package/dist/utils/standard-process-drivers/standard-process-drivers.js +324 -0
  238. package/dist/utils/standard-process-drivers/standard-process-drivers.js.map +1 -0
  239. package/dist/utils/time-utils.js +96 -0
  240. package/dist/utils/time-utils.js.map +1 -0
  241. package/dist/utils/timezone.js +105 -0
  242. package/dist/utils/timezone.js.map +1 -0
  243. package/dist/utils/trimObjectValues.js +11 -0
  244. package/dist/utils/trimObjectValues.js.map +1 -0
  245. package/dist/utils/uniqueRows.js +35 -0
  246. package/dist/utils/uniqueRows.js.map +1 -0
  247. package/package.json +5 -6
  248. package/src/index.ts +42 -42
  249. package/src/services/caching-service/batch-cache-manager.ts +2 -2
  250. package/src/services/caching-service/hashed-cache-manager.ts +5 -5
  251. package/src/services/caching-service/index.ts +1 -1
  252. package/src/services/caching-service/record-tracking-manager.ts +2 -2
  253. package/src/services/data-sync-service/configuration-manager.ts +2 -2
  254. package/src/services/data-sync-service/data-sync-service.ts +9 -3
  255. package/src/services/data-sync-service/index.ts +3 -3
  256. package/src/services/data-sync-service/jobs/clean-up-expired-cache.ts +3 -3
  257. package/src/services/data-sync-service/jobs/from-erp.ts +3 -3
  258. package/src/services/data-sync-service/jobs/retry-failed-labor-tickets.ts +2 -2
  259. package/src/services/data-sync-service/jobs/run-migrations.ts +2 -2
  260. package/src/services/data-sync-service/jobs/to-erp.ts +2 -2
  261. package/src/services/erp-api-services/errors.ts +3 -3
  262. package/src/services/erp-api-services/graphql/graphql-service.ts +5 -5
  263. package/src/services/erp-api-services/index.ts +8 -8
  264. package/src/services/erp-api-services/rest/rest-api-service.ts +4 -4
  265. package/src/services/erp-api-services/types.ts +2 -2
  266. package/src/services/mm-api-service/index.ts +6 -6
  267. package/src/services/mm-api-service/mm-api-service.ts +10 -10
  268. package/src/services/mm-api-service/token-mgr.ts +4 -4
  269. package/src/services/mm-api-service/types/entity-transformer.ts +3 -3
  270. package/src/services/psql-erp-service/index.ts +3 -3
  271. package/src/services/psql-erp-service/psql-service.ts +4 -4
  272. package/src/services/reporting-service/index.ts +1 -1
  273. package/src/services/sql-server-erp-service/index.ts +3 -3
  274. package/src/services/sql-server-erp-service/internal/sql-labor-ticket-operations.ts +2 -2
  275. package/src/services/sql-server-erp-service/internal/sql-transaction-manager.ts +1 -1
  276. package/src/services/sql-server-erp-service/sql-server-helpers.ts +6 -6
  277. package/src/services/sql-server-erp-service/sql-server-service.ts +4 -4
  278. package/src/services/sqlite-service/index.ts +1 -1
  279. package/src/services/sqlite-service/sqlite-coordinator.ts +2 -2
  280. package/src/types/erp-connector.ts +1 -1
  281. package/src/types/index.ts +2 -2
  282. package/src/utils/application-initializer.ts +5 -5
  283. package/src/utils/connector-factory.ts +2 -2
  284. package/src/utils/connector-log/log-deduper.ts +2 -2
  285. package/src/utils/connector-log/mm-connector-logger.ts +3 -3
  286. package/src/utils/erp-type-from-entity.ts +1 -1
  287. package/src/utils/http-client.ts +1 -1
  288. package/src/utils/index.ts +33 -33
  289. package/src/utils/local-data-store/database-lock.ts +1 -1
  290. package/src/utils/mm-labor-ticket-helpers.ts +2 -2
  291. package/src/utils/removeExtraneousFields.ts +1 -1
  292. package/src/utils/removeIdFieldFromPayload.ts +1 -1
  293. package/src/utils/resource-group.ts +2 -2
  294. package/src/utils/standard-process-drivers/error-processor.ts +5 -5
  295. package/src/utils/standard-process-drivers/index.ts +3 -3
  296. package/src/utils/standard-process-drivers/labor-ticket-erp-synchronizer.ts +6 -6
  297. package/src/utils/standard-process-drivers/mm-entity-processor.ts +7 -7
  298. package/src/utils/standard-process-drivers/standard-process-drivers.ts +6 -6
  299. package/src/utils/time-utils.ts +3 -3
  300. package/src/utils/timezone.ts +2 -2
  301. package/dist/config-Bax6Ofp5.js +0 -418
  302. package/dist/config-Bax6Ofp5.js.map +0 -1
  303. package/dist/connector-factory-BaMIlES8.js +0 -30
  304. package/dist/connector-factory-BaMIlES8.js.map +0 -1
  305. package/dist/hashed-cache-manager-C1u9jQgY.js +0 -322
  306. package/dist/hashed-cache-manager-C1u9jQgY.js.map +0 -1
  307. package/dist/index-BkVlW0ZW.js +0 -192
  308. package/dist/index-BkVlW0ZW.js.map +0 -1
  309. package/dist/knexfile-Bng2Ru9c.js +0 -20
  310. package/dist/knexfile-Bng2Ru9c.js.map +0 -1
  311. package/dist/logger-DW5fyhVS.js +0 -17593
  312. package/dist/logger-DW5fyhVS.js.map +0 -1
  313. package/dist/mm-erp-sdk.js +0 -4266
  314. package/dist/mm-erp-sdk.js.map +0 -1
@@ -1,4266 +0,0 @@
1
- import { C as CoreConfiguration, H as HashedCacheManager } from "./hashed-cache-manager-C1u9jQgY.js";
2
- import { E, g, a } from "./hashed-cache-manager-C1u9jQgY.js";
3
- import { l as logger } from "./logger-DW5fyhVS.js";
4
- import { g as getCachedMMToken, s as setCachedMMToken, a as setTimezoneOffsetInCache, b as setTimezoneNameInCache, c as getCachedTimezoneOffset, S as SQLiteCoordinator } from "./index-BkVlW0ZW.js";
5
- import { f, d, e } from "./index-BkVlW0ZW.js";
6
- import axios, { AxiosError } from "axios";
7
- import knex from "knex";
8
- import { c as config } from "./knexfile-Bng2Ru9c.js";
9
- import fs from "fs";
10
- import path from "path";
11
- import "./connector-factory-BaMIlES8.js";
12
- import Bree from "bree";
13
- import Graceful from "@ladjs/graceful";
14
- import { fileURLToPath } from "url";
15
- import sql from "mssql";
16
- import { z } from "zod";
17
- var ERPObjType = /* @__PURE__ */ ((ERPObjType2) => {
18
- ERPObjType2[ERPObjType2["RESOURCES"] = 0] = "RESOURCES";
19
- ERPObjType2[ERPObjType2["PARTS"] = 1] = "PARTS";
20
- ERPObjType2[ERPObjType2["PART_OPERATION"] = 2] = "PART_OPERATION";
21
- ERPObjType2[ERPObjType2["WORK_ORDERS"] = 3] = "WORK_ORDERS";
22
- ERPObjType2[ERPObjType2["WORK_ORDER_OPERATIONS"] = 4] = "WORK_ORDER_OPERATIONS";
23
- ERPObjType2[ERPObjType2["PERSONS"] = 5] = "PERSONS";
24
- ERPObjType2[ERPObjType2["REASONS"] = 6] = "REASONS";
25
- ERPObjType2[ERPObjType2["LABOR_TICKETS"] = 7] = "LABOR_TICKETS";
26
- return ERPObjType2;
27
- })(ERPObjType || {});
28
- var Operator = /* @__PURE__ */ ((Operator2) => {
29
- Operator2["eq"] = "eq";
30
- Operator2["lt"] = "lt";
31
- Operator2["lte"] = "lte";
32
- Operator2["gt"] = "gt";
33
- Operator2["gte"] = "gte";
34
- return Operator2;
35
- })(Operator || {});
36
- const buildLogicalCondition = (conditions, operator) => {
37
- return conditions.map(
38
- (condition) => `${condition.field} ${condition.operator} '${condition.value}'`
39
- ).join(` ${operator} `);
40
- };
41
- class MMReceiveLaborTicket {
42
- constructor(data) {
43
- Object.assign(this, data);
44
- }
45
- // Returns the closed date if it is a valid date, otherwise returns null
46
- get workOrderOperationClosedDate() {
47
- const closedDate = this.workOrderOperation?.closedDate;
48
- return typeof closedDate === "string" && closedDate !== "" && !isNaN(Date.parse(closedDate)) ? closedDate : null;
49
- }
50
- set workOrderOperationClosedDate(value) {
51
- if (this.workOrderOperation) {
52
- this.workOrderOperation.closedDate = value;
53
- }
54
- }
55
- // Returns 1 if the work order operation is closed (has a valid closed date), 0 otherwise
56
- get workOrderOpIsClosed() {
57
- return this.workOrderOperationClosedDate !== null ? 1 : 0;
58
- }
59
- /*Descriptions from machinemetrics.atlassian.net/wiki/spaces/DEVE/pages/842661901/MM+ERP+Schema+Descriptions*/
60
- badParts;
61
- // The number of parts produced that do not meet quality standards
62
- clockIn;
63
- // The timestamp when the work on this ticket started
64
- clockOut;
65
- // The timestamp when the work on this ticket ended
66
- comment;
67
- createdAt;
68
- goodParts;
69
- // The number of parts produced that meet quality standards
70
- laborTicketId;
71
- // The unique identifier for the labor ticket in the ERP
72
- laborTicketRef;
73
- // The unique identifier for the labor ticket in MM
74
- lot;
75
- // Refers to a material batch. If not available in the ERP, default to an empty string
76
- personId;
77
- // The person who did the work
78
- reasons;
79
- resourceId;
80
- // The physical resource that did the work
81
- sequenceNumber;
82
- // Which sequence this operation is for in the order, associates back to a part_operation with the part_number from the work_order, and sequence_number from the op
83
- split;
84
- // Batch number if order split for staggered delivery. If not available in the ERP, default to an empty string
85
- state;
86
- // The current state of the labor ticket (e.g., "CLOSED/OPEN")
87
- type;
88
- // If the labor is production, setup, or indirect
89
- syncedAt;
90
- updatedAt;
91
- workOrderId;
92
- // The order this labor ticket corresponds to
93
- workOrderOperation;
94
- sub;
95
- // Batch number for parts that had to be rerun. If not available in the ERP, default to an empty string
96
- transactionDate;
97
- }
98
- class HTTPError extends Error {
99
- constructor(message, status, code, data) {
100
- super(message);
101
- this.status = status;
102
- this.code = code;
103
- this.data = data;
104
- this.name = "HTTPError";
105
- }
106
- }
107
- class HTTPClientFactory {
108
- static getInstance(config2) {
109
- return new AxiosClient(config2.baseUrl, config2.retryAttempts);
110
- }
111
- }
112
- class AxiosClient {
113
- client = null;
114
- retryAttempts;
115
- isDestroyed = false;
116
- inFlightControllers = /* @__PURE__ */ new Set();
117
- pendingTimeouts = /* @__PURE__ */ new Set();
118
- pendingSleepResolvers = /* @__PURE__ */ new Set();
119
- /**
120
- * Note regarding baseURL, from https://github.com/axios/axios
121
- * `baseURL` will be prepended to `url` unless `url` is absolute and option `allowAbsoluteUrls` is set to true (the default).
122
- * It can be convenient to set `baseURL` for an instance of axios to pass relative URLs to methods of that instance.
123
- */
124
- constructor(baseUrl, retryAttempts) {
125
- this.client = axios.create({
126
- baseURL: baseUrl,
127
- timeout: 3e4,
128
- headers: {
129
- "Content-Type": "application/json"
130
- }
131
- });
132
- this.retryAttempts = retryAttempts;
133
- }
134
- sleep(ms) {
135
- return new Promise((resolve) => {
136
- if (this.isDestroyed) {
137
- resolve();
138
- return;
139
- }
140
- const timeout = setTimeout(() => {
141
- this.pendingTimeouts.delete(timeout);
142
- this.pendingSleepResolvers.delete(resolve);
143
- resolve();
144
- }, ms);
145
- this.pendingTimeouts.add(timeout);
146
- this.pendingSleepResolvers.add(resolve);
147
- });
148
- }
149
- async request(config2) {
150
- if (this.isDestroyed || !this.client) {
151
- throw new HTTPError("HTTP client has been destroyed", 500);
152
- }
153
- const controller = new AbortController();
154
- this.inFlightControllers.add(controller);
155
- const axiosConfig = {
156
- method: config2.method,
157
- url: config2.url,
158
- headers: config2.headers,
159
- data: config2.data,
160
- params: config2.params,
161
- signal: controller.signal
162
- };
163
- logger.info("HTTP request starting", {
164
- url: config2.url,
165
- method: config2.method,
166
- baseURL: this.client.defaults.baseURL,
167
- retryAttempts: this.retryAttempts
168
- });
169
- console.log("=== FULL URL DEBUG ===");
170
- console.log("baseURL:", this.client.defaults.baseURL);
171
- console.log("relative url:", config2.url);
172
- console.log("full constructed URL:", (this.client.defaults.baseURL || "") + config2.url);
173
- console.log("method:", config2.method);
174
- let lastError;
175
- try {
176
- for (let attempt = 0; attempt <= this.retryAttempts; attempt++) {
177
- try {
178
- logger.info(`HTTP request attempt ${attempt + 1}/${this.retryAttempts + 1}`);
179
- const response = await this.client.request(axiosConfig);
180
- logger.info("HTTP request succeeded", { status: response.status });
181
- return {
182
- data: response.data,
183
- status: response.status,
184
- headers: response.headers
185
- };
186
- } catch (error) {
187
- lastError = error;
188
- const isAxiosErr = error instanceof AxiosError;
189
- const code = isAxiosErr ? error.code : void 0;
190
- const status = isAxiosErr ? error.response?.status : void 0;
191
- const errorConstructor = error instanceof Error ? error.constructor.name : void 0;
192
- const message = error instanceof Error ? error.message : String(error);
193
- logger.info(`HTTP request attempt ${attempt + 1} failed`, {
194
- errorType: typeof error,
195
- errorConstructor,
196
- isAxiosError: isAxiosErr,
197
- message,
198
- code,
199
- status
200
- });
201
- if (error instanceof AxiosError && error.response?.status && error.response.status >= 400 && error.response.status < 500) {
202
- logger.info("Not retrying due to 4xx client error");
203
- break;
204
- }
205
- if (error instanceof AxiosError && error.code === "ERR_CANCELED") {
206
- break;
207
- }
208
- if (attempt < this.retryAttempts) {
209
- const waitTime = Math.pow(2, attempt) * 1e3;
210
- logger.info(`Waiting ${waitTime}ms before retry`);
211
- await this.sleep(waitTime);
212
- if (this.isDestroyed) {
213
- throw new HTTPError("HTTP client has been destroyed", 500);
214
- }
215
- }
216
- }
217
- }
218
- } finally {
219
- this.inFlightControllers.delete(controller);
220
- }
221
- logger.info("HTTP request failed after all retries, throwing error");
222
- throw this.handleError(lastError, config2);
223
- }
224
- handleError(error, requestConfig) {
225
- if (error instanceof AxiosError) {
226
- const baseUrl = this.client?.defaults.baseURL || "";
227
- const fullUrl = requestConfig ? `${baseUrl}${requestConfig.url}` : "Unknown URL";
228
- const method = requestConfig?.method || "Unknown method";
229
- const errorMessage = `${error.message} (${method} ${fullUrl})`;
230
- return new HTTPError(
231
- errorMessage,
232
- error.response?.status || 500,
233
- error.code,
234
- error.response?.data
235
- );
236
- }
237
- return new HTTPError(
238
- error instanceof Error ? error.message : "Unknown error occurred",
239
- 500
240
- );
241
- }
242
- async destroy() {
243
- if (this.isDestroyed) return;
244
- this.isDestroyed = true;
245
- for (const c of this.inFlightControllers) {
246
- try {
247
- c.abort();
248
- } catch {
249
- }
250
- }
251
- this.inFlightControllers.clear();
252
- for (const t of this.pendingTimeouts) {
253
- clearTimeout(t);
254
- }
255
- this.pendingTimeouts.clear();
256
- for (const resolve of this.pendingSleepResolvers) {
257
- try {
258
- resolve();
259
- } catch {
260
- }
261
- }
262
- this.pendingSleepResolvers.clear();
263
- this.client = null;
264
- }
265
- }
266
- class MMTokenManager {
267
- token;
268
- tokenExpiration;
269
- baseUrl;
270
- api;
271
- constructor() {
272
- const cached = getCachedMMToken();
273
- this.token = cached?.token || "";
274
- this.tokenExpiration = cached?.expiration ? new Date(cached.expiration) : null;
275
- const config2 = CoreConfiguration.inst();
276
- console.log("=== MMTOKEN MANAGER DEBUG ===");
277
- console.log("config.mmApiBaseUrl:", config2.mmApiBaseUrl);
278
- console.log("config object keys:", Object.keys(config2));
279
- this.baseUrl = config2.mmApiBaseUrl;
280
- console.log("this.baseUrl set to:", this.baseUrl);
281
- console.log("=== END MMTOKEN MANAGER DEBUG ===");
282
- this.api = HTTPClientFactory.getInstance({
283
- baseUrl: this.baseUrl,
284
- retryAttempts: config2.mmApiRetryAttempts
285
- });
286
- }
287
- /**
288
- * Checks if the current token is expired or will expire within the next minute
289
- * @returns boolean indicating if token needs refresh
290
- */
291
- isTokenExpired() {
292
- if (!this.tokenExpiration) return true;
293
- const bufferTimeMS = 6e4;
294
- const isExpired = this.tokenExpiration.getTime() - bufferTimeMS <= Date.now();
295
- if (isExpired) {
296
- logger.info("isTokenExpired: the api token from MM has expired");
297
- }
298
- return isExpired;
299
- }
300
- /**
301
- * Safely extracts expiration time from JWT token
302
- * @param token JWT token string
303
- * @returns Date object representing token expiration, or null if cannot be determined
304
- */
305
- getTokenExpiration(token) {
306
- try {
307
- const parts = token.split(".");
308
- if (parts.length !== 3) {
309
- console.warn("Invalid JWT format: token does not have 3 parts");
310
- return null;
311
- }
312
- const payload = Buffer.from(parts[1], "base64").toString("utf-8");
313
- const decodedPayload = JSON.parse(payload);
314
- if (typeof decodedPayload.exp !== "number") {
315
- console.warn("JWT does not contain expiration time (exp claim)");
316
- return null;
317
- }
318
- return new Date(decodedPayload.exp * 1e3);
319
- } catch (error) {
320
- console.warn("Error parsing JWT token:", error);
321
- return null;
322
- }
323
- }
324
- /**
325
- * Gets a valid token, either from cache or by requesting a new one
326
- * @returns Promise resolving to a valid token string
327
- */
328
- async getToken() {
329
- if (this.token && !this.isTokenExpired()) {
330
- return this.token;
331
- }
332
- const config2 = CoreConfiguration.inst();
333
- const serviceToken = config2.mmApiAuthToken;
334
- const tokenResponse = await this.api.request({
335
- url: "/user-token",
336
- method: "GET",
337
- headers: {
338
- Authorization: `Bearer ${serviceToken}`
339
- }
340
- });
341
- this.token = tokenResponse.data;
342
- this.tokenExpiration = this.getTokenExpiration(this.token);
343
- setCachedMMToken({
344
- token: this.token,
345
- expiration: this.tokenExpiration?.getTime() || null
346
- });
347
- logger.info("getToken: the api token from MM has been refreshed");
348
- return this.token;
349
- }
350
- /**
351
- * Invalidates the current token, forcing a fresh fetch on next getToken() call
352
- */
353
- invalidateToken() {
354
- this.token = "";
355
- this.tokenExpiration = null;
356
- setCachedMMToken({ token: "", expiration: null });
357
- }
358
- }
359
- class GraphQLError extends Error {
360
- constructor(message, errors) {
361
- super(message);
362
- this.errors = errors;
363
- this.name = "GraphQLError";
364
- }
365
- }
366
- class ErrorHandler {
367
- /**
368
- * Transforms any error into a standardized HTTPError or GraphQLError and throws it.
369
- * Never returns - always throws an error.
370
- *
371
- * @throws {HTTPError|GraphQLError} Standardized error with appropriate details
372
- */
373
- static handle(error) {
374
- if (error instanceof HTTPError) {
375
- if (error.data && typeof error.data === "object" && "errors" in error.data) {
376
- const graphqlError = new GraphQLError(
377
- "GraphQL Error",
378
- error.data.errors
379
- );
380
- logger.error("Error>>GraphQL", {
381
- message: graphqlError.message,
382
- errors: graphqlError.errors
383
- });
384
- throw graphqlError;
385
- }
386
- logger.error("Error>>HTTP", {
387
- status: error.status,
388
- message: error.message,
389
- code: error.code,
390
- data: error.data
391
- });
392
- throw error;
393
- }
394
- if (error instanceof AxiosError) {
395
- if (error.response?.data?.errors) {
396
- const graphqlError = new GraphQLError(
397
- "GraphQL Error",
398
- error.response.data.errors
399
- );
400
- logger.error("Error>>GraphQL", {
401
- message: graphqlError.message,
402
- errors: graphqlError.errors
403
- });
404
- throw graphqlError;
405
- }
406
- const httpError2 = new HTTPError(
407
- error.message,
408
- error.response?.status || 500,
409
- error.code,
410
- error.response?.data
411
- );
412
- logger.error("Error>>HTTP", {
413
- status: httpError2.status,
414
- message: httpError2.message,
415
- code: httpError2.code,
416
- data: httpError2.data
417
- });
418
- throw httpError2;
419
- }
420
- const httpError = new HTTPError(
421
- error instanceof Error ? error.message : "An unknown error occurred",
422
- 500
423
- );
424
- logger.error("Error>>Unknown", {
425
- message: httpError.message,
426
- status: httpError.status
427
- });
428
- throw httpError;
429
- }
430
- }
431
- const MAPPING = "MAPPING";
432
- const CHECKPOINTS = "CHECKPOINTS";
433
- const MACHINE_GROUPS = "MACHINE_GROUPS";
434
- const GRAPHQL = "GRAPHQL";
435
- var UrlBase = /* @__PURE__ */ ((UrlBase2) => {
436
- UrlBase2["ErpApiSvcBase"] = "ErpApiSvcBase";
437
- UrlBase2["ApiBase"] = "ApiBase";
438
- return UrlBase2;
439
- })(UrlBase || {});
440
- class MMApiClient {
441
- tokenMgr;
442
- api;
443
- baseUrls;
444
- resourceURLs = {
445
- [ERPObjType.RESOURCES]: "/erp/v1/resources",
446
- [ERPObjType.PARTS]: "/erp/v1/parts",
447
- [ERPObjType.PART_OPERATION]: "/erp/v1/part-operations",
448
- [ERPObjType.WORK_ORDERS]: "/erp/v1/production-orders",
449
- [ERPObjType.WORK_ORDER_OPERATIONS]: "/erp/v1/production-order-operations",
450
- [ERPObjType.PERSONS]: "/erp/v1/persons",
451
- [ERPObjType.REASONS]: "/erp/v1/reasons",
452
- [ERPObjType.LABOR_TICKETS]: "/erp/v1/labor-tickets",
453
- [MAPPING]: "/erp/v1/mapping",
454
- [CHECKPOINTS]: "/erp/v1/checkpoints",
455
- [MACHINE_GROUPS]: "/machine-groups",
456
- [GRAPHQL]: "/proxy/graphql"
457
- };
458
- constructor() {
459
- this.tokenMgr = new MMTokenManager();
460
- this.baseUrls = {
461
- [
462
- "ErpApiSvcBase"
463
- /* ErpApiSvcBase */
464
- ]: CoreConfiguration.inst().mmERPSvcApiBaseUrl,
465
- [
466
- "ApiBase"
467
- /* ApiBase */
468
- ]: CoreConfiguration.inst().mmApiBaseUrl
469
- };
470
- this.api = HTTPClientFactory.getInstance({
471
- baseUrl: "",
472
- retryAttempts: CoreConfiguration.inst().mmApiRetryAttempts
473
- });
474
- }
475
- //#region Private Methods
476
- async executeWithAuthRetry(operation, options = {}) {
477
- let token = options.token || await this.tokenMgr.getToken();
478
- try {
479
- return await operation(token);
480
- } catch (error) {
481
- const hasStatus = (err) => {
482
- return typeof err === "object" && err !== null && "status" in err;
483
- };
484
- const isAuthError = hasStatus(error) && (error.status === 401 || error.status === 403);
485
- if (isAuthError && !options.token) {
486
- logger.info("Retrying request with fresh token due to auth error");
487
- this.tokenMgr.invalidateToken();
488
- token = await this.tokenMgr.getToken();
489
- return await operation(token);
490
- }
491
- throw error;
492
- }
493
- }
494
- /**
495
- * Fetch data from the MM API, with an auth retry mechanism
496
- * Auth Retry Level (executeWithAuthRetry)
497
- * - 401 (Unauthorized) and 403 (Forbidden) get special treatment
498
- * - These trigger a token refresh and one retry attempt
499
- * - If the retry still fails, the error is re-thrown
500
- *
501
- * HTTP Status Codes behavior:
502
- * - 2xx - Success, returns normally
503
- * - 4xx - Client errors, throws immediately
504
- * - 5xx - Server errors, retries then throws
505
- *
506
- * Flags:
507
- */
508
- async getData(path2, queryParams = {}, options = {}) {
509
- try {
510
- return await this.executeWithAuthRetry(async (token) => {
511
- const baseUrl = options.baseUrl || "ErpApiSvcBase";
512
- const params = new URLSearchParams({
513
- ...queryParams,
514
- ...baseUrl === "ErpApiSvcBase" ? { raw: "true" } : {}
515
- });
516
- const url = params.size > 0 ? `${path2}?${params.toString()}` : path2;
517
- const fullUrl = this.baseUrls[baseUrl] + url;
518
- const result = await this.api.request({
519
- url: fullUrl,
520
- method: "GET",
521
- headers: {
522
- Authorization: `Bearer ${token}`,
523
- ...options.headers
524
- }
525
- });
526
- return {
527
- ...result.data,
528
- httpStatus: result.status
529
- };
530
- }, options);
531
- } catch (error) {
532
- ErrorHandler.handle(error);
533
- }
534
- }
535
- /**
536
- * Send data to the MM API, with an auth retry mechanism
537
- * Auth Retry Level (executeWithAuthRetry)
538
- * - 401 (Unauthorized) and 403 (Forbidden) get special treatment
539
- * - These trigger a token refresh and one retry attempt
540
- * - If the retry still fails, the error is re-thrown
541
- *
542
- * HTTP Status Codes behavior:
543
- * - 2xx - Success, returns normally
544
- * - 4xx - Client errors, throws immediately
545
- * - 5xx - Server errors, retries then throws
546
- *
547
- * Flags:
548
- * - 'raw' = true and 'dedupe' = true will be set for MM's ERP API url
549
- */
550
- async postData(path2, data = {}, queryParams = {}, options = {}) {
551
- try {
552
- return await this.executeWithAuthRetry(async (token) => {
553
- const baseUrl = options.baseUrl || "ErpApiSvcBase";
554
- const params = new URLSearchParams({
555
- ...queryParams,
556
- ...baseUrl === "ErpApiSvcBase" ? { dedupe: "true", raw: "true" } : {}
557
- });
558
- const url = params.size > 0 ? `${path2}?${params.toString()}` : path2;
559
- const fullUrl = this.baseUrls[baseUrl] + url;
560
- const request = {
561
- url: fullUrl,
562
- method: "POST",
563
- data: JSON.stringify(data),
564
- headers: {
565
- Authorization: `Bearer ${token}`,
566
- ...options.headers
567
- }
568
- };
569
- const result = await this.api.request(request);
570
- return {
571
- ...result.data,
572
- httpStatus: result.status
573
- };
574
- }, options);
575
- } catch (error) {
576
- ErrorHandler.handle(error);
577
- }
578
- }
579
- /**
580
- * Delete data from the MM API, with an auth retry mechanism
581
- * Auth Retry Level (executeWithAuthRetry)
582
- * - 401 (Unauthorized) and 403 (Forbidden) get special treatment
583
- * - These trigger a token refresh and one retry attempt
584
- * - If the retry still fails, the error is re-thrown
585
- *
586
- * HTTP Status Codes behavior:
587
- * - 2xx - Success, returns normally
588
- * - 4xx - Client errors, throws immediately
589
- * - 5xx - Server errors, retries then throws
590
- *
591
- */
592
- async deleteData(path2, data = {}, options = {}) {
593
- try {
594
- return await this.executeWithAuthRetry(async (token) => {
595
- const baseUrl = options.baseUrl || "ErpApiSvcBase";
596
- const params = new URLSearchParams({
597
- ...baseUrl === "ErpApiSvcBase" ? { raw: "true" } : {}
598
- });
599
- const url = params.size > 0 ? `${path2}?${params.toString()}` : path2;
600
- const fullUrl = this.baseUrls[baseUrl] + url;
601
- const result = await this.api.request({
602
- url: fullUrl,
603
- method: "DELETE",
604
- data,
605
- headers: {
606
- Authorization: `Bearer ${token}`,
607
- ...options.headers
608
- }
609
- });
610
- return {
611
- ...result.data,
612
- httpStatus: result.status
613
- };
614
- }, options);
615
- } catch (error) {
616
- ErrorHandler.handle(error);
617
- }
618
- }
619
- /**
620
- * Patch data to the MM API, with an auth retry mechanism
621
- * Auth Retry Level (executeWithAuthRetry)
622
- * - 401 (Unauthorized) and 403 (Forbidden) get special treatment
623
- * - These trigger a token refresh and one retry attempt
624
- * - If the retry still fails, the error is re-thrown
625
- *
626
- * HTTP Status Codes behavior:
627
- * - 2xx - Success, returns normally
628
- * - 4xx - Client errors, throws immediately
629
- * - 5xx - Server errors, retries then throws
630
- *
631
- */
632
- async patchData(path2, data = {}, options = {}) {
633
- try {
634
- return await this.executeWithAuthRetry(async (token) => {
635
- const baseUrl = options.baseUrl || "ErpApiSvcBase";
636
- const params = new URLSearchParams({
637
- ...baseUrl === "ErpApiSvcBase" ? { raw: "true" } : {}
638
- });
639
- const url = params.size > 0 ? `${path2}?${params.toString()}` : path2;
640
- const fullUrl = this.baseUrls[baseUrl] + url;
641
- const request = {
642
- url: fullUrl,
643
- method: "PATCH",
644
- data,
645
- headers: {
646
- Authorization: `Bearer ${token}`,
647
- ...options.headers
648
- }
649
- };
650
- const result = await this.api.request(request);
651
- return {
652
- ...result.data,
653
- httpStatus: result.status
654
- };
655
- }, options);
656
- } catch (error) {
657
- ErrorHandler.handle(error);
658
- }
659
- }
660
- async graphqlRequest(operationName, query) {
661
- try {
662
- return await this.postData(
663
- this.resourceURLs[GRAPHQL],
664
- { operationName, query },
665
- {},
666
- {
667
- baseUrl: "ApiBase",
668
- token: CoreConfiguration.inst().mmApiAuthToken,
669
- headers: { "Content-Type": "application/json" }
670
- }
671
- );
672
- } catch (error) {
673
- ErrorHandler.handle(error);
674
- }
675
- }
676
- /**
677
- * Fetch a checkpoint for a specific system, table, and checkpoint type
678
- * @param checkpoint The checkpoint to fetch
679
- * @returns Promise with the checkpoint data
680
- */
681
- async fetchCheckpoint(checkpoint) {
682
- const { system, table, checkpointType } = checkpoint;
683
- return this.getData(this.resourceURLs[CHECKPOINTS], {
684
- system,
685
- table,
686
- checkpointType
687
- });
688
- }
689
- //#endregion private methods
690
- //#region Public Methods
691
- /**
692
- * Send resources to the MM API
693
- * @param resources Array of resources to send
694
- * @returns Promise with the API response
695
- */
696
- async sendResourcesToMM(resources) {
697
- return await this.postData(this.resourceURLs[ERPObjType.RESOURCES], {
698
- data: resources.map((resource) => resource.toRESTApiObject())
699
- });
700
- }
701
- /**
702
- * Send parts to the MM API
703
- * @param parts Array of parts to send
704
- * @returns Promise with the API response
705
- */
706
- async sendPartsToMM(parts) {
707
- return await this.postData(this.resourceURLs[ERPObjType.PARTS], {
708
- data: parts.map((part) => part.toRESTApiObject())
709
- });
710
- }
711
- /**
712
- * Send part operations to the MM API
713
- * @param operations Array of part operations to send
714
- * @returns Promise with the API response
715
- */
716
- async sendPartOperationsToMM(operations) {
717
- return await this.postData(this.resourceURLs[ERPObjType.PART_OPERATION], {
718
- data: operations.map((operation) => operation.toRESTApiObject())
719
- });
720
- }
721
- /**
722
- * Send work orders to the MM API
723
- * @param workOrders Array of work orders to send
724
- * @returns Promise with the API response
725
- */
726
- async sendWorkOrdersToMM(workOrders) {
727
- return await this.postData(this.resourceURLs[ERPObjType.WORK_ORDERS], {
728
- data: workOrders.map((workOrder) => workOrder.toRESTApiObject())
729
- });
730
- }
731
- /**
732
- * Send work order operations to the MM API
733
- * @param workOrderOperations Array of work order operations to send
734
- * @returns Promise with the API response
735
- */
736
- async sendWorkOrderOperationsToMM(workOrderOperations) {
737
- return await this.postData(
738
- this.resourceURLs[ERPObjType.WORK_ORDER_OPERATIONS],
739
- {
740
- data: workOrderOperations.map(
741
- (operation) => operation.toRESTApiObject()
742
- )
743
- }
744
- );
745
- }
746
- /**
747
- * Send persons to the MM API
748
- * @param persons Array of persons to send
749
- * @returns Promise with the API response
750
- */
751
- async sendPersonsToMM(persons) {
752
- return await this.postData(this.resourceURLs[ERPObjType.PERSONS], {
753
- data: persons.map((person) => person.toRESTApiObject())
754
- });
755
- }
756
- /**
757
- * Send reasons to the MM API
758
- * @param reasons Array of reasons to send
759
- * @returns Promise with the API response
760
- */
761
- async sendReasonsToMM(reasons) {
762
- return await this.postData(this.resourceURLs[ERPObjType.REASONS], {
763
- data: reasons.map((reason) => reason.toRESTApiObject())
764
- });
765
- }
766
- /**
767
- * Send labor tickets to the MM API
768
- * @param laborTickets Array of labor tickets to send
769
- * @returns Promise with the API response
770
- */
771
- async sendLaborTicketsToMM(laborTickets) {
772
- return await this.postData(this.resourceURLs[ERPObjType.LABOR_TICKETS], {
773
- data: laborTickets.map((ticket) => ticket.toRESTApiObject())
774
- });
775
- }
776
- /**
777
- * Delete labor tickets from the MM API
778
- * @param laborTickets Array of labor ticket records to delete
779
- * @returns Promise with the API response
780
- */
781
- async deleteLaborTickets(laborTickets) {
782
- logger.debug("deleteLaborTickets:", { laborTickets });
783
- return await this.deleteData(this.resourceURLs[ERPObjType.LABOR_TICKETS], {
784
- laborTickets
785
- });
786
- }
787
- /**
788
- * Fetch transformed labor tickets from the MM API
789
- * @returns Promise with the transformed labor tickets
790
- */
791
- async fetchTransformedLaborTickets() {
792
- return await this.getData(
793
- `${this.resourceURLs[ERPObjType.LABOR_TICKETS]}/export`
794
- );
795
- }
796
- /**
797
- * Fetch labor ticket updates from the MM API
798
- * @param query Query parameters for filtering updates
799
- * @returns Promise with an array of labor ticket updates
800
- */
801
- async fetchLaborTicketUpdates(query) {
802
- const updates = await this.getData(
803
- `${this.resourceURLs[ERPObjType.LABOR_TICKETS]}/export/updates`,
804
- query
805
- );
806
- return updates.data.map((ticket) => new MMReceiveLaborTicket(ticket));
807
- }
808
- /**
809
- * Fetch a checkpoint for a specific system, table, and checkpoint type
810
- * @param checkpoint The checkpoint to fetch
811
- * @returns Promise with the checkpoint data
812
- */
813
- async getCheckpoint(checkpoint) {
814
- return await this.fetchCheckpoint(checkpoint);
815
- }
816
- /**
817
- * Save a checkpoint to the MM API
818
- * @param checkpoint The checkpoint to save
819
- * @returns Promise with the API response
820
- */
821
- async saveCheckpoint(checkpoint) {
822
- return await this.postData(this.resourceURLs[CHECKPOINTS], checkpoint);
823
- }
824
- /**
825
- * Initialize a checkpoint for a specific system, table, and checkpoint type
826
- * @param checkpoint The checkpoint to initialize
827
- * @returns Promise with the checkpoint data
828
- */
829
- async initializeCheckpoint(checkpoint) {
830
- const currentCheckpoint = await this.fetchCheckpoint(checkpoint);
831
- logger.info("currentCheckpoint:", { currentCheckpoint });
832
- logger.info("currentCheckpoint keys:", {
833
- keys: Object.keys(currentCheckpoint || {})
834
- });
835
- const checkpointResponse = currentCheckpoint;
836
- const hasCheckpointData = checkpointResponse && checkpointResponse.timestamp;
837
- if (!hasCheckpointData) {
838
- logger.info("No checkpoint data found, initializing checkpoint");
839
- const saveCheckpoint = await this.saveCheckpoint(checkpoint);
840
- logger.info("saveCheckpoint:", { saveCheckpoint });
841
- } else {
842
- logger.info("Existing checkpoint found:", {
843
- timestamp: checkpointResponse.timestamp
844
- });
845
- }
846
- }
847
- /**
848
- * Send data to MM API based on the object type
849
- * @param type The type of ERP object to send
850
- * @param objects Array of objects to send
851
- * @returns Promise with the API response including affected rows count
852
- */
853
- async sendDataToMMByType(type, objects) {
854
- switch (type) {
855
- case ERPObjType.PERSONS:
856
- return await this.sendPersonsToMM(
857
- objects
858
- );
859
- case ERPObjType.RESOURCES:
860
- return await this.sendResourcesToMM(
861
- objects
862
- );
863
- case ERPObjType.PARTS:
864
- return await this.sendPartsToMM(objects);
865
- case ERPObjType.PART_OPERATION:
866
- return await this.sendPartOperationsToMM(
867
- objects
868
- );
869
- case ERPObjType.WORK_ORDERS:
870
- return await this.sendWorkOrdersToMM(
871
- objects
872
- );
873
- case ERPObjType.WORK_ORDER_OPERATIONS:
874
- return await this.sendWorkOrderOperationsToMM(
875
- objects
876
- );
877
- case ERPObjType.REASONS:
878
- return await this.sendReasonsToMM(
879
- objects
880
- );
881
- case ERPObjType.LABOR_TICKETS:
882
- return await this.sendLaborTicketsToMM(
883
- objects
884
- );
885
- default:
886
- throw new Error(`Unsupported type: ${ERPObjType[type]}`);
887
- }
888
- }
889
- /**
890
- * Update the labor ticket ERP ID by laborTicketRef
891
- * @param laborTicketRef The MM API labor ticket unique ID
892
- * @param erpObjectId The ERP labor ticket ID to update
893
- * @returns The updated labor ticket
894
- */
895
- async updateLaborTicketIdByRef(laborTicketRef, laborTicketId) {
896
- return await this.patchData(
897
- `${this.resourceURLs[ERPObjType.LABOR_TICKETS]}/${laborTicketRef}`,
898
- { laborTicketId }
899
- );
900
- }
901
- /**
902
- * Add failed labor ticket refs to the MM API
903
- * @param failedTicketRefs The failed labor ticket references
904
- * @returns The response from the MM API
905
- */
906
- async addFailedLaborTicketRefs(system, failedTicketRefs) {
907
- return await this.postData(
908
- `${this.resourceURLs[ERPObjType.LABOR_TICKETS]}/failed`,
909
- { failedTicketRefs },
910
- { system }
911
- );
912
- }
913
- async fetchFailedLaborTickets(system) {
914
- const failedTickets = await this.getData(
915
- `${this.resourceURLs[ERPObjType.LABOR_TICKETS]}/failed`,
916
- { system }
917
- );
918
- return failedTickets.erpLaborTickets.map(
919
- (ticket) => new MMReceiveLaborTicket(ticket)
920
- );
921
- }
922
- /**
923
- * Send connector logs to the MM API
924
- * @param logEntry Single log entry to send
925
- * @returns Promise with the API response
926
- */
927
- async sendConnectorLog(logEntry) {
928
- return await this.postData(
929
- "/connector/logs",
930
- logEntry,
931
- {},
932
- {
933
- baseUrl: "ApiBase"
934
- /* ApiBase */
935
- }
936
- );
937
- }
938
- /**
939
- * Send bulk connector logs to the MM API
940
- * @param logs Array of log entries to send
941
- * @returns Promise with the API response
942
- */
943
- async sendBulkConnectorLogs(logs) {
944
- return await this.postData(
945
- "/connector/logs",
946
- { logs },
947
- {},
948
- {
949
- baseUrl: "ApiBase"
950
- /* ApiBase */
951
- }
952
- );
953
- }
954
- async deleteFailedLaborTicketIds(system, laborTicketRefs) {
955
- return await this.postData(
956
- `${this.resourceURLs[ERPObjType.LABOR_TICKETS]}/failed/remove`,
957
- { laborTicketRefs },
958
- { system }
959
- );
960
- }
961
- /**
962
- * Fetch machine groups from the MM API
963
- * @returns Promise with the machine groups data
964
- */
965
- async fetchMachineGroups() {
966
- return await this.getData(
967
- this.resourceURLs[MACHINE_GROUPS],
968
- {},
969
- {
970
- baseUrl: "ApiBase"
971
- /* ApiBase */
972
- }
973
- );
974
- }
975
- /**
976
- * Fetch resources using GraphQL
977
- * @returns Promise with the resources data
978
- */
979
- async fetchResourcesFromGraphQL() {
980
- return await this.graphqlRequest(
981
- "getErpResources",
982
- "query getErpResources { machineResource: erpResources { machineRef machineGroupId resourceId }}"
983
- );
984
- }
985
- /**
986
- * Cleanup all HTTP connections and resources
987
- * Call this when the service is no longer needed
988
- */
989
- async destroy() {
990
- await this.api.destroy();
991
- }
992
- //#endregion public methods
993
- }
994
- class MMSendPerson {
995
- constructor(personId, firstName, lastName, isActive) {
996
- this.personId = personId;
997
- this.firstName = firstName;
998
- this.lastName = lastName;
999
- this.isActive = isActive;
1000
- }
1001
- toRESTApiObject() {
1002
- return {
1003
- personId: this.personId,
1004
- firstName: this.firstName,
1005
- lastName: this.lastName,
1006
- isActive: this.isActive ? "1" : "0"
1007
- };
1008
- }
1009
- static fromPlainObject(data) {
1010
- return new MMSendPerson(
1011
- data.personId || "",
1012
- data.firstName || "",
1013
- data.lastName || "",
1014
- data.isActive === "1"
1015
- );
1016
- }
1017
- }
1018
- class MMSendResource {
1019
- constructor(resourceId, name, isResourceGroup, description, type, productionBurdenRateHourly, setupBurdenRateHourly) {
1020
- this.resourceId = resourceId;
1021
- this.name = name;
1022
- this.isResourceGroup = isResourceGroup;
1023
- this.description = description;
1024
- this.type = type;
1025
- this.productionBurdenRateHourly = productionBurdenRateHourly;
1026
- this.setupBurdenRateHourly = setupBurdenRateHourly;
1027
- }
1028
- toRESTApiObject() {
1029
- return {
1030
- resourceId: this.resourceId,
1031
- name: this.name,
1032
- isResourceGroup: this.isResourceGroup ? "1" : "0",
1033
- description: this.description,
1034
- type: this.type,
1035
- productionBurdenRateHourly: this.productionBurdenRateHourly.toString(),
1036
- setupBurdenRateHourly: this.setupBurdenRateHourly.toString()
1037
- };
1038
- }
1039
- static fromPlainObject(data) {
1040
- return new MMSendResource(
1041
- data.resourceId || "",
1042
- data.name || "",
1043
- data.isResourceGroup === "1",
1044
- data.description || "",
1045
- data.type || "",
1046
- parseFloat(data.productionBurdenRateHourly || "0"),
1047
- parseFloat(data.setupBurdenRateHourly || "0")
1048
- );
1049
- }
1050
- }
1051
- class MMSendPart {
1052
- constructor(partNumber, partRevision, method) {
1053
- this.partNumber = partNumber;
1054
- this.partRevision = partRevision;
1055
- this.method = method;
1056
- }
1057
- toRESTApiObject() {
1058
- return {
1059
- partNumber: this.partNumber,
1060
- partRevision: this.partRevision,
1061
- method: this.method
1062
- };
1063
- }
1064
- static fromPlainObject(data) {
1065
- return new MMSendPart(
1066
- data.partNumber || "",
1067
- data.partRevision || "",
1068
- data.method || ""
1069
- );
1070
- }
1071
- }
1072
- class MMSendPartOperation {
1073
- constructor(partNumber, partRevision, method, sequenceNumber, resourceId, cycleTimeMs, setupTimeMs, description, quantityPerPart) {
1074
- this.partNumber = partNumber;
1075
- this.partRevision = partRevision;
1076
- this.method = method;
1077
- this.sequenceNumber = sequenceNumber;
1078
- this.resourceId = resourceId;
1079
- this.cycleTimeMs = cycleTimeMs;
1080
- this.setupTimeMs = setupTimeMs;
1081
- this.description = description;
1082
- this.quantityPerPart = quantityPerPart;
1083
- }
1084
- toRESTApiObject() {
1085
- return {
1086
- partNumber: this.partNumber,
1087
- partRevision: this.partRevision,
1088
- method: this.method,
1089
- sequenceNumber: this.sequenceNumber,
1090
- resourceId: this.resourceId,
1091
- cycleTimeMs: this.cycleTimeMs.toString(),
1092
- setupTimeMs: this.setupTimeMs.toString(),
1093
- description: this.description,
1094
- quantityPerPart: this.quantityPerPart.toString()
1095
- };
1096
- }
1097
- static fromPlainObject(data) {
1098
- return new MMSendPartOperation(
1099
- data.partNumber || "",
1100
- data.partRevision || "",
1101
- data.method || "",
1102
- data.sequenceNumber || "",
1103
- data.resourceId || "",
1104
- parseInt(data.cycleTimeMs || "0"),
1105
- parseInt(data.setupTimeMs || "0"),
1106
- data.description || "",
1107
- parseFloat(data.quantityPerPart || "1")
1108
- );
1109
- }
1110
- }
1111
- class MMSendWorkOrder {
1112
- constructor(workOrderId, lot, split, sub, status, dueDate, description, scheduledStartDate, scheduledEndDate, closedDate, quantityRequired, partNumber, partRevision, method) {
1113
- this.workOrderId = workOrderId;
1114
- this.lot = lot;
1115
- this.split = split;
1116
- this.sub = sub;
1117
- this.status = status;
1118
- this.dueDate = dueDate;
1119
- this.description = description;
1120
- this.scheduledStartDate = scheduledStartDate;
1121
- this.scheduledEndDate = scheduledEndDate;
1122
- this.closedDate = closedDate;
1123
- this.quantityRequired = quantityRequired;
1124
- this.partNumber = partNumber;
1125
- this.partRevision = partRevision;
1126
- this.method = method;
1127
- }
1128
- toRESTApiObject() {
1129
- return {
1130
- workOrderId: this.workOrderId,
1131
- lot: this.lot,
1132
- split: this.split,
1133
- sub: this.sub,
1134
- status: this.status,
1135
- dueDate: this.dueDate,
1136
- description: this.description,
1137
- scheduledStartDate: this.scheduledStartDate,
1138
- scheduledEndDate: this.scheduledEndDate,
1139
- closedDate: this.closedDate,
1140
- quantityRequired: this.quantityRequired.toString(),
1141
- partNumber: this.partNumber,
1142
- partRevision: this.partRevision,
1143
- method: this.method
1144
- };
1145
- }
1146
- static fromPlainObject(data) {
1147
- return new MMSendWorkOrder(
1148
- data.workOrderId || "",
1149
- data.lot || "",
1150
- data.split || "",
1151
- data.sub || "",
1152
- data.status || "",
1153
- data.dueDate ?? null,
1154
- data.description || "",
1155
- data.scheduledStartDate ?? null,
1156
- data.scheduledEndDate ?? null,
1157
- data.closedDate ?? null,
1158
- parseFloat(data.quantityRequired || "0"),
1159
- data.partNumber || "",
1160
- data.partRevision || "",
1161
- data.method || ""
1162
- );
1163
- }
1164
- }
1165
- class MMSendWorkOrderOperation {
1166
- constructor(workOrderId, lot, split, sub, sequenceNumber, resourceId, startQuantity, finishQuantity, expectedRejectRate, scheduledStartDate, scheduledFinishDate, closedDate, cycleTimeMs, setupTimeMs, productionburdenRateHourly, setupburdenRatehourly, operationType, quantityPerPart, status) {
1167
- this.workOrderId = workOrderId;
1168
- this.lot = lot;
1169
- this.split = split;
1170
- this.sub = sub;
1171
- this.sequenceNumber = sequenceNumber;
1172
- this.resourceId = resourceId;
1173
- this.startQuantity = startQuantity;
1174
- this.finishQuantity = finishQuantity;
1175
- this.expectedRejectRate = expectedRejectRate;
1176
- this.scheduledStartDate = scheduledStartDate;
1177
- this.scheduledFinishDate = scheduledFinishDate;
1178
- this.closedDate = closedDate;
1179
- this.cycleTimeMs = cycleTimeMs;
1180
- this.setupTimeMs = setupTimeMs;
1181
- this.productionburdenRateHourly = productionburdenRateHourly;
1182
- this.setupburdenRatehourly = setupburdenRatehourly;
1183
- this.operationType = operationType;
1184
- this.quantityPerPart = quantityPerPart;
1185
- this.status = status;
1186
- }
1187
- toRESTApiObject() {
1188
- return {
1189
- workOrderId: this.workOrderId,
1190
- lot: this.lot,
1191
- split: this.split,
1192
- sub: this.sub,
1193
- sequenceNumber: this.sequenceNumber,
1194
- resourceId: this.resourceId,
1195
- startQuantity: this.startQuantity.toString(),
1196
- finishQuantity: this.finishQuantity.toString(),
1197
- expectedRejectRate: this.expectedRejectRate.toString(),
1198
- scheduledStartDate: this.scheduledStartDate,
1199
- scheduledFinishDate: this.scheduledFinishDate,
1200
- closedDate: this.closedDate,
1201
- cycleTimeMs: this.cycleTimeMs.toString(),
1202
- setupTimeMs: this.setupTimeMs.toString(),
1203
- productionburdenRateHourly: this.productionburdenRateHourly.toString(),
1204
- setupburdenRatehourly: this.setupburdenRatehourly.toString(),
1205
- operationType: this.operationType,
1206
- quantityPerPart: this.quantityPerPart.toString(),
1207
- status: this.status
1208
- };
1209
- }
1210
- static fromPlainObject(data) {
1211
- return new MMSendWorkOrderOperation(
1212
- data.workOrderId || "",
1213
- data.lot || "",
1214
- data.split || "",
1215
- data.sub || "",
1216
- data.sequenceNumber || "",
1217
- data.resourceId || "",
1218
- parseFloat(data.startQuantity || "0"),
1219
- parseFloat(data.finishQuantity || "0"),
1220
- parseFloat(data.expectedRejectRate || "0"),
1221
- data.scheduledStartDate ?? null,
1222
- data.scheduledFinishDate ?? null,
1223
- data.closedDate ?? null,
1224
- parseInt(data.cycleTimeMs || "0"),
1225
- parseInt(data.setupTimeMs || "0"),
1226
- parseFloat(data.productionburdenRateHourly || "0"),
1227
- parseFloat(data.setupburdenRatehourly || "0"),
1228
- data.operationType || "",
1229
- parseFloat(data.quantityPerPart || "1"),
1230
- data.status || ""
1231
- );
1232
- }
1233
- }
1234
- class MMSendReason {
1235
- constructor(reasonId, category, code, description, entityType) {
1236
- this.reasonId = reasonId;
1237
- this.category = category;
1238
- this.code = code;
1239
- this.description = description;
1240
- this.entityType = entityType;
1241
- }
1242
- toRESTApiObject() {
1243
- return {
1244
- reasonId: this.reasonId,
1245
- category: this.category,
1246
- code: this.code,
1247
- description: this.description,
1248
- entityType: this.entityType
1249
- };
1250
- }
1251
- static fromPlainObject(data) {
1252
- return new MMSendReason(
1253
- data.reasonId || "",
1254
- data.category || "",
1255
- data.code || "",
1256
- data.description || "",
1257
- data.entityType || ""
1258
- );
1259
- }
1260
- }
1261
- class MMSendLaborTicket {
1262
- constructor(workOrderId, lot, split, sub, sequenceNumber, resourceId, personId, laborTicketId, transactionDate, clockIn, clockOut, goodParts, badParts, type, comment, state) {
1263
- this.workOrderId = workOrderId;
1264
- this.lot = lot;
1265
- this.split = split;
1266
- this.sub = sub;
1267
- this.sequenceNumber = sequenceNumber;
1268
- this.resourceId = resourceId;
1269
- this.personId = personId;
1270
- this.laborTicketId = laborTicketId;
1271
- this.transactionDate = transactionDate;
1272
- this.clockIn = clockIn;
1273
- this.clockOut = clockOut;
1274
- this.goodParts = goodParts;
1275
- this.badParts = badParts;
1276
- this.type = type;
1277
- this.comment = comment;
1278
- this.state = state;
1279
- }
1280
- toRESTApiObject() {
1281
- return {
1282
- workOrderId: this.workOrderId,
1283
- lot: this.lot,
1284
- split: this.split,
1285
- sub: this.sub,
1286
- sequenceNumber: this.sequenceNumber,
1287
- resourceId: this.resourceId,
1288
- personId: this.personId,
1289
- laborTicketId: this.laborTicketId,
1290
- transactionDate: this.transactionDate,
1291
- clockIn: this.clockIn,
1292
- clockOut: this.clockOut,
1293
- goodParts: this.goodParts.toString(),
1294
- badParts: this.badParts.toString(),
1295
- type: this.type,
1296
- comment: this.comment,
1297
- state: this.state
1298
- };
1299
- }
1300
- static fromPlainObject(data) {
1301
- return new MMSendLaborTicket(
1302
- data.workOrderId || "",
1303
- data.lot || "",
1304
- data.split || "",
1305
- data.sub || "",
1306
- data.sequenceNumber || "",
1307
- data.resourceId || "",
1308
- data.personId || "",
1309
- data.laborTicketId || "",
1310
- data.transactionDate ?? null,
1311
- data.clockIn ?? null,
1312
- data.clockOut ?? null,
1313
- parseInt(data.goodParts || "0"),
1314
- parseInt(data.badParts || "0"),
1315
- data.type || "",
1316
- data.comment || "",
1317
- data.state || ""
1318
- );
1319
- }
1320
- }
1321
- function getUniqueRows(data, fields, sortFields) {
1322
- const createCompositeKey = (item) => {
1323
- return fields.map((field) => String(item[field])).join("|");
1324
- };
1325
- const uniqueKeys = /* @__PURE__ */ new Set();
1326
- const uniqueRows = [];
1327
- data.forEach((item) => {
1328
- const key = createCompositeKey(item);
1329
- if (!uniqueKeys.has(key)) {
1330
- uniqueKeys.add(key);
1331
- uniqueRows.push(item);
1332
- }
1333
- });
1334
- if (sortFields && sortFields.length > 0) {
1335
- uniqueRows.sort((a2, b) => {
1336
- for (let i = 0; i < sortFields.length; i++) {
1337
- const field = sortFields[i];
1338
- if (a2[field] < b[field]) return -1;
1339
- if (a2[field] > b[field]) return 1;
1340
- }
1341
- return 0;
1342
- });
1343
- }
1344
- return uniqueRows || [];
1345
- }
1346
- const removeExtraneousFields = (recordset, retainFields) => {
1347
- const data = recordset.map((row) => {
1348
- const transformedRow = {};
1349
- Object.keys(row).forEach((key) => {
1350
- if (retainFields.includes(key)) {
1351
- transformedRow[key] = row[key]?.toString() || "";
1352
- }
1353
- });
1354
- return transformedRow;
1355
- }) || [];
1356
- return data;
1357
- };
1358
- const getPayloadWithoutIDField = (recordset, idField) => {
1359
- const data = recordset.map((row) => {
1360
- const transformedRow = {};
1361
- Object.keys(row).forEach((key) => {
1362
- if (!idField.includes(key)) {
1363
- transformedRow[key] = row[key]?.toString() || "";
1364
- }
1365
- });
1366
- return transformedRow;
1367
- }) || [];
1368
- return data;
1369
- };
1370
- const trimObjectValues = (obj) => {
1371
- return Object.keys(obj).reduce((acc, key) => {
1372
- const value = obj[key];
1373
- acc[key] = typeof value === "string" ? value.trim() : value;
1374
- return acc;
1375
- }, {});
1376
- };
1377
- const cleanupNumbers = (data) => {
1378
- data = data.toString().replace(/[^0-9\.]+/g, "");
1379
- return data;
1380
- };
1381
- const addNewFieldFromExternalSource = (data, externalSource, externalSourceFieldName, newFieldName, defaultValue = "-") => {
1382
- return data.map((current) => {
1383
- const cacheEntry = externalSource.find(
1384
- (existing) => existing[externalSourceFieldName] === current[externalSourceFieldName]
1385
- );
1386
- const newFieldValue = cacheEntry?.[newFieldName] || defaultValue;
1387
- return {
1388
- ...current,
1389
- [newFieldName]: newFieldValue
1390
- };
1391
- });
1392
- };
1393
- const addNewFieldFromLookupField = (data, externalSource, lookupField, currentField, newFieldName, defaultValue = "-") => {
1394
- return data.map((current) => {
1395
- const cacheEntry = externalSource.find(
1396
- (existing) => existing[lookupField] === current[currentField]
1397
- );
1398
- const newFieldValue = cacheEntry?.[currentField] || defaultValue;
1399
- return {
1400
- ...current,
1401
- [newFieldName]: newFieldValue
1402
- };
1403
- });
1404
- };
1405
- const getTimezoneOffset = async () => {
1406
- try {
1407
- const config2 = CoreConfiguration.inst();
1408
- const apiUrl = config2.mmApiBaseUrl;
1409
- const authToken = config2.mmApiAuthToken;
1410
- if (!apiUrl || !authToken) {
1411
- throw new Error("Missing required configuration for timezone fetch");
1412
- }
1413
- const client = HTTPClientFactory.getInstance({
1414
- baseUrl: apiUrl,
1415
- retryAttempts: config2.mmApiRetryAttempts
1416
- });
1417
- const response = await client.request({
1418
- url: "/accounts/current",
1419
- method: "GET",
1420
- headers: {
1421
- Authorization: `Bearer ${authToken}`
1422
- }
1423
- });
1424
- const userInfo = response.data;
1425
- if (!userInfo?.company?.timezone) {
1426
- throw new Error("Unable to retrieve company timezone from API");
1427
- }
1428
- const timezone = userInfo.company.timezone;
1429
- const date = /* @__PURE__ */ new Date();
1430
- const utcDate = new Date(date.toLocaleString("en-US", { timeZone: "UTC" }));
1431
- const tzDate = new Date(
1432
- date.toLocaleString("en-US", { timeZone: timezone })
1433
- );
1434
- const offset = (tzDate.getTime() - utcDate.getTime()) / 36e5;
1435
- return { offset, timezone };
1436
- } catch (error) {
1437
- throw new Error(
1438
- `Failed to get timezone offset: ${error instanceof Error ? error.message : "Unknown error"}`
1439
- );
1440
- }
1441
- };
1442
- const convertToLocalTime = (zuluTime, timezoneOffset) => {
1443
- if (!zuluTime) return void 0;
1444
- const date = new Date(zuluTime);
1445
- return new Date(date.getTime() + timezoneOffset * 60 * 60 * 1e3);
1446
- };
1447
- const formatDateWithTZOffset = (date, timezoneOffset) => {
1448
- if (!date) return void 0;
1449
- const isoDate = date.replace(" ", "T");
1450
- const sign = timezoneOffset >= 0 ? "+" : "-";
1451
- const absOffset = Math.abs(timezoneOffset);
1452
- const hours = Math.floor(absOffset).toString().padStart(2, "0");
1453
- const minutes = Math.floor(absOffset % 1 * 60).toString().padStart(2, "0");
1454
- return `${isoDate}${sign}${hours}:${minutes}`;
1455
- };
1456
- const toISOWithOffset = (date, timezoneOffset) => {
1457
- const sign = timezoneOffset >= 0 ? "+" : "-";
1458
- const abs = Math.abs(timezoneOffset);
1459
- const hours = Math.floor(abs);
1460
- const minutes = Math.round((abs - hours) * 60);
1461
- const pad2 = (n) => n.toString().padStart(2, "0");
1462
- const pad3 = (n) => n.toString().padStart(3, "0");
1463
- const yyyy = date.getUTCFullYear();
1464
- const MM = pad2(date.getUTCMonth() + 1);
1465
- const dd = pad2(date.getUTCDate());
1466
- const HH = pad2(date.getUTCHours());
1467
- const mm = pad2(date.getUTCMinutes());
1468
- const ss = pad2(date.getUTCSeconds());
1469
- const SSS = pad3(date.getUTCMilliseconds());
1470
- const off = `${sign}${pad2(hours)}:${pad2(minutes)}`;
1471
- return `${yyyy}-${MM}-${dd}T${HH}:${mm}:${ss}.${SSS}${off}`;
1472
- };
1473
- function calculateTimeDifferenceInHours(startTime, endTime, timezoneOffset) {
1474
- if (!startTime || !endTime) return 0;
1475
- const localStartTime = convertToLocalTime(startTime, timezoneOffset);
1476
- const localEndTime = convertToLocalTime(endTime, timezoneOffset);
1477
- if (!localStartTime || !localEndTime) return 0;
1478
- const startHours = localStartTime.getHours();
1479
- const startMinutes = localStartTime.getMinutes();
1480
- const startSeconds = localStartTime.getSeconds();
1481
- const endHours = localEndTime.getHours();
1482
- const endMinutes = localEndTime.getMinutes();
1483
- const endSeconds = localEndTime.getSeconds();
1484
- const startTotalSeconds = startHours * 3600 + startMinutes * 60 + startSeconds;
1485
- const endTotalSeconds = endHours * 3600 + endMinutes * 60 + endSeconds;
1486
- if (endTotalSeconds > startTotalSeconds) {
1487
- return Number(((endTotalSeconds - startTotalSeconds) / 3600).toFixed(3));
1488
- }
1489
- return 0;
1490
- }
1491
- const getSecondsOfDay = (timestamp) => {
1492
- if (!timestamp) return null;
1493
- const time = new Date(timestamp);
1494
- const utcHours = time.getUTCHours();
1495
- const utcMinutes = time.getUTCMinutes();
1496
- const utcSeconds = time.getUTCSeconds();
1497
- return (utcHours * 3600 + utcMinutes * 60 + utcSeconds).toString();
1498
- };
1499
- const applyTimezoneOffsetsToFields = (item, fields, timezoneOffset) => {
1500
- const transformed = { ...item };
1501
- fields.forEach((field) => {
1502
- if (transformed[field] && transformed[field].trim()) {
1503
- const formattedDate = formatDateWithTZOffset(
1504
- transformed[field],
1505
- timezoneOffset
1506
- );
1507
- transformed[field] = formattedDate || "";
1508
- } else {
1509
- transformed[field] = "";
1510
- }
1511
- });
1512
- return transformed;
1513
- };
1514
- const getTimezoneOffsetAndPersist = async (params = {
1515
- maxRetries: 36e3,
1516
- // Retry for 10 hours before giving up.
1517
- retryIntervalMs: 1e4
1518
- }) => {
1519
- let success = false;
1520
- let retries = 0;
1521
- logger.info(
1522
- "Acquiring the timezone offset and timezone name from MachineMetrics and storing in cache"
1523
- );
1524
- while (!success && retries < params.maxRetries) {
1525
- try {
1526
- const { offset, timezone } = await getTimezoneOffset();
1527
- logger.info(`Timezone offset: ${offset} hours, timezone: ${timezone}`);
1528
- setTimezoneOffsetInCache(offset);
1529
- setTimezoneNameInCache(timezone);
1530
- success = true;
1531
- } catch (error) {
1532
- logger.error("Error getting timezone offset:", error);
1533
- logger.info(`Retrying in ${params.retryIntervalMs / 1e3} seconds...`);
1534
- await new Promise(
1535
- (resolve) => setTimeout(resolve, params.retryIntervalMs)
1536
- );
1537
- retries++;
1538
- }
1539
- }
1540
- if (!success) {
1541
- throw new Error(
1542
- `Failed to get the timezone offset after ${params.maxRetries} retries`
1543
- );
1544
- }
1545
- };
1546
- const DEFAULT_RECORD_TRACKING_TABLE_NAME = "record_tracking";
1547
- class RecordTrackingManager {
1548
- db;
1549
- constructor() {
1550
- this.db = knex(config.local);
1551
- }
1552
- async updateRecord(record) {
1553
- if (record.lastValue && record.recordId) {
1554
- const recordUpdated = await this.db(DEFAULT_RECORD_TRACKING_TABLE_NAME).where({ entityType: record.entityType }).update(record);
1555
- if (recordUpdated < 1) {
1556
- await this.db(DEFAULT_RECORD_TRACKING_TABLE_NAME).insert(record);
1557
- }
1558
- }
1559
- }
1560
- async getTrackingRecord(type) {
1561
- return await this.db(DEFAULT_RECORD_TRACKING_TABLE_NAME).select("*").where({ entityType: type.toString() });
1562
- }
1563
- async destroy() {
1564
- return this.db.destroy();
1565
- }
1566
- }
1567
- class BatchCacheManager {
1568
- cacheManager;
1569
- constructor(options) {
1570
- this.cacheManager = new HashedCacheManager({
1571
- ttl: options?.ttl,
1572
- tableName: options?.tableName
1573
- });
1574
- }
1575
- /**
1576
- * Checks a batch of objects against the cache and separates them into duplicates and non-duplicates
1577
- * @param type The type of objects
1578
- * @param objects Array of objects to check
1579
- * @returns Object containing arrays of duplicate and non-duplicate objects
1580
- */
1581
- async dedupeBatch(type, objects) {
1582
- const result = {
1583
- duplicates: [],
1584
- nonDuplicates: []
1585
- };
1586
- for (const object of objects) {
1587
- const hasChanged = await this.cacheManager.hasChanged(type, object);
1588
- if (hasChanged) {
1589
- result.nonDuplicates.push(object);
1590
- } else {
1591
- result.duplicates.push(object);
1592
- }
1593
- }
1594
- return result;
1595
- }
1596
- /**
1597
- * Stores a batch of objects in the cache
1598
- * @param type The type of objects
1599
- * @param objects Array of objects to store
1600
- */
1601
- async storeBatch(type, objects) {
1602
- let totalInserted = 0;
1603
- for (const object of objects) {
1604
- if (await this.cacheManager.store(type, object)) {
1605
- totalInserted++;
1606
- }
1607
- }
1608
- return { totalInserted };
1609
- }
1610
- /**
1611
- * Removes objects from the cache
1612
- * @param type The type of objects
1613
- * @param objects Array of objects to remove
1614
- */
1615
- async removeObjects(type, objects) {
1616
- for (const object of objects) {
1617
- await this.cacheManager.removeRecord(type, object);
1618
- }
1619
- }
1620
- /**
1621
- * Gets all records of a specific type
1622
- */
1623
- async getRecordsByType(type) {
1624
- return this.cacheManager.getRecordsByType(type);
1625
- }
1626
- /**
1627
- * Removes all records of a specific type
1628
- */
1629
- async removeRecordsByType(type) {
1630
- return this.cacheManager.removeRecordsByType(type);
1631
- }
1632
- /**
1633
- * Clears all records from the cache
1634
- */
1635
- async clear() {
1636
- return this.cacheManager.clear();
1637
- }
1638
- /**
1639
- * Cleans up resources
1640
- */
1641
- async destroy() {
1642
- return this.cacheManager.destroy();
1643
- }
1644
- }
1645
- function convertLaborTicketToLocalTimezone(laborTicket, timezoneOffset) {
1646
- const timeFields = [
1647
- "clockIn",
1648
- "clockOut",
1649
- "transactionDate",
1650
- "createdAt",
1651
- "updatedAt",
1652
- "workOrderOperationClosedDate"
1653
- ];
1654
- timeFields.forEach((field) => {
1655
- const localTime = convertToLocalTime(laborTicket[field], timezoneOffset);
1656
- laborTicket[field] = localTime ? toISOWithOffset(localTime, timezoneOffset) : null;
1657
- });
1658
- return laborTicket;
1659
- }
1660
- class LaborTicketERPSynchronizer {
1661
- /**
1662
- * Synchronizes updated labor tickets from MachineMetrics to an ERP system
1663
- */
1664
- static async syncToERP(connectorType, connector) {
1665
- try {
1666
- const mmApiClient = new MMApiClient();
1667
- const failedLaborTicketRefs = [];
1668
- await mmApiClient.initializeCheckpoint({
1669
- system: connectorType,
1670
- table: "labor_tickets",
1671
- checkpointType: "export",
1672
- checkpointValue: {
1673
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1674
- }
1675
- });
1676
- const fallbackTimestamp = (/* @__PURE__ */ new Date()).toISOString();
1677
- const laborTicketsUpdates = await mmApiClient.fetchLaborTicketUpdates({
1678
- system: connectorType,
1679
- checkpointType: "export"
1680
- });
1681
- if (laborTicketsUpdates.length === 0) {
1682
- logger.info("syncLaborTicketsToERP:No updated labor tickets found");
1683
- return;
1684
- }
1685
- logger.info(
1686
- `ToERP: Found ${laborTicketsUpdates.length} Labor Ticket Ids and Refs to process`,
1687
- {
1688
- laborTickets: laborTicketsUpdates.map(
1689
- (ticket) => ({
1690
- ref: ticket.laborTicketRef,
1691
- id: ticket.laborTicketId
1692
- })
1693
- )
1694
- }
1695
- );
1696
- const mostRecentUpdate = laborTicketsUpdates.reduce(
1697
- (latest, ticket) => {
1698
- if (!latest || !ticket.updatedAt) return latest;
1699
- return new Date(ticket.updatedAt) > new Date(latest) ? ticket.updatedAt : latest;
1700
- },
1701
- null
1702
- );
1703
- await Promise.all(
1704
- laborTicketsUpdates.map(async (laborTicket) => {
1705
- if (!laborTicket.laborTicketRef) {
1706
- logger.error(
1707
- "syncLaborTicketsToERP: laborTicketRef is not set for laborTicket pulled from MM:",
1708
- { laborTicket }
1709
- );
1710
- return void 0;
1711
- }
1712
- try {
1713
- return await this.processLaborTicket(
1714
- connector,
1715
- mmApiClient,
1716
- laborTicket
1717
- );
1718
- } catch (error) {
1719
- failedLaborTicketRefs.push(laborTicket.laborTicketRef);
1720
- logger.error(
1721
- `syncLaborTicketsToERP: Error processing laborTicketRef ${laborTicket.laborTicketRef}:`,
1722
- { error }
1723
- );
1724
- return void 0;
1725
- }
1726
- })
1727
- );
1728
- logger.info(
1729
- `syncLaborTicketsToERP: ${failedLaborTicketRefs.length} failed labor ticket ids`
1730
- );
1731
- if (failedLaborTicketRefs.length > 0) {
1732
- logger.info(
1733
- `syncLaborTicketsToERP: Reporting ${failedLaborTicketRefs.length} labor ticket failures:`,
1734
- {
1735
- failedLaborTicketRefs
1736
- }
1737
- );
1738
- const addFailedResult = await mmApiClient.addFailedLaborTicketRefs(
1739
- connectorType,
1740
- failedLaborTicketRefs
1741
- );
1742
- logger.info("syncLaborTicketsToERP: addFailedResult:", {
1743
- addFailedResult
1744
- });
1745
- }
1746
- mmApiClient.saveCheckpoint({
1747
- system: connectorType,
1748
- table: "labor_tickets",
1749
- checkpointType: "export",
1750
- checkpointValue: {
1751
- timestamp: mostRecentUpdate || fallbackTimestamp
1752
- }
1753
- });
1754
- } catch (error) {
1755
- logger.error("syncLaborTicketsToERP: Error:", error);
1756
- }
1757
- }
1758
- /**
1759
- * Retries labor tickets that have failed to be created or updated in the ERP during the sync
1760
- */
1761
- static async retryFailed(connectorType, connector) {
1762
- try {
1763
- const mmApiClient = new MMApiClient();
1764
- const successLaborTicketIds = [];
1765
- const laborTickets = await mmApiClient.fetchFailedLaborTickets(connectorType);
1766
- if (laborTickets.length === 0) {
1767
- logger.info("retryFailedLaborTickets: No failed labor tickets found");
1768
- return;
1769
- }
1770
- logger.info(
1771
- "retryFailedLaborTickets: Failed Labor Tickets count:" + laborTickets.length
1772
- );
1773
- await Promise.all(
1774
- laborTickets.map(async (laborTicket) => {
1775
- if (!laborTicket.laborTicketRef) {
1776
- logger.error(
1777
- "retryFailedLaborTickets: laborTicketRef is not set for laborTicket pulled from MM:",
1778
- { laborTicket }
1779
- );
1780
- return void 0;
1781
- }
1782
- try {
1783
- const laborTicketResult = await this.processLaborTicket(
1784
- connector,
1785
- mmApiClient,
1786
- laborTicket
1787
- );
1788
- successLaborTicketIds.push(laborTicket.laborTicketRef);
1789
- return laborTicketResult;
1790
- } catch (error) {
1791
- logger.error(
1792
- "retryFailedLaborTickets: Error processing laborTicketRef:",
1793
- { laborTicketRef: laborTicket.laborTicketRef, error }
1794
- );
1795
- return void 0;
1796
- }
1797
- })
1798
- );
1799
- if (successLaborTicketIds.length > 0) {
1800
- logger.info("Deleting failed labor ticket ids:", {
1801
- successLaborTicketIds
1802
- });
1803
- const deleteFailedResult = await mmApiClient.deleteFailedLaborTicketIds(
1804
- connectorType,
1805
- successLaborTicketIds
1806
- );
1807
- logger.info("deleteFailedResult:", { deleteFailedResult });
1808
- }
1809
- } catch (error) {
1810
- logger.error("retryFailedLaborTickets: Error:", error);
1811
- }
1812
- }
1813
- // ============================================================================
1814
- // PRIVATE HELPER METHODS
1815
- // ============================================================================
1816
- static async writeLaborTicketIdToMM(mmApiClient, laborTicket, laborTicketResult) {
1817
- const updateRefAPIResponse = await mmApiClient.updateLaborTicketIdByRef(
1818
- laborTicket.laborTicketRef,
1819
- laborTicketResult.laborTicketId
1820
- );
1821
- logger.info(
1822
- `Updated laborTicketId ${laborTicketResult.laborTicketId} for laborTicketRef ${laborTicket.laborTicketRef} in MM:`,
1823
- { updateRefAPIResponse }
1824
- );
1825
- }
1826
- static async processLaborTicket(connector, mmApiClient, laborTicket) {
1827
- let laborTicketResult;
1828
- laborTicketResult = convertLaborTicketToLocalTimezone(
1829
- laborTicket,
1830
- getCachedTimezoneOffset()
1831
- );
1832
- logger.info(
1833
- `processing laborTicket, id=${laborTicket.laborTicketId}, ref=${laborTicket.laborTicketRef}`
1834
- );
1835
- logger.debug({ laborTicket });
1836
- if (!laborTicket.laborTicketId) {
1837
- const { laborTicket: laborTicketResult2, erpUid } = await connector.createLaborTicketInERP(laborTicket);
1838
- laborTicketResult2.laborTicketId = erpUid;
1839
- await this.writeLaborTicketIdToMM(
1840
- mmApiClient,
1841
- laborTicket,
1842
- laborTicketResult2
1843
- );
1844
- } else {
1845
- laborTicketResult = await connector.updateLaborTicketInERP(laborTicket);
1846
- }
1847
- logger.info("ToERP: laborTicket update result:", {
1848
- laborTicketResult: laborTicketResult || "Failed to create/update labor ticket",
1849
- laborTicketRef: laborTicket.laborTicketRef,
1850
- operation: laborTicket.laborTicketId ? "update" : "create"
1851
- });
1852
- return laborTicketResult;
1853
- }
1854
- }
1855
- class EntityTransformer {
1856
- // ============================================================================
1857
- // PUBLIC INTERFACE METHODS
1858
- // ============================================================================
1859
- /**
1860
- * Extracts the primary key from a record based on entity type
1861
- * @param entityType The type of entity being processed
1862
- * @param record The record to extract primary key from
1863
- * @returns A string representation of the primary key
1864
- * @throws Error if primary key fields are missing or invalid
1865
- */
1866
- static extractPrimaryKey(entityType, record) {
1867
- switch (entityType) {
1868
- case ERPObjType.PERSONS:
1869
- return this.extractPersonKey(record);
1870
- case ERPObjType.RESOURCES:
1871
- return this.extractResourceKey(record);
1872
- case ERPObjType.PARTS:
1873
- return this.extractPartKey(record);
1874
- case ERPObjType.PART_OPERATION:
1875
- return this.extractPartOperationKey(record);
1876
- case ERPObjType.WORK_ORDERS:
1877
- return this.extractWorkOrderKey(record);
1878
- case ERPObjType.WORK_ORDER_OPERATIONS:
1879
- return this.extractWorkOrderOperationKey(record);
1880
- case ERPObjType.LABOR_TICKETS:
1881
- return this.extractLaborTicketKey(record);
1882
- case ERPObjType.REASONS:
1883
- return this.extractReasonKey(record);
1884
- default:
1885
- throw new Error(
1886
- `Unsupported entity type for primary key extraction: ${entityType}`
1887
- );
1888
- }
1889
- }
1890
- /**
1891
- * Reconstructs a typed object from plain data based on entity type
1892
- * @param entityType The type of entity being processed
1893
- * @param plainData The plain data object containing entity fields
1894
- * @returns A properly typed IToRESTApiObject instance
1895
- * @throws Error if the entity type is not supported
1896
- */
1897
- static reconstructFromPlainData(entityType, plainData) {
1898
- switch (entityType) {
1899
- case ERPObjType.PERSONS:
1900
- return this.reconstructPerson(plainData);
1901
- case ERPObjType.RESOURCES:
1902
- return this.reconstructResource(plainData);
1903
- case ERPObjType.PARTS:
1904
- return this.reconstructPart(plainData);
1905
- case ERPObjType.PART_OPERATION:
1906
- return this.reconstructPartOperation(plainData);
1907
- case ERPObjType.WORK_ORDERS:
1908
- return this.reconstructWorkOrder(plainData);
1909
- case ERPObjType.WORK_ORDER_OPERATIONS:
1910
- return this.reconstructWorkOrderOperation(plainData);
1911
- case ERPObjType.LABOR_TICKETS:
1912
- return this.reconstructLaborTicket(plainData);
1913
- case ERPObjType.REASONS:
1914
- return this.reconstructReason(plainData);
1915
- default:
1916
- throw new Error(
1917
- `Unsupported entity type for reconstruction: ${entityType}`
1918
- );
1919
- }
1920
- }
1921
- /**
1922
- * Reconstructs multiple typed objects from plain data based on entity type
1923
- * @param entityType The type of entity being processed
1924
- * @param plainDataArray Array of plain data objects containing entity fields
1925
- * @returns Array of properly typed IToRESTApiObject instances
1926
- */
1927
- static reconstructMultipleFromPlainData(entityType, plainDataArray) {
1928
- return plainDataArray.map(
1929
- (plainData) => this.reconstructFromPlainData(entityType, plainData)
1930
- );
1931
- }
1932
- // ============================================================================
1933
- // PRIVATE ENTITY-SPECIFIC KEY EXTRACTION METHODS
1934
- // ============================================================================
1935
- static extractPersonKey(record) {
1936
- const restApiObject = record.toRESTApiObject();
1937
- return this.validateAndExtractKey(restApiObject, ["personId"], "PERSONS", [
1938
- "personId"
1939
- ]);
1940
- }
1941
- static extractResourceKey(record) {
1942
- const restApiObject = record.toRESTApiObject();
1943
- return this.validateAndExtractKey(
1944
- restApiObject,
1945
- ["resourceId"],
1946
- "RESOURCES",
1947
- ["resourceId"]
1948
- );
1949
- }
1950
- static extractPartKey(record) {
1951
- const restApiObject = record.toRESTApiObject();
1952
- return this.validateAndExtractKey(
1953
- restApiObject,
1954
- ["partNumber", "partRevision", "method"],
1955
- "PARTS",
1956
- ["partNumber"]
1957
- );
1958
- }
1959
- static extractPartOperationKey(record) {
1960
- const restApiObject = record.toRESTApiObject();
1961
- return this.validateAndExtractKey(
1962
- restApiObject,
1963
- ["partNumber", "partRevision", "method", "sequenceNumber"],
1964
- "PART_OPERATION",
1965
- ["partNumber", "sequenceNumber"]
1966
- );
1967
- }
1968
- static extractWorkOrderKey(record) {
1969
- const restApiObject = record.toRESTApiObject();
1970
- return this.validateAndExtractKey(
1971
- restApiObject,
1972
- ["workOrderId", "lot", "split", "sub"],
1973
- "WORK_ORDERS",
1974
- ["workOrderId"]
1975
- );
1976
- }
1977
- static extractWorkOrderOperationKey(record) {
1978
- const restApiObject = record.toRESTApiObject();
1979
- return this.validateAndExtractKey(
1980
- restApiObject,
1981
- ["workOrderId", "lot", "split", "sub", "sequenceNumber"],
1982
- "WORK_ORDER_OPERATIONS",
1983
- ["workOrderId", "sequenceNumber"]
1984
- );
1985
- }
1986
- static extractLaborTicketKey(record) {
1987
- const restApiObject = record.toRESTApiObject();
1988
- if (restApiObject.laborTicketId) {
1989
- return this.validateAndExtractKey(
1990
- restApiObject,
1991
- ["laborTicketId"],
1992
- "LABOR_TICKETS",
1993
- ["laborTicketId"]
1994
- );
1995
- } else {
1996
- return this.validateAndExtractKey(
1997
- restApiObject,
1998
- [
1999
- "workOrderId",
2000
- "lot",
2001
- "split",
2002
- "sub",
2003
- "sequenceNumber",
2004
- "resourceId",
2005
- "personId"
2006
- ],
2007
- "LABOR_TICKETS",
2008
- ["workOrderId", "sequenceNumber", "resourceId", "personId"]
2009
- );
2010
- }
2011
- }
2012
- static extractReasonKey(record) {
2013
- const restApiObject = record.toRESTApiObject();
2014
- return this.validateAndExtractKey(restApiObject, ["reasonId"], "REASONS", [
2015
- "reasonId"
2016
- ]);
2017
- }
2018
- // ============================================================================
2019
- // PRIVATE ENTITY-SPECIFIC RECONSTRUCTION METHODS
2020
- // ============================================================================
2021
- static reconstructPerson(plainData) {
2022
- return MMSendPerson.fromPlainObject(plainData);
2023
- }
2024
- static reconstructResource(plainData) {
2025
- return MMSendResource.fromPlainObject(plainData);
2026
- }
2027
- static reconstructPart(plainData) {
2028
- return MMSendPart.fromPlainObject(plainData);
2029
- }
2030
- static reconstructPartOperation(plainData) {
2031
- return MMSendPartOperation.fromPlainObject(plainData);
2032
- }
2033
- static reconstructWorkOrder(plainData) {
2034
- return MMSendWorkOrder.fromPlainObject(plainData);
2035
- }
2036
- static reconstructWorkOrderOperation(plainData) {
2037
- return MMSendWorkOrderOperation.fromPlainObject(plainData);
2038
- }
2039
- static reconstructLaborTicket(plainData) {
2040
- return MMSendLaborTicket.fromPlainObject(plainData);
2041
- }
2042
- static reconstructReason(plainData) {
2043
- return MMSendReason.fromPlainObject(plainData);
2044
- }
2045
- // ============================================================================
2046
- // SHARED UTILITY METHODS
2047
- // ============================================================================
2048
- /**
2049
- * Helper method to validate and extract primary key components
2050
- * @param restApiObject The REST API object representation
2051
- * @param keyFields The fields that make up the primary key
2052
- * @param entityTypeName The entity type name for error messages
2053
- * @param requiredFields The fields that must be non-empty (others can be empty)
2054
- * @returns Combined primary key string
2055
- * @throws Error if any required field is missing or null
2056
- */
2057
- static validateAndExtractKey(restApiObject, keyFields, entityTypeName, requiredFields) {
2058
- const keyValues = [];
2059
- for (const field of keyFields) {
2060
- const value = restApiObject[field];
2061
- if (requiredFields.includes(field)) {
2062
- if (value === null || value === void 0 || value === "") {
2063
- throw new Error(
2064
- `Primary key field '${field}' is missing or empty for entity type ${entityTypeName}`
2065
- );
2066
- }
2067
- }
2068
- keyValues.push(value || "");
2069
- }
2070
- return keyValues.join("|");
2071
- }
2072
- }
2073
- class ErrorProcessor {
2074
- /**
2075
- * Creates a set of primary keys for all failed records from batch errors
2076
- * @param entityType The type of entity being processed
2077
- * @param batchErrors Array of batch errors containing failed entities
2078
- * @returns Set of primary keys for failed records
2079
- */
2080
- static createFailedRecordKeySet(entityType, batchErrors) {
2081
- const failedKeySet = /* @__PURE__ */ new Set();
2082
- batchErrors.forEach((batchError) => {
2083
- batchError.affectedEntities.forEach((affectedEntity) => {
2084
- try {
2085
- const primaryKey = EntityTransformer.extractPrimaryKey(
2086
- entityType,
2087
- affectedEntity
2088
- );
2089
- failedKeySet.add(primaryKey);
2090
- } catch (error) {
2091
- logger.warn(
2092
- `Failed to extract primary key from error entity: ${error}`
2093
- );
2094
- }
2095
- });
2096
- });
2097
- return failedKeySet;
2098
- }
2099
- /**
2100
- * Filters out failed records, returning only successful ones
2101
- * @param entityType The type of entity being processed
2102
- * @param allRecords All records (typed objects) that were sent to the API
2103
- * @param failedKeySet Set of primary keys for records that failed
2104
- * @returns Array of records that succeeded
2105
- */
2106
- static filterSuccessfulRecords(entityType, allRecords, failedKeySet) {
2107
- const successfulRecords = [];
2108
- allRecords.forEach((record) => {
2109
- try {
2110
- const primaryKey = EntityTransformer.extractPrimaryKey(
2111
- entityType,
2112
- record
2113
- );
2114
- if (!failedKeySet.has(primaryKey)) {
2115
- successfulRecords.push(record);
2116
- }
2117
- } catch (error) {
2118
- logger.warn(
2119
- `Failed to extract primary key from record during filtering: ${error}`
2120
- );
2121
- }
2122
- });
2123
- return successfulRecords;
2124
- }
2125
- /**
2126
- * Orchestrates the caching of successful records on partial failure
2127
- * @param entityType The type of entity being processed
2128
- * @param toProcess All records that were sent to the API (all are now guaranteed to be typed objects)
2129
- * @param batchErrors Array of batch errors containing failed entities
2130
- * @param batchCacheManager The cache manager instance
2131
- */
2132
- static async cacheSuccessfulRecordsOnPartialFailure(entityType, toProcess, batchErrors, batchCacheManager) {
2133
- const failedKeySet = this.createFailedRecordKeySet(entityType, batchErrors);
2134
- const successfulRecords = this.filterSuccessfulRecords(
2135
- entityType,
2136
- toProcess,
2137
- failedKeySet
2138
- );
2139
- logger.info(
2140
- `Caching ${successfulRecords.length} successful records out of ${toProcess.length} total records`
2141
- );
2142
- if (successfulRecords.length > 0) {
2143
- await batchCacheManager.storeBatch(entityType, successfulRecords);
2144
- }
2145
- }
2146
- /**
2147
- * Extracts error count and batch errors from MM API response for partial failures (HTTP 207)
2148
- * This supports all entities, including the slightly different format for labor tickets.
2149
- * In case of labor tickets, the updateErrors and insertErrors arrays are combined into affectedEntities.
2150
- * @param mmApiResponse The full MM API response object
2151
- * @param entityType The type of entity being processed (determines response structure)
2152
- * @returns Object containing errorCount and batchErrors
2153
- * See MM207NonLaborTicketResponse and MM207LaborTicketResponse for response structure details
2154
- */
2155
- static extractErrorDetails(mmApiResponse, entityType) {
2156
- const data = mmApiResponse.data;
2157
- let allErrors = [];
2158
- if (entityType === ERPObjType.LABOR_TICKETS) {
2159
- const updateErrors = data?.updateErrors || [];
2160
- const insertErrors = data?.insertErrors || [];
2161
- if (!data?.updateErrors && !data?.insertErrors) {
2162
- logger.warn(
2163
- "Labor tickets partial success response missing both updateErrors and insertErrors arrays"
2164
- );
2165
- }
2166
- allErrors = [...updateErrors, ...insertErrors];
2167
- } else {
2168
- const errors = data?.errors || [];
2169
- if (!data?.errors) {
2170
- logger.warn(
2171
- `${entityType} partial success response missing errors array`
2172
- );
2173
- }
2174
- allErrors = errors;
2175
- }
2176
- const batchErrors = allErrors.filter(
2177
- (error) => {
2178
- return error.batchData && error.batchData.length > 0;
2179
- }
2180
- ).map(
2181
- (error) => {
2182
- const typedErrorEntities = (error.batchData || []).map((entity) => {
2183
- if (typeof entity === "object" && entity !== null && "toRESTApiObject" in entity && typeof entity.toRESTApiObject === "function") {
2184
- return entity;
2185
- } else {
2186
- return EntityTransformer.reconstructFromPlainData(
2187
- entityType,
2188
- entity
2189
- );
2190
- }
2191
- });
2192
- return {
2193
- message: error.message,
2194
- affectedEntities: typedErrorEntities
2195
- };
2196
- }
2197
- );
2198
- const errorCount = batchErrors.reduce((total, batchError) => {
2199
- return total + batchError.affectedEntities.length;
2200
- }, 0);
2201
- return {
2202
- errorCount,
2203
- batchErrors
2204
- };
2205
- }
2206
- /**
2207
- * Extracts error details from a 500 HTTP exception when it contains structured error data
2208
- * @param exception The caught exception from MM API call
2209
- * @param entityType The type of entity being processed
2210
- * @returns Object containing errorCount and batchErrors, or null if not a structured 500 error
2211
- * See MM500NonLaborTicketException and MM500LaborTicketException for exception structure details
2212
- */
2213
- static extractErrorDetailsFrom500Exception(exception, entityType) {
2214
- try {
2215
- const ex = exception;
2216
- const data = ex?.data;
2217
- logger.info(
2218
- "writeEntitiesToMM: Analyzing 500 exception structure for diagnostic purposes",
2219
- {
2220
- status: ex?.status,
2221
- code: ex?.code,
2222
- hasResponseData: !!data,
2223
- responseDataKeys: data ? Object.keys(data) : [],
2224
- errorMessage: data?.error,
2225
- hasMessageObject: !!data?.message,
2226
- messageObjectKeys: data?.message ? Object.keys(data.message) : [],
2227
- entityType,
2228
- exceptionType: typeof exception,
2229
- exceptionKeys: ex ? Object.keys(ex) : []
2230
- }
2231
- );
2232
- if (ex?.status !== 500 || typeof data?.error !== "string" || !data.error.startsWith("Failed to import")) {
2233
- logger.info(
2234
- "writeEntitiesToMM: Not a structured 500 error - will re-throw exception as-is",
2235
- {
2236
- status: ex?.status,
2237
- errorMessage: data?.error,
2238
- expectedStatus: 500,
2239
- expectedMessagePrefix: "Failed to import"
2240
- }
2241
- );
2242
- return null;
2243
- }
2244
- logger.info(
2245
- "writeEntitiesToMM: Detected structured 500 error - extracting error details"
2246
- );
2247
- const messageObject = data?.message;
2248
- if (!messageObject) {
2249
- logger.warn(
2250
- "writeEntitiesToMM: Structured 500 error missing message object"
2251
- );
2252
- return null;
2253
- }
2254
- let allErrors = [];
2255
- if (entityType === ERPObjType.LABOR_TICKETS) {
2256
- const updateErrors = Array.isArray(messageObject?.updateErrors) ? messageObject.updateErrors : [];
2257
- const insertErrors = Array.isArray(messageObject?.insertErrors) ? messageObject.insertErrors : [];
2258
- logger.info("writeEntitiesToMM: Processing labor tickets 500 error", {
2259
- updateErrorsCount: updateErrors.length,
2260
- insertErrorsCount: insertErrors.length
2261
- });
2262
- if (updateErrors.length === 0 && insertErrors.length === 0) {
2263
- logger.warn(
2264
- "writeEntitiesToMM: Labor tickets 500 error missing both updateErrors and insertErrors arrays"
2265
- );
2266
- }
2267
- allErrors = [...updateErrors, ...insertErrors];
2268
- } else {
2269
- const errors = Array.isArray(messageObject?.errors) ? messageObject.errors : [];
2270
- logger.info("writeEntitiesToMM: Processing regular entity 500 error", {
2271
- errorsCount: errors.length
2272
- });
2273
- if (errors.length === 0) {
2274
- logger.warn(
2275
- `writeEntitiesToMM: ${entityType} 500 error missing errors array`
2276
- );
2277
- }
2278
- allErrors = errors;
2279
- }
2280
- const batchErrors = allErrors.filter((error) => {
2281
- const err = error;
2282
- return Array.isArray(err?.batchData) && err.batchData.length > 0;
2283
- }).map((error) => {
2284
- const err = error;
2285
- const batchData = err?.batchData;
2286
- const typedErrorEntities = (batchData || []).map((entity) => {
2287
- if (typeof entity === "object" && entity !== null && "toRESTApiObject" in entity && typeof entity.toRESTApiObject === "function") {
2288
- return entity;
2289
- } else {
2290
- return EntityTransformer.reconstructFromPlainData(
2291
- entityType,
2292
- entity
2293
- );
2294
- }
2295
- });
2296
- return {
2297
- message: typeof err?.message === "string" ? err.message : "Unknown error",
2298
- affectedEntities: typedErrorEntities
2299
- };
2300
- });
2301
- const errorCount = batchErrors.reduce((total, batchError) => {
2302
- return total + batchError.affectedEntities.length;
2303
- }, 0);
2304
- logger.info("writeEntitiesToMM: Extracted 500 error details", {
2305
- batchErrorsCount: batchErrors.length,
2306
- totalErrorCount: errorCount,
2307
- entityType
2308
- });
2309
- return {
2310
- errorCount,
2311
- batchErrors
2312
- };
2313
- } catch (error) {
2314
- logger.error(
2315
- "writeEntitiesToMM: Failed to parse 500 exception structure safely",
2316
- {
2317
- error: error instanceof Error ? error.message : String(error),
2318
- exceptionType: typeof exception,
2319
- entityType
2320
- }
2321
- );
2322
- return null;
2323
- }
2324
- }
2325
- }
2326
- class MMEntityProcessor {
2327
- /**
2328
- * Writes entities to MM API with deduplication and caching
2329
- */
2330
- static async writeEntities(entityType, mmRecords, batchCacheManager) {
2331
- const { toProcess, result } = await this._prepareAndDedupe(
2332
- entityType,
2333
- mmRecords,
2334
- batchCacheManager
2335
- );
2336
- if (toProcess.length === 0) {
2337
- result.message = "All records were deduplicated locally - no records sent to MM API";
2338
- return result;
2339
- }
2340
- let mmApiResponse;
2341
- try {
2342
- mmApiResponse = await this._sendToAPI(entityType, toProcess);
2343
- } catch (exception) {
2344
- this._handleException(exception, entityType, result);
2345
- }
2346
- return await this._handleResponse(
2347
- mmApiResponse,
2348
- entityType,
2349
- toProcess,
2350
- result,
2351
- batchCacheManager
2352
- );
2353
- }
2354
- // ============================================================================
2355
- // PRIVATE HELPER METHODS
2356
- // ============================================================================
2357
- /**
2358
- * Deduplicates records against cache
2359
- * Returns the records to process and the result object
2360
- * If the batchCacheManager is provided, the records are deduplicated against the cache
2361
- * If the batchCacheManager is not provided, the records are not deduplicated
2362
- */
2363
- static async _prepareAndDedupe(entityType, mmRecords, batchCacheManager) {
2364
- let toProcess = [];
2365
- const result = {
2366
- message: "",
2367
- upsertedEntities: 0,
2368
- localDedupeCount: 0,
2369
- apiDedupeCount: 0
2370
- };
2371
- if (batchCacheManager) {
2372
- const { nonDuplicates, duplicates } = await batchCacheManager.dedupeBatch(entityType, mmRecords);
2373
- toProcess = nonDuplicates;
2374
- result.localDedupeCount = duplicates.length;
2375
- } else {
2376
- toProcess = mmRecords;
2377
- }
2378
- return { toProcess, result };
2379
- }
2380
- /**
2381
- * Sends records to MM API
2382
- */
2383
- static async _sendToAPI(entityType, toProcess) {
2384
- const mmApiClient = new MMApiClient();
2385
- switch (entityType) {
2386
- case ERPObjType.PERSONS:
2387
- return await mmApiClient.sendPersonsToMM(toProcess);
2388
- case ERPObjType.RESOURCES:
2389
- return await mmApiClient.sendResourcesToMM(
2390
- toProcess
2391
- );
2392
- case ERPObjType.PARTS:
2393
- return await mmApiClient.sendPartsToMM(toProcess);
2394
- case ERPObjType.PART_OPERATION:
2395
- return await mmApiClient.sendPartOperationsToMM(
2396
- toProcess
2397
- );
2398
- case ERPObjType.WORK_ORDERS:
2399
- return await mmApiClient.sendWorkOrdersToMM(
2400
- toProcess
2401
- );
2402
- case ERPObjType.WORK_ORDER_OPERATIONS:
2403
- return await mmApiClient.sendWorkOrderOperationsToMM(
2404
- toProcess
2405
- );
2406
- case ERPObjType.LABOR_TICKETS:
2407
- return await mmApiClient.sendLaborTicketsToMM(
2408
- toProcess
2409
- );
2410
- case ERPObjType.REASONS:
2411
- return await mmApiClient.sendReasonsToMM(toProcess);
2412
- default:
2413
- throw new Error(`Unknown entity type: ${entityType}`);
2414
- }
2415
- }
2416
- /**
2417
- * Handles exceptions from API calls, converting structured 500 errors to MMBatchValidationError
2418
- * @throws MMBatchValidationError for structured 500 errors
2419
- * @throws The original exception for all other errors
2420
- */
2421
- static _handleException(exception, entityType, result) {
2422
- const structuredCompleteErrorSet = ErrorProcessor.extractErrorDetailsFrom500Exception(exception, entityType);
2423
- if (structuredCompleteErrorSet) {
2424
- const ex = exception;
2425
- const data = ex?.data;
2426
- const errorMessage = typeof data?.error === "string" ? data.error : "All entities failed to import";
2427
- throw new MMBatchValidationError({
2428
- message: errorMessage,
2429
- upsertedEntities: 0,
2430
- localDedupeCount: result.localDedupeCount,
2431
- apiDedupeCount: 0,
2432
- errorCount: structuredCompleteErrorSet.errorCount,
2433
- httpStatus: exception.status,
2434
- batchErrors: structuredCompleteErrorSet.batchErrors
2435
- });
2436
- }
2437
- throw exception;
2438
- }
2439
- /**
2440
- * Handles the MM API response based on HTTP status code, caching successful records
2441
- * and throwing exceptions for partial failures
2442
- *
2443
- * @returns The final result for success cases
2444
- * @throws MMBatchValidationError for partial success cases
2445
- * @throws Error for unknown status codes
2446
- */
2447
- static async _handleResponse(mmApiResponse, entityType, toProcess, result, batchCacheManager) {
2448
- if (mmApiResponse.httpStatus === 200) {
2449
- if (batchCacheManager) {
2450
- await batchCacheManager.storeBatch(entityType, toProcess);
2451
- }
2452
- if (entityType === ERPObjType.LABOR_TICKETS) {
2453
- const success = mmApiResponse;
2454
- result.message = success.message || "Entities processed successfully";
2455
- result.upsertedEntities = (success.updated || 0) + (success.inserted || 0);
2456
- } else {
2457
- const success = mmApiResponse;
2458
- result.message = success.message || "Entities processed successfully";
2459
- result.upsertedEntities = success.affectedRows || 0;
2460
- }
2461
- result.apiDedupeCount = toProcess.length - result.upsertedEntities;
2462
- return result;
2463
- } else if (mmApiResponse.httpStatus === 207) {
2464
- const partialResponse = mmApiResponse;
2465
- const { errorCount, batchErrors } = ErrorProcessor.extractErrorDetails(
2466
- partialResponse,
2467
- entityType
2468
- );
2469
- if (batchCacheManager) {
2470
- await ErrorProcessor.cacheSuccessfulRecordsOnPartialFailure(
2471
- entityType,
2472
- toProcess,
2473
- batchErrors,
2474
- batchCacheManager
2475
- );
2476
- }
2477
- let upsertedEntities = 0;
2478
- if (entityType === ERPObjType.LABOR_TICKETS) {
2479
- const partial = partialResponse;
2480
- upsertedEntities = (partial.data.updated || 0) + (partial.data.inserted || 0);
2481
- } else {
2482
- const partial = partialResponse;
2483
- upsertedEntities = partial.data.affectedRows || 0;
2484
- }
2485
- throw new MMBatchValidationError({
2486
- message: partialResponse.message || "Entities processed with partial failures",
2487
- upsertedEntities,
2488
- localDedupeCount: result.localDedupeCount,
2489
- apiDedupeCount: toProcess.length - upsertedEntities - errorCount,
2490
- errorCount,
2491
- httpStatus: mmApiResponse.httpStatus,
2492
- batchErrors
2493
- });
2494
- } else {
2495
- throw new Error(
2496
- `writeEntitiesToMM: Unknown HTTP status code: ${mmApiResponse.httpStatus}. An exception was expected.`
2497
- );
2498
- }
2499
- }
2500
- }
2501
- class MMBatchValidationError extends Error {
2502
- upsertedEntities;
2503
- localDedupeCount;
2504
- apiDedupeCount;
2505
- errorCount;
2506
- httpStatus;
2507
- batchErrors;
2508
- constructor(options) {
2509
- super(options.message);
2510
- this.name = "MMBatchValidationError";
2511
- this.upsertedEntities = options.upsertedEntities;
2512
- this.localDedupeCount = options.localDedupeCount;
2513
- this.apiDedupeCount = options.apiDedupeCount;
2514
- this.errorCount = options.errorCount;
2515
- this.httpStatus = options.httpStatus;
2516
- this.batchErrors = options.batchErrors;
2517
- }
2518
- }
2519
- class StandardProcessDrivers {
2520
- /**
2521
- * Synchronizes updated labor tickets from MachineMetrics to an ERP system:
2522
- *
2523
- * Initializes a checkpoint that tracks the last time labor tickets were synced,
2524
- * fetches labor tickets from MM and converts them to the company timezone,
2525
- * creates or updates the labor ticket in the ERP via connector-specific implementations,
2526
- * updates the labor ticket id in MM on newly created labor tickets,
2527
- * and saves the checkpoint
2528
- */
2529
- static async syncLaborTicketsToERP(connectorType, connector) {
2530
- return LaborTicketERPSynchronizer.syncToERP(connectorType, connector);
2531
- }
2532
- /**
2533
- * Retries labor tickets that have failed to be created or updated in the ERP during the sync:
2534
- *
2535
- * Fetches failed labor tickets from MM, processes them, and updates the labor ticket id in MM.
2536
- * If the labor ticket is successfully created or updated, it is added to the list of successful labor ticket ids,
2537
- * which are then deleted from the list of failed labor ticket ids.
2538
- */
2539
- static async retryFailedLaborTickets(connectorType, connector) {
2540
- return LaborTicketERPSynchronizer.retryFailed(connectorType, connector);
2541
- }
2542
- /**
2543
- * Writes a batch of records to MM for a specific entity type by:
2544
- * 1. Deduplicating against cached records (localDedupeCount)
2545
- * 2. Sending non-duplicate records to the MM API (apiDedupeCount)
2546
- * 3. Storing successful records in cache
2547
- *
2548
- * An example usage pattern including comprehensive error handling:
2549
- * ```
2550
- * try {
2551
- * const result = await StandardProcessDrivers.writeEntitiesToMM(
2552
- * 'WorkOrders',
2553
- * workOrderRecords,
2554
- * batchCacheManager
2555
- * );
2556
- *
2557
- * // HTTP 200 - Complete success
2558
- * console.log(`✅ Success: ${result.message}`);
2559
- * console.log(`📊 Metrics: ${result.upsertedEntities} upserted, ${result.localDedupeCount} locally deduplicated, ${result.apiDedupeCount} API deduplicated`);
2560
- *
2561
- * } catch (error) {
2562
- * if (error instanceof MMBatchValidationError) {
2563
- * // HTTP 207 - Partial success with some batches failing due to validation errors
2564
- * // HTTP 500 - A specific type representing complete failure due to validation issues;
2565
- * // other 500 types represent failure due to other issues and are not converted to MMBatchValidationError
2566
- * // Note: Each batch error contains ALL entities from the failing batch, not necessarily just the failed ones
2567
- *
2568
- * console.log(`⚠️ Batch processing completed with errors (HTTP ${error.httpStatus})`);
2569
- * console.log(`📊 Metrics: ${error.upsertedEntities} upserted, ${error.localDedupeCount} locally deduplicated, ${error.apiDedupeCount} API deduplicated`);
2570
- * console.log(`❌ Error count: ${error.errorCount}`);
2571
- *
2572
- * // Process specific batch errors for retry or logging
2573
- * error.batchErrors.forEach((batchError, index) => {
2574
- * console.log(`Batch ${index + 1} error: ${batchError.message}`);
2575
- * console.log(`All entities in failing batch:`, batchError.affectedEntities);
2576
- *
2577
- * // Example: Queue entire failing batch for retry (contains both successful and failed entities)
2578
- * await queueForRetry(batchError.affectedEntities);
2579
- * });
2580
- *
2581
- * // Decide whether to continue or halt based on httpStatus
2582
- * if (error.httpStatus === 207) {
2583
- * // Partial success - some batches processed successfully, others failed
2584
- * console.log('⚠️ Continuing with partial success');
2585
- * } else if (error.httpStatus === 500) {
2586
- * // Complete failure - all batches failed due to validation issues
2587
- * console.log('🛑 Complete failure - no records processed');
2588
- * throw error; // Re-throw if complete failure should halt the process
2589
- * }
2590
- *
2591
- * } else {
2592
- * // Other underlying errors (network issues, authentication, etc.)
2593
- * console.error('🚨 Unexpected error during MM API call:', error);
2594
- *
2595
- * // Example: Check for specific error types
2596
- * if (error.message?.includes('authentication')) {
2597
- * console.error('🔐 Authentication issue - check MM API credentials');
2598
- * } else if (error.message?.includes('network') || error.code === 'ECONNREFUSED') {
2599
- * console.error('🌐 Network connectivity issue - check MM API endpoint');
2600
- * }
2601
- *
2602
- * throw error; // Re-throw for upstream handling
2603
- * }
2604
- * }
2605
- * ```
2606
- *
2607
- * @param entityType The type of entity being processed
2608
- * @param mmRecords The records to process
2609
- * @param batchCacheManager The batch cache manager instance; pass in null if caching is not desired
2610
- *
2611
- * @returns WriteEntitiesToMMResult on complete success (HTTP 200)
2612
- * @throws MMBatchValidationError on partial success (HTTP 207) or complete failure (HTTP 500) with structured error details
2613
- * @throws Error on other underlying issues (network, authentication, etc.)
2614
- */
2615
- static async writeEntitiesToMM(entityType, mmRecords, batchCacheManager) {
2616
- return MMEntityProcessor.writeEntities(
2617
- entityType,
2618
- mmRecords,
2619
- batchCacheManager
2620
- );
2621
- }
2622
- /**
2623
- * Writes a batch of Work Order related entities to MM maintaining referential integrity by:
2624
- * 1. Processing parts first (base entities)
2625
- * 2. Processing part operations (depends on parts)
2626
- * 3. Processing work orders (depends on parts)
2627
- * 4. Processing work order operations (depends on work orders and part operations)
2628
- *
2629
- * This ensures all foreign key constraints are satisfied and prevents referential integrity errors.
2630
- *
2631
- * @param workOrderBatch The batch containing all related entities
2632
- * @param batchCacheManager The batch cache manager instance; pass in null if caching is not desired
2633
- *
2634
- * @returns Combined results from all entity processing
2635
- * @throws MMBatchValidationError on partial success or complete failure with structured error details
2636
- * @throws Error on other underlying issues (network, authentication, etc.)
2637
- */
2638
- static async writeWorkOrderBatchToMM(workOrderBatch, batchCacheManager) {
2639
- const partsResult = await MMEntityProcessor.writeEntities(
2640
- ERPObjType.PARTS,
2641
- workOrderBatch.parts,
2642
- batchCacheManager
2643
- );
2644
- const partOperationsResult = await MMEntityProcessor.writeEntities(
2645
- ERPObjType.PART_OPERATION,
2646
- workOrderBatch.partOperations,
2647
- batchCacheManager
2648
- );
2649
- const workOrdersResult = await MMEntityProcessor.writeEntities(
2650
- ERPObjType.WORK_ORDERS,
2651
- workOrderBatch.workOrders,
2652
- batchCacheManager
2653
- );
2654
- const workOrderOperationsResult = await MMEntityProcessor.writeEntities(
2655
- ERPObjType.WORK_ORDER_OPERATIONS,
2656
- workOrderBatch.workOrderOperations,
2657
- batchCacheManager
2658
- );
2659
- return {
2660
- parts: partsResult,
2661
- partOperations: partOperationsResult,
2662
- workOrders: workOrdersResult,
2663
- workOrderOperations: workOrderOperationsResult
2664
- };
2665
- }
2666
- /**
2667
- * Processes flattened work order data and syncs it to MM maintaining referential integrity.
2668
- *
2669
- * This method expects flattened data where each row contains both work order and operation information
2670
- * with camelCase field names matching the GraphQL schema. It will automatically extract and deduplicate
2671
- * parts, part operations, work orders, and work order operations, then process them in the correct order
2672
- * to maintain referential integrity.
2673
- *
2674
- * @param flattenedData Array of flattened rows containing both work order and operation data (camelCase fields)
2675
- * @param batchCacheManager The batch cache manager instance; pass in null if caching is not desired
2676
- *
2677
- * @returns Combined results from all entity processing with detailed logging information
2678
- * @throws MMBatchValidationError on partial success or complete failure with structured error details
2679
- * @throws Error on other underlying issues (network, authentication, etc.)
2680
- */
2681
- static async syncWorkOrderBatchFromFlattened(flattenedData, batchCacheManager) {
2682
- if (!flattenedData || flattenedData.length === 0) {
2683
- throw new Error("No flattened work order data provided");
2684
- }
2685
- const uniqueParts = /* @__PURE__ */ new Map();
2686
- const uniquePartOperations = /* @__PURE__ */ new Map();
2687
- const uniqueWorkOrders = /* @__PURE__ */ new Map();
2688
- const workOrderOperations = [];
2689
- for (const row of flattenedData) {
2690
- const partKey = `${row.partNumber}|${row.partRevision}|${row.method}`;
2691
- if (!uniqueParts.has(partKey)) {
2692
- uniqueParts.set(partKey, {
2693
- partNumber: row.partNumber,
2694
- // → partNumber
2695
- partRevision: row.partRevision,
2696
- // → partRevision
2697
- method: row.method
2698
- // → method
2699
- });
2700
- }
2701
- const partOpKey = `${row.partNumber}|${row.partRevision}|${row.method}|${row.sequenceNumber}`;
2702
- if (!uniquePartOperations.has(partOpKey)) {
2703
- uniquePartOperations.set(partOpKey, {
2704
- partNumber: row.partNumber,
2705
- // → partNumber
2706
- partRevision: row.partRevision,
2707
- // → partRevision
2708
- method: row.method,
2709
- // → method
2710
- sequenceNumber: row.sequenceNumber,
2711
- // → sequenceNumber
2712
- resourceId: row.resourceId,
2713
- // → resourceId
2714
- cycleTimeMs: row.cycleTimeMs,
2715
- // → cycleTimeMs
2716
- setupTimeMs: row.setupTimeMs,
2717
- // → setupTimeMs
2718
- description: row.operationDescription || "",
2719
- // → description
2720
- quantityPerPart: row.quantityPerPart || 1
2721
- // → quantityPerPart
2722
- });
2723
- }
2724
- const workOrderKey = row.workOrderId;
2725
- if (!uniqueWorkOrders.has(workOrderKey)) {
2726
- uniqueWorkOrders.set(workOrderKey, {
2727
- workOrderId: row.workOrderId,
2728
- // → workOrderId
2729
- lot: row.lot,
2730
- // → lot
2731
- split: row.split,
2732
- // → split
2733
- sub: row.sub,
2734
- // → sub
2735
- status: row.status,
2736
- // → status
2737
- dueDate: row.dueDate,
2738
- // → dueDate
2739
- description: row.description,
2740
- // → description
2741
- scheduledStartDate: row.scheduledStartDate,
2742
- // → scheduledStartDate
2743
- scheduledEndDate: row.scheduledEndDate,
2744
- // → scheduledEndDate
2745
- closedDate: row.closedDate,
2746
- // → closedDate
2747
- quantityRequired: row.quantityRequired,
2748
- // → quantityRequired
2749
- partNumber: row.partNumber,
2750
- // → partNumber
2751
- partRevision: row.partRevision,
2752
- // → partRevision
2753
- method: row.method
2754
- // → method
2755
- });
2756
- }
2757
- workOrderOperations.push({
2758
- workOrderId: row.workOrderId,
2759
- // → workOrderId
2760
- lot: row.lot,
2761
- // → lot
2762
- split: row.split,
2763
- // → split
2764
- sub: row.sub,
2765
- // → sub
2766
- sequenceNumber: row.sequenceNumber,
2767
- // → sequenceNumber
2768
- resourceId: row.resourceId,
2769
- // → resourceId
2770
- startQuantity: row.startQuantity,
2771
- // → startQuantity
2772
- finishQuantity: row.finishQuantity,
2773
- // → finishQuantity
2774
- expectedRejectRate: row.expectedRejectRate,
2775
- // → expectedRejectRate
2776
- scheduledStartDate: row.opScheduledStartDate,
2777
- // → scheduledStartDate
2778
- scheduledFinishDate: row.opScheduledFinishDate,
2779
- // → scheduledFinishDate
2780
- closedDate: row.opClosedDate,
2781
- // → closedDate
2782
- cycleTimeMs: row.cycleTimeMs,
2783
- // → cycleTimeMs
2784
- setupTimeMs: row.setupTimeMs,
2785
- // → setupTimeMs
2786
- productionburdenRateHourly: row.productionburdenRateHourly,
2787
- // → productionburdenRateHourly
2788
- setupburdenRatehourly: row.setupburdenRatehourly,
2789
- // → setupburdenRatehourly
2790
- operationType: row.operationType,
2791
- // → operationType
2792
- quantityPerPart: row.quantityPerPart,
2793
- // → quantityPerPart
2794
- status: row.opStatus || row.status
2795
- // → status
2796
- });
2797
- }
2798
- const parts = Array.from(uniqueParts.values()).map(
2799
- (item) => new MMSendPart(
2800
- item.partNumber || "",
2801
- // partNumber
2802
- item.partRevision || "",
2803
- // partRevision
2804
- item.method || "Standard"
2805
- // method
2806
- )
2807
- );
2808
- const partOperations = Array.from(uniquePartOperations.values()).map(
2809
- (item) => new MMSendPartOperation(
2810
- item.partNumber || "",
2811
- // partNumber
2812
- item.partRevision || "",
2813
- // partRevision
2814
- item.method || "Standard",
2815
- // method
2816
- item.sequenceNumber?.toString() || "",
2817
- // sequenceNumber
2818
- item.resourceId?.toString() || "",
2819
- // resourceId
2820
- item.cycleTimeMs || 0,
2821
- // cycleTimeMs
2822
- item.setupTimeMs || 0,
2823
- // setupTimeMs
2824
- item.description || "",
2825
- // description
2826
- item.quantityPerPart || 1
2827
- // quantityPerPart
2828
- )
2829
- );
2830
- const transformedWorkOrders = Array.from(uniqueWorkOrders.values()).map(
2831
- (item) => new MMSendWorkOrder(
2832
- item.workOrderId?.toString() || "",
2833
- // workOrderId
2834
- item.lot || "",
2835
- // lot
2836
- item.split || "",
2837
- // split
2838
- item.sub || "",
2839
- // sub
2840
- item.status || "Open",
2841
- // status
2842
- item.dueDate ? new Date(item.dueDate).toISOString() : null,
2843
- // dueDate
2844
- item.description || "",
2845
- // description
2846
- item.scheduledStartDate ? new Date(item.scheduledStartDate).toISOString() : null,
2847
- // scheduledStartDate
2848
- item.scheduledEndDate ? new Date(item.scheduledEndDate).toISOString() : null,
2849
- // scheduledEndDate
2850
- item.closedDate ? new Date(item.closedDate).toISOString() : null,
2851
- // closedDate
2852
- item.quantityRequired || 0,
2853
- // quantityRequired
2854
- item.partNumber || "",
2855
- // partNumber
2856
- item.partRevision || "",
2857
- // partRevision
2858
- item.method || "Standard"
2859
- // method
2860
- )
2861
- );
2862
- const transformedWorkOrderOperations = workOrderOperations.map(
2863
- (item) => new MMSendWorkOrderOperation(
2864
- item.workOrderId?.toString() || "",
2865
- // workOrderId
2866
- item.lot || "",
2867
- // lot
2868
- item.split || "",
2869
- // split
2870
- item.sub || "",
2871
- // sub
2872
- item.sequenceNumber?.toString() || "",
2873
- // sequenceNumber
2874
- item.resourceId?.toString() || "",
2875
- // resourceId
2876
- item.startQuantity || 0,
2877
- // startQuantity
2878
- item.finishQuantity || 0,
2879
- // finishQuantity
2880
- item.expectedRejectRate || 0,
2881
- // expectedRejectRate
2882
- item.scheduledStartDate ? new Date(item.scheduledStartDate).toISOString() : null,
2883
- // scheduledStartDate
2884
- item.scheduledFinishDate ? new Date(item.scheduledFinishDate).toISOString() : null,
2885
- // scheduledFinishDate
2886
- item.closedDate ? new Date(item.closedDate).toISOString() : null,
2887
- // closedDate
2888
- item.cycleTimeMs || 0,
2889
- // cycleTimeMs
2890
- item.setupTimeMs || 0,
2891
- // setupTimeMs
2892
- parseFloat(item.productionburdenRateHourly || "0"),
2893
- // productionburdenRateHourly
2894
- parseFloat(item.setupburdenRatehourly || "0"),
2895
- // setupburdenRatehourly
2896
- item.operationType || "Production",
2897
- // operationType
2898
- item.quantityPerPart || 1,
2899
- // quantityPerPart
2900
- item.status || "Open"
2901
- // status
2902
- )
2903
- );
2904
- const partsResult = await MMEntityProcessor.writeEntities(
2905
- ERPObjType.PARTS,
2906
- parts,
2907
- batchCacheManager
2908
- );
2909
- const partOperationsResult = await MMEntityProcessor.writeEntities(
2910
- ERPObjType.PART_OPERATION,
2911
- partOperations,
2912
- batchCacheManager
2913
- );
2914
- const workOrdersResult = await MMEntityProcessor.writeEntities(
2915
- ERPObjType.WORK_ORDERS,
2916
- transformedWorkOrders,
2917
- batchCacheManager
2918
- );
2919
- const workOrderOperationsResult = await MMEntityProcessor.writeEntities(
2920
- ERPObjType.WORK_ORDER_OPERATIONS,
2921
- transformedWorkOrderOperations,
2922
- batchCacheManager
2923
- );
2924
- return {
2925
- parts: partsResult,
2926
- partOperations: partOperationsResult,
2927
- workOrders: workOrdersResult,
2928
- workOrderOperations: workOrderOperationsResult
2929
- };
2930
- }
2931
- }
2932
- const DEFAULT_RETRY_ATTEMPTS$1 = 0;
2933
- const DEFAULT_PAGINATION_LIMIT = 100;
2934
- class RestAPIService {
2935
- client;
2936
- config;
2937
- paginationLimit;
2938
- constructor(config2, retryAttempts, paginationLimit) {
2939
- this.config = config2;
2940
- this.paginationLimit = paginationLimit ?? DEFAULT_PAGINATION_LIMIT;
2941
- this.client = HTTPClientFactory.getInstance({
2942
- baseUrl: config2.apiUrl,
2943
- retryAttempts: retryAttempts ?? DEFAULT_RETRY_ATTEMPTS$1
2944
- });
2945
- }
2946
- //#region Get Request Helpers
2947
- async getHeaders() {
2948
- const token = await this.config.getAuthToken();
2949
- return {
2950
- "Content-Type": "application/json",
2951
- Accept: "application/json",
2952
- ...token ? { Authorization: `Bearer ${token}` } : {}
2953
- };
2954
- }
2955
- buildQueryParams(query = {}) {
2956
- const { limit, nextPage, filter } = query;
2957
- const queryParams = {};
2958
- if (limit) {
2959
- queryParams.take = limit.toString();
2960
- }
2961
- if (nextPage) {
2962
- queryParams.skip = nextPage;
2963
- }
2964
- if (filter) {
2965
- if (filter.in) {
2966
- filter.in.forEach((filterIn) => {
2967
- const query2 = filterIn.value.join("|");
2968
- queryParams[`${filterIn.field}[in]`] = query2;
2969
- });
2970
- }
2971
- if (filter.and) {
2972
- queryParams["filter[and]"] = buildLogicalCondition(filter.and, "and");
2973
- }
2974
- if (filter.or) {
2975
- queryParams["filter[or]"] = buildLogicalCondition(filter.or, "or");
2976
- }
2977
- }
2978
- return new URLSearchParams(queryParams);
2979
- }
2980
- /**
2981
- * Builds pagination metadata for API responses
2982
- * @param limit - Optional limit for this specific request. If not provided, uses the service's default pagination limit
2983
- * @param nextPage - Optional next page token
2984
- * @param previousPage - Optional previous page token
2985
- * @param dataLength - Number of items in the current response
2986
- * @param totalCount - Total number of items available
2987
- * @returns Pagination metadata including count, limit, and page tokens
2988
- */
2989
- buildPagination(limit, nextPage, previousPage, dataLength = 0, totalCount) {
2990
- const paging = {
2991
- count: totalCount || 0,
2992
- limit: limit || this.paginationLimit,
2993
- nextPage: void 0,
2994
- previousPage
2995
- };
2996
- if (limit) {
2997
- paging.limit = limit;
2998
- const currentSkip = parseInt(nextPage || "0");
2999
- if (dataLength > 0 && (!totalCount || currentSkip + limit < totalCount)) {
3000
- paging.nextPage = `${currentSkip + limit}`;
3001
- }
3002
- }
3003
- return paging;
3004
- }
3005
- buildUrl(endpoint, queryParams) {
3006
- const pathParts = [this.config.apiUrl || ""];
3007
- pathParts.push(endpoint);
3008
- const path2 = pathParts.filter(Boolean).join("/");
3009
- return queryParams ? `${path2}?${queryParams.toString()}` : path2;
3010
- }
3011
- //#endregion get request helpers
3012
- async get(endpoint, query = {}) {
3013
- try {
3014
- const params = this.buildQueryParams(query);
3015
- const url = this.buildUrl(endpoint, params);
3016
- const headers = await this.getHeaders();
3017
- const response = await this.client.request({
3018
- method: "GET",
3019
- url,
3020
- headers
3021
- });
3022
- const paging = this.buildPagination(
3023
- query.limit,
3024
- query.nextPage,
3025
- query.previousPage,
3026
- response.data.Data?.length,
3027
- response.data.TotalCount
3028
- );
3029
- return {
3030
- data: response.data.Data || [],
3031
- metadata: {
3032
- pagination: paging
3033
- }
3034
- };
3035
- } catch (error) {
3036
- ErrorHandler.handle(error);
3037
- }
3038
- }
3039
- async patch(endpoint, id, data) {
3040
- try {
3041
- const url = this.buildUrl(`${endpoint}/${id}`);
3042
- const headers = await this.getHeaders();
3043
- const response = await this.client.request({
3044
- method: "PATCH",
3045
- url,
3046
- data,
3047
- headers
3048
- });
3049
- return {
3050
- data: response.data
3051
- };
3052
- } catch (error) {
3053
- ErrorHandler.handle(error);
3054
- }
3055
- }
3056
- async post(endpoint, data) {
3057
- try {
3058
- const url = this.buildUrl(endpoint);
3059
- const headers = await this.getHeaders();
3060
- const response = await this.client.request({
3061
- method: "POST",
3062
- url,
3063
- data,
3064
- headers
3065
- });
3066
- return {
3067
- data: response.data
3068
- };
3069
- } catch (error) {
3070
- ErrorHandler.handle(error);
3071
- }
3072
- }
3073
- /**
3074
- * Cleanup all HTTP connections and resources
3075
- * Call this when the service is no longer needed
3076
- */
3077
- async destroy() {
3078
- await this.client.destroy();
3079
- }
3080
- }
3081
- function getERPAPITypeFromEntity(entity, entityMap) {
3082
- const entry = Object.entries(entityMap).find(
3083
- ([_, value]) => value.entity === entity
3084
- );
3085
- return entry ? Number(entry[0]) : void 0;
3086
- }
3087
- const isNonEmptyString = (v) => typeof v === "string" && v.trim().length > 0;
3088
- function getErrorType(error) {
3089
- if (error && typeof error === "object") {
3090
- const o = error;
3091
- if (isNonEmptyString(o.code)) return o.code;
3092
- if (isNonEmptyString(o.name)) return o.name;
3093
- const ctorName = o.constructor?.name;
3094
- if (isNonEmptyString(ctorName) && ctorName !== "Object") return ctorName;
3095
- }
3096
- return "Error";
3097
- }
3098
- class LogEntry {
3099
- level;
3100
- message;
3101
- dedupeKey;
3102
- eventTime;
3103
- constructor(params) {
3104
- this.level = params.level;
3105
- this.message = params.message;
3106
- this.dedupeKey = params.dedupeKey;
3107
- this.eventTime = Date.now();
3108
- }
3109
- }
3110
- function isLogResponse(value) {
3111
- if (value === null || typeof value !== "object") return false;
3112
- const v = value;
3113
- if (typeof v.message !== "string") return false;
3114
- if ("processed" in v && typeof v.processed !== "number") return false;
3115
- return true;
3116
- }
3117
- class MMConnectorLogger {
3118
- MAX_MSG_LEN = 2e3;
3119
- mmApiClient;
3120
- deduper;
3121
- source;
3122
- constructor(source, deduper) {
3123
- if (source.length < 1 || source.length > 64) {
3124
- throw new Error("source must be 1-64 characters");
3125
- }
3126
- this.mmApiClient = new MMApiClient();
3127
- this.deduper = deduper;
3128
- this.source = source;
3129
- }
3130
- // Deduplication helpers are delegated to injected FileLogDeduper
3131
- /**
3132
- * Send a single log entry to the MM cloud with deduplication.
3133
- *
3134
- * The deduplication is handled by the injected LogDeduper.
3135
- * If no deduper is injected, the log entry is sent without deduplication.
3136
- *
3137
- * The standard deduper, FileLogDeduper, stores the deduplication state in a file,
3138
- * allowing deduplication across jobs,
3139
- *
3140
- * @param logEntry - The log entry to send
3141
- * @returns Promise resolving to the API response or null if suppressed
3142
- * @throws HTTPError if the request fails or Error if the log entry is invalid
3143
- */
3144
- async sendLog(logEntry) {
3145
- this.validateLogEntry(logEntry);
3146
- const now = Date.now();
3147
- let messageToSend = logEntry.message;
3148
- if (this.deduper) {
3149
- const decision = await this.deduper.decide(logEntry, now);
3150
- if (decision === null) return null;
3151
- messageToSend = decision;
3152
- }
3153
- try {
3154
- const logEntryToSend = {
3155
- source: this.source,
3156
- level: logEntry.level,
3157
- message: messageToSend
3158
- };
3159
- const response = await this.mmApiClient.sendConnectorLog(logEntryToSend);
3160
- if (this.deduper) {
3161
- await this.deduper.onSuccess(logEntry, now);
3162
- }
3163
- if (!isLogResponse(response)) {
3164
- logger.warn("Unexpected success response format from MM API for connector log", { response });
3165
- return { message: "Unexpected success response format when sending log" };
3166
- }
3167
- return { message: response.message };
3168
- } catch (error) {
3169
- logger.error("Failed to send log to MM cloud", {
3170
- level: logEntry.level,
3171
- error: error instanceof Error ? error.message : "Unknown error"
3172
- });
3173
- throw error;
3174
- }
3175
- }
3176
- /**
3177
- * @throws Error if validation fails
3178
- */
3179
- validateLogEntry(logEntry) {
3180
- const allowedLevels = ["info", "warn", "error"];
3181
- if (!logEntry.level || !allowedLevels.includes(logEntry.level)) {
3182
- throw new Error(`level must be one of: ${allowedLevels.join(", ")}`);
3183
- }
3184
- if (!logEntry.message || typeof logEntry.message !== "string") {
3185
- throw new Error("message is required and must be a string");
3186
- }
3187
- logEntry.message = logEntry.message.slice(0, this.MAX_MSG_LEN);
3188
- if (!logEntry.dedupeKey || typeof logEntry.dedupeKey !== "string") {
3189
- throw new Error("dedupeKey is required and must be a string");
3190
- }
3191
- if (logEntry.dedupeKey.trim().length < 1) {
3192
- throw new Error("dedupeKey must be a non-empty string");
3193
- }
3194
- }
3195
- /**
3196
- * Retry all failed transmissions silently
3197
- * This method attempts to retry all messages that failed to transmit
3198
- * and removes them from the failed list if successful, else leaves them for the client to retry
3199
- *
3200
- * Expected usage is by a client to call this as part of its own retry mechanism
3201
- */
3202
- async retryFailedTransmissions() {
3203
- if (!this.deduper || !this.deduper.retryFailedTransmissions) {
3204
- return;
3205
- }
3206
- await this.deduper.retryFailedTransmissions(async (entry, message) => {
3207
- await this.mmApiClient.sendConnectorLog({
3208
- source: this.source,
3209
- level: entry.level,
3210
- message
3211
- });
3212
- });
3213
- }
3214
- /**
3215
- * Clean up resources
3216
- */
3217
- async destroy() {
3218
- await this.mmApiClient.destroy();
3219
- }
3220
- }
3221
- class FileLogDeduper {
3222
- storeFilePath;
3223
- windowMs;
3224
- ttlMs;
3225
- sweepIntervalMs;
3226
- lastSweepTsMs;
3227
- DEFAULT_WINDOW_TEN_MINS = 600;
3228
- DEFAULT_TTL_ONE_HOUR = 3600;
3229
- DEFAULT_SWEEP_INTERVAL_FIVE_MINS = 300;
3230
- DEFAULT_STORE_FILE_PATH = path.join("/tmp", "log-deduplication.json");
3231
- /**
3232
- * Ctor.
3233
- * @param storeFilePath: The path to the file where the deduplication store is stored; recommended is to use the default
3234
- * @param windowSeconds: Suppression window. Duplicates within this period are suppressed.
3235
- * @param ttlSeconds: Eviction TTL. Store entries for keys inactive beyond this are removed. Enforced to be ≥ windowSeconds.
3236
- * @param sweepIntervalSeconds: Efficiency parameter. How often (min interval) to run opportunistic eviction; retry always sweeps
3237
- * The sweep is lazy, used only when the store is accessed
3238
- */
3239
- constructor({
3240
- storeFilePath = this.DEFAULT_STORE_FILE_PATH,
3241
- windowSeconds = this.DEFAULT_WINDOW_TEN_MINS,
3242
- ttlSeconds = this.DEFAULT_TTL_ONE_HOUR,
3243
- sweepIntervalSeconds = this.DEFAULT_SWEEP_INTERVAL_FIVE_MINS
3244
- } = {}) {
3245
- this.storeFilePath = storeFilePath;
3246
- this.windowMs = Math.max(1, windowSeconds) * 1e3;
3247
- this.ttlMs = Math.max(this.windowMs, Math.max(1, ttlSeconds) * 1e3);
3248
- this.sweepIntervalMs = Math.max(1, sweepIntervalSeconds) * 1e3;
3249
- this.lastSweepTsMs = 0;
3250
- this.ensureStoreFileExists();
3251
- }
3252
- /**
3253
- * Deduplication gating function
3254
- * Returns the formatted message to send, or null to suppress
3255
- * Decision is based on the dedupeKey and the time of the entry
3256
- */
3257
- async decide(entry, now) {
3258
- if (!entry.dedupeKey || typeof entry.dedupeKey !== "string" || entry.dedupeKey.trim().length === 0) {
3259
- throw new Error("dedupeKey is required and must be a non-empty string");
3260
- }
3261
- const key = entry.dedupeKey;
3262
- return this.withLock(async () => {
3263
- const store = this.readStore();
3264
- if (now - this.lastSweepTsMs >= this.sweepIntervalMs) {
3265
- this.evictExpiredInStore(store, now);
3266
- this.lastSweepTsMs = now;
3267
- this.writeStore(store);
3268
- }
3269
- const existing = store[key];
3270
- if (existing) {
3271
- const withinWindow = existing.lastTransmitted > 0 && existing.lastTransmitted + this.windowMs > now;
3272
- if (withinWindow) {
3273
- store[key] = {
3274
- ...existing,
3275
- suppressedCount: existing.suppressedCount + 1,
3276
- firstUnsentEventTs: existing.suppressedCount === 0 ? entry.eventTime ?? now : existing.firstUnsentEventTs,
3277
- lastEventTs: entry.eventTime ?? now,
3278
- level: entry.level,
3279
- message: entry.message
3280
- };
3281
- this.writeStore(store);
3282
- return null;
3283
- }
3284
- const messageToSend2 = this.formatMessage(entry.message, entry.eventTime ?? now, existing.suppressedCount, existing.firstUnsentEventTs);
3285
- store[key] = {
3286
- ...existing,
3287
- suppressedCount: 0,
3288
- firstUnsentEventTs: 0,
3289
- lastEventTs: entry.eventTime ?? now,
3290
- level: entry.level,
3291
- message: entry.message
3292
- };
3293
- this.writeStore(store);
3294
- return messageToSend2;
3295
- }
3296
- const messageToSend = this.formatMessage(entry.message, entry.eventTime ?? now, 0);
3297
- store[key] = {
3298
- lastTransmitted: 0,
3299
- suppressedCount: 0,
3300
- firstUnsentEventTs: entry.eventTime ?? now,
3301
- lastEventTs: entry.eventTime ?? now,
3302
- level: entry.level,
3303
- message: entry.message
3304
- };
3305
- this.writeStore(store);
3306
- return messageToSend;
3307
- });
3308
- }
3309
- async onSuccess(entry, now) {
3310
- if (!entry.dedupeKey || typeof entry.dedupeKey !== "string" || entry.dedupeKey.trim().length === 0) {
3311
- throw new Error("dedupeKey is required and must be a non-empty string");
3312
- }
3313
- const key = entry.dedupeKey;
3314
- await this.withLock(async () => {
3315
- const store = this.readStore();
3316
- const existing = store[key];
3317
- if (existing) {
3318
- store[key] = {
3319
- ...existing,
3320
- lastTransmitted: now,
3321
- firstUnsentEventTs: 0,
3322
- suppressedCount: 0
3323
- };
3324
- this.writeStore(store);
3325
- }
3326
- });
3327
- }
3328
- async retryFailedTransmissions(send) {
3329
- const now = Date.now();
3330
- const entries = await this.withLock(async () => {
3331
- const store = this.readStore();
3332
- this.evictExpiredInStore(store, now);
3333
- this.lastSweepTsMs = now;
3334
- this.writeStore(store);
3335
- return Object.entries(store).filter(([, rec]) => rec.lastTransmitted === 0).map(([key, rec]) => ({ key, rec }));
3336
- });
3337
- for (const { key, rec } of entries) {
3338
- try {
3339
- const message = this.formatMessage(rec.message, rec.lastEventTs, rec.suppressedCount, rec.firstUnsentEventTs);
3340
- await send({ level: rec.level, message: rec.message, dedupeKey: key, eventTime: rec.lastEventTs }, message);
3341
- await this.withLock(async () => {
3342
- const store = this.readStore();
3343
- const current = store[key];
3344
- if (current) {
3345
- store[key] = {
3346
- ...current,
3347
- lastTransmitted: Date.now(),
3348
- suppressedCount: 0
3349
- };
3350
- this.writeStore(store);
3351
- }
3352
- });
3353
- } catch (err) {
3354
- logger.error("Failed to retry failed transmission", { key, rec, error: err });
3355
- return;
3356
- }
3357
- }
3358
- }
3359
- // --- Internals ---
3360
- ensureStoreFileExists() {
3361
- try {
3362
- if (!fs.existsSync(this.storeFilePath)) {
3363
- fs.writeFileSync(this.storeFilePath, JSON.stringify({}), "utf-8");
3364
- }
3365
- } catch {
3366
- }
3367
- }
3368
- readStore() {
3369
- try {
3370
- if (!fs.existsSync(this.storeFilePath)) return {};
3371
- const content = fs.readFileSync(this.storeFilePath, "utf-8");
3372
- return content ? JSON.parse(content) : {};
3373
- } catch {
3374
- return {};
3375
- }
3376
- }
3377
- writeStore(store) {
3378
- try {
3379
- fs.writeFileSync(this.storeFilePath, JSON.stringify(store, null, 2), "utf-8");
3380
- } catch {
3381
- }
3382
- }
3383
- formatMessage(message, eventTs, suppressedCount, firstUnsentEventTs) {
3384
- const timestamp = new Date(eventTs).toISOString();
3385
- const base = `${timestamp} | ${message}`;
3386
- if (suppressedCount > 0) {
3387
- const since = firstUnsentEventTs && firstUnsentEventTs > 0 ? ` since ${new Date(firstUnsentEventTs).toISOString()}` : "";
3388
- return `${base} (${suppressedCount} suppressed${since})`;
3389
- }
3390
- return base;
3391
- }
3392
- async withLock(fn) {
3393
- const lockPath = `${this.storeFilePath}.lock`;
3394
- const start = Date.now();
3395
- while (true) {
3396
- try {
3397
- const fd = fs.openSync(lockPath, "wx");
3398
- try {
3399
- const result = await fn();
3400
- return result;
3401
- } finally {
3402
- try {
3403
- fs.closeSync(fd);
3404
- } catch {
3405
- }
3406
- try {
3407
- fs.unlinkSync(lockPath);
3408
- } catch {
3409
- }
3410
- }
3411
- } catch {
3412
- if (Date.now() - start > 3e3) {
3413
- return await fn();
3414
- }
3415
- await new Promise((resolve) => setTimeout(resolve, 50));
3416
- }
3417
- }
3418
- }
3419
- /**
3420
- * Evict expired entries from the store based on the TTL and the key's last transmitted time
3421
- */
3422
- evictExpiredInStore(store, now) {
3423
- const keys = Object.keys(store);
3424
- if (keys.length === 0) return;
3425
- for (const key of keys) {
3426
- const rec = store[key];
3427
- const referenceTs = rec.lastTransmitted > 0 ? rec.lastTransmitted : rec.lastEventTs;
3428
- if (now - referenceTs > this.ttlMs) {
3429
- delete store[key];
3430
- }
3431
- }
3432
- }
3433
- }
3434
- class ApplicationInitializer {
3435
- /**
3436
- * Performs all necessary application initialization tasks
3437
- * This should be called before starting any services or jobs
3438
- */
3439
- static async initialize() {
3440
- try {
3441
- logger.info(
3442
- "\n================================INITIALIZING APPLICATION================================\n"
3443
- );
3444
- const coreConfig = CoreConfiguration.inst();
3445
- logger.info("Core Configuration loaded:", coreConfig.toSafeLogObject());
3446
- logger.info("Performing database startup checks...");
3447
- await SQLiteCoordinator.performStartupCheck();
3448
- logger.info("Database startup checks completed successfully");
3449
- logger.info("Running database migrations...");
3450
- await ApplicationInitializer.runMigrations();
3451
- logger.info("Database migrations completed successfully");
3452
- await getTimezoneOffsetAndPersist();
3453
- logger.info(
3454
- "\n================================APPLICATION INITIALIZATION COMPLETED================================\n"
3455
- );
3456
- } catch (error) {
3457
- logger.error("Critical initialization failure. Exiting.", error);
3458
- process.exitCode = 1;
3459
- }
3460
- }
3461
- /**
3462
- * Runs database migrations to ensure all required tables exist
3463
- */
3464
- static async runMigrations() {
3465
- const db = knex(config.local);
3466
- try {
3467
- await db.migrate.latest();
3468
- } catch (error) {
3469
- logger.error("Error running migrations:", error);
3470
- throw error;
3471
- } finally {
3472
- await db.destroy();
3473
- }
3474
- }
3475
- }
3476
- const DEFAULT_RETRY_ATTEMPTS = 0;
3477
- class GraphQLService {
3478
- client;
3479
- config;
3480
- endpoint;
3481
- constructor(config2, endpoint, retryAttempts) {
3482
- this.config = config2;
3483
- this.endpoint = endpoint ? endpoint.startsWith("/") ? endpoint : `/${endpoint}` : "";
3484
- this.client = HTTPClientFactory.getInstance({
3485
- baseUrl: config2.apiUrl,
3486
- retryAttempts: retryAttempts ?? DEFAULT_RETRY_ATTEMPTS
3487
- });
3488
- }
3489
- async getHeaders() {
3490
- const token = await this.config.getAuthToken();
3491
- return {
3492
- "Content-Type": "application/json",
3493
- Accept: "application/json",
3494
- ...token ? { Authorization: `Bearer ${token}` } : {}
3495
- };
3496
- }
3497
- /**
3498
- * Handles a GraphQL response, properly handling both successful responses
3499
- * and GraphQL-level errors (which come in a 200 HTTP response)
3500
- *
3501
- * From the GraphQL specification (https://spec.graphql.org/draft/#sec-Errors):
3502
- > * "When a GraphQL server encounters an error, it should return a response with a
3503
- > * top-level "errors" field containing the error information. The response may still contain
3504
- * a partial result in the "data" field if the error occurred after some data was already resolved."
3505
- *
3506
- * And specifically about HTTP status codes:
3507
- * "A server should return a 200 status code when a GraphQL operation successfully executes, including when
3508
- * the operation returns errors. A server should return a 400 status code when a GraphQL operation fails to execute."
3509
- */
3510
- handleGraphQLResponse(response) {
3511
- return {
3512
- data: response.data.data,
3513
- metadata: {
3514
- errors: response.data.errors,
3515
- extensions: response.data.extensions
3516
- }
3517
- };
3518
- }
3519
- /**
3520
- * Executes a GraphQL query
3521
- * @param query The GraphQL query string
3522
- * @param variables Optional variables for the query
3523
- * @returns The query result
3524
- * @throws {HTTPError} For HTTP/network errors only
3525
- */
3526
- async query(query, variables) {
3527
- try {
3528
- const headers = await this.getHeaders();
3529
- const response = await this.client.request({
3530
- method: "POST",
3531
- url: this.endpoint,
3532
- data: { query, variables },
3533
- headers
3534
- });
3535
- return this.handleGraphQLResponse(response);
3536
- } catch (error) {
3537
- ErrorHandler.handle(error);
3538
- }
3539
- }
3540
- /**
3541
- * Executes a GraphQL mutation
3542
- * @param mutation The GraphQL mutation string
3543
- * @param variables Optional variables for the mutation
3544
- * @returns The mutation result
3545
- * @throws {HTTPError} For HTTP/network errors only
3546
- */
3547
- async mutate(mutation, variables) {
3548
- try {
3549
- const headers = await this.getHeaders();
3550
- const response = await this.client.request({
3551
- method: "POST",
3552
- url: this.endpoint,
3553
- data: { query: mutation, variables },
3554
- headers
3555
- });
3556
- return this.handleGraphQLResponse(response);
3557
- } catch (error) {
3558
- ErrorHandler.handle(error);
3559
- }
3560
- }
3561
- /**
3562
- * Cleanup all HTTP connections and resources
3563
- * Call this when the service is no longer needed
3564
- */
3565
- async destroy() {
3566
- await this.client.destroy();
3567
- }
3568
- }
3569
- class OAuthClient {
3570
- constructor(config2) {
3571
- this.config = config2;
3572
- }
3573
- /**
3574
- * Requests an OAuth token using the client credentials flow.
3575
- * The request is sent as application/x-www-form-urlencoded.
3576
- * @returns A promise that resolves to the token response containing access_token and expires_in
3577
- * @throws Error if the token request fails
3578
- */
3579
- async getToken() {
3580
- const formData = new URLSearchParams({
3581
- grant_type: "client_credentials",
3582
- client_id: this.config.clientId,
3583
- client_secret: this.config.clientSecret,
3584
- scope: this.config.scope
3585
- });
3586
- const response = await fetch(this.config.authUrl, {
3587
- method: "POST",
3588
- headers: {
3589
- "Content-Type": "application/x-www-form-urlencoded"
3590
- },
3591
- body: formData
3592
- });
3593
- if (!response.ok) {
3594
- throw new Error(`OAuth token request failed: ${response.statusText}`);
3595
- }
3596
- const data = await response.json();
3597
- if (data.token_type !== "Bearer") {
3598
- throw new Error(`Unexpected token type: ${data.token_type}`);
3599
- }
3600
- return data;
3601
- }
3602
- }
3603
- const runDataSyncService = async (connectorPath) => {
3604
- const config2 = CoreConfiguration.inst();
3605
- try {
3606
- const currentFileUrl = import.meta.url;
3607
- const currentFilePath = fileURLToPath(currentFileUrl);
3608
- const sdkDistPath = path.dirname(currentFilePath);
3609
- const jobsPath = path.join(
3610
- sdkDistPath,
3611
- "services",
3612
- "data-sync-service",
3613
- "jobs"
3614
- );
3615
- const bree = new Bree({
3616
- root: jobsPath,
3617
- logger,
3618
- worker: {
3619
- env: {
3620
- CONNECTOR_PATH: connectorPath,
3621
- // Pass through all required environment variables
3622
- MM_MAPPING_SERVICE_URL: process.env.MM_MAPPING_SERVICE_URL,
3623
- MM_MAPPING_AUTH_SERVICE_URL: process.env.MM_MAPPING_AUTH_SERVICE_URL,
3624
- MM_MAPPING_SERVICE_TOKEN: process.env.MM_MAPPING_SERVICE_TOKEN,
3625
- ERP_SYSTEM: process.env.ERP_SYSTEM,
3626
- LOG_LEVEL: process.env.LOG_LEVEL,
3627
- NODE_ENV: process.env.NODE_ENV,
3628
- RETRY_ATTEMPTS: process.env.RETRY_ATTEMPTS,
3629
- CACHE_TTL: process.env.CACHE_TTL,
3630
- // Pass through all other environment variables that might be needed
3631
- ...process.env
3632
- }
3633
- },
3634
- jobs: [
3635
- // {
3636
- // name: 'run-migrations', // Running this once on startup will create the tables in the sqlite database
3637
- // },
3638
- {
3639
- name: "from-erp",
3640
- timeout: "10s",
3641
- interval: config2.fromErpInterval
3642
- },
3643
- {
3644
- name: "to-erp",
3645
- //timeout: '3s', // Use timeout during development to see the job in action quickly
3646
- interval: config2.toErpInterval
3647
- },
3648
- {
3649
- name: "retry-failed-labor-tickets",
3650
- interval: config2.retryLaborTicketsInterval
3651
- },
3652
- {
3653
- name: "clean-up-expired-cache",
3654
- interval: config2.cacheExpirationCheckInterval
3655
- }
3656
- ]
3657
- });
3658
- logger.info(
3659
- "\n================================INITIATING DATA SYNC CYCLES (Bree)================================\n"
3660
- );
3661
- const jobsConfig = bree.config.jobs.map((job) => ({
3662
- name: job.name,
3663
- interval: job.interval,
3664
- timeout: job.timeout
3665
- }));
3666
- logger.info("JOBS CONFIGURATION:", { jobs: jobsConfig });
3667
- const graceful = new Graceful({ brees: [bree] });
3668
- graceful.listen();
3669
- (async () => {
3670
- await bree.start();
3671
- })();
3672
- bree.on("jobStarted", (job) => {
3673
- console.log("Job " + job.name + " started");
3674
- });
3675
- bree.on("jobCompleted", (job) => {
3676
- if (job.error) {
3677
- console.error("Job " + job.name + " failed:", job.error);
3678
- } else {
3679
- console.log("Job " + job.name + " completed successfully!");
3680
- }
3681
- });
3682
- bree.on("error", (error) => {
3683
- console.error("Bree error:", error);
3684
- });
3685
- logger.info(
3686
- "\n================================DATA SYNC CYCLES INITIATION COMPLETED================================\n"
3687
- );
3688
- } catch (error) {
3689
- logger.error("startUp: Error initiating data sync cycles:", error);
3690
- }
3691
- };
3692
- const SQLServerConfigSchema = z.object({
3693
- user: z.string().nonempty("User is required."),
3694
- password: z.string().nonempty("Password is required."),
3695
- database: z.string().nonempty("Database name is required."),
3696
- server: z.string().nonempty("Server is required."),
3697
- port: z.coerce.number().int().positive("Port must be a positive integer.").default(1433),
3698
- connectionTimeout: z.coerce.number().int().positive("Connection timeout must be a positive integer.").default(3e4),
3699
- requestTimeout: z.coerce.number().int().positive("Request timeout must be a positive integer.").default(6e4),
3700
- pool: z.object({
3701
- max: z.coerce.number().int().positive("Max pool size must be a positive integer.").default(10),
3702
- min: z.coerce.number().int().nonnegative("Min pool size must be a non-negative integer.").default(0),
3703
- idleTimeoutMillis: z.coerce.number().int().nonnegative("Idle timeout must be a non-negative integer.").default(3e4)
3704
- }),
3705
- options: z.object({
3706
- encrypt: z.coerce.boolean().default(false),
3707
- trustServerCertificate: z.coerce.boolean().default(false)
3708
- })
3709
- });
3710
- class SqlServerService {
3711
- connection = null;
3712
- config;
3713
- constructor(config2) {
3714
- this.config = config2;
3715
- }
3716
- async dispose() {
3717
- await this.closeConnection();
3718
- }
3719
- /**
3720
- * Execute a prepared statement and return the results
3721
- *
3722
- * @param statementToPrepare The SQL query to prepare
3723
- * @param params The parameters to bind to the prepared statement
3724
- * @param paging Optional paging parameters
3725
- * @returns The entities fetched from the database, along with paging information
3726
- */
3727
- async executePreparedStatement(statementToPrepare, params, paging) {
3728
- const connection = await this.openConnection();
3729
- const preparedStatement = new sql.PreparedStatement(connection);
3730
- Object.keys(params).forEach((key) => {
3731
- preparedStatement.input(key, sql.VarChar);
3732
- });
3733
- const finalQuery = paging?.limit !== void 0 ? `${statementToPrepare} OFFSET ${paging.offset || 0} ROWS FETCH NEXT ${paging.limit} ROWS ONLY` : statementToPrepare;
3734
- await preparedStatement.prepare(finalQuery);
3735
- let records;
3736
- try {
3737
- records = await preparedStatement.execute(params);
3738
- } catch (error) {
3739
- const errorInfo = error;
3740
- const errorMessage = "Error fetching data from ERP -> " + (errorInfo.cause ? `Cause: ${errorInfo.cause}. ` : "") + `Name: ${errorInfo.name}. Message: ${errorInfo.message}. Stack: ${errorInfo.stack}`;
3741
- throw new Error(errorMessage);
3742
- } finally {
3743
- try {
3744
- await preparedStatement.unprepare();
3745
- } catch (unprepareError) {
3746
- logger.error("Error during unprepare:", unprepareError);
3747
- }
3748
- }
3749
- const allRecords = SqlServerService.recordsetToRecords(records?.recordset);
3750
- const rowsFetched = records?.rowsAffected[0] || 0;
3751
- const pagedData = paging?.offset !== void 0 ? allRecords.slice(
3752
- paging.offset,
3753
- (paging.offset || 0) + (paging.limit || allRecords.length)
3754
- ) : allRecords;
3755
- return {
3756
- data: pagedData,
3757
- paging: {
3758
- count: rowsFetched,
3759
- limit: paging?.limit || 0,
3760
- offset: paging?.offset || 0,
3761
- nextPage: (() => {
3762
- const currentPageEnd = (paging?.offset || 0) + (paging?.limit || 0);
3763
- return paging?.limit && currentPageEnd < rowsFetched ? String(currentPageEnd) : void 0;
3764
- })(),
3765
- previousPage: paging?.offset ? String(Math.max(0, (paging.offset || 0) - (paging.limit || 10))) : void 0
3766
- }
3767
- };
3768
- }
3769
- /**
3770
- * Opens a connection to SQL Server
3771
- * Caches the connection so that it can be reused.
3772
- * On failure to connect, throws
3773
- */
3774
- async openConnection() {
3775
- if (this.connection?.connected) {
3776
- logger.debug("Reusing existing SQL Server connection");
3777
- return this.connection;
3778
- }
3779
- if (this.connection) {
3780
- logger.debug("Clearing disconnected SQL Server connection");
3781
- this.connection = null;
3782
- }
3783
- try {
3784
- logger.info("Opening new SQL Server connection");
3785
- const sqlConfig = SQLServerConfigSchema.parse({
3786
- user: this.config.username,
3787
- password: this.config.password,
3788
- database: this.config.database,
3789
- server: this.config.host,
3790
- port: parseInt(this.config.port),
3791
- connectionTimeout: parseInt(this.config.connectionTimeout),
3792
- requestTimeout: parseInt(this.config.requestTimeout),
3793
- pool: {
3794
- max: parseInt(this.config.poolMax),
3795
- min: parseInt(this.config.poolMin),
3796
- idleTimeoutMillis: parseInt(this.config.idleTimeoutMillis)
3797
- },
3798
- options: {
3799
- encrypt: this.config.encrypt,
3800
- trustServerCertificate: this.config.trustServer
3801
- }
3802
- });
3803
- this.connection = await sql.connect(sqlConfig);
3804
- return this.connection;
3805
- } catch (error) {
3806
- logger.error("SqlServerService>>openConnection>> Connection failed", {
3807
- error
3808
- });
3809
- throw new Error("SQL Server connection failed");
3810
- }
3811
- }
3812
- /**
3813
- * Transform a IRecordSet from a SQL query into an array of Record<string, string> instances.
3814
- * @param recordset IRecordSet from a SQL query
3815
- * @returns array of Record<string, string> instances
3816
- */
3817
- static recordsetToRecords(recordset) {
3818
- const data = recordset?.map((row) => {
3819
- const transformedRow = {};
3820
- Object.keys(row).forEach((key) => {
3821
- transformedRow[key] = row[key]?.toString() || "";
3822
- });
3823
- return transformedRow;
3824
- }) || [];
3825
- return data;
3826
- }
3827
- async closeConnection() {
3828
- if (this.connection?.connected) {
3829
- logger.info("Closing SQL Server connection");
3830
- try {
3831
- await this.connection.close();
3832
- } catch (error) {
3833
- logger.error(
3834
- "SqlServerService::closeConnection: Error closing connection",
3835
- {
3836
- error
3837
- }
3838
- );
3839
- }
3840
- this.connection = null;
3841
- }
3842
- }
3843
- }
3844
- class SQLTransactionManager {
3845
- constructor(connection) {
3846
- this.connection = connection;
3847
- }
3848
- /**
3849
- * Executes a transaction with the given operation and data, manages rollbacks
3850
- * @param operation The SQLTransactionOperation to execute
3851
- * @param data The sql input parameters to pass to the operation
3852
- * @param config The configuration for the transaction
3853
- * @returns The result of the operation; throws exceptions on failures
3854
- */
3855
- async executeTransaction(operation, data, config2 = {}) {
3856
- const transaction = new sql.Transaction(this.connection);
3857
- const isolationLevel = config2.isolationLevel || sql.ISOLATION_LEVEL.READ_COMMITTED;
3858
- try {
3859
- await transaction.begin(isolationLevel);
3860
- const result = await operation.execute(transaction, data);
3861
- await transaction.commit();
3862
- return result;
3863
- } catch (error) {
3864
- logger.error("Transaction error:", error);
3865
- try {
3866
- await transaction.rollback();
3867
- } catch (rollbackError) {
3868
- logger.error("Rollback error:", rollbackError);
3869
- }
3870
- throw error;
3871
- }
3872
- }
3873
- }
3874
- class SQLLaborTicketInsertOperation {
3875
- constructor(sqlQuery) {
3876
- this.sqlQuery = sqlQuery;
3877
- }
3878
- async execute(transaction, inputs) {
3879
- const request = transaction.request();
3880
- inputs.forEach((input) => {
3881
- request.input(input.name, input.type, input.value);
3882
- });
3883
- const result = await request.query(this.sqlQuery);
3884
- if (!result.recordset[0].NewRowUniqueId) {
3885
- throw new Error(
3886
- "No LaborTicketId generated by the labor ticket insert query: " + JSON.stringify(request.parameters, null, 2)
3887
- );
3888
- }
3889
- return result.recordset[0].NewRowUniqueId;
3890
- }
3891
- }
3892
- class SQLLaborTicketUpdateOperation {
3893
- constructor(sqlQuery) {
3894
- this.sqlQuery = sqlQuery;
3895
- }
3896
- async execute(transaction, inputs) {
3897
- const request = transaction.request();
3898
- inputs.forEach((input) => {
3899
- request.input(input.name, input.type, input.value);
3900
- });
3901
- const result = await request.query(this.sqlQuery);
3902
- return result.rowsAffected[0];
3903
- }
3904
- }
3905
- class SqlServerHelper {
3906
- /**
3907
- * Creates a new labor ticket in the SQL Server database
3908
- * Opens but does not close the connection
3909
- *
3910
- * @param sqlServerService The SQL Server service to use for connections
3911
- * @param laborTicket The labor ticket to create
3912
- * @param sqlInputs The SQL query parameters
3913
- * @param insertQuery The SQL query to execute for insertion
3914
- *
3915
- * @returns The processed labor ticket, with the ERP's laborTicketId set
3916
- * Throws exceptions on failures, including if the query does not return a laborTicketId
3917
- */
3918
- static async createLaborTicket(sqlServerService, laborTicket, sqlInputs, insertQuery) {
3919
- const connection = await sqlServerService.openConnection();
3920
- if (!connection) {
3921
- throw new Error(
3922
- "Unable to establish database connection to create labor ticket."
3923
- );
3924
- }
3925
- const transactionManager = new SQLTransactionManager(connection);
3926
- const laborTicketId = await transactionManager.executeTransaction(
3927
- new SQLLaborTicketInsertOperation(insertQuery),
3928
- sqlInputs
3929
- );
3930
- if (laborTicketId) {
3931
- laborTicket.laborTicketId = laborTicketId.toString();
3932
- return laborTicket;
3933
- } else {
3934
- throw new Error(
3935
- `The query did not return the labor ticket id for labor ticket ref: ${laborTicket.laborTicketRef}`
3936
- );
3937
- }
3938
- }
3939
- /**
3940
- * Updates an existing labor ticket in the SQL Server database
3941
- * Opens but does not close the connection
3942
- * @param sqlServerService The SQL Server service to use for connections
3943
- * @param laborTicket The labor ticket to update
3944
- * @param sqlInputs The SQL query parameters
3945
- * @param updateQuery The SQL query to execute for update
3946
- *
3947
- * @returns The processed labor ticket
3948
- * Throws exceptions on failures
3949
- */
3950
- static async updateLaborTicket(sqlServerService, laborTicket, sqlInputs, updateQuery) {
3951
- const connection = await sqlServerService.openConnection();
3952
- if (!connection) {
3953
- throw new Error(
3954
- "Unable to establish database connection to update labor ticket."
3955
- );
3956
- }
3957
- const transactionManager = new SQLTransactionManager(connection);
3958
- await transactionManager.executeTransaction(
3959
- new SQLLaborTicketUpdateOperation(updateQuery),
3960
- sqlInputs
3961
- );
3962
- return laborTicket;
3963
- }
3964
- /**
3965
- * Logs the SQL input parameters for debugging
3966
- */
3967
- static logQueryInputs(inputs) {
3968
- logger.info("SQL Input Variables:");
3969
- logger.info("----------------------------------------");
3970
- logger.info("Variable Name | Value");
3971
- logger.info("----------------------------------------");
3972
- inputs.forEach((input) => {
3973
- logger.info(`${input.name.padEnd(20)} | ${input.value}`);
3974
- });
3975
- logger.info("----------------------------------------");
3976
- }
3977
- }
3978
- class PsqlService {
3979
- config;
3980
- static odbcModule = null;
3981
- static odbcLoadError = null;
3982
- constructor(config2) {
3983
- this.config = config2;
3984
- }
3985
- /**
3986
- * Dynamically load the ODBC module with lazy initialization and caching
3987
- * @throws Error with helpful message if ODBC package is not installed
3988
- */
3989
- static async getOdbc() {
3990
- if (this.odbcLoadError) {
3991
- throw this.odbcLoadError;
3992
- }
3993
- if (this.odbcModule) {
3994
- return this.odbcModule;
3995
- }
3996
- try {
3997
- const odbcImport = await import("odbc");
3998
- const odbc = odbcImport.default || odbcImport;
3999
- this.odbcModule = odbc;
4000
- return this.odbcModule;
4001
- } catch (error) {
4002
- const errorMessage = error instanceof Error ? error.message : String(error);
4003
- this.odbcLoadError = new Error(
4004
- `ODBC package is required for PSQL service but is not installed or failed to load.
4005
- Install it with: npm install odbc
4006
- Also install OS-level dependencies, e.g. on Alpine Linux:
4007
- apk add --no-cache unixodbc unixodbc-dev python3 make g++
4008
- For other Linux distributions, install unixodbc and unixodbc-dev packages.
4009
- Original error: ${errorMessage}`
4010
- );
4011
- throw this.odbcLoadError;
4012
- }
4013
- }
4014
- // REMOVED: dispose() method - not needed anymore
4015
- // REMOVED: connection property - not needed anymore
4016
- // REMOVED: openConnection() method - not needed anymore
4017
- // REMOVED: closeConnection() method - not needed anymore
4018
- /**
4019
- * Build PSQL ODBC connection string
4020
- * CRITICAL: ServerName must use IP.PORT format (e.g., 10.4.0.11.1583)
4021
- */
4022
- buildConnectionString() {
4023
- const serverName = `${this.config.host}.${this.config.port}`;
4024
- return [
4025
- "Driver={Pervasive ODBC Interface}",
4026
- `ServerName=${serverName}`,
4027
- `DBQ=${this.config.database}`,
4028
- `UID=${this.config.username}`,
4029
- `PWD=${this.config.password}`,
4030
- "AutoDoubleQuote=0"
4031
- ].join(";") + ";";
4032
- }
4033
- /**
4034
- * Execute a query and return the results
4035
- * Creates a fresh connection for each query to avoid handle corruption
4036
- *
4037
- * SECURITY WARNING: This method executes the provided SQL string as-is.
4038
- * - Parameter binding is NOT implemented; the `params` argument is currently ignored.
4039
- * - Never concatenate untrusted/user-supplied input into `query`.
4040
- * - Doing so can result in SQL injection vulnerabilities and data exposure.
4041
- * If dynamic values are required, ensure they are strictly validated/escaped
4042
- * or implement proper parameterized execution before accepting untrusted input.
4043
- *
4044
- * @param query The SQL query to execute
4045
- * @param params Query parameters (currently unused for PSQL read operations)
4046
- * @param paging Optional paging parameters
4047
- * @returns The entities fetched from the database, along with paging information
4048
- */
4049
- async executePreparedStatement(query, params = {}, paging) {
4050
- const odbc = await PsqlService.getOdbc();
4051
- let connection = null;
4052
- try {
4053
- const connStr = this.buildConnectionString();
4054
- logger.debug("Creating fresh PSQL connection for query");
4055
- connection = await odbc.connect(connStr);
4056
- if (Object.keys(params).length > 0) {
4057
- logger.warn(
4058
- "PsqlService: Query parameters provided but parameter binding not yet implemented. Using direct query execution."
4059
- );
4060
- }
4061
- const records = await connection.query(query);
4062
- const allRecords = PsqlService.recordsetToRecords(records);
4063
- const rowsFetched = allRecords.length;
4064
- const pagedData = paging?.offset !== void 0 || paging?.limit !== void 0 ? allRecords.slice(
4065
- paging.offset || 0,
4066
- (paging.offset || 0) + (paging.limit || allRecords.length)
4067
- ) : allRecords;
4068
- return {
4069
- data: pagedData,
4070
- paging: {
4071
- count: rowsFetched,
4072
- limit: paging?.limit || 0,
4073
- offset: paging?.offset || 0,
4074
- nextPage: paging?.limit && (paging.offset || 0) + paging.limit < rowsFetched ? String((paging.offset || 0) + paging.limit) : void 0,
4075
- previousPage: paging?.offset ? String(Math.max(0, (paging.offset || 0) - (paging.limit || 10))) : void 0
4076
- }
4077
- };
4078
- } catch (error) {
4079
- if (error instanceof Error && error.message.includes("ODBC package is required")) {
4080
- throw error;
4081
- }
4082
- const errorInfo = error;
4083
- logger.error("Error fetching data from PSQL", {
4084
- error: errorInfo.message,
4085
- odbcErrors: errorInfo.odbcErrors,
4086
- query: query.substring(0, 200)
4087
- // Log first 200 chars of query
4088
- });
4089
- throw this.handleOdbcError(errorInfo);
4090
- } finally {
4091
- if (connection) {
4092
- try {
4093
- await connection.close();
4094
- logger.debug("PSQL connection closed successfully");
4095
- } catch (err) {
4096
- logger.warn("Error closing PSQL connection (non-fatal)", {
4097
- error: err
4098
- });
4099
- }
4100
- }
4101
- }
4102
- }
4103
- /**
4104
- * Transform ODBC result set to array of Record<string, string> instances.
4105
- * IMPORTANT: PSQL CHAR fields are often padded with spaces - we trim them
4106
- */
4107
- static recordsetToRecords(recordset) {
4108
- if (!Array.isArray(recordset)) {
4109
- return [];
4110
- }
4111
- const data = recordset.map((row) => {
4112
- const transformedRow = {};
4113
- Object.keys(row).forEach((key) => {
4114
- const value = row[key];
4115
- transformedRow[key] = value !== null && value !== void 0 ? String(value).trim() : "";
4116
- });
4117
- return transformedRow;
4118
- });
4119
- return data;
4120
- }
4121
- /**
4122
- * Handle ODBC errors and provide meaningful messages
4123
- */
4124
- handleOdbcError(error) {
4125
- const odbcError = error.odbcErrors?.[0];
4126
- const errorCode = odbcError?.state;
4127
- const message = odbcError?.message || error.message;
4128
- switch (errorCode) {
4129
- case "08S01":
4130
- return new Error(
4131
- `PSQL connection failed. Check: 1) PVSW environment variable set to /usr/local/psql/etc/pvsw.ini, 2) Network connectivity to ports 1583/3351, 3) ODBC configuration files in /usr/local/psql/etc/ and /etc/. Original error: ${message}`
4132
- );
4133
- case "28000":
4134
- return new Error(
4135
- `PSQL authentication failed. Check username/password. Original error: ${message}`
4136
- );
4137
- case "42000":
4138
- return new Error(`PSQL SQL syntax error. Original error: ${message}`);
4139
- case "42S02":
4140
- return new Error(
4141
- `PSQL table or view not found. Check table names in query. Original error: ${message}`
4142
- );
4143
- default:
4144
- return new Error(`PSQL error (${errorCode || "unknown"}): ${message}`);
4145
- }
4146
- }
4147
- }
4148
- function formatPsqlDate(psqlDate) {
4149
- if (!psqlDate || psqlDate.trim().length !== 6 || psqlDate === "000000") {
4150
- return null;
4151
- }
4152
- try {
4153
- const year = parseInt(psqlDate.substring(0, 2), 10);
4154
- const month = parseInt(psqlDate.substring(2, 4), 10);
4155
- const day = parseInt(psqlDate.substring(4, 6), 10);
4156
- const fullYear = year + 2e3;
4157
- if (month < 1 || month > 12 || day < 1 || day > 31) {
4158
- return null;
4159
- }
4160
- const date = new Date(fullYear, month - 1, day);
4161
- if (date.getFullYear() !== fullYear || date.getMonth() !== month - 1 || date.getDate() !== day) {
4162
- return null;
4163
- }
4164
- return date.toISOString().split("T")[0];
4165
- } catch (error) {
4166
- return null;
4167
- }
4168
- }
4169
- function formatPsqlTime(psqlTime) {
4170
- if (!psqlTime) {
4171
- return null;
4172
- }
4173
- const trimmed = psqlTime.trim();
4174
- if (trimmed.length !== 4) {
4175
- return null;
4176
- }
4177
- try {
4178
- const hours = parseInt(trimmed.substring(0, 2), 10);
4179
- const minutes = parseInt(trimmed.substring(2, 4), 10);
4180
- if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {
4181
- return null;
4182
- }
4183
- const hoursStr = hours.toString().padStart(2, "0");
4184
- const minutesStr = minutes.toString().padStart(2, "0");
4185
- return `${hoursStr}:${minutesStr}:00`;
4186
- } catch (error) {
4187
- return null;
4188
- }
4189
- }
4190
- function combinePsqlDateTime(psqlDate, psqlTime) {
4191
- const date = formatPsqlDate(psqlDate);
4192
- const time = formatPsqlTime(psqlTime);
4193
- if (!date || !time) {
4194
- return null;
4195
- }
4196
- return `${date}T${time}`;
4197
- }
4198
- function isPsqlDateEmpty(psqlDate) {
4199
- return !psqlDate || psqlDate === "000000" || psqlDate.trim() === "";
4200
- }
4201
- function cleanPsqlCharField(value) {
4202
- if (value === null || value === void 0) {
4203
- return "";
4204
- }
4205
- return String(value).trim();
4206
- }
4207
- export {
4208
- ApplicationInitializer,
4209
- BatchCacheManager,
4210
- CoreConfiguration,
4211
- ERPObjType,
4212
- E as ErpApiConnectionParams,
4213
- ErrorHandler,
4214
- FileLogDeduper,
4215
- GraphQLError,
4216
- GraphQLService,
4217
- HTTPClientFactory,
4218
- HTTPError,
4219
- LogEntry,
4220
- MMApiClient,
4221
- MMBatchValidationError,
4222
- MMConnectorLogger,
4223
- MMReceiveLaborTicket,
4224
- MMSendLaborTicket,
4225
- MMSendPart,
4226
- MMSendPartOperation,
4227
- MMSendPerson,
4228
- MMSendReason,
4229
- MMSendResource,
4230
- MMSendWorkOrder,
4231
- MMSendWorkOrderOperation,
4232
- OAuthClient,
4233
- PsqlService,
4234
- RecordTrackingManager,
4235
- RestAPIService,
4236
- SqlServerHelper,
4237
- SqlServerService,
4238
- StandardProcessDrivers,
4239
- addNewFieldFromExternalSource,
4240
- addNewFieldFromLookupField,
4241
- applyTimezoneOffsetsToFields,
4242
- buildLogicalCondition,
4243
- cleanPsqlCharField,
4244
- cleanupNumbers,
4245
- combinePsqlDateTime,
4246
- convertToLocalTime,
4247
- formatDateWithTZOffset,
4248
- formatPsqlDate,
4249
- formatPsqlTime,
4250
- f as getCachedTimezoneName,
4251
- getCachedTimezoneOffset,
4252
- g as getErpApiConnectionParams,
4253
- getErrorType,
4254
- d as getInitialLoadComplete,
4255
- getPayloadWithoutIDField,
4256
- a as getSQLServerConfiguration,
4257
- getUniqueRows,
4258
- isPsqlDateEmpty,
4259
- config as knexDatabaseConfig,
4260
- logger,
4261
- removeExtraneousFields,
4262
- runDataSyncService,
4263
- e as setInitialLoadComplete,
4264
- trimObjectValues
4265
- };
4266
- //# sourceMappingURL=mm-erp-sdk.js.map