@machinemetrics/mm-erp-sdk 0.1.9-beta.4 → 0.1.9-beta.5

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