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

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