@fluentcommerce/fc-connect-sdk 0.1.53 → 0.1.55

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 (495) hide show
  1. package/CHANGELOG.md +30 -2
  2. package/README.md +39 -0
  3. package/dist/cjs/auth/index.d.ts +3 -0
  4. package/dist/cjs/auth/index.js +13 -0
  5. package/dist/cjs/auth/profile-loader.d.ts +18 -0
  6. package/dist/cjs/auth/profile-loader.js +208 -0
  7. package/dist/cjs/client-factory.d.ts +4 -0
  8. package/dist/cjs/client-factory.js +10 -0
  9. package/dist/cjs/clients/fluent-client.js +13 -6
  10. package/dist/cjs/index.d.ts +3 -1
  11. package/dist/cjs/index.js +8 -2
  12. package/dist/cjs/utils/pagination-helpers.js +38 -2
  13. package/dist/cjs/versori/fluent-versori-client.js +11 -5
  14. package/dist/esm/auth/index.d.ts +3 -0
  15. package/dist/esm/auth/index.js +2 -0
  16. package/dist/esm/auth/profile-loader.d.ts +18 -0
  17. package/dist/esm/auth/profile-loader.js +169 -0
  18. package/dist/esm/client-factory.d.ts +4 -0
  19. package/dist/esm/client-factory.js +9 -0
  20. package/dist/esm/clients/fluent-client.js +13 -6
  21. package/dist/esm/index.d.ts +3 -1
  22. package/dist/esm/index.js +2 -1
  23. package/dist/esm/utils/pagination-helpers.js +38 -2
  24. package/dist/esm/versori/fluent-versori-client.js +11 -5
  25. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  26. package/dist/tsconfig.tsbuildinfo +1 -1
  27. package/dist/tsconfig.types.tsbuildinfo +1 -1
  28. package/dist/types/auth/index.d.ts +3 -0
  29. package/dist/types/auth/profile-loader.d.ts +18 -0
  30. package/dist/types/client-factory.d.ts +4 -0
  31. package/dist/types/index.d.ts +3 -1
  32. package/docs/00-START-HERE/EXPORT-VALIDATION.md +158 -158
  33. package/docs/00-START-HERE/cli-analyze-source-structure-guide.md +655 -655
  34. package/docs/00-START-HERE/cli-documentation-index.md +202 -202
  35. package/docs/00-START-HERE/cli-quick-reference.md +252 -252
  36. package/docs/00-START-HERE/decision-tree.md +552 -552
  37. package/docs/00-START-HERE/getting-started.md +1070 -1070
  38. package/docs/00-START-HERE/mapper-quick-decision-guide.md +235 -235
  39. package/docs/00-START-HERE/readme.md +237 -237
  40. package/docs/00-START-HERE/retailerid-configuration.md +404 -404
  41. package/docs/00-START-HERE/sdk-philosophy.md +794 -794
  42. package/docs/00-START-HERE/troubleshooting-quick-reference.md +1086 -1086
  43. package/docs/01-TEMPLATES/faq.md +686 -686
  44. package/docs/01-TEMPLATES/patterns/pattern-templates-guide.md +68 -68
  45. package/docs/01-TEMPLATES/patterns/patterns-csv-schema-validation-and-rejection-report.md +233 -233
  46. package/docs/01-TEMPLATES/patterns/patterns-custom-resolvers.md +407 -407
  47. package/docs/01-TEMPLATES/patterns/patterns-error-handling-retry.md +511 -511
  48. package/docs/01-TEMPLATES/patterns/patterns-field-mapping-universal.md +701 -701
  49. package/docs/01-TEMPLATES/patterns/patterns-large-file-splitting.md +1430 -1430
  50. package/docs/01-TEMPLATES/patterns/patterns-master-data-etl.md +2399 -2399
  51. package/docs/01-TEMPLATES/patterns/patterns-pagination-streaming.md +447 -447
  52. package/docs/01-TEMPLATES/patterns/patterns-state-duplicate-prevention.md +385 -385
  53. package/docs/01-TEMPLATES/readme.md +957 -957
  54. package/docs/01-TEMPLATES/standalone/standalone-asn-inbound-processing.md +1209 -1209
  55. package/docs/01-TEMPLATES/standalone/standalone-graphql-query-export.md +1140 -1140
  56. package/docs/01-TEMPLATES/standalone/standalone-graphql-to-parquet-partitioned-s3.md +432 -432
  57. package/docs/01-TEMPLATES/standalone/standalone-multi-channel-inventory-sync.md +1185 -1185
  58. package/docs/01-TEMPLATES/standalone/standalone-multi-source-aggregation.md +1462 -1462
  59. package/docs/01-TEMPLATES/standalone/standalone-s3-csv-batch-api.md +1390 -1390
  60. package/docs/01-TEMPLATES/standalone/standalone-s3-csv-inventory-to-batch.md +330 -330
  61. package/docs/01-TEMPLATES/standalone/standalone-scripts-guide.md +87 -87
  62. package/docs/01-TEMPLATES/standalone/standalone-sftp-xml-graphql.md +1444 -1444
  63. package/docs/01-TEMPLATES/standalone/standalone-webhook-payload-processing.md +688 -688
  64. package/docs/01-TEMPLATES/versori/business-examples/business-examples-dropship-order-routing.md +193 -193
  65. package/docs/01-TEMPLATES/versori/business-examples/business-examples-graphql-parquet-extraction.md +518 -518
  66. package/docs/01-TEMPLATES/versori/business-examples/business-examples-inter-location-transfers.md +2162 -2162
  67. package/docs/01-TEMPLATES/versori/business-examples/business-examples-pre-order-allocation.md +2226 -2226
  68. package/docs/01-TEMPLATES/versori/business-examples/business-scenarios-guide.md +87 -87
  69. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-connection-validation-pattern.md +656 -656
  70. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-dual-workflow-connector.md +835 -835
  71. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-guide.md +108 -108
  72. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-kv-state-management.md +1533 -1533
  73. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-xml-response-patterns.md +1160 -1160
  74. package/docs/01-TEMPLATES/versori/versori-platform-guide.md +201 -201
  75. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-asn-purchase-order.md +1906 -1906
  76. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-dropship-routing.md +1074 -1074
  77. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-flash-sale-reserve.md +1395 -1395
  78. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-generic-xml-order.md +888 -888
  79. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-payment-gateway-integration.md +2478 -2478
  80. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-rma-returns-comprehensive.md +2240 -2240
  81. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-xml-order-ingestion.md +2029 -2029
  82. package/docs/01-TEMPLATES/versori/webhooks/webhook-templates-guide.md +140 -140
  83. package/docs/01-TEMPLATES/versori/workflows/_examples/sample-data/inventory-mapping.json +20 -20
  84. package/docs/01-TEMPLATES/versori/workflows/_examples/sample-data/products_2025-01-22.csv +11 -11
  85. package/docs/01-TEMPLATES/versori/workflows/_examples/sample-data/sample-data-guide.md +34 -34
  86. package/docs/01-TEMPLATES/versori/workflows/_examples/workflow-examples-guide.md +36 -36
  87. package/docs/01-TEMPLATES/versori/workflows/extraction/extraction-modes-guide.md +1038 -1038
  88. package/docs/01-TEMPLATES/versori/workflows/extraction/extraction-workflows-guide.md +138 -138
  89. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/graphql-extraction-guide.md +63 -63
  90. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-fulfillments-to-sftp-csv.md +2062 -2062
  91. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-fulfillments-to-sftp-xml.md +2294 -2294
  92. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-positions-to-s3-csv.md +2461 -2461
  93. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-positions-to-sftp-xml.md +2529 -2529
  94. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-quantities-to-s3-csv.md +2464 -2464
  95. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-quantities-to-s3-json.md +1959 -1959
  96. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-orders-to-s3-csv.md +1953 -1953
  97. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-orders-to-sftp-xml.md +2541 -2541
  98. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-products-to-s3-json.md +2384 -2384
  99. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-products-to-sftp-xml.md +2445 -2445
  100. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-virtual-positions-to-s3-csv.md +2355 -2355
  101. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-virtual-positions-to-s3-json.md +2042 -2042
  102. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-virtual-positions-to-sftp-xml.md +2726 -2726
  103. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/batch-api-guide.md +206 -206
  104. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-cycle-count-reconciliation.md +2030 -2030
  105. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-multi-channel-inventory-sync.md +1882 -1882
  106. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-s3-csv-inventory-batch.md +2827 -2827
  107. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-s3-json-inventory-batch.md +1952 -1952
  108. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-s3-xml-inventory-batch.md +3289 -3289
  109. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-sftp-csv-inventory-batch.md +3064 -3064
  110. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-sftp-json-inventory-batch.md +3238 -3238
  111. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-sftp-xml-inventory-batch.md +2977 -2977
  112. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/event-api-guide.md +321 -321
  113. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-payload-json-order-cancel-event.md +959 -959
  114. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-payload-xml-order-cancel-event.md +1170 -1170
  115. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-csv-product-event.md +2312 -2312
  116. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-json-product-event.md +2999 -2999
  117. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-parquet-product-event.md +2836 -2836
  118. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-xml-product-event.md +2395 -2395
  119. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-csv-product-event.md +2295 -2295
  120. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-json-product-event.md +2602 -2602
  121. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-parquet-product-event.md +2589 -2589
  122. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-xml-product-event.md +3578 -3578
  123. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/graphql-mutations-guide.md +93 -93
  124. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-payload-json-order-update-graphql.md +1260 -1260
  125. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-payload-xml-order-update-graphql.md +1472 -1472
  126. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-csv-control-graphql.md +2417 -2417
  127. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-csv-location-graphql.md +2811 -2811
  128. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-csv-price-graphql.md +2619 -2619
  129. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-json-location-graphql.md +2807 -2807
  130. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-xml-location-graphql.md +2373 -2373
  131. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-sftp-csv-control-graphql.md +2740 -2740
  132. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-sftp-csv-location-graphql.md +2760 -2760
  133. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-sftp-json-location-graphql.md +1710 -1710
  134. package/docs/01-TEMPLATES/versori/workflows/ingestion/ingestion-workflows-guide.md +136 -136
  135. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/rubix-webhooks-guide.md +520 -520
  136. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/template-webhook-rubix-fulfilment-to-sftp-xml-inline.md +1418 -1418
  137. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/template-webhook-rubix-fulfilment-to-sftp-xml-universal-mapper.md +1785 -1785
  138. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/template-webhook-rubix-order-attribute-update.md +824 -824
  139. package/docs/01-TEMPLATES/versori/workflows/workflows-overview-guide.md +646 -646
  140. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-batch-archival.md +724 -724
  141. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-job-tracker.md +627 -627
  142. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-partial-batch-recovery.md +561 -561
  143. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-quick-reference.md +367 -367
  144. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-readme.md +407 -407
  145. package/docs/02-CORE-GUIDES/advanced-services/readme.md +49 -49
  146. package/docs/02-CORE-GUIDES/api-reference/api-reference-quick-reference.md +548 -548
  147. package/docs/02-CORE-GUIDES/api-reference/event-api-input-output-reference.md +702 -1171
  148. package/docs/02-CORE-GUIDES/api-reference/examples/client-initialization.ts +286 -286
  149. package/docs/02-CORE-GUIDES/api-reference/graphql-error-classification.md +337 -337
  150. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-01-client-api.md +399 -482
  151. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-03-authentication.md +199 -199
  152. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-04-graphql-mapping.md +925 -925
  153. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-05-services.md +1198 -1198
  154. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-06-data-sources.md +1083 -1083
  155. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-07-parsers.md +1097 -1097
  156. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-08-pagination.md +513 -513
  157. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-08-types.md +545 -597
  158. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-09-error-handling.md +527 -527
  159. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-09-webhook-validation.md +514 -514
  160. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-10-extraction.md +557 -557
  161. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-10-utilities.md +412 -412
  162. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-11-cli-tools.md +423 -423
  163. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-11-error-handling.md +716 -716
  164. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-12-analyze-source-structure.md +518 -518
  165. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-12-partial-responses.md +212 -212
  166. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-12-testing.md +300 -300
  167. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-13-resolver-builder.md +322 -322
  168. package/docs/02-CORE-GUIDES/api-reference/readme.md +279 -279
  169. package/docs/02-CORE-GUIDES/auto-pagination/auto-pagination-quick-reference.md +351 -351
  170. package/docs/02-CORE-GUIDES/auto-pagination/auto-pagination-readme.md +277 -277
  171. package/docs/02-CORE-GUIDES/auto-pagination/examples/auto-pagination-readme.md +178 -178
  172. package/docs/02-CORE-GUIDES/auto-pagination/examples/common-patterns.ts +351 -351
  173. package/docs/02-CORE-GUIDES/auto-pagination/examples/paginate-products.ts +384 -384
  174. package/docs/02-CORE-GUIDES/auto-pagination/examples/paginate-virtual-positions.ts +308 -308
  175. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-01-foundations.md +470 -470
  176. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-02-quick-start.md +713 -713
  177. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-03-configuration.md +754 -754
  178. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-04-advanced-patterns.md +732 -732
  179. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-05-sdk-integration.md +847 -847
  180. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-06-troubleshooting.md +359 -359
  181. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-07-api-reference.md +462 -462
  182. package/docs/02-CORE-GUIDES/auto-pagination/readme.md +54 -54
  183. package/docs/02-CORE-GUIDES/data-sources/data-sources-file-operations-error-handling.md +1487 -1487
  184. package/docs/02-CORE-GUIDES/data-sources/data-sources-quick-reference.md +836 -836
  185. package/docs/02-CORE-GUIDES/data-sources/data-sources-readme.md +276 -276
  186. package/docs/02-CORE-GUIDES/data-sources/data-sources-sftp-credential-access-security.md +553 -553
  187. package/docs/02-CORE-GUIDES/data-sources/examples/common-patterns.ts +409 -409
  188. package/docs/02-CORE-GUIDES/data-sources/examples/data-sources-readme.md +178 -178
  189. package/docs/02-CORE-GUIDES/data-sources/examples/s3-operations.ts +308 -308
  190. package/docs/02-CORE-GUIDES/data-sources/examples/sftp-operations.ts +371 -371
  191. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-01-foundations.md +735 -735
  192. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-02-s3-operations.md +1302 -1302
  193. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-03-sftp-operations.md +1379 -1379
  194. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-04-file-patterns.md +941 -941
  195. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-05-advanced-topics.md +813 -813
  196. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-06-integration-patterns.md +486 -486
  197. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-07-troubleshooting.md +387 -387
  198. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-08-api-reference.md +417 -417
  199. package/docs/02-CORE-GUIDES/data-sources/readme.md +77 -77
  200. package/docs/02-CORE-GUIDES/error-handling-guide.md +936 -936
  201. package/docs/02-CORE-GUIDES/extraction/examples/02-core-guides-extraction-readme.md +116 -116
  202. package/docs/02-CORE-GUIDES/extraction/examples/common-patterns.ts +428 -428
  203. package/docs/02-CORE-GUIDES/extraction/examples/extract-inventory-basic.ts +187 -187
  204. package/docs/02-CORE-GUIDES/extraction/extraction-quick-reference.md +596 -596
  205. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-01-foundations.md +514 -514
  206. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-02-basic-extraction.md +823 -823
  207. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-03-parquet-processing.md +507 -507
  208. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-04-data-enrichment.md +546 -546
  209. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-05-transformation.md +494 -494
  210. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-06-export-formats.md +458 -458
  211. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-06-performance.md +138 -138
  212. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-07-api-reference.md +148 -148
  213. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-07-optimization.md +692 -692
  214. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-08-extraction-orchestrator.md +1008 -1008
  215. package/docs/02-CORE-GUIDES/extraction/readme.md +151 -151
  216. package/docs/02-CORE-GUIDES/ingestion/examples/_simple-kv-store.ts +40 -40
  217. package/docs/02-CORE-GUIDES/ingestion/examples/error-recovery.ts +728 -728
  218. package/docs/02-CORE-GUIDES/ingestion/examples/event-driven.ts +501 -501
  219. package/docs/02-CORE-GUIDES/ingestion/examples/local-file-ingestion.ts +88 -88
  220. package/docs/02-CORE-GUIDES/ingestion/examples/parquet-ingestion.ts +117 -117
  221. package/docs/02-CORE-GUIDES/ingestion/examples/performance-optimized.ts +647 -647
  222. package/docs/02-CORE-GUIDES/ingestion/examples/s3-csv-ingestion.ts +169 -169
  223. package/docs/02-CORE-GUIDES/ingestion/examples/sftp-csv-ingestion.ts +134 -134
  224. package/docs/02-CORE-GUIDES/ingestion/ingestion-quick-reference.md +546 -546
  225. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-01-introduction.md +626 -626
  226. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-02-quick-start.md +658 -658
  227. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-03-data-sources.md +1052 -1052
  228. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-04-field-mapping.md +763 -763
  229. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-05-advanced-parsers.md +676 -676
  230. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-06-batch-api.md +1295 -1295
  231. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-07-api-reference.md +138 -138
  232. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-07-state-management.md +1037 -1037
  233. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-08-performance-optimization.md +1349 -1349
  234. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-09-best-practices.md +1893 -1893
  235. package/docs/02-CORE-GUIDES/ingestion/readme.md +160 -160
  236. package/docs/02-CORE-GUIDES/logging-guide.md +585 -585
  237. package/docs/02-CORE-GUIDES/mapping/error-handling-patterns.md +401 -401
  238. package/docs/02-CORE-GUIDES/mapping/examples/02-core-guides-mapping-readme.md +128 -128
  239. package/docs/02-CORE-GUIDES/mapping/examples/common-patterns.ts +273 -273
  240. package/docs/02-CORE-GUIDES/mapping/examples/csv-location-ingestion.json +36 -36
  241. package/docs/02-CORE-GUIDES/mapping/examples/csv-mapping.ts +242 -242
  242. package/docs/02-CORE-GUIDES/mapping/examples/graphql-to-parquet-extraction.json +36 -36
  243. package/docs/02-CORE-GUIDES/mapping/examples/json-mapping.ts +213 -213
  244. package/docs/02-CORE-GUIDES/mapping/examples/json-product-to-mutation.json +48 -48
  245. package/docs/02-CORE-GUIDES/mapping/examples/xml-mapping.ts +291 -291
  246. package/docs/02-CORE-GUIDES/mapping/examples/xml-order-to-mutation.json +45 -45
  247. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/graphql-mutation-mapping-quick-reference.md +463 -463
  248. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/graphql-mutation-mapping-readme.md +227 -227
  249. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-01-introduction.md +222 -222
  250. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-02-quick-start.md +351 -351
  251. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-03-schema-validation.md +569 -569
  252. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-04-mapping-patterns.md +471 -471
  253. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-05-configuration-reference.md +611 -611
  254. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-06-advanced-xpath.md +148 -148
  255. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-06-path-syntax.md +464 -464
  256. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-07-api-reference.md +94 -94
  257. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-07-array-handling.md +307 -307
  258. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-08-custom-resolvers.md +544 -544
  259. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-09-advanced-patterns.md +427 -427
  260. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-10-hooks-and-variables.md +336 -336
  261. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-11-error-handling.md +488 -488
  262. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-12-arguments-vs-nodes.md +383 -383
  263. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-13-best-practices.md +477 -477
  264. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/readme.md +62 -62
  265. package/docs/02-CORE-GUIDES/mapping/mapping-format-decision-tree.md +480 -480
  266. package/docs/02-CORE-GUIDES/mapping/mapping-graphql-alias-batching-guide.md +820 -820
  267. package/docs/02-CORE-GUIDES/mapping/mapping-javascript-objects.md +2369 -2369
  268. package/docs/02-CORE-GUIDES/mapping/mapping-mapper-comparison-guide.md +682 -682
  269. package/docs/02-CORE-GUIDES/mapping/modules/02-core-guides-mapping-07-api-reference.md +1327 -1327
  270. package/docs/02-CORE-GUIDES/mapping/modules/02-core-guides-mapping-08-error-handling.md +1142 -1142
  271. package/docs/02-CORE-GUIDES/mapping/modules/mapping-04-use-cases.md +891 -891
  272. package/docs/02-CORE-GUIDES/mapping/modules/mapping-06-helpers-resolvers.md +1126 -1126
  273. package/docs/02-CORE-GUIDES/mapping/modules/mapping-06-sdk-resolvers.md +199 -199
  274. package/docs/02-CORE-GUIDES/mapping/modules/mapping-07-api-reference.md +1319 -1319
  275. package/docs/02-CORE-GUIDES/mapping/readme.md +178 -178
  276. package/docs/02-CORE-GUIDES/mapping/resolver-registration.md +410 -410
  277. package/docs/02-CORE-GUIDES/mapping/resolvers/examples/common-patterns.ts +226 -226
  278. package/docs/02-CORE-GUIDES/mapping/resolvers/examples/custom-resolvers.ts +227 -227
  279. package/docs/02-CORE-GUIDES/mapping/resolvers/examples/sdk-resolvers-usage.ts +203 -203
  280. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-readme.md +274 -274
  281. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-api-reference.md +679 -679
  282. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-cookbook.md +826 -826
  283. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-guide.md +1330 -1330
  284. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-helpers-reference.md +1437 -1437
  285. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-parameters-reference.md +553 -553
  286. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-troubleshooting.md +854 -854
  287. package/docs/02-CORE-GUIDES/mapping/resolvers/readme.md +75 -75
  288. package/docs/02-CORE-GUIDES/parsers/examples/02-core-guides-parsers-readme.md +161 -161
  289. package/docs/02-CORE-GUIDES/parsers/examples/csv-parser-examples.ts +110 -110
  290. package/docs/02-CORE-GUIDES/parsers/examples/json-parser-examples.ts +33 -33
  291. package/docs/02-CORE-GUIDES/parsers/examples/parquet-parser-examples.ts +47 -47
  292. package/docs/02-CORE-GUIDES/parsers/examples/xml-parser-examples.ts +38 -38
  293. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-01-foundations.md +355 -355
  294. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-02-csv-parser.md +772 -772
  295. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-03-json-parser.md +789 -789
  296. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-04-xml-parser.md +857 -857
  297. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-05-parquet-parser.md +603 -603
  298. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-06-integration-patterns.md +702 -702
  299. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-06-streaming.md +121 -121
  300. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-07-api-reference.md +89 -89
  301. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-07-troubleshooting.md +727 -727
  302. package/docs/02-CORE-GUIDES/parsers/parsers-quick-reference.md +482 -482
  303. package/docs/02-CORE-GUIDES/parsers/parsers-readme.md +258 -258
  304. package/docs/02-CORE-GUIDES/parsers/readme.md +65 -65
  305. package/docs/02-CORE-GUIDES/readme.md +194 -194
  306. package/docs/02-CORE-GUIDES/webhook-validation/examples/basic-validation.ts +108 -108
  307. package/docs/02-CORE-GUIDES/webhook-validation/examples/common-patterns.ts +316 -316
  308. package/docs/02-CORE-GUIDES/webhook-validation/examples/webhook-validation-readme.md +61 -61
  309. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-01-foundations.md +440 -440
  310. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-02-quick-start.md +525 -525
  311. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-03-versori-integration.md +741 -741
  312. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-04-platform-integration.md +629 -629
  313. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-05-configuration.md +535 -535
  314. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-06-error-handling.md +611 -611
  315. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-06-troubleshooting.md +124 -124
  316. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-07-api-reference.md +511 -511
  317. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-08-rubix-webhooks.md +590 -590
  318. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-09-rubix-event-vs-http-call.md +432 -432
  319. package/docs/02-CORE-GUIDES/webhook-validation/readme.md +239 -239
  320. package/docs/02-CORE-GUIDES/webhook-validation/webhook-validation-quick-reference.md +392 -392
  321. package/docs/03-PATTERN-GUIDES/connector-scenarios/connector-scenarios-quick-reference.md +498 -498
  322. package/docs/03-PATTERN-GUIDES/connector-scenarios/connector-scenarios-readme.md +313 -313
  323. package/docs/03-PATTERN-GUIDES/connector-scenarios/examples/common-patterns.ts +612 -612
  324. package/docs/03-PATTERN-GUIDES/connector-scenarios/examples/connector-scenarios-readme.md +253 -253
  325. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-01-foundations.md +452 -452
  326. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-02-simple-scenarios.md +681 -681
  327. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-03-intermediate-scenarios.md +637 -637
  328. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-04-advanced-scenarios.md +650 -650
  329. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-05-bidirectional-sync.md +233 -233
  330. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-06-production-patterns.md +442 -442
  331. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-07-reference.md +445 -445
  332. package/docs/03-PATTERN-GUIDES/connector-scenarios/readme.md +31 -31
  333. package/docs/03-PATTERN-GUIDES/enterprise-integration-patterns.md +1528 -1528
  334. package/docs/03-PATTERN-GUIDES/error-handling/comprehensive-error-handling-guide.md +1437 -1437
  335. package/docs/03-PATTERN-GUIDES/error-handling/error-handling-quick-reference.md +390 -390
  336. package/docs/03-PATTERN-GUIDES/error-handling/examples/common-patterns.ts +438 -438
  337. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-01-foundations.md +362 -362
  338. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-02-error-types.md +850 -850
  339. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-03-utf8-handling.md +456 -456
  340. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-04-error-scenarios.md +658 -658
  341. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-05-calling-patterns.md +671 -671
  342. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-06-retry-strategies.md +1034 -1034
  343. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-07-monitoring.md +653 -653
  344. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-08-api-reference.md +847 -847
  345. package/docs/03-PATTERN-GUIDES/error-handling/readme.md +36 -36
  346. package/docs/03-PATTERN-GUIDES/examples/__tests__/readme.md +40 -40
  347. package/docs/03-PATTERN-GUIDES/examples/__tests__/resolver-examples.test.js +282 -282
  348. package/docs/03-PATTERN-GUIDES/examples/test-data/03-pattern-guides-readme.md +110 -110
  349. package/docs/03-PATTERN-GUIDES/examples/test-data/canonical-inventory.json +123 -123
  350. package/docs/03-PATTERN-GUIDES/examples/test-data/canonical-order.json +171 -171
  351. package/docs/03-PATTERN-GUIDES/examples/test-data/readme.md +28 -28
  352. package/docs/03-PATTERN-GUIDES/extraction/extraction-readme.md +15 -15
  353. package/docs/03-PATTERN-GUIDES/extraction/readme.md +25 -25
  354. package/docs/03-PATTERN-GUIDES/file-operations/examples/common-patterns.ts +407 -407
  355. package/docs/03-PATTERN-GUIDES/file-operations/examples/file-operations-readme.md +142 -142
  356. package/docs/03-PATTERN-GUIDES/file-operations/file-operations-quick-reference.md +462 -462
  357. package/docs/03-PATTERN-GUIDES/file-operations/file-operations-readme.md +379 -379
  358. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-01-foundations.md +430 -430
  359. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-02-quick-start.md +484 -484
  360. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-03-s3-operations.md +507 -507
  361. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-04-sftp-operations.md +963 -963
  362. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-05-streaming-performance.md +503 -503
  363. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-06-archive-patterns.md +386 -386
  364. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-06-error-handling.md +117 -117
  365. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-07-api-reference.md +78 -78
  366. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-07-testing-troubleshooting.md +567 -567
  367. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-08-api-reference.md +1055 -1055
  368. package/docs/03-PATTERN-GUIDES/file-operations/readme.md +32 -32
  369. package/docs/03-PATTERN-GUIDES/ingestion/ingestion-readme.md +15 -15
  370. package/docs/03-PATTERN-GUIDES/ingestion/readme.md +25 -25
  371. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/batch-processing.ts +130 -130
  372. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/common-patterns.ts +360 -360
  373. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/delta-sync.ts +130 -130
  374. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/integration-patterns-readme.md +100 -100
  375. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/real-time-webhook.ts +398 -398
  376. package/docs/03-PATTERN-GUIDES/integration-patterns/integration-patterns-quick-reference.md +962 -962
  377. package/docs/03-PATTERN-GUIDES/integration-patterns/integration-patterns-readme.md +134 -134
  378. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-01-real-time-processing.md +991 -991
  379. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-02-batch-processing.md +1547 -1547
  380. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-03-delta-sync.md +1108 -1108
  381. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-04-webhook-patterns.md +1181 -1181
  382. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-05-error-handling.md +1061 -1061
  383. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-06-advanced-integration-services.md +1547 -1547
  384. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-06-performance.md +109 -109
  385. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-07-api-reference.md +34 -34
  386. package/docs/03-PATTERN-GUIDES/integration-patterns/readme.md +30 -30
  387. package/docs/03-PATTERN-GUIDES/logging-minimal-mode.md +128 -128
  388. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/common-patterns.ts +380 -380
  389. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/multiple-connections-readme.md +139 -139
  390. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/parallel-root-connections.ts +149 -149
  391. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/real-world-scenarios.ts +405 -405
  392. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-01-foundations.md +378 -378
  393. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-02-quick-start.md +566 -566
  394. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-03-targeting-connections.md +659 -659
  395. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-04-parallel-queries.md +656 -656
  396. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-05-best-practices.md +624 -624
  397. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-06-api-reference.md +824 -824
  398. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-06-versori.md +119 -119
  399. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-07-api-reference.md +87 -87
  400. package/docs/03-PATTERN-GUIDES/multiple-connections/multiple-connections-quick-reference.md +353 -353
  401. package/docs/03-PATTERN-GUIDES/multiple-connections/multiple-connections-readme.md +270 -270
  402. package/docs/03-PATTERN-GUIDES/multiple-connections/readme.md +30 -30
  403. package/docs/03-PATTERN-GUIDES/pagination/pagination-readme.md +14 -14
  404. package/docs/03-PATTERN-GUIDES/pagination/readme.md +24 -24
  405. package/docs/03-PATTERN-GUIDES/parquet/examples/common-patterns.ts +180 -180
  406. package/docs/03-PATTERN-GUIDES/parquet/examples/read-parquet.ts +48 -48
  407. package/docs/03-PATTERN-GUIDES/parquet/examples/write-parquet.ts +65 -65
  408. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-01-introduction.md +393 -393
  409. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-02-quick-start.md +572 -572
  410. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-03-reading-parquet.md +525 -525
  411. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-04-writing-parquet.md +554 -554
  412. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-05-graphql-extraction.md +405 -405
  413. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-06-performance.md +104 -104
  414. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-06-s3-integration.md +511 -511
  415. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-07-api-reference.md +90 -90
  416. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-07-performance-optimization.md +525 -525
  417. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-08-best-practices.md +712 -712
  418. package/docs/03-PATTERN-GUIDES/parquet/parquet-quick-reference.md +683 -683
  419. package/docs/03-PATTERN-GUIDES/parquet/parquet-readme.md +248 -248
  420. package/docs/03-PATTERN-GUIDES/parquet/readme.md +32 -32
  421. package/docs/03-PATTERN-GUIDES/parsers/parsers-readme.md +12 -12
  422. package/docs/03-PATTERN-GUIDES/parsers/readme.md +24 -24
  423. package/docs/03-PATTERN-GUIDES/readme.md +159 -159
  424. package/docs/03-PATTERN-GUIDES/webhooks/readme.md +24 -24
  425. package/docs/03-PATTERN-GUIDES/webhooks/webhooks-readme.md +8 -8
  426. package/docs/04-REFERENCE/architecture/architecture-01-overview.md +427 -427
  427. package/docs/04-REFERENCE/architecture/architecture-02-client-architecture.md +424 -424
  428. package/docs/04-REFERENCE/architecture/architecture-03-data-flow.md +690 -690
  429. package/docs/04-REFERENCE/architecture/architecture-04-service-layer.md +834 -834
  430. package/docs/04-REFERENCE/architecture/architecture-05-integration-architecture.md +655 -655
  431. package/docs/04-REFERENCE/architecture/architecture-06-state-management.md +653 -653
  432. package/docs/04-REFERENCE/architecture/architecture-adding-new-data-sources.md +686 -686
  433. package/docs/04-REFERENCE/architecture/readme.md +279 -279
  434. package/docs/04-REFERENCE/platforms/deno/readme.md +117 -117
  435. package/docs/04-REFERENCE/platforms/nodejs/readme.md +146 -146
  436. package/docs/04-REFERENCE/platforms/readme.md +135 -135
  437. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-01-introduction.md +398 -398
  438. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-02-quick-start.md +560 -560
  439. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-03-authentication.md +757 -757
  440. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-04-workflows.md +2476 -2476
  441. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-05-connections.md +1167 -1167
  442. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-06-kv-storage.md +990 -990
  443. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-06-state-management.md +121 -121
  444. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-07-api-reference.md +68 -68
  445. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-07-deployment.md +731 -731
  446. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-08-best-practices.md +1111 -1111
  447. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-09-signature-reference.md +766 -766
  448. package/docs/04-REFERENCE/platforms/versori/platforms-versori-readme.md +299 -299
  449. package/docs/04-REFERENCE/platforms/versori/platforms-versori-s3-sftp-configuration-guide.md +1425 -1425
  450. package/docs/04-REFERENCE/platforms/versori/platforms-versori-webhook-api-key-security.md +816 -816
  451. package/docs/04-REFERENCE/platforms/versori/platforms-versori-webhook-connection-security.md +681 -681
  452. package/docs/04-REFERENCE/platforms/versori/platforms-versori-workflow-task-types.md +708 -708
  453. package/docs/04-REFERENCE/platforms/versori/readme.md +108 -108
  454. package/docs/04-REFERENCE/readme.md +148 -148
  455. package/docs/04-REFERENCE/resolver-signature/examples/advanced-resolvers.ts +482 -482
  456. package/docs/04-REFERENCE/resolver-signature/examples/async-resolvers.ts +496 -496
  457. package/docs/04-REFERENCE/resolver-signature/examples/basic-resolvers.ts +343 -343
  458. package/docs/04-REFERENCE/resolver-signature/examples/resolver-signature-readme.md +188 -188
  459. package/docs/04-REFERENCE/resolver-signature/examples/testing-resolvers.ts +463 -463
  460. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-01-foundations.md +286 -286
  461. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-02-parameter-reference.md +643 -643
  462. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-03-basic-examples.md +521 -521
  463. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-04-advanced-patterns.md +739 -739
  464. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-05-sdk-resolvers.md +531 -531
  465. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-06-migration-guide.md +650 -650
  466. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-06-testing.md +125 -125
  467. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-07-api-reference.md +794 -794
  468. package/docs/04-REFERENCE/resolver-signature/readme.md +64 -64
  469. package/docs/04-REFERENCE/resolver-signature/resolver-signature-quick-reference.md +270 -270
  470. package/docs/04-REFERENCE/resolver-signature/resolver-signature-readme.md +351 -351
  471. package/docs/04-REFERENCE/schema/fluent-commerce-schema.json +764 -764
  472. package/docs/04-REFERENCE/schema/readme.md +141 -141
  473. package/docs/04-REFERENCE/testing/examples/04-reference-testing-readme.md +158 -158
  474. package/docs/04-REFERENCE/testing/examples/fluent-testing.ts +62 -62
  475. package/docs/04-REFERENCE/testing/examples/health-check.ts +155 -155
  476. package/docs/04-REFERENCE/testing/examples/integration-test.ts +119 -119
  477. package/docs/04-REFERENCE/testing/examples/performance-test.ts +183 -183
  478. package/docs/04-REFERENCE/testing/examples/s3-testing.ts +127 -127
  479. package/docs/04-REFERENCE/testing/modules/04-reference-testing-01-foundations.md +267 -267
  480. package/docs/04-REFERENCE/testing/modules/04-reference-testing-02-s3-testing.md +599 -599
  481. package/docs/04-REFERENCE/testing/modules/04-reference-testing-03-fluent-testing.md +589 -589
  482. package/docs/04-REFERENCE/testing/modules/04-reference-testing-04-integration-testing.md +699 -699
  483. package/docs/04-REFERENCE/testing/modules/04-reference-testing-05-debugging.md +478 -478
  484. package/docs/04-REFERENCE/testing/modules/04-reference-testing-06-cicd-integration.md +463 -463
  485. package/docs/04-REFERENCE/testing/modules/04-reference-testing-06-preflight-validation.md +131 -131
  486. package/docs/04-REFERENCE/testing/modules/04-reference-testing-07-best-practices.md +499 -499
  487. package/docs/04-REFERENCE/testing/modules/04-reference-testing-07-coverage-ci.md +165 -165
  488. package/docs/04-REFERENCE/testing/modules/04-reference-testing-08-api-reference.md +634 -634
  489. package/docs/04-REFERENCE/testing/readme.md +86 -86
  490. package/docs/04-REFERENCE/testing/testing-quick-reference.md +667 -667
  491. package/docs/04-REFERENCE/testing/testing-readme.md +286 -286
  492. package/docs/04-REFERENCE/troubleshooting/readme.md +144 -144
  493. package/docs/04-REFERENCE/troubleshooting/troubleshooting-deno-sftp-compatibility.md +392 -392
  494. package/docs/template-loading-matrix.md +242 -242
  495. package/package.json +5 -3
@@ -1,2294 +1,2294 @@
1
- ---
2
- template_id: tpl-extract-fulfillments-to-sftp-xml
3
- canonical_filename: template-extraction-fulfillments-to-sftp-xml.md
4
- version: 2.0.0
5
- sdk_version: ^0.1.39
6
- runtime: versori
7
- direction: extraction
8
- source: fluent-graphql
9
- destination: sftp-xml
10
- entity: fulfillments
11
- format: xml
12
- logging: versori
13
- status: stable
14
- features:
15
- - memory-management
16
- - enhanced-logging
17
- - pagination-progress
18
- - dispose-finally
19
- ---
20
-
21
- # Template: Extraction - Fulfillments to SFTP XML
22
-
23
- **Template Version:** 2.0.0
24
- **SDK Version:** @fluentcommerce/fc-connect-sdk@^0.1.39
25
- **Last Updated:** 2025-01-24
26
- **Deployment Target:** Versori Platform
27
-
28
- **🆕 Version 2.0.0 Enhancements:**
29
- - ✅ **Memory Management** - Clear large result sets after processing batches
30
- - ✅ **Enhanced Logging** - Pagination progress tracking with emoji indicators (📊, 📥, ✅)
31
- - ✅ **Pagination Progress** - Real-time page-by-page progress logging with metrics
32
- - ✅ **Resource Cleanup** - SFTP dispose in finally blocks prevents connection leaks
33
-
34
- ## Installation
35
-
36
- ```bash
37
- npm install @fluentcommerce/fc-connect-sdk@^0.1.39
38
- ```
39
-
40
- Use version `^0.1.39` to ensure compatibility with this template.
41
-
42
- ---
43
-
44
- ## 📚 STEP 1: Load These Docs (Human Checklist)
45
-
46
- 1. REQUIRED (load all)
47
- - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
48
- - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
49
- - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
50
- - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
51
- - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/extraction/
52
- - [ ] fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
53
-
54
- Copy-paste list (open these):
55
- fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
56
- fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
57
- fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
58
- fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
59
- fc-connect-sdk/docs/03-PATTERN-GUIDES/extraction/
60
- fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
61
-
62
- ---
63
-
64
- ## 📋 STEP 2: Tell Your AI (Prompt)
65
-
66
- Copy/paste this prompt after loading the documentation above:
67
-
68
- ```
69
- Create a Versori scheduled extractor for fulfillments that uses ExtractionOrchestrator + JobTracker, incremental updatedOn with a 60s overlap buffer, transforms via UniversalMapper, generates XML with fast-xml-parser XMLBuilder, uploads to SFTP using SftpDataSource with dispose(). Include 3 workflows: scheduled, ad-hoc webhook, and job-status query with native Versori logging.
70
- ```
71
-
72
- ---
73
-
74
- ## 📦 SDK Imports (Verified - Versori Optimized)
75
-
76
- ```typescript
77
- import { Buffer } from 'node:buffer';
78
- import {
79
- createClient,
80
- ExtractionOrchestrator,
81
- JobTracker,
82
- UniversalMapper,
83
- XMLBuilder,
84
- SftpDataSource,
85
- VersoriKVAdapter,
86
- } from '@fluentcommerce/fc-connect-sdk';
87
-
88
- import { schedule, webhook, http, fn } from '@versori/run';
89
- ```
90
-
91
- ---
92
-
93
- # Versori Scheduled: Fulfillments Extraction to SFTP XML (Shipment Tracking)
94
-
95
- **FC Connect SDK Use Case Guide**
96
-
97
- > SDK: [@fluentcommerce/fc-connect-sdk](https://www.npmjs.com/package/@fluentcommerce/fc-connect-sdk)
98
- > Version: Use ^0.1.39 - `npm install @fluentcommerce/fc-connect-sdk@^0.1.39`
99
-
100
- Context: Scheduled Versori workflow that extracts fulfillment data (shipment tracking, delivery information) from Fluent Commerce via GraphQL query with **ExtractionOrchestrator**, **JobTracker**, and **incremental timestamp tracking**, transforms with `UniversalMapper`, and writes **XML files** to SFTP for logistics coordination and delivery tracking.
101
-
102
- **Pattern**: EXTRACTION (Fluent → SFTP XML)
103
- **Complexity**: High | Runtime: Versori Platform (Scheduled)
104
-
105
- ---
106
-
107
- ## ⚠️ IMPORTANT: Production-Ready Base Template
108
-
109
- > **📋 BASE TEMPLATE - Ready for Production (Customize for Your Needs)**
110
- >
111
- > This is a **production-ready base template** demonstrating FC Connect SDK best practices for fulfillment extraction workflows with XML output.
112
- >
113
- > **✅ INCLUDED FEATURES:**
114
- >
115
- > - ✅ Comprehensive error handling with retry logic
116
- > - ✅ SFTP upload with exponential backoff (3 attempts)
117
- > - ✅ State management with overlap buffer (prevents missed records)
118
- > - ✅ Job tracking with lifecycle management
119
- > - ✅ Security (credential masking in logs)
120
- > - ✅ UTC time enforcement (prevents timezone bugs)
121
- > - ✅ Incremental extraction (safe, efficient, production-ready)
122
- > - ✅ Natural rate limiting via timestamps
123
- >
124
- > **📝 BEFORE DEPLOYING:**
125
- >
126
- > 1. Review and customize activation variables for your environment
127
- > 2. Test with sample data in your Versori workspace
128
- > 3. Adjust safety limits (pageSize, maxRecords) if needed
129
- > 4. Configure monitoring alerts for extraction failures
130
- > 5. Verify SFTP credentials and paths
131
- >
132
- > **This base template follows SDK best practices - tweak specific to your needs.**
133
-
134
- ---
135
-
136
- ## 🚀 Quick Deploy to Versori
137
-
138
- 1. **Create Integration:** Versori Dashboard → New Integration → Name it "Fulfillments Extraction"
139
- 2. **Copy Code:** Copy all workflow code from this template into Versori editor
140
- 3. **Configure Connections:**
141
- - `fluent_commerce` - Fluent Commerce API (OAuth2)
142
- - `sftp_export_server` - SFTP destination (Basic Auth)
143
- - `fulfillments-adhoc` - Ad-hoc webhook auth (API Key)
144
- - `fulfillments-job-status` - Status webhook auth (API Key)
145
- 4. **Set Activation Variables:** Configure all variables listed in Activation Variables section
146
- 5. **Test:** Use ad-hoc webhook to test extraction before enabling schedule
147
- 6. **Enable Schedule:** Activate scheduled workflow after successful test
148
-
149
- **Time to Deploy:** ~15 minutes
150
-
151
- ---
152
-
153
- ## 🔧 Common Customizations
154
-
155
- **Most Common Changes:**
156
-
157
- | What to Change | Where | Why |
158
- | ---------------------- | ----------------------------------------- | ---------------------------------- |
159
- | **Status filters** | Activation variable `fulfillmentStatuses` | Target specific fulfillment states |
160
- | **Schedule frequency** | Workflow: `'0 */4 * * *'` | Change from 4-hourly to your needs |
161
- | **XML field mapping** | `config/fulfillments.export.xml.json` | Add/remove/modify output fields |
162
- | **Date filters** | GraphQL query variables | Filter by creation/update dates |
163
- | **Page size** | Activation variable `pageSize` | Tune for performance (50-1000) |
164
- | **Safety limits** | Activation variable `maxRecords` | Adjust based on dataset size |
165
-
166
- **Less Common Changes:**
167
-
168
- | What to Change | Where | Default | When to Change |
169
- | ----------------------- | ------------------------------------------ | ----------------------- | ---------------------------- |
170
- | **Overlap buffer** | Activation variable `overlapBufferSeconds` | 60s | If seeing missed records |
171
- | **SFTP retry attempts** | Code: `uploadWithRetry(..., 3)` | 3 | For unreliable networks |
172
- | **Fallback start date** | Activation variable `fallbackStartDate` | 2024-01-01 | For historical extraction |
173
- | **Remote path** | Activation variable `sftpRemotePath` | /incoming/fulfillments/ | Match partner's requirements |
174
-
175
- **What NOT to Change (Unless You Know Why):**
176
-
177
- - 10-step workflow structure
178
- - Error taxonomy (CONFIG/API/SFTP/NO_DATA)
179
- - State management logic
180
- - UTC time enforcement
181
- - Connection cleanup (`sftp.dispose()`)
182
-
183
- ---
184
-
185
- ## What You'll Build
186
-
187
- - **Incremental extraction** using `updatedOn >= (lastRunTime - buffer)` with **overlap buffer**
188
- - **ExtractionOrchestrator** for auto-pagination and path-based extraction
189
- - **JobTracker** for lifecycle management
190
- - **State management** with VersoriKV to track last successful run
191
- - **Safety buffer** (60 seconds) to handle clock skew and race conditions
192
- - GraphQL query with status-based filtering and date range support
193
- - UniversalMapper transformation with nested order data
194
- - **XML file generation** with fulfillment/shipment data
195
- - **SFTP upload** to partner systems with proper connection cleanup
196
- - **3 workflow patterns**: scheduled, ad-hoc webhook, job status query
197
- - **Failure recovery** with timestamp tracking
198
-
199
- ## Business Use Case
200
-
201
- **4-hourly shipment tracking extraction for logistics:**
202
-
203
- - Extract shipment and delivery information for carrier integration
204
- - Track fulfillment status changes (SHIPPED, DELIVERED)
205
- - Monitor delivery exceptions and returns (RMA)
206
- - Support logistics partner feeds
207
- - Enable shipment tracking updates
208
- - Run every 4 hours for timely status updates
209
- - Deliver XML format to enterprise systems via SFTP
210
-
211
- ## Fulfillments Explained
212
-
213
- **Fulfillment** = Shipment execution record
214
-
215
- - Represents order fulfillment process
216
- - Tracks shipment status and delivery progress
217
- - Links to orders, items, and locations
218
- - Used for: Shipment tracking, delivery coordination, logistics integration
219
-
220
- **Key Fields:**
221
-
222
- - `ref` - Unique fulfillment reference
223
- - `status` - Fulfillment state (SHIPPED, DELIVERED, etc.)
224
- - `deliveryType` - Shipping method
225
- - `order.ref` - Associated order reference
226
- - `fromLocation` - Shipping origin
227
- - `items` - Fulfilled order items
228
- - `createdOn`, `updatedOn` - Timestamps for tracking
229
-
230
- ## SDK Methods Used
231
-
232
- ```typescript
233
- import { Buffer } from 'node:buffer';
234
- import {
235
- createClient,
236
- ExtractionOrchestrator,
237
- JobTracker,
238
- UniversalMapper,
239
- XMLBuilder,
240
- SftpDataSource,
241
- VersoriKVAdapter,
242
- } from '@fluentcommerce/fc-connect-sdk';
243
-
244
- await createClient(ctx); // Versori-aware client
245
- const orchestrator = new ExtractionOrchestrator(client, log); // Auto-pagination
246
- const tracker = new JobTracker(kv, log); // Job lifecycle tracking
247
- await orchestrator.extract({ query, resultPath, variables, pageSize, maxRecords }); // Extract
248
- new VersoriKVAdapter(ctx.openKv(':project:')); // State management
249
- new UniversalMapper(exportMapping); // Field transformation
250
- new XMLBuilder({ prettyPrint: true, xmlDeclaration: true }); // XML generation
251
- const xml = xmlBuilder.build(data, 'RootElement'); // Build XML string
252
- await sftp.uploadFile(remotePath, buffer, options); // SFTP upload
253
- await sftp.dispose(); // CRITICAL: Connection cleanup
254
- ```
255
-
256
- ## Activation Variables
257
-
258
- **Configuration is driven by activation variables - modify these instead of code:**
259
-
260
- ```json
261
- {
262
- "fulfillmentStatuses": "SHIPPED,DELIVERED",
263
- "sftpHost": "sftp.partner.com",
264
- "sftpPort": 22,
265
- "sftpPrivateKey": "",
266
- "sftpRemotePath": "/incoming/fulfillments/",
267
- "fileNamePrefix": "fulfillments",
268
- "requireAbsolutePaths": "false",
269
- "pageSize": 200,
270
- "maxRecords": 50000,
271
- "fallbackStartDate": "2024-01-01T00:00:00Z",
272
- "overlapBufferSeconds": "60"
273
- }
274
- ```
275
-
276
- > **Note:** `sftpUsername` and `sftpPassword` are fetched from the `sftp_export_server` connection (see SFTP Credential Management section below).
277
-
278
- ## SFTP Credential Management
279
-
280
- Fetch credentials securely from Versori connection vault using `ctx.credentials().getAccessToken()`:
281
-
282
- ```typescript
283
- import { Buffer } from 'node:buffer'; // Required for Versori/Deno
284
-
285
- // ========================================
286
- // SFTP CREDENTIAL RETRIEVAL
287
- // ========================================
288
-
289
- /**
290
- * Retrieve SFTP credentials from connection configuration
291
- *
292
- * This approach retrieves credentials stored in the Versori connection settings.
293
- * The connection must be configured in the UI with Basic Authentication.
294
- *
295
- * Steps:
296
- * 1. Call ctx.credentials().getAccessToken('SFTP') to get base64-encoded credentials
297
- * 2. Decode the accessToken from base64 to get "username:password" string
298
- * 3. Split on ':' to extract username and password
299
- *
300
- * Connection Name: 'sftp_export_server' (must match the connection name in Versori UI)
301
- * Auth Type: Basic Authentication (username + password)
302
- *
303
- * This method provides:
304
- * - Centralized credential management through Versori UI
305
- * - Better security (credentials not stored in integration variables)
306
- * - Easier credential rotation and updates
307
- */
308
- log.info('Retrieving SFTP credentials from connection configuration');
309
-
310
- let sftpUsername: string;
311
- let sftpPassword: string;
312
-
313
- try {
314
- // Retrieve credentials from the 'sftp_export_server' connection
315
- const sftpCred = await ctx.credentials().getAccessToken('sftp_export_server');
316
-
317
- if (!sftpCred?.accessToken) {
318
- throw new Error('No SFTP credentials found in connection configuration');
319
- }
320
-
321
- // Decode base64 accessToken to get "username:password"
322
- const rawBasicAuth = Buffer.from(sftpCred.accessToken, 'base64').toString('utf-8');
323
-
324
- // Split on ':' to extract username and password
325
- const parts = rawBasicAuth.split(':');
326
-
327
- if (parts.length !== 2) {
328
- throw new Error('Invalid SFTP credential format - expected username:password');
329
- }
330
-
331
- sftpUsername = parts[0];
332
- sftpPassword = parts[1];
333
-
334
- log.info('SFTP credentials retrieved successfully', {
335
- hasUsername: !!sftpUsername,
336
- hasPassword: !!sftpPassword,
337
- usernameLength: sftpUsername.length,
338
- passwordLength: sftpPassword.length,
339
- });
340
- } catch (error: any) {
341
- log.error('Failed to retrieve SFTP credentials', {
342
- message: error instanceof Error ? error.message : String(error),
343
- stack: error instanceof Error ? error.stack : undefined,
344
- errorType: error instanceof Error ? error.constructor.name : 'Error',
345
- });
346
-
347
- return {
348
- success: false,
349
- error: 'Failed to retrieve SFTP credentials from connection configuration',
350
- details: error instanceof Error ? error.message : String(error),
351
- recommendation: 'Please ensure the SFTP connection is configured in the Connections section with Basic Authentication (username and password)',
352
- };
353
- }
354
-
355
- // Initialize SFTP with connection credentials
356
- const sftp = new SftpDataSource(
357
- {
358
- type: 'SFTP_XML',
359
- connectionId: 'sftp_export_server',
360
- name: 'Export SFTP',
361
- settings: {
362
- host: ctx.activation.getVariable('sftpHost'),
363
- port: parseInt(ctx.activation.getVariable('sftpPort') || '22'),
364
- username: sftpUsername,
365
- password: sftpPassword,
366
- remotePath: ctx.activation.getVariable('sftpRemotePath') || '/exports',
367
- encoding: 'utf8',
368
- },
369
- },
370
- log
371
- );
372
- ```
373
-
374
- **Benefits:**
375
-
376
- - ✅ Credentials stored securely in Versori vault
377
- - ✅ Centralized management - update in one place
378
- - ✅ Access control enforced by platform
379
- - ✅ No credentials in activation variables
380
- - ✅ Explicit error handling with validation
381
-
382
- ### Setup Steps
383
-
384
- 1. In Versori Dashboard → Connections → Add Connection
385
- 2. Name: `sftp_export_server`
386
- 3. Type: Basic Auth
387
- 4. Enter SFTP username and password
388
- 5. Save connection
389
- 6. Reference in code: `ctx.credentials().getAccessToken('sftp_export_server')`
390
-
391
- ---
392
-
393
- ## Webhook Security Configuration
394
-
395
- **⚠️ IMPORTANT:** Webhook security is now handled at the **Versori connection level** (not in code).
396
-
397
- ### Required Connections
398
-
399
- Create these connections in Versori Dashboard before deploying:
400
-
401
- 1. **`fulfillments-adhoc`** (Ad-hoc webhook auth)
402
- - Configure authentication (e.g., API Key) in the connection settings
403
-
404
- 2. **`fulfillments-job-status`** (Job status query auth)
405
- - Configure authentication (e.g., API Key) in the connection settings
406
-
407
- ### How to Create Webhook Connections
408
-
409
- 1. **Navigate to Versori Dashboard** → Connections
410
- 2. **Click "Add Connection"**
411
- 3. **Configure:**
412
- - Name: `fulfillments-adhoc`
413
- - Authentication: API Key (or preferred method)
414
- - Provide header name/value in the connection UI
415
- 4. **Save Connection**
416
- 5. **Repeat** for `fulfillments-job-status` connection
417
-
418
- ### Generate Secure API Keys
419
-
420
- ```bash
421
- # Node.js - Generate cryptographically secure 64-character key
422
- node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
423
-
424
- # Example output:
425
- # 7f3e9a2b1c8d6e4f5a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8f
426
- ```
427
-
428
- ### How It Works
429
-
430
- ```
431
- ┌────────────────┐
432
- │ External │
433
- │ System │
434
- └──────┬─────────┘
435
-
436
- │ POST /webhook/fulfillments-adhoc
437
- │ Headers: (as configured on the connection)
438
-
439
- ┌─────────────────────────┐
440
- │ Versori Platform │
441
- │ ✓ Validates API key │ ← Authentication happens HERE
442
- │ ✓ Checks header │
443
- │ ✗ Rejects if invalid │
444
- └──────┬──────────────────┘
445
-
446
- │ ✅ Only reaches workflow if valid
447
-
448
- ┌─────────────────────────┐
449
- │ Your Workflow Code │
450
- │ (No auth code needed!) │
451
- └──────────────────────────┘
452
- ```
453
-
454
- **Benefits:**
455
-
456
- - ✅ Security at platform level (before code runs)
457
- - ✅ No manual validation code needed
458
- - ✅ Consistent across all webhooks
459
- - ✅ Easy to rotate keys (update connection, not code)
460
- - ✅ Failed auth never hits your workflow (saves resources)
461
-
462
- ## Export Mapping Configuration
463
-
464
- Create file: `config/fulfillments.export.xml.json`
465
-
466
- ```json
467
- {
468
- "name": "fulfillments.export.xml",
469
- "version": "1.0.0",
470
- "description": "Fluent Fulfillments → SFTP XML Export (shipment tracking)",
471
- "fields": {
472
- "fulfillment_ref": { "source": "ref", "required": true, "resolver": "sdk.trim" },
473
- "order_ref": { "source": "order.ref", "required": true, "resolver": "sdk.trim" },
474
- "status": { "source": "status", "required": true, "resolver": "sdk.uppercase" },
475
- "delivery_type": { "source": "deliveryType", "required": false, "resolver": "sdk.trim" },
476
- "from_location_ref": {
477
- "source": "fromLocation.ref",
478
- "required": false,
479
- "resolver": "sdk.trim"
480
- },
481
- "from_location_name": {
482
- "source": "fromLocation.name",
483
- "required": false,
484
- "resolver": "sdk.trim"
485
- },
486
- "created_on": { "source": "createdOn", "required": true, "resolver": "sdk.toString" },
487
- "updated_on": { "source": "updatedOn", "required": true, "resolver": "sdk.toString" }
488
- }
489
- }
490
- ```
491
-
492
- **Note**: The mapping uses nested paths like `order.ref` and `fromLocation.ref` to access related entity fields.
493
-
494
- ## Mapping & Resolvers Explained
495
-
496
- This section explains how the SDK transforms raw GraphQL data into your XML export format using **UniversalMapper** and **SDK resolvers**.
497
-
498
- ### SDK Resolvers Used
499
-
500
- | Field | Resolver | Why? | Example Transformation |
501
- | -------------------- | --------------- | ---------------------------- | --------------------------------------- |
502
- | `fulfillment_ref` | `sdk.trim` | Clean fulfillment references | `" FF-001 "` → `"FF-001"` |
503
- | `order_ref` | `sdk.trim` | Clean order references | `" ORD-001 "` → `"ORD-001"` |
504
- | `status` | `sdk.uppercase` | Normalize status codes | `"shipped"` → `"SHIPPED"` |
505
- | `delivery_type` | `sdk.trim` | Clean delivery method | `" STANDARD "` → `"STANDARD"` |
506
- | `from_location_ref` | `sdk.trim` | Clean location references | `" LOC-001 "` → `"LOC-001"` |
507
- | `from_location_name` | `sdk.trim` | Clean location names | `" NYC Warehouse "` → `"NYC Warehouse"` |
508
- | `created_on` | `sdk.toString` | Preserve ISO 8601 timestamp | `"2025-01-15T10:00:00.000Z"` → same |
509
- | `updated_on` | `sdk.toString` | Preserve ISO 8601 timestamp | `"2025-01-22T08:30:00.000Z"` → same |
510
-
511
- ### Transformation Flow
512
-
513
- ```typescript
514
- // 1. GraphQL Response (raw data from Fluent Commerce)
515
- const rawFulfillment = {
516
- ref: ' FF-001 ',
517
- status: 'shipped',
518
- deliveryType: ' STANDARD ',
519
- order: {
520
- ref: ' ORD-001 ',
521
- },
522
- fromLocation: {
523
- ref: ' LOC-001 ',
524
- name: ' NYC Warehouse ',
525
- },
526
- items: {
527
- edges: [
528
- {
529
- node: {
530
- productRef: 'PROD-001',
531
- requestedQuantity: 2,
532
- filledQuantity: 2,
533
- },
534
- },
535
- ],
536
- },
537
- createdOn: '2025-01-15T10:00:00.000Z',
538
- updatedOn: '2025-01-22T08:30:00.000Z',
539
- };
540
-
541
- // 2. UniversalMapper applies SDK resolvers (handles nested paths automatically)
542
- const mapper = new UniversalMapper(fulfillmentsExportMapping);
543
- const result = await mapper.map(rawFulfillment);
544
-
545
- // 3. Transformed Output (clean, normalized for XML)
546
- const transformedFulfillment = {
547
- fulfillment_ref: 'FF-001',
548
- order_ref: 'ORD-001',
549
- status: 'SHIPPED',
550
- delivery_type: 'STANDARD',
551
- from_location_ref: 'LOC-001',
552
- from_location_name: 'NYC Warehouse',
553
- created_on: '2025-01-15T10:00:00.000Z',
554
- updated_on: '2025-01-22T08:30:00.000Z',
555
- };
556
- ```
557
-
558
- ### Nested Object Mapping
559
-
560
- Fulfillments include **nested objects** that require special path syntax:
561
-
562
- ```typescript
563
- // ✅ CORRECT - Access nested object fields with dot notation
564
- {
565
- "order_ref": { "source": "order.ref" },
566
- "from_location_ref": { "source": "fromLocation.ref" },
567
- "from_location_name": { "source": "fromLocation.name" }
568
- }
569
- ```
570
-
571
- **GraphQL must fetch the nested objects:**
572
-
573
- ```graphql
574
- node {
575
- ref # Direct field
576
- status
577
- order { # Nested Order object
578
- ref # Access via order.ref
579
- }
580
- fromLocation { # Nested Location object
581
- ref # Access via fromLocation.ref
582
- name # Access via fromLocation.name
583
- }
584
- items { # Nested items collection
585
- edges {
586
- node {
587
- productRef
588
- requestedQuantity
589
- filledQuantity
590
- }
591
- }
592
- }
593
- }
594
- ```
595
-
596
- **UniversalMapper handles nested paths automatically** - just use dot notation in the mapping configuration.
597
-
598
- ### Available SDK Resolvers
599
-
600
- The SDK provides these built-in resolvers (no custom code needed):
601
-
602
- **String Transformations:**
603
-
604
- - `sdk.trim` - Remove leading/trailing whitespace
605
- - `sdk.uppercase` - Convert to uppercase
606
- - `sdk.lowercase` - Convert to lowercase
607
- - `sdk.toString` - Convert to string
608
-
609
- **Number Parsing:**
610
-
611
- - `sdk.parseInt` - Parse as integer
612
- - `sdk.parseFloat` - Parse as decimal
613
- - `sdk.number` - Parse as number (auto-detect int/float)
614
-
615
- **Date Formatting:**
616
-
617
- - `sdk.formatDate` - ISO 8601 date only (YYYY-MM-DD)
618
- - `sdk.formatDateShort` - Short date format
619
- - `sdk.parseDate` - Parse various date formats
620
-
621
- **Type Conversions:**
622
-
623
- - `sdk.boolean` - Convert to boolean
624
- - `sdk.parseJson` - Parse JSON strings
625
- - `sdk.toJson` - Convert to JSON string
626
-
627
- **Utilities:**
628
-
629
- - `sdk.identity` - Return value unchanged
630
- - `sdk.coalesce` - Return first non-null value
631
-
632
- See [Universal Mapping Guide](../../../../../02-CORE-GUIDES/advanced-services/advanced-services-readme.md) for complete resolver documentation.
633
-
634
- ## GraphQL Query
635
-
636
- **Note**: This query is verified against Fluent Commerce schema introspection.
637
-
638
- ```graphql
639
- query GetFulfillments(
640
- $statuses: [String!]
641
- $updatedFrom: DateTime
642
- $updatedTo: DateTime
643
- $first: Int!
644
- $after: String
645
- ) {
646
- fulfillments(
647
- status: $statuses
648
- updatedOn: { from: $updatedFrom, to: $updatedTo }
649
- first: $first
650
- after: $after
651
- ) {
652
- edges {
653
- node {
654
- id
655
- ref
656
- status
657
- deliveryType
658
- order {
659
- ref
660
- }
661
- fromLocation {
662
- ref
663
- name
664
- }
665
- items {
666
- edges {
667
- node {
668
- productRef
669
- requestedQuantity
670
- filledQuantity
671
- }
672
- }
673
- }
674
- createdOn
675
- updatedOn
676
- }
677
- cursor
678
- }
679
- pageInfo {
680
- hasNextPage
681
- }
682
- }
683
- }
684
- ```
685
-
686
- ---
687
-
688
- ## Versori Workflows Structure
689
-
690
- **Key Concept**: Versori workflows are organized by **trigger type** at the first level, then by **specific workflow** with descriptive file names.
691
-
692
- **Trigger Types:**
693
- - **`schedule()`** → Time-based triggers (cron expressions) - NOT exposed as HTTP endpoints
694
- - **`webhook()`** → HTTP-based triggers (event-driven) - Creates HTTP endpoints
695
- - **`workflow()`** → Durable workflows (advanced, rarely used)
696
-
697
- **Execution Steps (chained to triggers):**
698
- - **`http()`** → External API calls (chained from schedule/webhook)
699
- - **`fn()`** → Internal processing (chained from schedule/webhook)
700
-
701
- ### Recommended Project Structure
702
-
703
- **This template demonstrates a complete workflow implementation in a single file.** In production, consider organizing your code into this modular structure:
704
-
705
- ```
706
- fulfillments-extraction/
707
- ├── index.ts # Entry point - exports all workflows
708
- └── src/
709
- ├── workflows/
710
- │ └── fulfillments-extraction.ts # All workflows (scheduled + webhooks)
711
-
712
- ├── services/
713
- │ └── extraction-orchestration.ts # Shared orchestration logic (reusable)
714
-
715
- └── config/
716
- ├── queries.ts # GraphQL queries
717
- └── fulfillments.export.xml.json # Mapping configuration
718
- ```
719
-
720
- **Alternative Modular Structure** (for larger projects with multiple workflows):
721
- ```
722
- fulfillments-extraction/
723
- ├── index.ts
724
- └── src/
725
- ├── workflows/
726
- │ ├── scheduled/
727
- │ │ └── daily-fulfillments-extraction.ts # Scheduled extraction only
728
- │ └── webhook/
729
- │ ├── adhoc-fulfillments-extraction.ts # Ad-hoc webhook
730
- │ └── job-status-check.ts # Status query webhook
731
- ├── services/
732
- │ └── extraction-orchestration.ts
733
- └── config/
734
- ├── queries.ts
735
- └── fulfillments.export.xml.json
736
- ```
737
-
738
- ---
739
-
740
- ## Expected XML Output
741
-
742
- ```xml
743
- <?xml version="1.0" encoding="UTF-8"?>
744
- <Fulfillments>
745
- <Fulfillment>
746
- <fulfillment_ref>FF-001</fulfillment_ref>
747
- <order_ref>ORD-001</order_ref>
748
- <status>SHIPPED</status>
749
- <delivery_type>STANDARD</delivery_type>
750
- <from_location_ref>LOC-001</from_location_ref>
751
- <from_location_name>NYC Warehouse</from_location_name>
752
- <created_on>2025-01-15T10:00:00Z</created_on>
753
- <updated_on>2025-01-22T08:30:00Z</updated_on>
754
- </Fulfillment>
755
- <Fulfillment>
756
- <fulfillment_ref>FF-002</fulfillment_ref>
757
- <order_ref>ORD-002</order_ref>
758
- <status>DELIVERED</status>
759
- <delivery_type>EXPRESS</delivery_type>
760
- <from_location_ref>LOC-002</from_location_ref>
761
- <from_location_name>LA Warehouse</from_location_name>
762
- <created_on>2025-01-16T11:00:00Z</created_on>
763
- <updated_on>2025-01-22T09:15:00Z</updated_on>
764
- </Fulfillment>
765
- </Fulfillments>
766
- ```
767
-
768
- ## Production Safety & Guardrails
769
-
770
- ### Overview
771
-
772
- Fulfillments require safeguards even in incremental mode:
773
-
774
- - **Status changes**: Fulfillments can update frequently during processing
775
- - **Delivery tracking**: Real-time status updates create rapid data changes
776
- - **Order volume**: High-volume retailers process thousands of fulfillments daily
777
- - **Partner feeds**: Logistics systems need predictable file sizes
778
-
779
- ### Hard Limits
780
-
781
- ```typescript
782
- const SAFETY_LIMITS = {
783
- MAX_RECORDS_PER_RUN: 100000, // 100k fulfillments per run
784
- MAX_RECORDS_PER_FILE: 25000, // 25k per XML file
785
- MAX_FILE_SIZE_MB: 75, // 75MB per file
786
- MAX_XML_SIZE_MB: 150, // Total extraction size
787
- CHUNK_SIZE: 5000, // Process in chunks
788
- ESTIMATED_BYTES_PER_RECORD: 600, // Conservative estimate for XML
789
- };
790
- ```
791
-
792
- **Why these limits?**
793
-
794
- - Fulfillments have nested items (larger than simple entities)
795
- - Shipment tracking needs fast processing for timely updates
796
- - Multiple status changes can accumulate quickly
797
- - Partner systems require predictable batch sizes
798
- - XML is more verbose than CSV (~25% larger)
799
-
800
- ### Runtime Validation Function
801
-
802
- ```typescript
803
- /**
804
- * Validate extraction safety limits before processing
805
- */
806
- function validateExtractionLimits(recordCount: number, estimatedSizeMB: number) {
807
- const MAX_RECORDS_PER_RUN = 100000;
808
- const MAX_XML_SIZE_MB = 150;
809
-
810
- if (recordCount > MAX_RECORDS_PER_RUN) {
811
- return {
812
- valid: false,
813
- error: `Extraction limit exceeded: ${recordCount} records (max: ${MAX_RECORDS_PER_RUN})`,
814
- recommendation: `Fulfillments dataset too large. Consider:
815
- 1. Increase extraction frequency (4-hourly → hourly)
816
- 2. Filter by status (extract SHIPPED and DELIVERED separately)
817
- 3. Filter by date range (last 24 hours only)
818
- 4. Split by location (extract by fulfillment center)`,
819
- recordCount,
820
- maxAllowed: MAX_RECORDS_PER_RUN,
821
- };
822
- }
823
-
824
- if (estimatedSizeMB > MAX_XML_SIZE_MB) {
825
- return {
826
- valid: false,
827
- error: `XML size limit exceeded: ${estimatedSizeMB}MB (max: ${MAX_XML_SIZE_MB}MB)`,
828
- recommendation: 'File splitting required. Filter by status or date range.',
829
- estimatedSizeMB,
830
- maxAllowed: MAX_XML_SIZE_MB,
831
- };
832
- }
833
-
834
- return { valid: true };
835
- }
836
- ```
837
-
838
- ---
839
-
840
- ## Production Capabilities
841
-
842
- Built-in safeguards and best practices:
843
-
844
- | Capability | Implementation | Benefit |
845
- | ----------------------- | ------------------------------------------ | ------------------------------- |
846
- | **Config Validation** | Fail-fast with detailed error messages | Catches issues before execution |
847
- | **SFTP Retry** | 3 attempts with exponential backoff | Resilient to network issues |
848
- | **UTC Enforcement** | Normalize all dates to UTC | Prevents timezone bugs |
849
- | **Window Persistence** | Save effective time window in job metadata | Complete execution history |
850
- | **Error Taxonomy** | Categorize errors: CONFIG/API/SFTP/NO_DATA | Better support triage |
851
- | **Extended Metrics** | Track pages, skipped records, XML size | Enhanced observability |
852
- | **Input Normalization** | Lowercase, trim, dedupe list inputs | Consistent filtering |
853
- | **Secrets Masking** | Mask credentials in error logs | Security compliance |
854
-
855
- ---
856
-
857
- ## Complete Workflow Code
858
-
859
- ### File Structure
860
-
861
- **This template demonstrates a single-file implementation** (all workflows in one file for easier understanding). The actual code structure matches the "Recommended Project Structure" shown earlier.
862
-
863
- ```
864
- fulfillments-extraction/
865
- ├── src/
866
- │ ├── index.ts # Entry point (exports workflows)
867
- │ ├── workflows/
868
- │ │ └── fulfillments-extraction.ts # All 3 workflows (scheduled + 2 webhooks)
869
- │ ├── services/
870
- │ │ └── extraction-orchestration.ts # Main orchestration logic (shared)
871
- │ └── config/
872
- │ └── queries.ts # GraphQL queries & mapping
873
- ├── config/
874
- │ └── fulfillments.export.xml.json # Field mapping config
875
- └── package.json
876
- ```
877
-
878
- **Why Single File?**
879
- - ✅ Easier to understand workflow relationships
880
- - ✅ All patterns visible in one place
881
- - ✅ Simpler to maintain for small projects
882
- - ⚠️ For larger projects, split into `scheduled/` and `webhook/` subdirectories (see "Alternative Modular Structure" above)
883
-
884
- **Entry Point (`src/index.ts`):**
885
-
886
- ```typescript
887
- // Export all workflows for Versori to discover
888
- export {
889
- scheduledFulfillmentsExtraction,
890
- adhocFulfillmentsExtraction,
891
- fulfillmentsJobStatus,
892
- } from './workflows/fulfillments-extraction';
893
-
894
- // Export services for testing or direct use
895
- export {
896
- executeFulfillmentExtraction,
897
- queryJobStatus,
898
- generateJobId,
899
- } from './services/extraction-orchestration';
900
-
901
- // Export configuration for reference
902
- export { FULFILLMENTS_QUERY, FULFILLMENTS_EXPORT_MAPPING } from './config/queries';
903
- ```
904
-
905
- **How Versori Discovers Workflows:**
906
- Versori scans exported workflow objects (created with `schedule()`, `webhook()`) from your entry point and automatically registers them.
907
-
908
- ---
909
-
910
- ## 📄 src/workflows/fulfillments-extraction.ts
911
-
912
- ```typescript
913
- // ============================================================================
914
- // FULFILLMENTS EXTRACTION WORKFLOWS
915
- // ============================================================================
916
- // Purpose: Extract shipment tracking and delivery data from Fluent Commerce
917
- // and export as XML to SFTP for logistics coordination
918
- //
919
- // Workflows:
920
- // 1. Scheduled: 4-hourly incremental extraction with state tracking
921
- // 2. Ad-hoc: Manual trigger with custom date ranges
922
- // 3. Job Status: Query extraction job progress and results
923
- // ============================================================================
924
-
925
- import { schedule, webhook, http, fn } from '@versori/run';
926
- import type { Context } from '@versori/run';
927
- import {
928
- executeFulfillmentExtraction,
929
- queryJobStatus,
930
- generateJobId,
931
- } from '../services/extraction-orchestration';
932
-
933
- // ============================================================================
934
- // SECTION 1: TYPE DEFINITIONS
935
- // ============================================================================
936
-
937
- /**
938
- * Error categories for classification and triage
939
- */
940
- type ErrorCategory = 'CONFIG' | 'API' | 'SFTP' | 'NO_DATA';
941
-
942
- /**
943
- * Extraction time window with buffer tracking
944
- */
945
- interface TimeWindow {
946
- from: string; // Original start time (ISO 8601 UTC)
947
- to: string; // End time (ISO 8601 UTC)
948
- bufferedFrom: string; // Actual query start with overlap buffer applied
949
- }
950
-
951
- /**
952
- * Detailed extraction metrics for observability
953
- */
954
- interface ExtractionMetrics {
955
- totalPages: number; // GraphQL pages retrieved
956
- validRecords: number; // Successfully transformed records
957
- skippedRecords: number; // Records that failed mapping
958
- xmlSizeKb: number; // Final XML file size
959
- window: TimeWindow; // Time window used for extraction
960
- }
961
-
962
- /**
963
- * Result structure returned by extraction workflows
964
- */
965
- interface ExtractionResult {
966
- success: boolean;
967
- jobId: string;
968
- recordCount?: number;
969
- fileName?: string;
970
- message?: string;
971
- error?: string;
972
- errorCategory?: ErrorCategory;
973
- metrics?: ExtractionMetrics;
974
- }
975
-
976
- /**
977
- * Webhook payload for ad-hoc extraction
978
- */
979
- interface AdhocExtractionPayload {
980
- fromDate?: string; // ISO 8601 UTC timestamp - extraction start
981
- toDate?: string; // ISO 8601 UTC timestamp - extraction end
982
- updateState?: boolean; // Whether to update last run timestamp
983
- }
984
-
985
- /**
986
- * Webhook payload for job status query
987
- */
988
- interface JobStatusPayload {
989
- jobId: string; // Job ID to query
990
- }
991
-
992
- // ============================================================================
993
- // SECTION 2: WORKFLOW EXPORTS
994
- // ============================================================================
995
-
996
- /**
997
- * WORKFLOW 1: Scheduled Extraction
998
- *
999
- * Runs: Every 4 hours (0 */4 * * *)
1000
- * Purpose: Incremental extraction of updated fulfillments
1001
- * State: Updates lastRunTime after successful extraction
1002
- *
1003
- * Behavior:
1004
- * - Loads last run timestamp from KV storage
1005
- * - Applies 60-second overlap buffer for clock skew
1006
- * - Extracts records with updatedOn >= (lastRunTime - buffer)
1007
- * - Generates XML and uploads to SFTP with retry
1008
- * - Updates state with current timestamp
1009
- */
1010
- export const scheduledFulfillmentsExtraction = schedule(
1011
- 'fulfillments-extract-xml-4hourly',
1012
- '0 */4 * * *' // Every 4 hours at minute 0
1013
- ).then(
1014
- http('execute-scheduled-extraction', { connection: 'fluent_commerce' }, handleScheduledExtraction)
1015
- );
1016
-
1017
- /**
1018
- * WORKFLOW 2: Ad-hoc Extraction
1019
- *
1020
- * Trigger: Webhook POST to /webhooks/fulfillments-adhoc
1021
- * Purpose: On-demand extraction with custom date ranges
1022
- * State: Optional - only updates if updateState: true in payload
1023
- *
1024
- * Payload Examples:
1025
- *
1026
- * 1. Extract last 7 days (no state update):
1027
- * {
1028
- * "fromDate": "2025-01-22T00:00:00Z",
1029
- * "toDate": "2025-01-29T00:00:00Z"
1030
- * }
1031
- *
1032
- * 2. Full re-extraction with state reset:
1033
- * {
1034
- * "fromDate": "2024-01-01T00:00:00Z",
1035
- * "updateState": true
1036
- * }
1037
- *
1038
- * Note: fromDate and toDate MUST be ISO 8601 UTC timestamps
1039
- */
1040
- export const adhocFulfillmentsExtraction = webhook('fulfillments-adhoc', {
1041
- connection: 'fulfillments-adhoc', // Security via Versori connection
1042
- response: { mode: 'sync' }, // ✅ Sync mode: response sent when handler returns
1043
- }).then(http('execute-adhoc-extraction', { connection: 'fluent_commerce' }, handleAdhocExtraction));
1044
-
1045
- /**
1046
- * WORKFLOW 3: Job Status Query
1047
- *
1048
- * Trigger: Webhook GET/POST to /webhooks/fulfillments-job-status
1049
- * Purpose: Check extraction job progress and results
1050
- *
1051
- * Query Payload:
1052
- * {
1053
- * "jobId": "SCHEDULED_FULFILLMENTS_20250129_120000_abc123"
1054
- * }
1055
- *
1056
- * Response:
1057
- * {
1058
- * "success": true,
1059
- * "jobId": "...",
1060
- * "status": "completed",
1061
- * "stage": "upload_complete",
1062
- * "recordCount": 1250,
1063
- * "fileName": "fulfillments_20250129_120000.xml",
1064
- * "metrics": { ... }
1065
- * }
1066
- */
1067
- export const fulfillmentsJobStatus = webhook('fulfillments-job-status', {
1068
- connection: 'fulfillments-job-status', // Security via Versori connection
1069
- response: { mode: 'sync' },
1070
- }).then(fn('query-job-status', handleJobStatusQuery));
1071
-
1072
- // ============================================================================
1073
- // SECTION 3: WORKFLOW HANDLERS
1074
- // ============================================================================
1075
-
1076
- /**
1077
- * Handle scheduled extraction workflow
1078
- *
1079
- * Always updates state for next incremental run
1080
- */
1081
- async function handleScheduledExtraction(ctx: Context): Promise<ExtractionResult> {
1082
- const { log } = ctx;
1083
- const jobId = generateJobId('SCHEDULED', 'FULFILLMENTS');
1084
-
1085
- log.info('Scheduled extraction started', { jobId });
1086
-
1087
- try {
1088
- const result = await executeFulfillmentExtraction(ctx, {
1089
- jobId,
1090
- triggeredBy: 'schedule',
1091
- updateState: true, // Always update state for scheduled runs
1092
- });
1093
-
1094
- log.info('Scheduled extraction completed', {
1095
- jobId,
1096
- success: result.success,
1097
- recordCount: result.recordCount,
1098
- errorCategory: result.errorCategory,
1099
- });
1100
-
1101
- return result;
1102
- } catch (error: any) {
1103
- log.error('Scheduled extraction failed', {
1104
- jobId,
1105
- message: error instanceof Error ? error.message : String(error),
1106
- stack: error instanceof Error ? error.stack : undefined,
1107
- errorType: error instanceof Error ? error.constructor.name : 'Error',
1108
- });
1109
- throw error;
1110
- }
1111
- }
1112
-
1113
- /**
1114
- * Handle ad-hoc extraction workflow
1115
- *
1116
- * Allows custom date ranges and optional state updates
1117
- */
1118
- async function handleAdhocExtraction(ctx: Context): Promise<{ success: boolean; jobId: string; message: string; statusEndpoint: string; note: string }> {
1119
- const { data, log } = ctx;
1120
- const payload = data as AdhocExtractionPayload;
1121
- const jobId = generateJobId('ADHOC', 'FULFILLMENTS');
1122
-
1123
- log.info('🚀 [WEBHOOK] Adhoc fulfillments extraction triggered', {
1124
- jobId,
1125
- fromDate: payload.fromDate || 'lastRunTime',
1126
- toDate: payload.toDate || 'now',
1127
- updateState: payload.updateState || false,
1128
- });
1129
-
1130
- // ✅ Fire-and-forget: Start background processing WITHOUT await
1131
- // The promise continues execution after we return the response
1132
- executeFulfillmentExtraction(ctx, {
1133
- jobId,
1134
- triggeredBy: 'webhook',
1135
- fromDate: payload.fromDate,
1136
- toDate: payload.toDate,
1137
- updateState: payload.updateState === true,
1138
- })
1139
- .then((result) => {
1140
- log.info('✅ [BACKGROUND] Fulfillments extraction completed successfully', {
1141
- jobId,
1142
- recordCount: result.recordCount,
1143
- fileName: result.fileName,
1144
- errorCategory: result.errorCategory,
1145
- });
1146
- })
1147
- .catch((error: unknown) => {
1148
- const errorMessage = error instanceof Error ? error.message : String(error);
1149
- log.error('❌ [BACKGROUND] Fulfillments extraction failed', {
1150
- jobId,
1151
- error: errorMessage,
1152
- stack: error instanceof Error ? error.stack : undefined,
1153
- errorType: error instanceof Error ? error.constructor.name : typeof error,
1154
- });
1155
- });
1156
-
1157
- // Return immediately with jobId (response sent with this return value)
1158
- return {
1159
- success: true,
1160
- jobId,
1161
- message: 'Fulfillments extraction started in background',
1162
- statusEndpoint: `https://{workspace}.versori.run/fulfillments-job-status`,
1163
- note: 'Poll the status endpoint with jobId to check progress',
1164
- };
1165
- }
1166
-
1167
- /**
1168
- * Handle job status query workflow
1169
- *
1170
- * Returns current job state from KV storage
1171
- */
1172
- async function handleJobStatusQuery(ctx: Context): Promise<any> {
1173
- const { data, log, openKv } = ctx;
1174
- const payload = data as JobStatusPayload;
1175
-
1176
- if (!payload.jobId) {
1177
- return {
1178
- success: false,
1179
- error: 'Job ID required',
1180
- message: 'Provide jobId in request payload',
1181
- };
1182
- }
1183
-
1184
- log.info('Job status query', { jobId: payload.jobId });
1185
-
1186
- const status = await queryJobStatus(openKv(':project:'), payload.jobId, log);
1187
-
1188
- if (!status) {
1189
- return {
1190
- success: false,
1191
- error: 'Job not found',
1192
- jobId: payload.jobId,
1193
- message: 'Job may have been deleted or never existed',
1194
- };
1195
- }
1196
-
1197
- return {
1198
- success: true,
1199
- jobId: payload.jobId,
1200
- ...status,
1201
- };
1202
- }
1203
- ```
1204
-
1205
- ---
1206
-
1207
- ## 📄 src/services/extraction-orchestration.ts
1208
-
1209
- ```typescript
1210
- import { Buffer } from 'node:buffer';
1211
- import {
1212
- createClient,
1213
- ExtractionOrchestrator,
1214
- JobTracker,
1215
- UniversalMapper,
1216
- XMLBuilder,
1217
- SftpDataSource,
1218
- } from '@fluentcommerce/fc-connect-sdk';
1219
-
1220
- import mappingConfig from '../../config/fulfillments.export.xml.json' with { type: 'json' };
1221
- import { FULFILLMENTS_QUERY } from '../config/queries';
1222
-
1223
- type ErrorCategory = 'CONFIG' | 'API' | 'SFTP' | 'NO_DATA';
1224
-
1225
- interface TimeWindow {
1226
- from: string;
1227
- to: string;
1228
- bufferedFrom: string;
1229
- }
1230
-
1231
- interface ExtractionMetrics {
1232
- totalPages: number;
1233
- validRecords: number;
1234
- skippedRecords: number;
1235
- xmlSizeKb: number;
1236
- window: TimeWindow;
1237
- }
1238
-
1239
- export interface FulfillmentExtractionParams {
1240
- jobId: string;
1241
- triggeredBy: 'schedule' | 'webhook';
1242
- fromDate?: string;
1243
- toDate?: string;
1244
- updateState: boolean;
1245
- fulfillmentStatuses?: string[];
1246
- }
1247
-
1248
- export interface FulfillmentExtractionResult {
1249
- success: boolean;
1250
- jobId: string;
1251
- recordCount: number;
1252
- fileName?: string;
1253
- sftpPath?: string;
1254
- message?: string;
1255
- error?: string;
1256
- errorCategory?: ErrorCategory;
1257
- metrics?: ExtractionMetrics;
1258
- }
1259
-
1260
- interface FulfillmentLineItem {
1261
- product_ref: string;
1262
- requested_quantity: number | string;
1263
- filled_quantity: number | string;
1264
- }
1265
-
1266
- const STATE_KEY = 'lastFulfillmentSync';
1267
- const DEFAULT_FALLBACK = '2024-01-01T00:00:00Z';
1268
- const STATUS_DELIMITER = ',';
1269
-
1270
- function normalizeStatuses(input?: string[] | string | null): string[] | undefined {
1271
- if (!input) {
1272
- return undefined;
1273
- }
1274
-
1275
- const raw = Array.isArray(input) ? input : input.split(STATUS_DELIMITER);
1276
- const cleaned = raw.map(status => status.trim()).filter(Boolean);
1277
- return cleaned.length > 0 ? cleaned : undefined;
1278
- }
1279
-
1280
- function joinSftpPath(
1281
- requireAbsolutePath: boolean,
1282
- ...segments: Array<string | undefined>
1283
- ): string {
1284
- const sanitized = segments
1285
- .filter(Boolean)
1286
- .map(segment => String(segment).replace(/^\/+|\/+$/g, ''))
1287
- .join('/');
1288
-
1289
- if (!sanitized) {
1290
- return requireAbsolutePath ? '/' : '';
1291
- }
1292
-
1293
- return requireAbsolutePath && !sanitized.startsWith('/') ? `/${sanitized}` : sanitized;
1294
- }
1295
-
1296
- export async function queryJobStatus(kv: any, jobId: string, log: any): Promise<any | undefined> {
1297
- try {
1298
- const tracker = new JobTracker(kv, log);
1299
- return await tracker.getJob(jobId);
1300
- } catch (error: any) {
1301
- log.error('Failed to get job status', {
1302
- jobId,
1303
- message: error instanceof Error ? error.message : String(error),
1304
- stack: error instanceof Error ? error.stack : undefined,
1305
- errorType: error instanceof Error ? error.constructor.name : 'Error',
1306
- });
1307
- return undefined;
1308
- }
1309
- }
1310
-
1311
- export async function executeFulfillmentExtraction(
1312
- ctx: any,
1313
- params: FulfillmentExtractionParams
1314
- ): Promise<FulfillmentExtractionResult> {
1315
- const { log, openKv, activation } = ctx;
1316
- const { jobId, triggeredBy, fromDate, toDate, updateState } = params;
1317
-
1318
- const kv = openKv(':project:');
1319
- const tracker = new JobTracker(kv, log);
1320
-
1321
- // Track execution duration
1322
- const executionStartTime = Date.now();
1323
-
1324
- const overlapBufferSeconds = parseInt(activation.getVariable('overlapBufferSeconds') || '60', 10);
1325
- const fallbackStartDate = activation.getVariable('fallbackStartDate') || DEFAULT_FALLBACK;
1326
- const isManualOverride = Boolean(fromDate);
1327
- const shouldUpdateState = updateState === true;
1328
-
1329
- try {
1330
- log.info('🚀 [STEP 1/8] Initializing job tracking', { jobId, triggeredBy });
1331
- await tracker.createJob(jobId, {
1332
- triggeredBy,
1333
- hasDateOverride: isManualOverride,
1334
- updateStateAfterRun: shouldUpdateState,
1335
- fromDate,
1336
- toDate,
1337
- });
1338
-
1339
- log.info('📡 [STEP 2/8] Initializing Fluent Commerce client', { jobId });
1340
- const client = await createClient(ctx, { validateConnection: true });
1341
- if (!client) {
1342
- throw new Error('Failed to create Fluent Commerce client');
1343
- }
1344
-
1345
- log.info('📅 [STEP 3/8] Determining date range for extraction', { jobId });
1346
-
1347
- let rawState = fallbackStartDate;
1348
- if (!isManualOverride) {
1349
- try {
1350
- const stored = await kv.get(STATE_KEY);
1351
- if (typeof stored === 'string') {
1352
- rawState = stored;
1353
- } else if (stored?.timestamp) {
1354
- rawState = stored.timestamp;
1355
- }
1356
- } catch {
1357
- rawState = fallbackStartDate;
1358
- }
1359
- }
1360
-
1361
- const overlapMs = overlapBufferSeconds * 1000;
1362
- const queryFrom = isManualOverride
1363
- ? fromDate!
1364
- : new Date(Math.max(0, new Date(rawState).getTime() - overlapMs)).toISOString();
1365
- const windowStart = isManualOverride ? (fromDate ?? queryFrom) : rawState;
1366
- const windowEnd = toDate || new Date().toISOString();
1367
-
1368
- const statusesInput =
1369
- params.fulfillmentStatuses ?? activation.getVariable('fulfillmentStatuses');
1370
- const fulfillmentStatuses = normalizeStatuses(statusesInput);
1371
-
1372
- await tracker.updateJob(jobId, {
1373
- stage: 'extraction',
1374
- message: 'Extracting fulfillments with auto-pagination',
1375
- status: 'processing',
1376
- statuses: fulfillmentStatuses,
1377
- });
1378
-
1379
- const pageSize = parseInt(activation.getVariable('pageSize') || '200', 10);
1380
- const maxRecords = parseInt(activation.getVariable('maxRecords') || '50000', 10);
1381
-
1382
- log.info('📊 [STEP 4/8] Extracting fulfillments via GraphQL', {
1383
- jobId,
1384
- pageSize,
1385
- maxRecords,
1386
- queryFrom,
1387
- windowEnd,
1388
- statuses: fulfillmentStatuses,
1389
- });
1390
-
1391
- const orchestrator = new ExtractionOrchestrator(client, log);
1392
-
1393
- // Extract context for progress logging
1394
- const dateRangeInfo = {
1395
- start: queryFrom || 'N/A',
1396
- end: windowEnd || 'N/A',
1397
- statuses: fulfillmentStatuses?.join(', ') || 'all'
1398
- };
1399
-
1400
- // Start logging with context
1401
- log.info(`📥 [ExtractionOrchestrator] Starting extraction`, {
1402
- query: 'fulfillments',
1403
- pageSize,
1404
- maxRecords,
1405
- dateRange: `${dateRangeInfo.start} to ${dateRangeInfo.end}`,
1406
- statuses: dateRangeInfo.statuses,
1407
- jobId
1408
- });
1409
-
1410
- const extractionResult = await orchestrator.extract({
1411
- query: FULFILLMENTS_QUERY,
1412
- resultPath: 'fulfillments.edges.node',
1413
- variables: {
1414
- statuses: fulfillmentStatuses,
1415
- updatedFrom: queryFrom,
1416
- updatedTo: windowEnd,
1417
- },
1418
- pageSize,
1419
- maxRecords,
1420
- validateItem: (item: any) => Boolean(item?.ref && item?.order?.ref),
1421
- });
1422
-
1423
- const rawRecords = extractionResult.data || [];
1424
- const extractionErrors = extractionResult.errors || [];
1425
- const totalPages = extractionResult.stats.totalPages ?? 0;
1426
-
1427
- log.info('✅ [STEP 4/8] Extraction complete', {
1428
- jobId,
1429
- totalPages,
1430
- totalRecords: extractionResult.stats.totalRecords,
1431
- validRecords: extractionResult.stats.validRecords ?? rawRecords.length,
1432
- truncated: extractionResult.stats.truncated ?? false,
1433
- errorCount: extractionErrors.length,
1434
- });
1435
-
1436
- // Completion logging with summary
1437
- log.info(`✅ [ExtractionOrchestrator] Extraction completed`, {
1438
- totalRecords: extractionResult.stats.totalRecords,
1439
- totalPages,
1440
- validRecords: extractionResult.stats.validRecords ?? rawRecords.length,
1441
- failedValidations: extractionResult.stats.failedValidations,
1442
- truncated: extractionResult.stats.truncated,
1443
- truncationReason: extractionResult.stats.truncationReason,
1444
- dateRange: `${dateRangeInfo.start} to ${dateRangeInfo.end}`,
1445
- jobId
1446
- });
1447
-
1448
- if (extractionErrors.length > 0) {
1449
- log.warn('[STEP 4/8] Non-fatal extraction errors detected', {
1450
- jobId,
1451
- sampleErrors: extractionErrors.slice(0, 3),
1452
- });
1453
- }
1454
-
1455
- if (rawRecords.length === 0) {
1456
- log.info('No fulfillments to process', { jobId });
1457
-
1458
- if (shouldUpdateState) {
1459
- await kv.set(STATE_KEY, {
1460
- timestamp: windowEnd,
1461
- updatedAt: new Date().toISOString(),
1462
- recordCount: 0,
1463
- triggeredBy,
1464
- });
1465
- }
1466
-
1467
- await tracker.markCompleted(jobId, {
1468
- recordCount: 0,
1469
- message: 'No fulfillments to extract',
1470
- stateUpdated: shouldUpdateState,
1471
- window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1472
- });
1473
-
1474
- return {
1475
- success: true,
1476
- jobId,
1477
- recordCount: 0,
1478
- message: 'No fulfillments to extract',
1479
- metrics: {
1480
- totalPages,
1481
- validRecords: 0,
1482
- skippedRecords: 0,
1483
- xmlSizeKb: 0,
1484
- window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1485
- },
1486
- };
1487
- }
1488
-
1489
- log.info('🔄 [STEP 5/8] Transforming data with UniversalMapper', {
1490
- jobId,
1491
- recordCount: rawRecords.length,
1492
- });
1493
-
1494
- await tracker.updateJob(jobId, {
1495
- stage: 'transformation',
1496
- message: `Transforming ${rawRecords.length} fulfillments`,
1497
- status: 'processing',
1498
- });
1499
-
1500
- const mapper = new UniversalMapper(mappingConfig);
1501
- const mappingResult = await mapper.map(rawRecords);
1502
- const mappingErrors = mappingResult.errors || [];
1503
-
1504
- if (!mappingResult.success) {
1505
- log.error('[STEP 5/8] Transformation failed', {
1506
- jobId,
1507
- errorCount: mappingErrors.length,
1508
- sampleErrors: mappingErrors.slice(0, 3),
1509
- });
1510
-
1511
- await tracker.markFailed(jobId, 'UniversalMapper returned unsuccessful result', {
1512
- failedCount: mappingErrors.length,
1513
- errors: mappingErrors,
1514
- });
1515
-
1516
- return {
1517
- success: false,
1518
- jobId,
1519
- recordCount: 0,
1520
- error: `Transformation failed: ${mappingErrors[0] || 'Unknown error'}`,
1521
- errorCategory: 'CONFIG',
1522
- };
1523
- }
1524
-
1525
- const headerRecords: any[] = Array.isArray(mappingResult.data) ? mappingResult.data : [];
1526
- const mappingErrors = mappingResult.errors || [];
1527
-
1528
- if (mappingErrors.length > 0) {
1529
- log.warn('[STEP 5/8] Some records failed transformation', {
1530
- jobId,
1531
- errorCount: mappingErrors.length,
1532
- sampleErrors: mappingErrors.slice(0, 3),
1533
- });
1534
- }
1535
-
1536
- if (mappingResult.skippedFields && mappingResult.skippedFields.length > 0) {
1537
- log.info('ℹ️ [MAPPING] Optional fields skipped (undefined values)', {
1538
- jobId,
1539
- skippedFields: mappingResult.skippedFields,
1540
- note: 'These fields were not present in source data. Add defaultValue to mapping config if they should always appear.',
1541
- });
1542
- }
1543
-
1544
- const transformedRecords = headerRecords.map((record, index) => {
1545
- const raw = rawRecords[index] ?? {};
1546
- const lineItems: FulfillmentLineItem[] = ((raw.items?.edges ?? []) as any[])
1547
- .map(edge => edge?.node)
1548
- .filter(Boolean)
1549
- .map((item: any) => ({
1550
- product_ref: item.productRef ?? '',
1551
- requested_quantity: item.requestedQuantity ?? '',
1552
- filled_quantity: item.filledQuantity ?? '',
1553
- }));
1554
-
1555
- return {
1556
- ...record,
1557
- line_items: lineItems,
1558
- };
1559
- });
1560
-
1561
- if (transformedRecords.length === 0) {
1562
- await tracker.markFailed(jobId, 'All fulfillments failed mapping', {
1563
- failedCount: mappingErrors.length,
1564
- errors: mappingErrors,
1565
- });
1566
-
1567
- return {
1568
- success: false,
1569
- jobId,
1570
- recordCount: 0,
1571
- error: 'All records failed mapping',
1572
- errorCategory: 'CONFIG',
1573
- metrics: {
1574
- totalPages,
1575
- validRecords: 0,
1576
- skippedRecords: rawRecords.length,
1577
- xmlSizeKb: 0,
1578
- window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1579
- },
1580
- };
1581
- }
1582
-
1583
- if (mappingErrors.length > 0) {
1584
- log.warn('[STEP 5/8] Some fulfillments failed transformation', {
1585
- jobId,
1586
- errorCount: mappingErrors.length,
1587
- sampleErrors: mappingErrors.slice(0, 3),
1588
- });
1589
- }
1590
-
1591
- const totalLineItems = transformedRecords.reduce(
1592
- (sum, record) => sum + record.line_items.length,
1593
- 0
1594
- );
1595
-
1596
- log.info('📝 [STEP 6/8] Generating XML document', {
1597
- jobId,
1598
- fulfillmentCount: transformedRecords.length,
1599
- lineItemCount: totalLineItems,
1600
- });
1601
-
1602
- await tracker.updateJob(jobId, {
1603
- stage: 'xml_generation',
1604
- message: `Generating XML for ${transformedRecords.length} fulfillments`,
1605
- status: 'processing',
1606
- });
1607
-
1608
- const xmlBuilder = new XMLBuilder({
1609
- prettyPrint: true,
1610
- indent: ' ',
1611
- xmlDeclaration: true,
1612
- encoding: 'UTF-8',
1613
- attributePrefix: '@',
1614
- textKey: '#text',
1615
- });
1616
-
1617
- const xmlData = {
1618
- Fulfillments: {
1619
- Fulfillment: transformedRecords.map(record => {
1620
- const lineItemNodes =
1621
- record.line_items.length > 0
1622
- ? {
1623
- LineItem: record.line_items.map(item => ({
1624
- product_ref: item.product_ref,
1625
- requested_quantity: String(item.requested_quantity ?? ''),
1626
- filled_quantity: String(item.filled_quantity ?? ''),
1627
- })),
1628
- }
1629
- : undefined;
1630
-
1631
- return {
1632
- fulfillment_ref: record.fulfillment_ref,
1633
- order_ref: record.order_ref,
1634
- status: record.status,
1635
- delivery_type: record.delivery_type ?? '',
1636
- from_location_ref: record.from_location_ref ?? '',
1637
- from_location_name: record.from_location_name ?? '',
1638
- created_on: record.created_on,
1639
- updated_on: record.updated_on,
1640
- ...(lineItemNodes ? { LineItems: lineItemNodes } : {}),
1641
- };
1642
- }),
1643
- },
1644
- };
1645
-
1646
- const xmlString = xmlBuilder.build(xmlData, 'Fulfillments');
1647
- const xmlBuffer = Buffer.from(xmlString, 'utf8');
1648
- const xmlSizeKb = Math.round(xmlBuffer.length / 1024);
1649
-
1650
- const fileNamePrefix = activation.getVariable('fileNamePrefix') || 'fulfillments';
1651
- const timestampSuffix = new Date().toISOString().replace(/[:.]/g, '-');
1652
- const fileName = `${fileNamePrefix}-${timestampSuffix}.xml`;
1653
-
1654
- log.info('📤 [STEP 7/8] Preparing SFTP upload', { jobId, fileName });
1655
-
1656
- await tracker.updateJob(jobId, {
1657
- stage: 'sftp_upload',
1658
- message: `Uploading ${fileName} to SFTP`,
1659
- status: 'processing',
1660
- });
1661
-
1662
- const sftpHost = activation.getVariable('sftpHost');
1663
- const sftpPort = parseInt(activation.getVariable('sftpPort') || '22', 10);
1664
- const sftpRemotePath = activation.getVariable('sftpRemotePath') || '/incoming/fulfillments/';
1665
- const sftpPrivateKey = activation.getVariable('sftpPrivateKey');
1666
- const requireAbsolutePaths = activation.getVariable('requireAbsolutePaths') === 'true';
1667
-
1668
- if (!sftpHost) {
1669
- throw new Error('SFTP configuration incomplete: sftpHost activation variable missing');
1670
- }
1671
-
1672
- const allConnections = activation.connections || [];
1673
- const sftpConnection = allConnections.find((conn: any) => conn.name === 'sftp_export_server');
1674
- if (!sftpConnection) {
1675
- throw new Error('SFTP connection "sftp_export_server" not found');
1676
- }
1677
-
1678
- const credential = sftpConnection.credentials?.[0]?.credential;
1679
- if (!credential?.data?.basicAuth) {
1680
- throw new Error('SFTP connection not configured with Basic Authentication');
1681
- }
1682
-
1683
- const { username, password } = credential.data.basicAuth;
1684
-
1685
- const sftp = new SftpDataSource(
1686
- {
1687
- type: 'SFTP_XML',
1688
- connectionId: 'sftp_export_server',
1689
- name: 'Fulfillments XML Export',
1690
- settings: {
1691
- host: sftpHost,
1692
- port: sftpPort,
1693
- username,
1694
- password,
1695
- privateKey: sftpPrivateKey,
1696
- remotePath: sftpRemotePath,
1697
- filePattern: '*.xml',
1698
- requireAbsolutePaths,
1699
- },
1700
- },
1701
- log
1702
- );
1703
-
1704
- const fullPath = joinSftpPath(requireAbsolutePaths, sftpRemotePath, fileName);
1705
-
1706
- try {
1707
- await sftp.uploadFile(fullPath, xmlBuffer, {
1708
- createDirectories: true,
1709
- overwrite: true,
1710
- });
1711
-
1712
- if (mappingErrors.length > 0) {
1713
- const reportPayload = {
1714
- fileName,
1715
- processedAt: new Date().toISOString(),
1716
- failedRecords: mappingErrors.length,
1717
- sampleErrors: mappingErrors.slice(0, 10),
1718
- };
1719
-
1720
- const reportPath = joinSftpPath(
1721
- requireAbsolutePaths,
1722
- sftpRemotePath,
1723
- `${fileName.replace(/\.xml$/i, '')}-errors.json`
1724
- );
1725
-
1726
- await sftp.uploadFile(
1727
- reportPath,
1728
- Buffer.from(JSON.stringify(reportPayload, null, 2), 'utf8'),
1729
- {
1730
- createDirectories: true,
1731
- overwrite: true,
1732
- }
1733
- );
1734
-
1735
- log.warn('Uploaded transformation error report', { jobId, reportPath });
1736
- }
1737
- } finally {
1738
- await sftp.dispose();
1739
- log.info('SFTP connection disposed', { jobId });
1740
- }
1741
-
1742
- log.info('💾 [STEP 8/8] Updating state and completing job', { jobId });
1743
-
1744
- const newTimestamp = (() => {
1745
- const maxUpdated = rawRecords.reduce((max, record) => {
1746
- const current = new Date(record.updatedOn || windowEnd).getTime();
1747
- return current > max ? current : max;
1748
- }, new Date(windowStart).getTime());
1749
- return new Date(maxUpdated).toISOString();
1750
- })();
1751
-
1752
- if (shouldUpdateState) {
1753
- await kv.set(STATE_KEY, {
1754
- timestamp: newTimestamp,
1755
- updatedAt: new Date().toISOString(),
1756
- recordCount: transformedRecords.length,
1757
- lineItemCount: totalLineItems,
1758
- fileName,
1759
- sftpPath: fullPath,
1760
- statuses: fulfillmentStatuses ?? [],
1761
- });
1762
- }
1763
-
1764
- const executionDurationMs = Date.now() - executionStartTime;
1765
-
1766
- await tracker.markCompleted(jobId, {
1767
- recordCount: transformedRecords.length,
1768
- lineItemCount: totalLineItems,
1769
- fileName,
1770
- remotePath: fullPath,
1771
- errorCount: mappingErrors.length,
1772
- errors: mappingErrors,
1773
- stateUpdated: shouldUpdateState,
1774
- window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1775
- durationMs: executionDurationMs,
1776
- });
1777
-
1778
- log.info('✅ Extraction completed successfully', {
1779
- jobId,
1780
- recordCount: transformedRecords.length,
1781
- durationMs: executionDurationMs,
1782
- durationSeconds: (executionDurationMs / 1000).toFixed(2),
1783
- });
1784
-
1785
- return {
1786
- success: true,
1787
- jobId,
1788
- recordCount: transformedRecords.length,
1789
- fileName,
1790
- sftpPath: fullPath,
1791
- message: `Uploaded ${transformedRecords.length} fulfillments`,
1792
- metrics: {
1793
- totalPages,
1794
- validRecords: transformedRecords.length,
1795
- skippedRecords: mappingErrors.length,
1796
- xmlSizeKb,
1797
- window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1798
- },
1799
- };
1800
- } catch (error: any) {
1801
- const errorMessage = error instanceof Error ? error.message : String(error);
1802
-
1803
- log.error('❌ Fulfillment extraction failed', {
1804
- jobId,
1805
- message: errorMessage,
1806
- stack: error instanceof Error ? error.stack : undefined,
1807
- errorType: error instanceof Error ? error.constructor.name : 'Error',
1808
- });
1809
-
1810
- // Determine error category and recommendation
1811
- let errorCategory: ErrorCategory = 'API';
1812
- let recommendation = '';
1813
-
1814
- if (errorMessage.includes('SFTP') || errorMessage.includes('connection')) {
1815
- errorCategory = 'SFTP';
1816
- recommendation = 'Check SFTP credentials and network connectivity. Verify host, port, and authentication settings in activation variables.';
1817
- } else if (errorMessage.includes('mapping') || errorMessage.includes('transformation')) {
1818
- errorCategory = 'CONFIG';
1819
- recommendation = 'Review mapping configuration in config/fulfillments.export.xml.json. Verify all source paths match GraphQL response structure.';
1820
- } else if (errorMessage.includes('GraphQL') || errorMessage.includes('query')) {
1821
- errorCategory = 'API';
1822
- recommendation = 'Verify Fluent Commerce API credentials and GraphQL query syntax. Check if the query matches the current schema.';
1823
- } else if (errorMessage.includes('No records') || errorMessage.includes('empty')) {
1824
- errorCategory = 'NO_DATA';
1825
- recommendation = 'No fulfillments found in the specified date range. This may be expected if there are no recent updates.';
1826
- }
1827
-
1828
- await tracker.markFailed(jobId, {
1829
- error: errorMessage,
1830
- errorCategory,
1831
- recommendation,
1832
- triggeredBy,
1833
- });
1834
-
1835
- return {
1836
- success: false,
1837
- jobId,
1838
- recordCount: 0,
1839
- error: errorMessage,
1840
- errorCategory,
1841
- details: {
1842
- recommendation,
1843
- errorType: error instanceof Error ? error.constructor.name : 'Error',
1844
- },
1845
- };
1846
- }
1847
- }
1848
- ```
1849
-
1850
- ---
1851
-
1852
- ## 📄 src/config/queries.ts
1853
-
1854
- ```typescript
1855
- // ============================================================================
1856
- // GRAPHQL QUERIES AND MAPPING CONFIGURATION
1857
- // ============================================================================
1858
-
1859
- import mappingConfig from '../../config/fulfillments.export.xml.json' with { type: 'json' };
1860
-
1861
- /**
1862
- * GraphQL query for fulfillments extraction
1863
- *
1864
- * Supports:
1865
- * - Pagination (first, after)
1866
- * - Date range filtering (updatedOn) - UTC timestamps required
1867
- * - Status filtering (statuses)
1868
- */
1869
- export const FULFILLMENTS_QUERY = `
1870
- query GetFulfillments(
1871
- $statuses: [String!]
1872
- $updatedFrom: DateTime
1873
- $updatedTo: DateTime
1874
- $first: Int!
1875
- $after: String
1876
- ) {
1877
- fulfillments(
1878
- status: $statuses
1879
- updatedOn: { from: $updatedFrom, to: $updatedTo }
1880
- first: $first
1881
- after: $after
1882
- ) {
1883
- edges {
1884
- node {
1885
- id
1886
- ref
1887
- status
1888
- deliveryType
1889
- order {
1890
- ref
1891
- }
1892
- fromLocation {
1893
- ref
1894
- name
1895
- }
1896
- items {
1897
- edges {
1898
- node {
1899
- productRef
1900
- requestedQuantity
1901
- filledQuantity
1902
- }
1903
- }
1904
- }
1905
- createdOn
1906
- updatedOn
1907
- }
1908
- cursor
1909
- }
1910
- pageInfo {
1911
- hasNextPage
1912
- # Note: Fluent doesn't return endCursor - cursors are in edges[].cursor
1913
- }
1914
- }
1915
- }
1916
- `;
1917
-
1918
- /**
1919
- * Field mapping configuration loaded from JSON file
1920
- *
1921
- * Location: config/fulfillments.export.xml.json
1922
- */
1923
- export const FULFILLMENTS_EXPORT_MAPPING = mappingConfig;
1924
- ```
1925
-
1926
- ---
1927
-
1928
- ## Testing
1929
-
1930
- ### Test Scheduled Extraction
1931
-
1932
- The scheduled workflow runs automatically every 4 hours.
1933
-
1934
- **Check logs:**
1935
-
1936
- ```
1937
- [STEP 1/10] Loading and validating configuration
1938
- [STEP 2/10] Initializing job tracker
1939
- [STEP 3/10] Calculating extraction time window
1940
- [STEP 4/10] Initializing SDK services
1941
- [STEP 5/10] Extracting fulfillments from Fluent
1942
- [STEP 6/10] Transforming records with UniversalMapper
1943
- [STEP 7/10] Generating XML file
1944
- [STEP 8/10] Uploading XML to SFTP
1945
- [STEP 9/10] Updating extraction state
1946
- [STEP 10/10] Finalizing job
1947
- ```
1948
-
1949
- ### Test Ad-hoc Extraction
1950
-
1951
- ```bash
1952
- # Incremental (uses last sync timestamp)
1953
- curl -X POST https://api.versori.com/webhooks/fulfillments-adhoc \
1954
- -H "Content-Type: application/json" \
1955
- -d '{}'
1956
-
1957
- # Date range override
1958
- curl -X POST https://api.versori.com/webhooks/fulfillments-adhoc \
1959
- -H "Content-Type: application/json" \
1960
- -d '{
1961
- "fromDate": "2025-01-01T00:00:00Z",
1962
- "toDate": "2025-01-31T23:59:59Z",
1963
- "updateState": false
1964
- }'
1965
- ```
1966
-
1967
- ### Test Job Status Query
1968
-
1969
- ```bash
1970
- curl -X POST https://api.versori.com/webhooks/fulfillments-job-status \
1971
- -H "Content-Type: application/json" \
1972
- -d '{
1973
- "jobId": "ADHOC_FULFILLMENTS_20251027_183045_abc123"
1974
- }'
1975
- ```
1976
-
1977
- **Response:**
1978
-
1979
- ```json
1980
- {
1981
- "success": true,
1982
- "jobId": "ADHOC_FULFILLMENTS_20251027_183045_abc123",
1983
- "status": "processing",
1984
- "stage": "transformation",
1985
- "message": "Transforming 150 records",
1986
- "createdAt": "2025-10-27T18:30:45.000Z",
1987
- "startedAt": "2025-10-27T18:30:46.000Z"
1988
- }
1989
- ```
1990
-
1991
- ---
1992
-
1993
- ## Next Steps
1994
-
1995
- 1. **Review Configuration:** Verify all activation variables match your environment
1996
- 2. **Test with Sample Data:** Run ad-hoc extraction with small date range
1997
- 3. **Validate XML Output:** Check SFTP server for correctly formatted files
1998
- 4. **Enable Schedule:** Activate 4-hourly schedule after successful test
1999
- 5. **Monitor Jobs:** Use job status webhook to track extraction progress
2000
- 6. **Adjust Filters:** Customize status filters and date ranges as needed
2001
- 7. **Scale:** Increase page size and max records based on data volume
2002
-
2003
- ---
2004
-
2005
- ## Testing Checklist
2006
-
2007
- **Before production deployment:**
2008
-
2009
- ### 1. Schema Validation
2010
-
2011
- - [ ] Run `npx fc-connect introspect-schema --url <your-graphql-url>`
2012
- - [ ] Run `npx fc-connect validate-schema --mapping ./config/fulfillments.export.xml.json --schema ./fluent-schema.json`
2013
- - [ ] Run `npx fc-connect analyze-coverage --mapping ./config/fulfillments.export.xml.json --schema ./fluent-schema.json`
2014
- - [ ] Verify all `source` paths in mapping exist in GraphQL schema
2015
- - [ ] Verify query structure matches schema (fields, types, filters)
2016
-
2017
- ### 2. Extraction Testing
2018
-
2019
- - [ ] Test with small dataset first (maxRecords=10)
2020
- - [ ] Verify ExtractionOrchestrator pagination works correctly
2021
- - [ ] Test with multiple pages of data (verify cursor handling)
2022
- - [ ] Verify date range filtering (updatedOn filter)
2023
- - [ ] Test empty result handling (no records in date range)
2024
- - [ ] Verify extraction stops at maxRecords limit
2025
-
2026
- ### 3. Mapping Testing
2027
-
2028
- - [ ] Verify required fields are populated
2029
- - [ ] Verify SDK resolvers work correctly (sdk.trim, sdk.parseInt, sdk.formatDate, etc.)
2030
- - [ ] Test custom resolvers with edge cases (if any)
2031
- - [ ] Verify nested field extraction
2032
- - [ ] Test with null/missing fields
2033
- - [ ] Verify mapping error collection works
2034
-
2035
- ### 4. XML Generation Testing
2036
-
2037
- - [ ] Verify XML structure matches expected format
2038
- - [ ] Test XML validation against XSD schema (if applicable)
2039
- - [ ] Verify special character escaping in XML
2040
- - [ ] Test with large datasets (>1000 records)
2041
- - [ ] Verify UTF-8 encoding
2042
- - [ ] Test XML namespace handling (if applicable)
2043
-
2044
- ### 5. SFTP Upload Testing
2045
-
2046
- - [ ] Test SFTP connection and authentication
2047
- - [ ] Verify file upload to correct path
2048
- - [ ] Test file naming convention (timestamp format)
2049
- - [ ] Verify file permissions on SFTP server
2050
- - [ ] Test upload retry logic (simulate network failure)
2051
- - [ ] Verify SFTP connection disposal (no connection leaks)
2052
-
2053
- ### 6. State Management Testing
2054
-
2055
- - [ ] Verify overlap buffer prevents missed records (60-second default)
2056
- - [ ] Test state recovery after extraction failure
2057
- - [ ] Verify timestamp saved WITHOUT buffer (MAX(updatedOn))
2058
- - [ ] Test first run with no previous state (uses fallbackStartDate)
2059
- - [ ] Verify state update only happens on successful upload
2060
- - [ ] Test manual date override (doesn't update state)
2061
-
2062
- ### 7. Job Tracking Testing
2063
-
2064
- - [ ] Test job creation with JobTracker
2065
- - [ ] Verify job status updates at each stage
2066
- - [ ] Test job completion with metadata
2067
- - [ ] Test job failure handling
2068
- - [ ] Query job status via webhook endpoint
2069
- - [ ] Verify job status persists in KV store
2070
-
2071
- ### 8. Error Handling Testing
2072
-
2073
- - [ ] Test with invalid GraphQL query
2074
- - [ ] Test with mapping errors (invalid field paths)
2075
- - [ ] Test with SFTP connection failures
2076
- - [ ] Test with authentication failures
2077
- - [ ] Test with network timeouts
2078
- - [ ] Verify error logging includes context (jobId, stage, error details)
2079
- - [ ] Test error threshold logic (if applicable)
2080
-
2081
- ### 9. Staging Environment Testing
2082
-
2083
- - [ ] Run full extraction in staging environment
2084
- - [ ] Verify XML file format with downstream system
2085
- - [ ] Monitor extraction duration and resource usage
2086
- - [ ] Test with production-like data volumes
2087
- - [ ] Verify no performance degradation over time
2088
-
2089
- ### 10. Integration Testing
2090
-
2091
- - [ ] Test scheduled workflow (cron trigger)
2092
- - [ ] Test ad hoc webhook trigger
2093
- - [ ] Test job status query webhook
2094
- - [ ] Verify activation variables are read correctly
2095
- - [ ] Test with different extraction modes (incremental, date range)
2096
- - [ ] End-to-end test: trigger → extract → transform → upload → verify file
2097
-
2098
- ---
2099
- ## Monitoring & Alerting
2100
-
2101
- ### Success Response Example
2102
-
2103
- ```json
2104
- {
2105
- "success": true,
2106
- "jobId": "SCHEDULED_FUL_20251102_140000_abc123",
2107
- "recordsExtracted": 1523,
2108
- "fileName": "fulfillments-2025-11-02T14-00-00-000Z.xml",
2109
- "sftpPath": "/outbound/fulfillments/fulfillments-2025-11-02T14-00-00-000Z.xml",
2110
- "metrics": {
2111
- "extractionDurationMs": 12543,
2112
- "totalPages": 8,
2113
- "pageSize": 200,
2114
- "mappingErrors": 0,
2115
- "fileSizeBytes": 524288,
2116
- "uploadDurationMs": 1234
2117
- },
2118
- "timestamps": {
2119
- "extractionStart": "2025-11-02T14:00:00.000Z",
2120
- "extractionEnd": "2025-11-02T14:00:12.543Z",
2121
- "uploadComplete": "2025-11-02T14:00:13.777Z"
2122
- },
2123
- "state": {
2124
- "previousTimestamp": "2025-11-02T13:00:00.000Z",
2125
- "newTimestamp": "2025-11-02T13:59:58.123Z",
2126
- "stateUpdated": true,
2127
- "overlapBufferSeconds": 60
2128
- }
2129
- }
2130
- ```
2131
-
2132
- ### Error Response Example
2133
-
2134
- ```json
2135
- {
2136
- "success": false,
2137
- "jobId": "ADHOC_FUL_20251102_140500_xyz789",
2138
- "error": "SFTP upload failed: Connection timeout",
2139
- "errorCategory": "NETWORK",
2140
- "recordsExtracted": 0,
2141
- "stage": "sftp_upload",
2142
- "details": {
2143
- "message": "Failed to upload file after 3 retry attempts",
2144
- "retryAttempts": 3,
2145
- "lastError": "ETIMEDOUT: Connection timed out after 30000ms"
2146
- },
2147
- "state": {
2148
- "stateUpdated": false,
2149
- "willRetryNextRun": true,
2150
- "note": "State not advanced - next extraction will retry same time window"
2151
- }
2152
- }
2153
- ```
2154
-
2155
- ### Key Metrics to Track
2156
-
2157
- ```typescript
2158
- const METRICS = {
2159
- // Extraction Performance
2160
- extractionDurationMs: Date.now() - extractionStart,
2161
- recordCount: records.length,
2162
- pageCount: extractionResult.stats.totalPages,
2163
- avgRecordsPerPage: records.length / extractionResult.stats.totalPages,
2164
-
2165
- // Transformation Performance
2166
- transformedCount: transformedRecords.length,
2167
- failedCount: mappingErrors.length,
2168
- errorRate: ((mappingErrors.length / records.length) * 100).toFixed(2) + '%',
2169
-
2170
- // File Generation
2171
- fileSizeMB: (xmlContent.length / (1024 * 1024)).toFixed(2),
2172
-
2173
- // Upload Performance
2174
- uploadDurationMs: uploadEnd - uploadStart,
2175
- uploadSpeedMBps: (fileSizeMB / (uploadDurationMs / 1000)).toFixed(2),
2176
-
2177
- // State Management
2178
- timeSinceLastRun: Date.now() - new Date(lastTimestamp).getTime(),
2179
- recordsPerMinute: (records.length / (extractionDurationMs / 60000)).toFixed(0),
2180
- };
2181
-
2182
- log.info('Extraction metrics', metrics);
2183
- ```
2184
-
2185
- ### Alert Thresholds
2186
-
2187
- ```typescript
2188
- const ALERT_THRESHOLDS = {
2189
- // Duration Alerts
2190
- EXTRACTION_DURATION_MS: 5 * 60 * 1000, // 5 minutes
2191
- UPLOAD_DURATION_MS: 2 * 60 * 1000, // 2 minutes
2192
- TOTAL_DURATION_MS: 10 * 60 * 1000, // 10 minutes
2193
-
2194
- // Error Rate Alerts
2195
- MAX_ERROR_RATE: 0.05, // 5% mapping errors
2196
- MAX_VALIDATION_FAILURES: 0.02, // 2% validation failures
2197
-
2198
- // Volume Alerts
2199
- MAX_RECORDS_PER_RUN: 100000,
2200
- MIN_RECORDS_WARNING: 0, // Alert if no records found
2201
- MAX_FILE_SIZE_MB: 150, // 150MB
2202
-
2203
- // State Alerts
2204
- MAX_TIME_SINCE_LAST_RUN_HOURS: 25, // Alert if >25 hours (should run hourly)
2205
- MAX_OVERLAP_BUFFER_SECONDS: 300, // Alert if buffer >5 minutes
2206
- };
2207
-
2208
- // Check thresholds
2209
- if (metrics.extractionDurationMs > ALERT_THRESHOLDS.EXTRACTION_DURATION_MS) {
2210
- log.warn('Extraction duration exceeded threshold', {
2211
- duration: metrics.extractionDurationMs,
2212
- threshold: ALERT_THRESHOLDS.EXTRACTION_DURATION_MS,
2213
- recommendation: 'Consider reducing maxRecords or increasing extraction frequency'
2214
- });
2215
- }
2216
- ```
2217
-
2218
- ### Monitoring Dashboard Queries
2219
-
2220
- **Versori Platform Logs Query:**
2221
-
2222
- ```
2223
- # Successful extractions
2224
- log_level:info AND message:"Extraction complete" AND jobId:*
2225
-
2226
- # Failed extractions
2227
- log_level:error AND message:"Extraction workflow failed" AND jobId:*
2228
-
2229
- # Performance issues
2230
- extractionDurationMs:>300000 OR uploadDurationMs:>120000
2231
-
2232
- # High error rates
2233
- errorRate:>5
2234
-
2235
- # State management issues
2236
- stateUpdated:false AND success:true
2237
- ```
2238
-
2239
- ### Common Issues and Solutions
2240
-
2241
- **Issue**: "Extraction timeout after 10 minutes"
2242
-
2243
- - **Cause**: Too many records in single extraction
2244
- - **Fix**: Reduce maxRecords, increase extraction frequency, or optimize query filters
2245
- - **Prevention**: Monitor recordCount trends, set appropriate maxRecords
2246
-
2247
- **Issue**: "Mapping errors for 50% of records"
2248
-
2249
- - **Cause**: Schema mismatch between GraphQL response and mapping config
2250
- - **Fix**: Run schema validation, update mapping config paths
2251
- - **Prevention**: Use `npx fc-connect validate-schema` before deployment
2252
-
2253
- **Issue**: "SFTP connection timeout"
2254
-
2255
- - **Cause**: Network issues, firewall, or connection pool exhaustion
2256
- - **Fix**: Check SFTP credentials, verify network connectivity
2257
- - **Prevention**: Implement connection health checks, monitor connection status
2258
-
2259
- **Issue**: "State not updating after successful extraction"
2260
-
2261
- - **Cause**: KV write failure or intentional retry logic
2262
- - **Fix**: Check KV logs, verify state update code executed
2263
- - **Prevention**: Add KV write verification, log state updates explicitly
2264
-
2265
- **Issue**: "First run exceeds record limits"
2266
-
2267
- - **Cause**: No previous timestamp, fetches all historical records
2268
- - **Fix**: Set fallbackStartDate close to current date, apply additional filters
2269
- - **Prevention**: Use appropriate fallbackStartDate for initial runs
2270
-
2271
- **Issue**: "Excessive duplicate records in output"
2272
-
2273
- - **Cause**: Overlap buffer (expected) or timestamp not saved correctly
2274
- - **Fix**: Verify newTimestamp saved WITHOUT buffer, check state persistence
2275
- - **Prevention**: Monitor duplicate rates, verify state update logic
2276
-
2277
- ---
2278
-
2279
- ## Troubleshooting Quick Reference
2280
-
2281
- | Error Message | Likely Cause | Solution |
2282
- |--------------|--------------|----------|
2283
- | "Failed to create Fluent Commerce client" | Authentication failure | Check OAuth2 credentials, verify connection config |
2284
- | "GraphQL query validation error" | Invalid query syntax | Validate query against schema with introspection tool |
2285
- | "Pagination cursor invalid" | Stale cursor or query change | Reset extraction, verify cursor handling in query |
2286
- | "Mapping failed: field not found" | Schema mismatch | Run schema validation, update mapping paths |
2287
- | "SFTP authentication failed" | Invalid credentials | Verify SFTP credentials in activation variables |
2288
- | "Connection pool exhausted" | Too many concurrent requests | Reduce concurrency, increase pool size |
2289
- | "KV operation failed" | Versori KV issue | Check Versori platform status, retry operation |
2290
- | "Job status not found" | Invalid jobId or expired | Verify jobId format, check KV retention policy |
2291
- | "Memory limit exceeded" | Dataset too large | Reduce maxRecords, enable streaming mode |
2292
- | "XML generation failed" | Format-specific error | Check XML generation logic, validate output |
2293
-
2294
- ---
1
+ ---
2
+ template_id: tpl-extract-fulfillments-to-sftp-xml
3
+ canonical_filename: template-extraction-fulfillments-to-sftp-xml.md
4
+ version: 2.0.0
5
+ sdk_version: ^0.1.39
6
+ runtime: versori
7
+ direction: extraction
8
+ source: fluent-graphql
9
+ destination: sftp-xml
10
+ entity: fulfillments
11
+ format: xml
12
+ logging: versori
13
+ status: stable
14
+ features:
15
+ - memory-management
16
+ - enhanced-logging
17
+ - pagination-progress
18
+ - dispose-finally
19
+ ---
20
+
21
+ # Template: Extraction - Fulfillments to SFTP XML
22
+
23
+ **Template Version:** 2.0.0
24
+ **SDK Version:** @fluentcommerce/fc-connect-sdk@^0.1.39
25
+ **Last Updated:** 2025-01-24
26
+ **Deployment Target:** Versori Platform
27
+
28
+ **🆕 Version 2.0.0 Enhancements:**
29
+ - ✅ **Memory Management** - Clear large result sets after processing batches
30
+ - ✅ **Enhanced Logging** - Pagination progress tracking with emoji indicators (📊, 📥, ✅)
31
+ - ✅ **Pagination Progress** - Real-time page-by-page progress logging with metrics
32
+ - ✅ **Resource Cleanup** - SFTP dispose in finally blocks prevents connection leaks
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ npm install @fluentcommerce/fc-connect-sdk@^0.1.39
38
+ ```
39
+
40
+ Use version `^0.1.39` to ensure compatibility with this template.
41
+
42
+ ---
43
+
44
+ ## 📚 STEP 1: Load These Docs (Human Checklist)
45
+
46
+ 1. REQUIRED (load all)
47
+ - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
48
+ - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
49
+ - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
50
+ - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
51
+ - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/extraction/
52
+ - [ ] fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
53
+
54
+ Copy-paste list (open these):
55
+ fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
56
+ fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
57
+ fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
58
+ fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
59
+ fc-connect-sdk/docs/03-PATTERN-GUIDES/extraction/
60
+ fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
61
+
62
+ ---
63
+
64
+ ## 📋 STEP 2: Tell Your AI (Prompt)
65
+
66
+ Copy/paste this prompt after loading the documentation above:
67
+
68
+ ```
69
+ Create a Versori scheduled extractor for fulfillments that uses ExtractionOrchestrator + JobTracker, incremental updatedOn with a 60s overlap buffer, transforms via UniversalMapper, generates XML with fast-xml-parser XMLBuilder, uploads to SFTP using SftpDataSource with dispose(). Include 3 workflows: scheduled, ad-hoc webhook, and job-status query with native Versori logging.
70
+ ```
71
+
72
+ ---
73
+
74
+ ## 📦 SDK Imports (Verified - Versori Optimized)
75
+
76
+ ```typescript
77
+ import { Buffer } from 'node:buffer';
78
+ import {
79
+ createClient,
80
+ ExtractionOrchestrator,
81
+ JobTracker,
82
+ UniversalMapper,
83
+ XMLBuilder,
84
+ SftpDataSource,
85
+ VersoriKVAdapter,
86
+ } from '@fluentcommerce/fc-connect-sdk';
87
+
88
+ import { schedule, webhook, http, fn } from '@versori/run';
89
+ ```
90
+
91
+ ---
92
+
93
+ # Versori Scheduled: Fulfillments Extraction to SFTP XML (Shipment Tracking)
94
+
95
+ **FC Connect SDK Use Case Guide**
96
+
97
+ > SDK: [@fluentcommerce/fc-connect-sdk](https://www.npmjs.com/package/@fluentcommerce/fc-connect-sdk)
98
+ > Version: Use ^0.1.39 - `npm install @fluentcommerce/fc-connect-sdk@^0.1.39`
99
+
100
+ Context: Scheduled Versori workflow that extracts fulfillment data (shipment tracking, delivery information) from Fluent Commerce via GraphQL query with **ExtractionOrchestrator**, **JobTracker**, and **incremental timestamp tracking**, transforms with `UniversalMapper`, and writes **XML files** to SFTP for logistics coordination and delivery tracking.
101
+
102
+ **Pattern**: EXTRACTION (Fluent → SFTP XML)
103
+ **Complexity**: High | Runtime: Versori Platform (Scheduled)
104
+
105
+ ---
106
+
107
+ ## ⚠️ IMPORTANT: Production-Ready Base Template
108
+
109
+ > **📋 BASE TEMPLATE - Ready for Production (Customize for Your Needs)**
110
+ >
111
+ > This is a **production-ready base template** demonstrating FC Connect SDK best practices for fulfillment extraction workflows with XML output.
112
+ >
113
+ > **✅ INCLUDED FEATURES:**
114
+ >
115
+ > - ✅ Comprehensive error handling with retry logic
116
+ > - ✅ SFTP upload with exponential backoff (3 attempts)
117
+ > - ✅ State management with overlap buffer (prevents missed records)
118
+ > - ✅ Job tracking with lifecycle management
119
+ > - ✅ Security (credential masking in logs)
120
+ > - ✅ UTC time enforcement (prevents timezone bugs)
121
+ > - ✅ Incremental extraction (safe, efficient, production-ready)
122
+ > - ✅ Natural rate limiting via timestamps
123
+ >
124
+ > **📝 BEFORE DEPLOYING:**
125
+ >
126
+ > 1. Review and customize activation variables for your environment
127
+ > 2. Test with sample data in your Versori workspace
128
+ > 3. Adjust safety limits (pageSize, maxRecords) if needed
129
+ > 4. Configure monitoring alerts for extraction failures
130
+ > 5. Verify SFTP credentials and paths
131
+ >
132
+ > **This base template follows SDK best practices - tweak specific to your needs.**
133
+
134
+ ---
135
+
136
+ ## 🚀 Quick Deploy to Versori
137
+
138
+ 1. **Create Integration:** Versori Dashboard → New Integration → Name it "Fulfillments Extraction"
139
+ 2. **Copy Code:** Copy all workflow code from this template into Versori editor
140
+ 3. **Configure Connections:**
141
+ - `fluent_commerce` - Fluent Commerce API (OAuth2)
142
+ - `sftp_export_server` - SFTP destination (Basic Auth)
143
+ - `fulfillments-adhoc` - Ad-hoc webhook auth (API Key)
144
+ - `fulfillments-job-status` - Status webhook auth (API Key)
145
+ 4. **Set Activation Variables:** Configure all variables listed in Activation Variables section
146
+ 5. **Test:** Use ad-hoc webhook to test extraction before enabling schedule
147
+ 6. **Enable Schedule:** Activate scheduled workflow after successful test
148
+
149
+ **Time to Deploy:** ~15 minutes
150
+
151
+ ---
152
+
153
+ ## 🔧 Common Customizations
154
+
155
+ **Most Common Changes:**
156
+
157
+ | What to Change | Where | Why |
158
+ | ---------------------- | ----------------------------------------- | ---------------------------------- |
159
+ | **Status filters** | Activation variable `fulfillmentStatuses` | Target specific fulfillment states |
160
+ | **Schedule frequency** | Workflow: `'0 */4 * * *'` | Change from 4-hourly to your needs |
161
+ | **XML field mapping** | `config/fulfillments.export.xml.json` | Add/remove/modify output fields |
162
+ | **Date filters** | GraphQL query variables | Filter by creation/update dates |
163
+ | **Page size** | Activation variable `pageSize` | Tune for performance (50-1000) |
164
+ | **Safety limits** | Activation variable `maxRecords` | Adjust based on dataset size |
165
+
166
+ **Less Common Changes:**
167
+
168
+ | What to Change | Where | Default | When to Change |
169
+ | ----------------------- | ------------------------------------------ | ----------------------- | ---------------------------- |
170
+ | **Overlap buffer** | Activation variable `overlapBufferSeconds` | 60s | If seeing missed records |
171
+ | **SFTP retry attempts** | Code: `uploadWithRetry(..., 3)` | 3 | For unreliable networks |
172
+ | **Fallback start date** | Activation variable `fallbackStartDate` | 2024-01-01 | For historical extraction |
173
+ | **Remote path** | Activation variable `sftpRemotePath` | /incoming/fulfillments/ | Match partner's requirements |
174
+
175
+ **What NOT to Change (Unless You Know Why):**
176
+
177
+ - 10-step workflow structure
178
+ - Error taxonomy (CONFIG/API/SFTP/NO_DATA)
179
+ - State management logic
180
+ - UTC time enforcement
181
+ - Connection cleanup (`sftp.dispose()`)
182
+
183
+ ---
184
+
185
+ ## What You'll Build
186
+
187
+ - **Incremental extraction** using `updatedOn >= (lastRunTime - buffer)` with **overlap buffer**
188
+ - **ExtractionOrchestrator** for auto-pagination and path-based extraction
189
+ - **JobTracker** for lifecycle management
190
+ - **State management** with VersoriKV to track last successful run
191
+ - **Safety buffer** (60 seconds) to handle clock skew and race conditions
192
+ - GraphQL query with status-based filtering and date range support
193
+ - UniversalMapper transformation with nested order data
194
+ - **XML file generation** with fulfillment/shipment data
195
+ - **SFTP upload** to partner systems with proper connection cleanup
196
+ - **3 workflow patterns**: scheduled, ad-hoc webhook, job status query
197
+ - **Failure recovery** with timestamp tracking
198
+
199
+ ## Business Use Case
200
+
201
+ **4-hourly shipment tracking extraction for logistics:**
202
+
203
+ - Extract shipment and delivery information for carrier integration
204
+ - Track fulfillment status changes (SHIPPED, DELIVERED)
205
+ - Monitor delivery exceptions and returns (RMA)
206
+ - Support logistics partner feeds
207
+ - Enable shipment tracking updates
208
+ - Run every 4 hours for timely status updates
209
+ - Deliver XML format to enterprise systems via SFTP
210
+
211
+ ## Fulfillments Explained
212
+
213
+ **Fulfillment** = Shipment execution record
214
+
215
+ - Represents order fulfillment process
216
+ - Tracks shipment status and delivery progress
217
+ - Links to orders, items, and locations
218
+ - Used for: Shipment tracking, delivery coordination, logistics integration
219
+
220
+ **Key Fields:**
221
+
222
+ - `ref` - Unique fulfillment reference
223
+ - `status` - Fulfillment state (SHIPPED, DELIVERED, etc.)
224
+ - `deliveryType` - Shipping method
225
+ - `order.ref` - Associated order reference
226
+ - `fromLocation` - Shipping origin
227
+ - `items` - Fulfilled order items
228
+ - `createdOn`, `updatedOn` - Timestamps for tracking
229
+
230
+ ## SDK Methods Used
231
+
232
+ ```typescript
233
+ import { Buffer } from 'node:buffer';
234
+ import {
235
+ createClient,
236
+ ExtractionOrchestrator,
237
+ JobTracker,
238
+ UniversalMapper,
239
+ XMLBuilder,
240
+ SftpDataSource,
241
+ VersoriKVAdapter,
242
+ } from '@fluentcommerce/fc-connect-sdk';
243
+
244
+ await createClient(ctx); // Versori-aware client
245
+ const orchestrator = new ExtractionOrchestrator(client, log); // Auto-pagination
246
+ const tracker = new JobTracker(kv, log); // Job lifecycle tracking
247
+ await orchestrator.extract({ query, resultPath, variables, pageSize, maxRecords }); // Extract
248
+ new VersoriKVAdapter(ctx.openKv(':project:')); // State management
249
+ new UniversalMapper(exportMapping); // Field transformation
250
+ new XMLBuilder({ prettyPrint: true, xmlDeclaration: true }); // XML generation
251
+ const xml = xmlBuilder.build(data, 'RootElement'); // Build XML string
252
+ await sftp.uploadFile(remotePath, buffer, options); // SFTP upload
253
+ await sftp.dispose(); // CRITICAL: Connection cleanup
254
+ ```
255
+
256
+ ## Activation Variables
257
+
258
+ **Configuration is driven by activation variables - modify these instead of code:**
259
+
260
+ ```json
261
+ {
262
+ "fulfillmentStatuses": "SHIPPED,DELIVERED",
263
+ "sftpHost": "sftp.partner.com",
264
+ "sftpPort": 22,
265
+ "sftpPrivateKey": "",
266
+ "sftpRemotePath": "/incoming/fulfillments/",
267
+ "fileNamePrefix": "fulfillments",
268
+ "requireAbsolutePaths": "false",
269
+ "pageSize": 200,
270
+ "maxRecords": 50000,
271
+ "fallbackStartDate": "2024-01-01T00:00:00Z",
272
+ "overlapBufferSeconds": "60"
273
+ }
274
+ ```
275
+
276
+ > **Note:** `sftpUsername` and `sftpPassword` are fetched from the `sftp_export_server` connection (see SFTP Credential Management section below).
277
+
278
+ ## SFTP Credential Management
279
+
280
+ Fetch credentials securely from Versori connection vault using `ctx.credentials().getAccessToken()`:
281
+
282
+ ```typescript
283
+ import { Buffer } from 'node:buffer'; // Required for Versori/Deno
284
+
285
+ // ========================================
286
+ // SFTP CREDENTIAL RETRIEVAL
287
+ // ========================================
288
+
289
+ /**
290
+ * Retrieve SFTP credentials from connection configuration
291
+ *
292
+ * This approach retrieves credentials stored in the Versori connection settings.
293
+ * The connection must be configured in the UI with Basic Authentication.
294
+ *
295
+ * Steps:
296
+ * 1. Call ctx.credentials().getAccessToken('SFTP') to get base64-encoded credentials
297
+ * 2. Decode the accessToken from base64 to get "username:password" string
298
+ * 3. Split on ':' to extract username and password
299
+ *
300
+ * Connection Name: 'sftp_export_server' (must match the connection name in Versori UI)
301
+ * Auth Type: Basic Authentication (username + password)
302
+ *
303
+ * This method provides:
304
+ * - Centralized credential management through Versori UI
305
+ * - Better security (credentials not stored in integration variables)
306
+ * - Easier credential rotation and updates
307
+ */
308
+ log.info('Retrieving SFTP credentials from connection configuration');
309
+
310
+ let sftpUsername: string;
311
+ let sftpPassword: string;
312
+
313
+ try {
314
+ // Retrieve credentials from the 'sftp_export_server' connection
315
+ const sftpCred = await ctx.credentials().getAccessToken('sftp_export_server');
316
+
317
+ if (!sftpCred?.accessToken) {
318
+ throw new Error('No SFTP credentials found in connection configuration');
319
+ }
320
+
321
+ // Decode base64 accessToken to get "username:password"
322
+ const rawBasicAuth = Buffer.from(sftpCred.accessToken, 'base64').toString('utf-8');
323
+
324
+ // Split on ':' to extract username and password
325
+ const parts = rawBasicAuth.split(':');
326
+
327
+ if (parts.length !== 2) {
328
+ throw new Error('Invalid SFTP credential format - expected username:password');
329
+ }
330
+
331
+ sftpUsername = parts[0];
332
+ sftpPassword = parts[1];
333
+
334
+ log.info('SFTP credentials retrieved successfully', {
335
+ hasUsername: !!sftpUsername,
336
+ hasPassword: !!sftpPassword,
337
+ usernameLength: sftpUsername.length,
338
+ passwordLength: sftpPassword.length,
339
+ });
340
+ } catch (error: any) {
341
+ log.error('Failed to retrieve SFTP credentials', {
342
+ message: error instanceof Error ? error.message : String(error),
343
+ stack: error instanceof Error ? error.stack : undefined,
344
+ errorType: error instanceof Error ? error.constructor.name : 'Error',
345
+ });
346
+
347
+ return {
348
+ success: false,
349
+ error: 'Failed to retrieve SFTP credentials from connection configuration',
350
+ details: error instanceof Error ? error.message : String(error),
351
+ recommendation: 'Please ensure the SFTP connection is configured in the Connections section with Basic Authentication (username and password)',
352
+ };
353
+ }
354
+
355
+ // Initialize SFTP with connection credentials
356
+ const sftp = new SftpDataSource(
357
+ {
358
+ type: 'SFTP_XML',
359
+ connectionId: 'sftp_export_server',
360
+ name: 'Export SFTP',
361
+ settings: {
362
+ host: ctx.activation.getVariable('sftpHost'),
363
+ port: parseInt(ctx.activation.getVariable('sftpPort') || '22'),
364
+ username: sftpUsername,
365
+ password: sftpPassword,
366
+ remotePath: ctx.activation.getVariable('sftpRemotePath') || '/exports',
367
+ encoding: 'utf8',
368
+ },
369
+ },
370
+ log
371
+ );
372
+ ```
373
+
374
+ **Benefits:**
375
+
376
+ - ✅ Credentials stored securely in Versori vault
377
+ - ✅ Centralized management - update in one place
378
+ - ✅ Access control enforced by platform
379
+ - ✅ No credentials in activation variables
380
+ - ✅ Explicit error handling with validation
381
+
382
+ ### Setup Steps
383
+
384
+ 1. In Versori Dashboard → Connections → Add Connection
385
+ 2. Name: `sftp_export_server`
386
+ 3. Type: Basic Auth
387
+ 4. Enter SFTP username and password
388
+ 5. Save connection
389
+ 6. Reference in code: `ctx.credentials().getAccessToken('sftp_export_server')`
390
+
391
+ ---
392
+
393
+ ## Webhook Security Configuration
394
+
395
+ **⚠️ IMPORTANT:** Webhook security is now handled at the **Versori connection level** (not in code).
396
+
397
+ ### Required Connections
398
+
399
+ Create these connections in Versori Dashboard before deploying:
400
+
401
+ 1. **`fulfillments-adhoc`** (Ad-hoc webhook auth)
402
+ - Configure authentication (e.g., API Key) in the connection settings
403
+
404
+ 2. **`fulfillments-job-status`** (Job status query auth)
405
+ - Configure authentication (e.g., API Key) in the connection settings
406
+
407
+ ### How to Create Webhook Connections
408
+
409
+ 1. **Navigate to Versori Dashboard** → Connections
410
+ 2. **Click "Add Connection"**
411
+ 3. **Configure:**
412
+ - Name: `fulfillments-adhoc`
413
+ - Authentication: API Key (or preferred method)
414
+ - Provide header name/value in the connection UI
415
+ 4. **Save Connection**
416
+ 5. **Repeat** for `fulfillments-job-status` connection
417
+
418
+ ### Generate Secure API Keys
419
+
420
+ ```bash
421
+ # Node.js - Generate cryptographically secure 64-character key
422
+ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
423
+
424
+ # Example output:
425
+ # 7f3e9a2b1c8d6e4f5a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8f
426
+ ```
427
+
428
+ ### How It Works
429
+
430
+ ```
431
+ ┌────────────────┐
432
+ │ External │
433
+ │ System │
434
+ └──────┬─────────┘
435
+
436
+ │ POST /webhook/fulfillments-adhoc
437
+ │ Headers: (as configured on the connection)
438
+
439
+ ┌─────────────────────────┐
440
+ │ Versori Platform │
441
+ │ ✓ Validates API key │ ← Authentication happens HERE
442
+ │ ✓ Checks header │
443
+ │ ✗ Rejects if invalid │
444
+ └──────┬──────────────────┘
445
+
446
+ │ ✅ Only reaches workflow if valid
447
+
448
+ ┌─────────────────────────┐
449
+ │ Your Workflow Code │
450
+ │ (No auth code needed!) │
451
+ └──────────────────────────┘
452
+ ```
453
+
454
+ **Benefits:**
455
+
456
+ - ✅ Security at platform level (before code runs)
457
+ - ✅ No manual validation code needed
458
+ - ✅ Consistent across all webhooks
459
+ - ✅ Easy to rotate keys (update connection, not code)
460
+ - ✅ Failed auth never hits your workflow (saves resources)
461
+
462
+ ## Export Mapping Configuration
463
+
464
+ Create file: `config/fulfillments.export.xml.json`
465
+
466
+ ```json
467
+ {
468
+ "name": "fulfillments.export.xml",
469
+ "version": "1.0.0",
470
+ "description": "Fluent Fulfillments → SFTP XML Export (shipment tracking)",
471
+ "fields": {
472
+ "fulfillment_ref": { "source": "ref", "required": true, "resolver": "sdk.trim" },
473
+ "order_ref": { "source": "order.ref", "required": true, "resolver": "sdk.trim" },
474
+ "status": { "source": "status", "required": true, "resolver": "sdk.uppercase" },
475
+ "delivery_type": { "source": "deliveryType", "required": false, "resolver": "sdk.trim" },
476
+ "from_location_ref": {
477
+ "source": "fromLocation.ref",
478
+ "required": false,
479
+ "resolver": "sdk.trim"
480
+ },
481
+ "from_location_name": {
482
+ "source": "fromLocation.name",
483
+ "required": false,
484
+ "resolver": "sdk.trim"
485
+ },
486
+ "created_on": { "source": "createdOn", "required": true, "resolver": "sdk.toString" },
487
+ "updated_on": { "source": "updatedOn", "required": true, "resolver": "sdk.toString" }
488
+ }
489
+ }
490
+ ```
491
+
492
+ **Note**: The mapping uses nested paths like `order.ref` and `fromLocation.ref` to access related entity fields.
493
+
494
+ ## Mapping & Resolvers Explained
495
+
496
+ This section explains how the SDK transforms raw GraphQL data into your XML export format using **UniversalMapper** and **SDK resolvers**.
497
+
498
+ ### SDK Resolvers Used
499
+
500
+ | Field | Resolver | Why? | Example Transformation |
501
+ | -------------------- | --------------- | ---------------------------- | --------------------------------------- |
502
+ | `fulfillment_ref` | `sdk.trim` | Clean fulfillment references | `" FF-001 "` → `"FF-001"` |
503
+ | `order_ref` | `sdk.trim` | Clean order references | `" ORD-001 "` → `"ORD-001"` |
504
+ | `status` | `sdk.uppercase` | Normalize status codes | `"shipped"` → `"SHIPPED"` |
505
+ | `delivery_type` | `sdk.trim` | Clean delivery method | `" STANDARD "` → `"STANDARD"` |
506
+ | `from_location_ref` | `sdk.trim` | Clean location references | `" LOC-001 "` → `"LOC-001"` |
507
+ | `from_location_name` | `sdk.trim` | Clean location names | `" NYC Warehouse "` → `"NYC Warehouse"` |
508
+ | `created_on` | `sdk.toString` | Preserve ISO 8601 timestamp | `"2025-01-15T10:00:00.000Z"` → same |
509
+ | `updated_on` | `sdk.toString` | Preserve ISO 8601 timestamp | `"2025-01-22T08:30:00.000Z"` → same |
510
+
511
+ ### Transformation Flow
512
+
513
+ ```typescript
514
+ // 1. GraphQL Response (raw data from Fluent Commerce)
515
+ const rawFulfillment = {
516
+ ref: ' FF-001 ',
517
+ status: 'shipped',
518
+ deliveryType: ' STANDARD ',
519
+ order: {
520
+ ref: ' ORD-001 ',
521
+ },
522
+ fromLocation: {
523
+ ref: ' LOC-001 ',
524
+ name: ' NYC Warehouse ',
525
+ },
526
+ items: {
527
+ edges: [
528
+ {
529
+ node: {
530
+ productRef: 'PROD-001',
531
+ requestedQuantity: 2,
532
+ filledQuantity: 2,
533
+ },
534
+ },
535
+ ],
536
+ },
537
+ createdOn: '2025-01-15T10:00:00.000Z',
538
+ updatedOn: '2025-01-22T08:30:00.000Z',
539
+ };
540
+
541
+ // 2. UniversalMapper applies SDK resolvers (handles nested paths automatically)
542
+ const mapper = new UniversalMapper(fulfillmentsExportMapping);
543
+ const result = await mapper.map(rawFulfillment);
544
+
545
+ // 3. Transformed Output (clean, normalized for XML)
546
+ const transformedFulfillment = {
547
+ fulfillment_ref: 'FF-001',
548
+ order_ref: 'ORD-001',
549
+ status: 'SHIPPED',
550
+ delivery_type: 'STANDARD',
551
+ from_location_ref: 'LOC-001',
552
+ from_location_name: 'NYC Warehouse',
553
+ created_on: '2025-01-15T10:00:00.000Z',
554
+ updated_on: '2025-01-22T08:30:00.000Z',
555
+ };
556
+ ```
557
+
558
+ ### Nested Object Mapping
559
+
560
+ Fulfillments include **nested objects** that require special path syntax:
561
+
562
+ ```typescript
563
+ // ✅ CORRECT - Access nested object fields with dot notation
564
+ {
565
+ "order_ref": { "source": "order.ref" },
566
+ "from_location_ref": { "source": "fromLocation.ref" },
567
+ "from_location_name": { "source": "fromLocation.name" }
568
+ }
569
+ ```
570
+
571
+ **GraphQL must fetch the nested objects:**
572
+
573
+ ```graphql
574
+ node {
575
+ ref # Direct field
576
+ status
577
+ order { # Nested Order object
578
+ ref # Access via order.ref
579
+ }
580
+ fromLocation { # Nested Location object
581
+ ref # Access via fromLocation.ref
582
+ name # Access via fromLocation.name
583
+ }
584
+ items { # Nested items collection
585
+ edges {
586
+ node {
587
+ productRef
588
+ requestedQuantity
589
+ filledQuantity
590
+ }
591
+ }
592
+ }
593
+ }
594
+ ```
595
+
596
+ **UniversalMapper handles nested paths automatically** - just use dot notation in the mapping configuration.
597
+
598
+ ### Available SDK Resolvers
599
+
600
+ The SDK provides these built-in resolvers (no custom code needed):
601
+
602
+ **String Transformations:**
603
+
604
+ - `sdk.trim` - Remove leading/trailing whitespace
605
+ - `sdk.uppercase` - Convert to uppercase
606
+ - `sdk.lowercase` - Convert to lowercase
607
+ - `sdk.toString` - Convert to string
608
+
609
+ **Number Parsing:**
610
+
611
+ - `sdk.parseInt` - Parse as integer
612
+ - `sdk.parseFloat` - Parse as decimal
613
+ - `sdk.number` - Parse as number (auto-detect int/float)
614
+
615
+ **Date Formatting:**
616
+
617
+ - `sdk.formatDate` - ISO 8601 date only (YYYY-MM-DD)
618
+ - `sdk.formatDateShort` - Short date format
619
+ - `sdk.parseDate` - Parse various date formats
620
+
621
+ **Type Conversions:**
622
+
623
+ - `sdk.boolean` - Convert to boolean
624
+ - `sdk.parseJson` - Parse JSON strings
625
+ - `sdk.toJson` - Convert to JSON string
626
+
627
+ **Utilities:**
628
+
629
+ - `sdk.identity` - Return value unchanged
630
+ - `sdk.coalesce` - Return first non-null value
631
+
632
+ See [Universal Mapping Guide](../../../../../02-CORE-GUIDES/advanced-services/advanced-services-readme.md) for complete resolver documentation.
633
+
634
+ ## GraphQL Query
635
+
636
+ **Note**: This query is verified against Fluent Commerce schema introspection.
637
+
638
+ ```graphql
639
+ query GetFulfillments(
640
+ $statuses: [String!]
641
+ $updatedFrom: DateTime
642
+ $updatedTo: DateTime
643
+ $first: Int!
644
+ $after: String
645
+ ) {
646
+ fulfillments(
647
+ status: $statuses
648
+ updatedOn: { from: $updatedFrom, to: $updatedTo }
649
+ first: $first
650
+ after: $after
651
+ ) {
652
+ edges {
653
+ node {
654
+ id
655
+ ref
656
+ status
657
+ deliveryType
658
+ order {
659
+ ref
660
+ }
661
+ fromLocation {
662
+ ref
663
+ name
664
+ }
665
+ items {
666
+ edges {
667
+ node {
668
+ productRef
669
+ requestedQuantity
670
+ filledQuantity
671
+ }
672
+ }
673
+ }
674
+ createdOn
675
+ updatedOn
676
+ }
677
+ cursor
678
+ }
679
+ pageInfo {
680
+ hasNextPage
681
+ }
682
+ }
683
+ }
684
+ ```
685
+
686
+ ---
687
+
688
+ ## Versori Workflows Structure
689
+
690
+ **Key Concept**: Versori workflows are organized by **trigger type** at the first level, then by **specific workflow** with descriptive file names.
691
+
692
+ **Trigger Types:**
693
+ - **`schedule()`** → Time-based triggers (cron expressions) - NOT exposed as HTTP endpoints
694
+ - **`webhook()`** → HTTP-based triggers (event-driven) - Creates HTTP endpoints
695
+ - **`workflow()`** → Durable workflows (advanced, rarely used)
696
+
697
+ **Execution Steps (chained to triggers):**
698
+ - **`http()`** → External API calls (chained from schedule/webhook)
699
+ - **`fn()`** → Internal processing (chained from schedule/webhook)
700
+
701
+ ### Recommended Project Structure
702
+
703
+ **This template demonstrates a complete workflow implementation in a single file.** In production, consider organizing your code into this modular structure:
704
+
705
+ ```
706
+ fulfillments-extraction/
707
+ ├── index.ts # Entry point - exports all workflows
708
+ └── src/
709
+ ├── workflows/
710
+ │ └── fulfillments-extraction.ts # All workflows (scheduled + webhooks)
711
+
712
+ ├── services/
713
+ │ └── extraction-orchestration.ts # Shared orchestration logic (reusable)
714
+
715
+ └── config/
716
+ ├── queries.ts # GraphQL queries
717
+ └── fulfillments.export.xml.json # Mapping configuration
718
+ ```
719
+
720
+ **Alternative Modular Structure** (for larger projects with multiple workflows):
721
+ ```
722
+ fulfillments-extraction/
723
+ ├── index.ts
724
+ └── src/
725
+ ├── workflows/
726
+ │ ├── scheduled/
727
+ │ │ └── daily-fulfillments-extraction.ts # Scheduled extraction only
728
+ │ └── webhook/
729
+ │ ├── adhoc-fulfillments-extraction.ts # Ad-hoc webhook
730
+ │ └── job-status-check.ts # Status query webhook
731
+ ├── services/
732
+ │ └── extraction-orchestration.ts
733
+ └── config/
734
+ ├── queries.ts
735
+ └── fulfillments.export.xml.json
736
+ ```
737
+
738
+ ---
739
+
740
+ ## Expected XML Output
741
+
742
+ ```xml
743
+ <?xml version="1.0" encoding="UTF-8"?>
744
+ <Fulfillments>
745
+ <Fulfillment>
746
+ <fulfillment_ref>FF-001</fulfillment_ref>
747
+ <order_ref>ORD-001</order_ref>
748
+ <status>SHIPPED</status>
749
+ <delivery_type>STANDARD</delivery_type>
750
+ <from_location_ref>LOC-001</from_location_ref>
751
+ <from_location_name>NYC Warehouse</from_location_name>
752
+ <created_on>2025-01-15T10:00:00Z</created_on>
753
+ <updated_on>2025-01-22T08:30:00Z</updated_on>
754
+ </Fulfillment>
755
+ <Fulfillment>
756
+ <fulfillment_ref>FF-002</fulfillment_ref>
757
+ <order_ref>ORD-002</order_ref>
758
+ <status>DELIVERED</status>
759
+ <delivery_type>EXPRESS</delivery_type>
760
+ <from_location_ref>LOC-002</from_location_ref>
761
+ <from_location_name>LA Warehouse</from_location_name>
762
+ <created_on>2025-01-16T11:00:00Z</created_on>
763
+ <updated_on>2025-01-22T09:15:00Z</updated_on>
764
+ </Fulfillment>
765
+ </Fulfillments>
766
+ ```
767
+
768
+ ## Production Safety & Guardrails
769
+
770
+ ### Overview
771
+
772
+ Fulfillments require safeguards even in incremental mode:
773
+
774
+ - **Status changes**: Fulfillments can update frequently during processing
775
+ - **Delivery tracking**: Real-time status updates create rapid data changes
776
+ - **Order volume**: High-volume retailers process thousands of fulfillments daily
777
+ - **Partner feeds**: Logistics systems need predictable file sizes
778
+
779
+ ### Hard Limits
780
+
781
+ ```typescript
782
+ const SAFETY_LIMITS = {
783
+ MAX_RECORDS_PER_RUN: 100000, // 100k fulfillments per run
784
+ MAX_RECORDS_PER_FILE: 25000, // 25k per XML file
785
+ MAX_FILE_SIZE_MB: 75, // 75MB per file
786
+ MAX_XML_SIZE_MB: 150, // Total extraction size
787
+ CHUNK_SIZE: 5000, // Process in chunks
788
+ ESTIMATED_BYTES_PER_RECORD: 600, // Conservative estimate for XML
789
+ };
790
+ ```
791
+
792
+ **Why these limits?**
793
+
794
+ - Fulfillments have nested items (larger than simple entities)
795
+ - Shipment tracking needs fast processing for timely updates
796
+ - Multiple status changes can accumulate quickly
797
+ - Partner systems require predictable batch sizes
798
+ - XML is more verbose than CSV (~25% larger)
799
+
800
+ ### Runtime Validation Function
801
+
802
+ ```typescript
803
+ /**
804
+ * Validate extraction safety limits before processing
805
+ */
806
+ function validateExtractionLimits(recordCount: number, estimatedSizeMB: number) {
807
+ const MAX_RECORDS_PER_RUN = 100000;
808
+ const MAX_XML_SIZE_MB = 150;
809
+
810
+ if (recordCount > MAX_RECORDS_PER_RUN) {
811
+ return {
812
+ valid: false,
813
+ error: `Extraction limit exceeded: ${recordCount} records (max: ${MAX_RECORDS_PER_RUN})`,
814
+ recommendation: `Fulfillments dataset too large. Consider:
815
+ 1. Increase extraction frequency (4-hourly → hourly)
816
+ 2. Filter by status (extract SHIPPED and DELIVERED separately)
817
+ 3. Filter by date range (last 24 hours only)
818
+ 4. Split by location (extract by fulfillment center)`,
819
+ recordCount,
820
+ maxAllowed: MAX_RECORDS_PER_RUN,
821
+ };
822
+ }
823
+
824
+ if (estimatedSizeMB > MAX_XML_SIZE_MB) {
825
+ return {
826
+ valid: false,
827
+ error: `XML size limit exceeded: ${estimatedSizeMB}MB (max: ${MAX_XML_SIZE_MB}MB)`,
828
+ recommendation: 'File splitting required. Filter by status or date range.',
829
+ estimatedSizeMB,
830
+ maxAllowed: MAX_XML_SIZE_MB,
831
+ };
832
+ }
833
+
834
+ return { valid: true };
835
+ }
836
+ ```
837
+
838
+ ---
839
+
840
+ ## Production Capabilities
841
+
842
+ Built-in safeguards and best practices:
843
+
844
+ | Capability | Implementation | Benefit |
845
+ | ----------------------- | ------------------------------------------ | ------------------------------- |
846
+ | **Config Validation** | Fail-fast with detailed error messages | Catches issues before execution |
847
+ | **SFTP Retry** | 3 attempts with exponential backoff | Resilient to network issues |
848
+ | **UTC Enforcement** | Normalize all dates to UTC | Prevents timezone bugs |
849
+ | **Window Persistence** | Save effective time window in job metadata | Complete execution history |
850
+ | **Error Taxonomy** | Categorize errors: CONFIG/API/SFTP/NO_DATA | Better support triage |
851
+ | **Extended Metrics** | Track pages, skipped records, XML size | Enhanced observability |
852
+ | **Input Normalization** | Lowercase, trim, dedupe list inputs | Consistent filtering |
853
+ | **Secrets Masking** | Mask credentials in error logs | Security compliance |
854
+
855
+ ---
856
+
857
+ ## Complete Workflow Code
858
+
859
+ ### File Structure
860
+
861
+ **This template demonstrates a single-file implementation** (all workflows in one file for easier understanding). The actual code structure matches the "Recommended Project Structure" shown earlier.
862
+
863
+ ```
864
+ fulfillments-extraction/
865
+ ├── src/
866
+ │ ├── index.ts # Entry point (exports workflows)
867
+ │ ├── workflows/
868
+ │ │ └── fulfillments-extraction.ts # All 3 workflows (scheduled + 2 webhooks)
869
+ │ ├── services/
870
+ │ │ └── extraction-orchestration.ts # Main orchestration logic (shared)
871
+ │ └── config/
872
+ │ └── queries.ts # GraphQL queries & mapping
873
+ ├── config/
874
+ │ └── fulfillments.export.xml.json # Field mapping config
875
+ └── package.json
876
+ ```
877
+
878
+ **Why Single File?**
879
+ - ✅ Easier to understand workflow relationships
880
+ - ✅ All patterns visible in one place
881
+ - ✅ Simpler to maintain for small projects
882
+ - ⚠️ For larger projects, split into `scheduled/` and `webhook/` subdirectories (see "Alternative Modular Structure" above)
883
+
884
+ **Entry Point (`src/index.ts`):**
885
+
886
+ ```typescript
887
+ // Export all workflows for Versori to discover
888
+ export {
889
+ scheduledFulfillmentsExtraction,
890
+ adhocFulfillmentsExtraction,
891
+ fulfillmentsJobStatus,
892
+ } from './workflows/fulfillments-extraction';
893
+
894
+ // Export services for testing or direct use
895
+ export {
896
+ executeFulfillmentExtraction,
897
+ queryJobStatus,
898
+ generateJobId,
899
+ } from './services/extraction-orchestration';
900
+
901
+ // Export configuration for reference
902
+ export { FULFILLMENTS_QUERY, FULFILLMENTS_EXPORT_MAPPING } from './config/queries';
903
+ ```
904
+
905
+ **How Versori Discovers Workflows:**
906
+ Versori scans exported workflow objects (created with `schedule()`, `webhook()`) from your entry point and automatically registers them.
907
+
908
+ ---
909
+
910
+ ## 📄 src/workflows/fulfillments-extraction.ts
911
+
912
+ ```typescript
913
+ // ============================================================================
914
+ // FULFILLMENTS EXTRACTION WORKFLOWS
915
+ // ============================================================================
916
+ // Purpose: Extract shipment tracking and delivery data from Fluent Commerce
917
+ // and export as XML to SFTP for logistics coordination
918
+ //
919
+ // Workflows:
920
+ // 1. Scheduled: 4-hourly incremental extraction with state tracking
921
+ // 2. Ad-hoc: Manual trigger with custom date ranges
922
+ // 3. Job Status: Query extraction job progress and results
923
+ // ============================================================================
924
+
925
+ import { schedule, webhook, http, fn } from '@versori/run';
926
+ import type { Context } from '@versori/run';
927
+ import {
928
+ executeFulfillmentExtraction,
929
+ queryJobStatus,
930
+ generateJobId,
931
+ } from '../services/extraction-orchestration';
932
+
933
+ // ============================================================================
934
+ // SECTION 1: TYPE DEFINITIONS
935
+ // ============================================================================
936
+
937
+ /**
938
+ * Error categories for classification and triage
939
+ */
940
+ type ErrorCategory = 'CONFIG' | 'API' | 'SFTP' | 'NO_DATA';
941
+
942
+ /**
943
+ * Extraction time window with buffer tracking
944
+ */
945
+ interface TimeWindow {
946
+ from: string; // Original start time (ISO 8601 UTC)
947
+ to: string; // End time (ISO 8601 UTC)
948
+ bufferedFrom: string; // Actual query start with overlap buffer applied
949
+ }
950
+
951
+ /**
952
+ * Detailed extraction metrics for observability
953
+ */
954
+ interface ExtractionMetrics {
955
+ totalPages: number; // GraphQL pages retrieved
956
+ validRecords: number; // Successfully transformed records
957
+ skippedRecords: number; // Records that failed mapping
958
+ xmlSizeKb: number; // Final XML file size
959
+ window: TimeWindow; // Time window used for extraction
960
+ }
961
+
962
+ /**
963
+ * Result structure returned by extraction workflows
964
+ */
965
+ interface ExtractionResult {
966
+ success: boolean;
967
+ jobId: string;
968
+ recordCount?: number;
969
+ fileName?: string;
970
+ message?: string;
971
+ error?: string;
972
+ errorCategory?: ErrorCategory;
973
+ metrics?: ExtractionMetrics;
974
+ }
975
+
976
+ /**
977
+ * Webhook payload for ad-hoc extraction
978
+ */
979
+ interface AdhocExtractionPayload {
980
+ fromDate?: string; // ISO 8601 UTC timestamp - extraction start
981
+ toDate?: string; // ISO 8601 UTC timestamp - extraction end
982
+ updateState?: boolean; // Whether to update last run timestamp
983
+ }
984
+
985
+ /**
986
+ * Webhook payload for job status query
987
+ */
988
+ interface JobStatusPayload {
989
+ jobId: string; // Job ID to query
990
+ }
991
+
992
+ // ============================================================================
993
+ // SECTION 2: WORKFLOW EXPORTS
994
+ // ============================================================================
995
+
996
+ /**
997
+ * WORKFLOW 1: Scheduled Extraction
998
+ *
999
+ * Runs: Every 4 hours (0 */4 * * *)
1000
+ * Purpose: Incremental extraction of updated fulfillments
1001
+ * State: Updates lastRunTime after successful extraction
1002
+ *
1003
+ * Behavior:
1004
+ * - Loads last run timestamp from KV storage
1005
+ * - Applies 60-second overlap buffer for clock skew
1006
+ * - Extracts records with updatedOn >= (lastRunTime - buffer)
1007
+ * - Generates XML and uploads to SFTP with retry
1008
+ * - Updates state with current timestamp
1009
+ */
1010
+ export const scheduledFulfillmentsExtraction = schedule(
1011
+ 'fulfillments-extract-xml-4hourly',
1012
+ '0 */4 * * *' // Every 4 hours at minute 0
1013
+ ).then(
1014
+ http('execute-scheduled-extraction', { connection: 'fluent_commerce' }, handleScheduledExtraction)
1015
+ );
1016
+
1017
+ /**
1018
+ * WORKFLOW 2: Ad-hoc Extraction
1019
+ *
1020
+ * Trigger: Webhook POST to /webhooks/fulfillments-adhoc
1021
+ * Purpose: On-demand extraction with custom date ranges
1022
+ * State: Optional - only updates if updateState: true in payload
1023
+ *
1024
+ * Payload Examples:
1025
+ *
1026
+ * 1. Extract last 7 days (no state update):
1027
+ * {
1028
+ * "fromDate": "2025-01-22T00:00:00Z",
1029
+ * "toDate": "2025-01-29T00:00:00Z"
1030
+ * }
1031
+ *
1032
+ * 2. Full re-extraction with state reset:
1033
+ * {
1034
+ * "fromDate": "2024-01-01T00:00:00Z",
1035
+ * "updateState": true
1036
+ * }
1037
+ *
1038
+ * Note: fromDate and toDate MUST be ISO 8601 UTC timestamps
1039
+ */
1040
+ export const adhocFulfillmentsExtraction = webhook('fulfillments-adhoc', {
1041
+ connection: 'fulfillments-adhoc', // Security via Versori connection
1042
+ response: { mode: 'sync' }, // ✅ Sync mode: response sent when handler returns
1043
+ }).then(http('execute-adhoc-extraction', { connection: 'fluent_commerce' }, handleAdhocExtraction));
1044
+
1045
+ /**
1046
+ * WORKFLOW 3: Job Status Query
1047
+ *
1048
+ * Trigger: Webhook GET/POST to /webhooks/fulfillments-job-status
1049
+ * Purpose: Check extraction job progress and results
1050
+ *
1051
+ * Query Payload:
1052
+ * {
1053
+ * "jobId": "SCHEDULED_FULFILLMENTS_20250129_120000_abc123"
1054
+ * }
1055
+ *
1056
+ * Response:
1057
+ * {
1058
+ * "success": true,
1059
+ * "jobId": "...",
1060
+ * "status": "completed",
1061
+ * "stage": "upload_complete",
1062
+ * "recordCount": 1250,
1063
+ * "fileName": "fulfillments_20250129_120000.xml",
1064
+ * "metrics": { ... }
1065
+ * }
1066
+ */
1067
+ export const fulfillmentsJobStatus = webhook('fulfillments-job-status', {
1068
+ connection: 'fulfillments-job-status', // Security via Versori connection
1069
+ response: { mode: 'sync' },
1070
+ }).then(fn('query-job-status', handleJobStatusQuery));
1071
+
1072
+ // ============================================================================
1073
+ // SECTION 3: WORKFLOW HANDLERS
1074
+ // ============================================================================
1075
+
1076
+ /**
1077
+ * Handle scheduled extraction workflow
1078
+ *
1079
+ * Always updates state for next incremental run
1080
+ */
1081
+ async function handleScheduledExtraction(ctx: Context): Promise<ExtractionResult> {
1082
+ const { log } = ctx;
1083
+ const jobId = generateJobId('SCHEDULED', 'FULFILLMENTS');
1084
+
1085
+ log.info('Scheduled extraction started', { jobId });
1086
+
1087
+ try {
1088
+ const result = await executeFulfillmentExtraction(ctx, {
1089
+ jobId,
1090
+ triggeredBy: 'schedule',
1091
+ updateState: true, // Always update state for scheduled runs
1092
+ });
1093
+
1094
+ log.info('Scheduled extraction completed', {
1095
+ jobId,
1096
+ success: result.success,
1097
+ recordCount: result.recordCount,
1098
+ errorCategory: result.errorCategory,
1099
+ });
1100
+
1101
+ return result;
1102
+ } catch (error: any) {
1103
+ log.error('Scheduled extraction failed', {
1104
+ jobId,
1105
+ message: error instanceof Error ? error.message : String(error),
1106
+ stack: error instanceof Error ? error.stack : undefined,
1107
+ errorType: error instanceof Error ? error.constructor.name : 'Error',
1108
+ });
1109
+ throw error;
1110
+ }
1111
+ }
1112
+
1113
+ /**
1114
+ * Handle ad-hoc extraction workflow
1115
+ *
1116
+ * Allows custom date ranges and optional state updates
1117
+ */
1118
+ async function handleAdhocExtraction(ctx: Context): Promise<{ success: boolean; jobId: string; message: string; statusEndpoint: string; note: string }> {
1119
+ const { data, log } = ctx;
1120
+ const payload = data as AdhocExtractionPayload;
1121
+ const jobId = generateJobId('ADHOC', 'FULFILLMENTS');
1122
+
1123
+ log.info('🚀 [WEBHOOK] Adhoc fulfillments extraction triggered', {
1124
+ jobId,
1125
+ fromDate: payload.fromDate || 'lastRunTime',
1126
+ toDate: payload.toDate || 'now',
1127
+ updateState: payload.updateState || false,
1128
+ });
1129
+
1130
+ // ✅ Fire-and-forget: Start background processing WITHOUT await
1131
+ // The promise continues execution after we return the response
1132
+ executeFulfillmentExtraction(ctx, {
1133
+ jobId,
1134
+ triggeredBy: 'webhook',
1135
+ fromDate: payload.fromDate,
1136
+ toDate: payload.toDate,
1137
+ updateState: payload.updateState === true,
1138
+ })
1139
+ .then((result) => {
1140
+ log.info('✅ [BACKGROUND] Fulfillments extraction completed successfully', {
1141
+ jobId,
1142
+ recordCount: result.recordCount,
1143
+ fileName: result.fileName,
1144
+ errorCategory: result.errorCategory,
1145
+ });
1146
+ })
1147
+ .catch((error: unknown) => {
1148
+ const errorMessage = error instanceof Error ? error.message : String(error);
1149
+ log.error('❌ [BACKGROUND] Fulfillments extraction failed', {
1150
+ jobId,
1151
+ error: errorMessage,
1152
+ stack: error instanceof Error ? error.stack : undefined,
1153
+ errorType: error instanceof Error ? error.constructor.name : typeof error,
1154
+ });
1155
+ });
1156
+
1157
+ // Return immediately with jobId (response sent with this return value)
1158
+ return {
1159
+ success: true,
1160
+ jobId,
1161
+ message: 'Fulfillments extraction started in background',
1162
+ statusEndpoint: `https://{workspace}.versori.run/fulfillments-job-status`,
1163
+ note: 'Poll the status endpoint with jobId to check progress',
1164
+ };
1165
+ }
1166
+
1167
+ /**
1168
+ * Handle job status query workflow
1169
+ *
1170
+ * Returns current job state from KV storage
1171
+ */
1172
+ async function handleJobStatusQuery(ctx: Context): Promise<any> {
1173
+ const { data, log, openKv } = ctx;
1174
+ const payload = data as JobStatusPayload;
1175
+
1176
+ if (!payload.jobId) {
1177
+ return {
1178
+ success: false,
1179
+ error: 'Job ID required',
1180
+ message: 'Provide jobId in request payload',
1181
+ };
1182
+ }
1183
+
1184
+ log.info('Job status query', { jobId: payload.jobId });
1185
+
1186
+ const status = await queryJobStatus(openKv(':project:'), payload.jobId, log);
1187
+
1188
+ if (!status) {
1189
+ return {
1190
+ success: false,
1191
+ error: 'Job not found',
1192
+ jobId: payload.jobId,
1193
+ message: 'Job may have been deleted or never existed',
1194
+ };
1195
+ }
1196
+
1197
+ return {
1198
+ success: true,
1199
+ jobId: payload.jobId,
1200
+ ...status,
1201
+ };
1202
+ }
1203
+ ```
1204
+
1205
+ ---
1206
+
1207
+ ## 📄 src/services/extraction-orchestration.ts
1208
+
1209
+ ```typescript
1210
+ import { Buffer } from 'node:buffer';
1211
+ import {
1212
+ createClient,
1213
+ ExtractionOrchestrator,
1214
+ JobTracker,
1215
+ UniversalMapper,
1216
+ XMLBuilder,
1217
+ SftpDataSource,
1218
+ } from '@fluentcommerce/fc-connect-sdk';
1219
+
1220
+ import mappingConfig from '../../config/fulfillments.export.xml.json' with { type: 'json' };
1221
+ import { FULFILLMENTS_QUERY } from '../config/queries';
1222
+
1223
+ type ErrorCategory = 'CONFIG' | 'API' | 'SFTP' | 'NO_DATA';
1224
+
1225
+ interface TimeWindow {
1226
+ from: string;
1227
+ to: string;
1228
+ bufferedFrom: string;
1229
+ }
1230
+
1231
+ interface ExtractionMetrics {
1232
+ totalPages: number;
1233
+ validRecords: number;
1234
+ skippedRecords: number;
1235
+ xmlSizeKb: number;
1236
+ window: TimeWindow;
1237
+ }
1238
+
1239
+ export interface FulfillmentExtractionParams {
1240
+ jobId: string;
1241
+ triggeredBy: 'schedule' | 'webhook';
1242
+ fromDate?: string;
1243
+ toDate?: string;
1244
+ updateState: boolean;
1245
+ fulfillmentStatuses?: string[];
1246
+ }
1247
+
1248
+ export interface FulfillmentExtractionResult {
1249
+ success: boolean;
1250
+ jobId: string;
1251
+ recordCount: number;
1252
+ fileName?: string;
1253
+ sftpPath?: string;
1254
+ message?: string;
1255
+ error?: string;
1256
+ errorCategory?: ErrorCategory;
1257
+ metrics?: ExtractionMetrics;
1258
+ }
1259
+
1260
+ interface FulfillmentLineItem {
1261
+ product_ref: string;
1262
+ requested_quantity: number | string;
1263
+ filled_quantity: number | string;
1264
+ }
1265
+
1266
+ const STATE_KEY = 'lastFulfillmentSync';
1267
+ const DEFAULT_FALLBACK = '2024-01-01T00:00:00Z';
1268
+ const STATUS_DELIMITER = ',';
1269
+
1270
+ function normalizeStatuses(input?: string[] | string | null): string[] | undefined {
1271
+ if (!input) {
1272
+ return undefined;
1273
+ }
1274
+
1275
+ const raw = Array.isArray(input) ? input : input.split(STATUS_DELIMITER);
1276
+ const cleaned = raw.map(status => status.trim()).filter(Boolean);
1277
+ return cleaned.length > 0 ? cleaned : undefined;
1278
+ }
1279
+
1280
+ function joinSftpPath(
1281
+ requireAbsolutePath: boolean,
1282
+ ...segments: Array<string | undefined>
1283
+ ): string {
1284
+ const sanitized = segments
1285
+ .filter(Boolean)
1286
+ .map(segment => String(segment).replace(/^\/+|\/+$/g, ''))
1287
+ .join('/');
1288
+
1289
+ if (!sanitized) {
1290
+ return requireAbsolutePath ? '/' : '';
1291
+ }
1292
+
1293
+ return requireAbsolutePath && !sanitized.startsWith('/') ? `/${sanitized}` : sanitized;
1294
+ }
1295
+
1296
+ export async function queryJobStatus(kv: any, jobId: string, log: any): Promise<any | undefined> {
1297
+ try {
1298
+ const tracker = new JobTracker(kv, log);
1299
+ return await tracker.getJob(jobId);
1300
+ } catch (error: any) {
1301
+ log.error('Failed to get job status', {
1302
+ jobId,
1303
+ message: error instanceof Error ? error.message : String(error),
1304
+ stack: error instanceof Error ? error.stack : undefined,
1305
+ errorType: error instanceof Error ? error.constructor.name : 'Error',
1306
+ });
1307
+ return undefined;
1308
+ }
1309
+ }
1310
+
1311
+ export async function executeFulfillmentExtraction(
1312
+ ctx: any,
1313
+ params: FulfillmentExtractionParams
1314
+ ): Promise<FulfillmentExtractionResult> {
1315
+ const { log, openKv, activation } = ctx;
1316
+ const { jobId, triggeredBy, fromDate, toDate, updateState } = params;
1317
+
1318
+ const kv = openKv(':project:');
1319
+ const tracker = new JobTracker(kv, log);
1320
+
1321
+ // Track execution duration
1322
+ const executionStartTime = Date.now();
1323
+
1324
+ const overlapBufferSeconds = parseInt(activation.getVariable('overlapBufferSeconds') || '60', 10);
1325
+ const fallbackStartDate = activation.getVariable('fallbackStartDate') || DEFAULT_FALLBACK;
1326
+ const isManualOverride = Boolean(fromDate);
1327
+ const shouldUpdateState = updateState === true;
1328
+
1329
+ try {
1330
+ log.info('🚀 [STEP 1/8] Initializing job tracking', { jobId, triggeredBy });
1331
+ await tracker.createJob(jobId, {
1332
+ triggeredBy,
1333
+ hasDateOverride: isManualOverride,
1334
+ updateStateAfterRun: shouldUpdateState,
1335
+ fromDate,
1336
+ toDate,
1337
+ });
1338
+
1339
+ log.info('📡 [STEP 2/8] Initializing Fluent Commerce client', { jobId });
1340
+ const client = await createClient(ctx, { validateConnection: true });
1341
+ if (!client) {
1342
+ throw new Error('Failed to create Fluent Commerce client');
1343
+ }
1344
+
1345
+ log.info('📅 [STEP 3/8] Determining date range for extraction', { jobId });
1346
+
1347
+ let rawState = fallbackStartDate;
1348
+ if (!isManualOverride) {
1349
+ try {
1350
+ const stored = await kv.get(STATE_KEY);
1351
+ if (typeof stored === 'string') {
1352
+ rawState = stored;
1353
+ } else if (stored?.timestamp) {
1354
+ rawState = stored.timestamp;
1355
+ }
1356
+ } catch {
1357
+ rawState = fallbackStartDate;
1358
+ }
1359
+ }
1360
+
1361
+ const overlapMs = overlapBufferSeconds * 1000;
1362
+ const queryFrom = isManualOverride
1363
+ ? fromDate!
1364
+ : new Date(Math.max(0, new Date(rawState).getTime() - overlapMs)).toISOString();
1365
+ const windowStart = isManualOverride ? (fromDate ?? queryFrom) : rawState;
1366
+ const windowEnd = toDate || new Date().toISOString();
1367
+
1368
+ const statusesInput =
1369
+ params.fulfillmentStatuses ?? activation.getVariable('fulfillmentStatuses');
1370
+ const fulfillmentStatuses = normalizeStatuses(statusesInput);
1371
+
1372
+ await tracker.updateJob(jobId, {
1373
+ stage: 'extraction',
1374
+ message: 'Extracting fulfillments with auto-pagination',
1375
+ status: 'processing',
1376
+ statuses: fulfillmentStatuses,
1377
+ });
1378
+
1379
+ const pageSize = parseInt(activation.getVariable('pageSize') || '200', 10);
1380
+ const maxRecords = parseInt(activation.getVariable('maxRecords') || '50000', 10);
1381
+
1382
+ log.info('📊 [STEP 4/8] Extracting fulfillments via GraphQL', {
1383
+ jobId,
1384
+ pageSize,
1385
+ maxRecords,
1386
+ queryFrom,
1387
+ windowEnd,
1388
+ statuses: fulfillmentStatuses,
1389
+ });
1390
+
1391
+ const orchestrator = new ExtractionOrchestrator(client, log);
1392
+
1393
+ // Extract context for progress logging
1394
+ const dateRangeInfo = {
1395
+ start: queryFrom || 'N/A',
1396
+ end: windowEnd || 'N/A',
1397
+ statuses: fulfillmentStatuses?.join(', ') || 'all'
1398
+ };
1399
+
1400
+ // Start logging with context
1401
+ log.info(`📥 [ExtractionOrchestrator] Starting extraction`, {
1402
+ query: 'fulfillments',
1403
+ pageSize,
1404
+ maxRecords,
1405
+ dateRange: `${dateRangeInfo.start} to ${dateRangeInfo.end}`,
1406
+ statuses: dateRangeInfo.statuses,
1407
+ jobId
1408
+ });
1409
+
1410
+ const extractionResult = await orchestrator.extract({
1411
+ query: FULFILLMENTS_QUERY,
1412
+ resultPath: 'fulfillments.edges.node',
1413
+ variables: {
1414
+ statuses: fulfillmentStatuses,
1415
+ updatedFrom: queryFrom,
1416
+ updatedTo: windowEnd,
1417
+ },
1418
+ pageSize,
1419
+ maxRecords,
1420
+ validateItem: (item: any) => Boolean(item?.ref && item?.order?.ref),
1421
+ });
1422
+
1423
+ const rawRecords = extractionResult.data || [];
1424
+ const extractionErrors = extractionResult.errors || [];
1425
+ const totalPages = extractionResult.stats.totalPages ?? 0;
1426
+
1427
+ log.info('✅ [STEP 4/8] Extraction complete', {
1428
+ jobId,
1429
+ totalPages,
1430
+ totalRecords: extractionResult.stats.totalRecords,
1431
+ validRecords: extractionResult.stats.validRecords ?? rawRecords.length,
1432
+ truncated: extractionResult.stats.truncated ?? false,
1433
+ errorCount: extractionErrors.length,
1434
+ });
1435
+
1436
+ // Completion logging with summary
1437
+ log.info(`✅ [ExtractionOrchestrator] Extraction completed`, {
1438
+ totalRecords: extractionResult.stats.totalRecords,
1439
+ totalPages,
1440
+ validRecords: extractionResult.stats.validRecords ?? rawRecords.length,
1441
+ failedValidations: extractionResult.stats.failedValidations,
1442
+ truncated: extractionResult.stats.truncated,
1443
+ truncationReason: extractionResult.stats.truncationReason,
1444
+ dateRange: `${dateRangeInfo.start} to ${dateRangeInfo.end}`,
1445
+ jobId
1446
+ });
1447
+
1448
+ if (extractionErrors.length > 0) {
1449
+ log.warn('[STEP 4/8] Non-fatal extraction errors detected', {
1450
+ jobId,
1451
+ sampleErrors: extractionErrors.slice(0, 3),
1452
+ });
1453
+ }
1454
+
1455
+ if (rawRecords.length === 0) {
1456
+ log.info('No fulfillments to process', { jobId });
1457
+
1458
+ if (shouldUpdateState) {
1459
+ await kv.set(STATE_KEY, {
1460
+ timestamp: windowEnd,
1461
+ updatedAt: new Date().toISOString(),
1462
+ recordCount: 0,
1463
+ triggeredBy,
1464
+ });
1465
+ }
1466
+
1467
+ await tracker.markCompleted(jobId, {
1468
+ recordCount: 0,
1469
+ message: 'No fulfillments to extract',
1470
+ stateUpdated: shouldUpdateState,
1471
+ window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1472
+ });
1473
+
1474
+ return {
1475
+ success: true,
1476
+ jobId,
1477
+ recordCount: 0,
1478
+ message: 'No fulfillments to extract',
1479
+ metrics: {
1480
+ totalPages,
1481
+ validRecords: 0,
1482
+ skippedRecords: 0,
1483
+ xmlSizeKb: 0,
1484
+ window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1485
+ },
1486
+ };
1487
+ }
1488
+
1489
+ log.info('🔄 [STEP 5/8] Transforming data with UniversalMapper', {
1490
+ jobId,
1491
+ recordCount: rawRecords.length,
1492
+ });
1493
+
1494
+ await tracker.updateJob(jobId, {
1495
+ stage: 'transformation',
1496
+ message: `Transforming ${rawRecords.length} fulfillments`,
1497
+ status: 'processing',
1498
+ });
1499
+
1500
+ const mapper = new UniversalMapper(mappingConfig);
1501
+ const mappingResult = await mapper.map(rawRecords);
1502
+ const mappingErrors = mappingResult.errors || [];
1503
+
1504
+ if (!mappingResult.success) {
1505
+ log.error('[STEP 5/8] Transformation failed', {
1506
+ jobId,
1507
+ errorCount: mappingErrors.length,
1508
+ sampleErrors: mappingErrors.slice(0, 3),
1509
+ });
1510
+
1511
+ await tracker.markFailed(jobId, 'UniversalMapper returned unsuccessful result', {
1512
+ failedCount: mappingErrors.length,
1513
+ errors: mappingErrors,
1514
+ });
1515
+
1516
+ return {
1517
+ success: false,
1518
+ jobId,
1519
+ recordCount: 0,
1520
+ error: `Transformation failed: ${mappingErrors[0] || 'Unknown error'}`,
1521
+ errorCategory: 'CONFIG',
1522
+ };
1523
+ }
1524
+
1525
+ const headerRecords: any[] = Array.isArray(mappingResult.data) ? mappingResult.data : [];
1526
+ const mappingErrors = mappingResult.errors || [];
1527
+
1528
+ if (mappingErrors.length > 0) {
1529
+ log.warn('[STEP 5/8] Some records failed transformation', {
1530
+ jobId,
1531
+ errorCount: mappingErrors.length,
1532
+ sampleErrors: mappingErrors.slice(0, 3),
1533
+ });
1534
+ }
1535
+
1536
+ if (mappingResult.skippedFields && mappingResult.skippedFields.length > 0) {
1537
+ log.info('ℹ️ [MAPPING] Optional fields skipped (undefined values)', {
1538
+ jobId,
1539
+ skippedFields: mappingResult.skippedFields,
1540
+ note: 'These fields were not present in source data. Add defaultValue to mapping config if they should always appear.',
1541
+ });
1542
+ }
1543
+
1544
+ const transformedRecords = headerRecords.map((record, index) => {
1545
+ const raw = rawRecords[index] ?? {};
1546
+ const lineItems: FulfillmentLineItem[] = ((raw.items?.edges ?? []) as any[])
1547
+ .map(edge => edge?.node)
1548
+ .filter(Boolean)
1549
+ .map((item: any) => ({
1550
+ product_ref: item.productRef ?? '',
1551
+ requested_quantity: item.requestedQuantity ?? '',
1552
+ filled_quantity: item.filledQuantity ?? '',
1553
+ }));
1554
+
1555
+ return {
1556
+ ...record,
1557
+ line_items: lineItems,
1558
+ };
1559
+ });
1560
+
1561
+ if (transformedRecords.length === 0) {
1562
+ await tracker.markFailed(jobId, 'All fulfillments failed mapping', {
1563
+ failedCount: mappingErrors.length,
1564
+ errors: mappingErrors,
1565
+ });
1566
+
1567
+ return {
1568
+ success: false,
1569
+ jobId,
1570
+ recordCount: 0,
1571
+ error: 'All records failed mapping',
1572
+ errorCategory: 'CONFIG',
1573
+ metrics: {
1574
+ totalPages,
1575
+ validRecords: 0,
1576
+ skippedRecords: rawRecords.length,
1577
+ xmlSizeKb: 0,
1578
+ window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1579
+ },
1580
+ };
1581
+ }
1582
+
1583
+ if (mappingErrors.length > 0) {
1584
+ log.warn('[STEP 5/8] Some fulfillments failed transformation', {
1585
+ jobId,
1586
+ errorCount: mappingErrors.length,
1587
+ sampleErrors: mappingErrors.slice(0, 3),
1588
+ });
1589
+ }
1590
+
1591
+ const totalLineItems = transformedRecords.reduce(
1592
+ (sum, record) => sum + record.line_items.length,
1593
+ 0
1594
+ );
1595
+
1596
+ log.info('📝 [STEP 6/8] Generating XML document', {
1597
+ jobId,
1598
+ fulfillmentCount: transformedRecords.length,
1599
+ lineItemCount: totalLineItems,
1600
+ });
1601
+
1602
+ await tracker.updateJob(jobId, {
1603
+ stage: 'xml_generation',
1604
+ message: `Generating XML for ${transformedRecords.length} fulfillments`,
1605
+ status: 'processing',
1606
+ });
1607
+
1608
+ const xmlBuilder = new XMLBuilder({
1609
+ prettyPrint: true,
1610
+ indent: ' ',
1611
+ xmlDeclaration: true,
1612
+ encoding: 'UTF-8',
1613
+ attributePrefix: '@',
1614
+ textKey: '#text',
1615
+ });
1616
+
1617
+ const xmlData = {
1618
+ Fulfillments: {
1619
+ Fulfillment: transformedRecords.map(record => {
1620
+ const lineItemNodes =
1621
+ record.line_items.length > 0
1622
+ ? {
1623
+ LineItem: record.line_items.map(item => ({
1624
+ product_ref: item.product_ref,
1625
+ requested_quantity: String(item.requested_quantity ?? ''),
1626
+ filled_quantity: String(item.filled_quantity ?? ''),
1627
+ })),
1628
+ }
1629
+ : undefined;
1630
+
1631
+ return {
1632
+ fulfillment_ref: record.fulfillment_ref,
1633
+ order_ref: record.order_ref,
1634
+ status: record.status,
1635
+ delivery_type: record.delivery_type ?? '',
1636
+ from_location_ref: record.from_location_ref ?? '',
1637
+ from_location_name: record.from_location_name ?? '',
1638
+ created_on: record.created_on,
1639
+ updated_on: record.updated_on,
1640
+ ...(lineItemNodes ? { LineItems: lineItemNodes } : {}),
1641
+ };
1642
+ }),
1643
+ },
1644
+ };
1645
+
1646
+ const xmlString = xmlBuilder.build(xmlData, 'Fulfillments');
1647
+ const xmlBuffer = Buffer.from(xmlString, 'utf8');
1648
+ const xmlSizeKb = Math.round(xmlBuffer.length / 1024);
1649
+
1650
+ const fileNamePrefix = activation.getVariable('fileNamePrefix') || 'fulfillments';
1651
+ const timestampSuffix = new Date().toISOString().replace(/[:.]/g, '-');
1652
+ const fileName = `${fileNamePrefix}-${timestampSuffix}.xml`;
1653
+
1654
+ log.info('📤 [STEP 7/8] Preparing SFTP upload', { jobId, fileName });
1655
+
1656
+ await tracker.updateJob(jobId, {
1657
+ stage: 'sftp_upload',
1658
+ message: `Uploading ${fileName} to SFTP`,
1659
+ status: 'processing',
1660
+ });
1661
+
1662
+ const sftpHost = activation.getVariable('sftpHost');
1663
+ const sftpPort = parseInt(activation.getVariable('sftpPort') || '22', 10);
1664
+ const sftpRemotePath = activation.getVariable('sftpRemotePath') || '/incoming/fulfillments/';
1665
+ const sftpPrivateKey = activation.getVariable('sftpPrivateKey');
1666
+ const requireAbsolutePaths = activation.getVariable('requireAbsolutePaths') === 'true';
1667
+
1668
+ if (!sftpHost) {
1669
+ throw new Error('SFTP configuration incomplete: sftpHost activation variable missing');
1670
+ }
1671
+
1672
+ const allConnections = activation.connections || [];
1673
+ const sftpConnection = allConnections.find((conn: any) => conn.name === 'sftp_export_server');
1674
+ if (!sftpConnection) {
1675
+ throw new Error('SFTP connection "sftp_export_server" not found');
1676
+ }
1677
+
1678
+ const credential = sftpConnection.credentials?.[0]?.credential;
1679
+ if (!credential?.data?.basicAuth) {
1680
+ throw new Error('SFTP connection not configured with Basic Authentication');
1681
+ }
1682
+
1683
+ const { username, password } = credential.data.basicAuth;
1684
+
1685
+ const sftp = new SftpDataSource(
1686
+ {
1687
+ type: 'SFTP_XML',
1688
+ connectionId: 'sftp_export_server',
1689
+ name: 'Fulfillments XML Export',
1690
+ settings: {
1691
+ host: sftpHost,
1692
+ port: sftpPort,
1693
+ username,
1694
+ password,
1695
+ privateKey: sftpPrivateKey,
1696
+ remotePath: sftpRemotePath,
1697
+ filePattern: '*.xml',
1698
+ requireAbsolutePaths,
1699
+ },
1700
+ },
1701
+ log
1702
+ );
1703
+
1704
+ const fullPath = joinSftpPath(requireAbsolutePaths, sftpRemotePath, fileName);
1705
+
1706
+ try {
1707
+ await sftp.uploadFile(fullPath, xmlBuffer, {
1708
+ createDirectories: true,
1709
+ overwrite: true,
1710
+ });
1711
+
1712
+ if (mappingErrors.length > 0) {
1713
+ const reportPayload = {
1714
+ fileName,
1715
+ processedAt: new Date().toISOString(),
1716
+ failedRecords: mappingErrors.length,
1717
+ sampleErrors: mappingErrors.slice(0, 10),
1718
+ };
1719
+
1720
+ const reportPath = joinSftpPath(
1721
+ requireAbsolutePaths,
1722
+ sftpRemotePath,
1723
+ `${fileName.replace(/\.xml$/i, '')}-errors.json`
1724
+ );
1725
+
1726
+ await sftp.uploadFile(
1727
+ reportPath,
1728
+ Buffer.from(JSON.stringify(reportPayload, null, 2), 'utf8'),
1729
+ {
1730
+ createDirectories: true,
1731
+ overwrite: true,
1732
+ }
1733
+ );
1734
+
1735
+ log.warn('Uploaded transformation error report', { jobId, reportPath });
1736
+ }
1737
+ } finally {
1738
+ await sftp.dispose();
1739
+ log.info('SFTP connection disposed', { jobId });
1740
+ }
1741
+
1742
+ log.info('💾 [STEP 8/8] Updating state and completing job', { jobId });
1743
+
1744
+ const newTimestamp = (() => {
1745
+ const maxUpdated = rawRecords.reduce((max, record) => {
1746
+ const current = new Date(record.updatedOn || windowEnd).getTime();
1747
+ return current > max ? current : max;
1748
+ }, new Date(windowStart).getTime());
1749
+ return new Date(maxUpdated).toISOString();
1750
+ })();
1751
+
1752
+ if (shouldUpdateState) {
1753
+ await kv.set(STATE_KEY, {
1754
+ timestamp: newTimestamp,
1755
+ updatedAt: new Date().toISOString(),
1756
+ recordCount: transformedRecords.length,
1757
+ lineItemCount: totalLineItems,
1758
+ fileName,
1759
+ sftpPath: fullPath,
1760
+ statuses: fulfillmentStatuses ?? [],
1761
+ });
1762
+ }
1763
+
1764
+ const executionDurationMs = Date.now() - executionStartTime;
1765
+
1766
+ await tracker.markCompleted(jobId, {
1767
+ recordCount: transformedRecords.length,
1768
+ lineItemCount: totalLineItems,
1769
+ fileName,
1770
+ remotePath: fullPath,
1771
+ errorCount: mappingErrors.length,
1772
+ errors: mappingErrors,
1773
+ stateUpdated: shouldUpdateState,
1774
+ window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1775
+ durationMs: executionDurationMs,
1776
+ });
1777
+
1778
+ log.info('✅ Extraction completed successfully', {
1779
+ jobId,
1780
+ recordCount: transformedRecords.length,
1781
+ durationMs: executionDurationMs,
1782
+ durationSeconds: (executionDurationMs / 1000).toFixed(2),
1783
+ });
1784
+
1785
+ return {
1786
+ success: true,
1787
+ jobId,
1788
+ recordCount: transformedRecords.length,
1789
+ fileName,
1790
+ sftpPath: fullPath,
1791
+ message: `Uploaded ${transformedRecords.length} fulfillments`,
1792
+ metrics: {
1793
+ totalPages,
1794
+ validRecords: transformedRecords.length,
1795
+ skippedRecords: mappingErrors.length,
1796
+ xmlSizeKb,
1797
+ window: { from: windowStart, to: windowEnd, bufferedFrom: queryFrom },
1798
+ },
1799
+ };
1800
+ } catch (error: any) {
1801
+ const errorMessage = error instanceof Error ? error.message : String(error);
1802
+
1803
+ log.error('❌ Fulfillment extraction failed', {
1804
+ jobId,
1805
+ message: errorMessage,
1806
+ stack: error instanceof Error ? error.stack : undefined,
1807
+ errorType: error instanceof Error ? error.constructor.name : 'Error',
1808
+ });
1809
+
1810
+ // Determine error category and recommendation
1811
+ let errorCategory: ErrorCategory = 'API';
1812
+ let recommendation = '';
1813
+
1814
+ if (errorMessage.includes('SFTP') || errorMessage.includes('connection')) {
1815
+ errorCategory = 'SFTP';
1816
+ recommendation = 'Check SFTP credentials and network connectivity. Verify host, port, and authentication settings in activation variables.';
1817
+ } else if (errorMessage.includes('mapping') || errorMessage.includes('transformation')) {
1818
+ errorCategory = 'CONFIG';
1819
+ recommendation = 'Review mapping configuration in config/fulfillments.export.xml.json. Verify all source paths match GraphQL response structure.';
1820
+ } else if (errorMessage.includes('GraphQL') || errorMessage.includes('query')) {
1821
+ errorCategory = 'API';
1822
+ recommendation = 'Verify Fluent Commerce API credentials and GraphQL query syntax. Check if the query matches the current schema.';
1823
+ } else if (errorMessage.includes('No records') || errorMessage.includes('empty')) {
1824
+ errorCategory = 'NO_DATA';
1825
+ recommendation = 'No fulfillments found in the specified date range. This may be expected if there are no recent updates.';
1826
+ }
1827
+
1828
+ await tracker.markFailed(jobId, {
1829
+ error: errorMessage,
1830
+ errorCategory,
1831
+ recommendation,
1832
+ triggeredBy,
1833
+ });
1834
+
1835
+ return {
1836
+ success: false,
1837
+ jobId,
1838
+ recordCount: 0,
1839
+ error: errorMessage,
1840
+ errorCategory,
1841
+ details: {
1842
+ recommendation,
1843
+ errorType: error instanceof Error ? error.constructor.name : 'Error',
1844
+ },
1845
+ };
1846
+ }
1847
+ }
1848
+ ```
1849
+
1850
+ ---
1851
+
1852
+ ## 📄 src/config/queries.ts
1853
+
1854
+ ```typescript
1855
+ // ============================================================================
1856
+ // GRAPHQL QUERIES AND MAPPING CONFIGURATION
1857
+ // ============================================================================
1858
+
1859
+ import mappingConfig from '../../config/fulfillments.export.xml.json' with { type: 'json' };
1860
+
1861
+ /**
1862
+ * GraphQL query for fulfillments extraction
1863
+ *
1864
+ * Supports:
1865
+ * - Pagination (first, after)
1866
+ * - Date range filtering (updatedOn) - UTC timestamps required
1867
+ * - Status filtering (statuses)
1868
+ */
1869
+ export const FULFILLMENTS_QUERY = `
1870
+ query GetFulfillments(
1871
+ $statuses: [String!]
1872
+ $updatedFrom: DateTime
1873
+ $updatedTo: DateTime
1874
+ $first: Int!
1875
+ $after: String
1876
+ ) {
1877
+ fulfillments(
1878
+ status: $statuses
1879
+ updatedOn: { from: $updatedFrom, to: $updatedTo }
1880
+ first: $first
1881
+ after: $after
1882
+ ) {
1883
+ edges {
1884
+ node {
1885
+ id
1886
+ ref
1887
+ status
1888
+ deliveryType
1889
+ order {
1890
+ ref
1891
+ }
1892
+ fromLocation {
1893
+ ref
1894
+ name
1895
+ }
1896
+ items {
1897
+ edges {
1898
+ node {
1899
+ productRef
1900
+ requestedQuantity
1901
+ filledQuantity
1902
+ }
1903
+ }
1904
+ }
1905
+ createdOn
1906
+ updatedOn
1907
+ }
1908
+ cursor
1909
+ }
1910
+ pageInfo {
1911
+ hasNextPage
1912
+ # Note: Fluent doesn't return endCursor - cursors are in edges[].cursor
1913
+ }
1914
+ }
1915
+ }
1916
+ `;
1917
+
1918
+ /**
1919
+ * Field mapping configuration loaded from JSON file
1920
+ *
1921
+ * Location: config/fulfillments.export.xml.json
1922
+ */
1923
+ export const FULFILLMENTS_EXPORT_MAPPING = mappingConfig;
1924
+ ```
1925
+
1926
+ ---
1927
+
1928
+ ## Testing
1929
+
1930
+ ### Test Scheduled Extraction
1931
+
1932
+ The scheduled workflow runs automatically every 4 hours.
1933
+
1934
+ **Check logs:**
1935
+
1936
+ ```
1937
+ [STEP 1/10] Loading and validating configuration
1938
+ [STEP 2/10] Initializing job tracker
1939
+ [STEP 3/10] Calculating extraction time window
1940
+ [STEP 4/10] Initializing SDK services
1941
+ [STEP 5/10] Extracting fulfillments from Fluent
1942
+ [STEP 6/10] Transforming records with UniversalMapper
1943
+ [STEP 7/10] Generating XML file
1944
+ [STEP 8/10] Uploading XML to SFTP
1945
+ [STEP 9/10] Updating extraction state
1946
+ [STEP 10/10] Finalizing job
1947
+ ```
1948
+
1949
+ ### Test Ad-hoc Extraction
1950
+
1951
+ ```bash
1952
+ # Incremental (uses last sync timestamp)
1953
+ curl -X POST https://api.versori.com/webhooks/fulfillments-adhoc \
1954
+ -H "Content-Type: application/json" \
1955
+ -d '{}'
1956
+
1957
+ # Date range override
1958
+ curl -X POST https://api.versori.com/webhooks/fulfillments-adhoc \
1959
+ -H "Content-Type: application/json" \
1960
+ -d '{
1961
+ "fromDate": "2025-01-01T00:00:00Z",
1962
+ "toDate": "2025-01-31T23:59:59Z",
1963
+ "updateState": false
1964
+ }'
1965
+ ```
1966
+
1967
+ ### Test Job Status Query
1968
+
1969
+ ```bash
1970
+ curl -X POST https://api.versori.com/webhooks/fulfillments-job-status \
1971
+ -H "Content-Type: application/json" \
1972
+ -d '{
1973
+ "jobId": "ADHOC_FULFILLMENTS_20251027_183045_abc123"
1974
+ }'
1975
+ ```
1976
+
1977
+ **Response:**
1978
+
1979
+ ```json
1980
+ {
1981
+ "success": true,
1982
+ "jobId": "ADHOC_FULFILLMENTS_20251027_183045_abc123",
1983
+ "status": "processing",
1984
+ "stage": "transformation",
1985
+ "message": "Transforming 150 records",
1986
+ "createdAt": "2025-10-27T18:30:45.000Z",
1987
+ "startedAt": "2025-10-27T18:30:46.000Z"
1988
+ }
1989
+ ```
1990
+
1991
+ ---
1992
+
1993
+ ## Next Steps
1994
+
1995
+ 1. **Review Configuration:** Verify all activation variables match your environment
1996
+ 2. **Test with Sample Data:** Run ad-hoc extraction with small date range
1997
+ 3. **Validate XML Output:** Check SFTP server for correctly formatted files
1998
+ 4. **Enable Schedule:** Activate 4-hourly schedule after successful test
1999
+ 5. **Monitor Jobs:** Use job status webhook to track extraction progress
2000
+ 6. **Adjust Filters:** Customize status filters and date ranges as needed
2001
+ 7. **Scale:** Increase page size and max records based on data volume
2002
+
2003
+ ---
2004
+
2005
+ ## Testing Checklist
2006
+
2007
+ **Before production deployment:**
2008
+
2009
+ ### 1. Schema Validation
2010
+
2011
+ - [ ] Run `npx fc-connect introspect-schema --url <your-graphql-url>`
2012
+ - [ ] Run `npx fc-connect validate-schema --mapping ./config/fulfillments.export.xml.json --schema ./fluent-schema.json`
2013
+ - [ ] Run `npx fc-connect analyze-coverage --mapping ./config/fulfillments.export.xml.json --schema ./fluent-schema.json`
2014
+ - [ ] Verify all `source` paths in mapping exist in GraphQL schema
2015
+ - [ ] Verify query structure matches schema (fields, types, filters)
2016
+
2017
+ ### 2. Extraction Testing
2018
+
2019
+ - [ ] Test with small dataset first (maxRecords=10)
2020
+ - [ ] Verify ExtractionOrchestrator pagination works correctly
2021
+ - [ ] Test with multiple pages of data (verify cursor handling)
2022
+ - [ ] Verify date range filtering (updatedOn filter)
2023
+ - [ ] Test empty result handling (no records in date range)
2024
+ - [ ] Verify extraction stops at maxRecords limit
2025
+
2026
+ ### 3. Mapping Testing
2027
+
2028
+ - [ ] Verify required fields are populated
2029
+ - [ ] Verify SDK resolvers work correctly (sdk.trim, sdk.parseInt, sdk.formatDate, etc.)
2030
+ - [ ] Test custom resolvers with edge cases (if any)
2031
+ - [ ] Verify nested field extraction
2032
+ - [ ] Test with null/missing fields
2033
+ - [ ] Verify mapping error collection works
2034
+
2035
+ ### 4. XML Generation Testing
2036
+
2037
+ - [ ] Verify XML structure matches expected format
2038
+ - [ ] Test XML validation against XSD schema (if applicable)
2039
+ - [ ] Verify special character escaping in XML
2040
+ - [ ] Test with large datasets (>1000 records)
2041
+ - [ ] Verify UTF-8 encoding
2042
+ - [ ] Test XML namespace handling (if applicable)
2043
+
2044
+ ### 5. SFTP Upload Testing
2045
+
2046
+ - [ ] Test SFTP connection and authentication
2047
+ - [ ] Verify file upload to correct path
2048
+ - [ ] Test file naming convention (timestamp format)
2049
+ - [ ] Verify file permissions on SFTP server
2050
+ - [ ] Test upload retry logic (simulate network failure)
2051
+ - [ ] Verify SFTP connection disposal (no connection leaks)
2052
+
2053
+ ### 6. State Management Testing
2054
+
2055
+ - [ ] Verify overlap buffer prevents missed records (60-second default)
2056
+ - [ ] Test state recovery after extraction failure
2057
+ - [ ] Verify timestamp saved WITHOUT buffer (MAX(updatedOn))
2058
+ - [ ] Test first run with no previous state (uses fallbackStartDate)
2059
+ - [ ] Verify state update only happens on successful upload
2060
+ - [ ] Test manual date override (doesn't update state)
2061
+
2062
+ ### 7. Job Tracking Testing
2063
+
2064
+ - [ ] Test job creation with JobTracker
2065
+ - [ ] Verify job status updates at each stage
2066
+ - [ ] Test job completion with metadata
2067
+ - [ ] Test job failure handling
2068
+ - [ ] Query job status via webhook endpoint
2069
+ - [ ] Verify job status persists in KV store
2070
+
2071
+ ### 8. Error Handling Testing
2072
+
2073
+ - [ ] Test with invalid GraphQL query
2074
+ - [ ] Test with mapping errors (invalid field paths)
2075
+ - [ ] Test with SFTP connection failures
2076
+ - [ ] Test with authentication failures
2077
+ - [ ] Test with network timeouts
2078
+ - [ ] Verify error logging includes context (jobId, stage, error details)
2079
+ - [ ] Test error threshold logic (if applicable)
2080
+
2081
+ ### 9. Staging Environment Testing
2082
+
2083
+ - [ ] Run full extraction in staging environment
2084
+ - [ ] Verify XML file format with downstream system
2085
+ - [ ] Monitor extraction duration and resource usage
2086
+ - [ ] Test with production-like data volumes
2087
+ - [ ] Verify no performance degradation over time
2088
+
2089
+ ### 10. Integration Testing
2090
+
2091
+ - [ ] Test scheduled workflow (cron trigger)
2092
+ - [ ] Test ad hoc webhook trigger
2093
+ - [ ] Test job status query webhook
2094
+ - [ ] Verify activation variables are read correctly
2095
+ - [ ] Test with different extraction modes (incremental, date range)
2096
+ - [ ] End-to-end test: trigger → extract → transform → upload → verify file
2097
+
2098
+ ---
2099
+ ## Monitoring & Alerting
2100
+
2101
+ ### Success Response Example
2102
+
2103
+ ```json
2104
+ {
2105
+ "success": true,
2106
+ "jobId": "SCHEDULED_FUL_20251102_140000_abc123",
2107
+ "recordsExtracted": 1523,
2108
+ "fileName": "fulfillments-2025-11-02T14-00-00-000Z.xml",
2109
+ "sftpPath": "/outbound/fulfillments/fulfillments-2025-11-02T14-00-00-000Z.xml",
2110
+ "metrics": {
2111
+ "extractionDurationMs": 12543,
2112
+ "totalPages": 8,
2113
+ "pageSize": 200,
2114
+ "mappingErrors": 0,
2115
+ "fileSizeBytes": 524288,
2116
+ "uploadDurationMs": 1234
2117
+ },
2118
+ "timestamps": {
2119
+ "extractionStart": "2025-11-02T14:00:00.000Z",
2120
+ "extractionEnd": "2025-11-02T14:00:12.543Z",
2121
+ "uploadComplete": "2025-11-02T14:00:13.777Z"
2122
+ },
2123
+ "state": {
2124
+ "previousTimestamp": "2025-11-02T13:00:00.000Z",
2125
+ "newTimestamp": "2025-11-02T13:59:58.123Z",
2126
+ "stateUpdated": true,
2127
+ "overlapBufferSeconds": 60
2128
+ }
2129
+ }
2130
+ ```
2131
+
2132
+ ### Error Response Example
2133
+
2134
+ ```json
2135
+ {
2136
+ "success": false,
2137
+ "jobId": "ADHOC_FUL_20251102_140500_xyz789",
2138
+ "error": "SFTP upload failed: Connection timeout",
2139
+ "errorCategory": "NETWORK",
2140
+ "recordsExtracted": 0,
2141
+ "stage": "sftp_upload",
2142
+ "details": {
2143
+ "message": "Failed to upload file after 3 retry attempts",
2144
+ "retryAttempts": 3,
2145
+ "lastError": "ETIMEDOUT: Connection timed out after 30000ms"
2146
+ },
2147
+ "state": {
2148
+ "stateUpdated": false,
2149
+ "willRetryNextRun": true,
2150
+ "note": "State not advanced - next extraction will retry same time window"
2151
+ }
2152
+ }
2153
+ ```
2154
+
2155
+ ### Key Metrics to Track
2156
+
2157
+ ```typescript
2158
+ const METRICS = {
2159
+ // Extraction Performance
2160
+ extractionDurationMs: Date.now() - extractionStart,
2161
+ recordCount: records.length,
2162
+ pageCount: extractionResult.stats.totalPages,
2163
+ avgRecordsPerPage: records.length / extractionResult.stats.totalPages,
2164
+
2165
+ // Transformation Performance
2166
+ transformedCount: transformedRecords.length,
2167
+ failedCount: mappingErrors.length,
2168
+ errorRate: ((mappingErrors.length / records.length) * 100).toFixed(2) + '%',
2169
+
2170
+ // File Generation
2171
+ fileSizeMB: (xmlContent.length / (1024 * 1024)).toFixed(2),
2172
+
2173
+ // Upload Performance
2174
+ uploadDurationMs: uploadEnd - uploadStart,
2175
+ uploadSpeedMBps: (fileSizeMB / (uploadDurationMs / 1000)).toFixed(2),
2176
+
2177
+ // State Management
2178
+ timeSinceLastRun: Date.now() - new Date(lastTimestamp).getTime(),
2179
+ recordsPerMinute: (records.length / (extractionDurationMs / 60000)).toFixed(0),
2180
+ };
2181
+
2182
+ log.info('Extraction metrics', metrics);
2183
+ ```
2184
+
2185
+ ### Alert Thresholds
2186
+
2187
+ ```typescript
2188
+ const ALERT_THRESHOLDS = {
2189
+ // Duration Alerts
2190
+ EXTRACTION_DURATION_MS: 5 * 60 * 1000, // 5 minutes
2191
+ UPLOAD_DURATION_MS: 2 * 60 * 1000, // 2 minutes
2192
+ TOTAL_DURATION_MS: 10 * 60 * 1000, // 10 minutes
2193
+
2194
+ // Error Rate Alerts
2195
+ MAX_ERROR_RATE: 0.05, // 5% mapping errors
2196
+ MAX_VALIDATION_FAILURES: 0.02, // 2% validation failures
2197
+
2198
+ // Volume Alerts
2199
+ MAX_RECORDS_PER_RUN: 100000,
2200
+ MIN_RECORDS_WARNING: 0, // Alert if no records found
2201
+ MAX_FILE_SIZE_MB: 150, // 150MB
2202
+
2203
+ // State Alerts
2204
+ MAX_TIME_SINCE_LAST_RUN_HOURS: 25, // Alert if >25 hours (should run hourly)
2205
+ MAX_OVERLAP_BUFFER_SECONDS: 300, // Alert if buffer >5 minutes
2206
+ };
2207
+
2208
+ // Check thresholds
2209
+ if (metrics.extractionDurationMs > ALERT_THRESHOLDS.EXTRACTION_DURATION_MS) {
2210
+ log.warn('Extraction duration exceeded threshold', {
2211
+ duration: metrics.extractionDurationMs,
2212
+ threshold: ALERT_THRESHOLDS.EXTRACTION_DURATION_MS,
2213
+ recommendation: 'Consider reducing maxRecords or increasing extraction frequency'
2214
+ });
2215
+ }
2216
+ ```
2217
+
2218
+ ### Monitoring Dashboard Queries
2219
+
2220
+ **Versori Platform Logs Query:**
2221
+
2222
+ ```
2223
+ # Successful extractions
2224
+ log_level:info AND message:"Extraction complete" AND jobId:*
2225
+
2226
+ # Failed extractions
2227
+ log_level:error AND message:"Extraction workflow failed" AND jobId:*
2228
+
2229
+ # Performance issues
2230
+ extractionDurationMs:>300000 OR uploadDurationMs:>120000
2231
+
2232
+ # High error rates
2233
+ errorRate:>5
2234
+
2235
+ # State management issues
2236
+ stateUpdated:false AND success:true
2237
+ ```
2238
+
2239
+ ### Common Issues and Solutions
2240
+
2241
+ **Issue**: "Extraction timeout after 10 minutes"
2242
+
2243
+ - **Cause**: Too many records in single extraction
2244
+ - **Fix**: Reduce maxRecords, increase extraction frequency, or optimize query filters
2245
+ - **Prevention**: Monitor recordCount trends, set appropriate maxRecords
2246
+
2247
+ **Issue**: "Mapping errors for 50% of records"
2248
+
2249
+ - **Cause**: Schema mismatch between GraphQL response and mapping config
2250
+ - **Fix**: Run schema validation, update mapping config paths
2251
+ - **Prevention**: Use `npx fc-connect validate-schema` before deployment
2252
+
2253
+ **Issue**: "SFTP connection timeout"
2254
+
2255
+ - **Cause**: Network issues, firewall, or connection pool exhaustion
2256
+ - **Fix**: Check SFTP credentials, verify network connectivity
2257
+ - **Prevention**: Implement connection health checks, monitor connection status
2258
+
2259
+ **Issue**: "State not updating after successful extraction"
2260
+
2261
+ - **Cause**: KV write failure or intentional retry logic
2262
+ - **Fix**: Check KV logs, verify state update code executed
2263
+ - **Prevention**: Add KV write verification, log state updates explicitly
2264
+
2265
+ **Issue**: "First run exceeds record limits"
2266
+
2267
+ - **Cause**: No previous timestamp, fetches all historical records
2268
+ - **Fix**: Set fallbackStartDate close to current date, apply additional filters
2269
+ - **Prevention**: Use appropriate fallbackStartDate for initial runs
2270
+
2271
+ **Issue**: "Excessive duplicate records in output"
2272
+
2273
+ - **Cause**: Overlap buffer (expected) or timestamp not saved correctly
2274
+ - **Fix**: Verify newTimestamp saved WITHOUT buffer, check state persistence
2275
+ - **Prevention**: Monitor duplicate rates, verify state update logic
2276
+
2277
+ ---
2278
+
2279
+ ## Troubleshooting Quick Reference
2280
+
2281
+ | Error Message | Likely Cause | Solution |
2282
+ |--------------|--------------|----------|
2283
+ | "Failed to create Fluent Commerce client" | Authentication failure | Check OAuth2 credentials, verify connection config |
2284
+ | "GraphQL query validation error" | Invalid query syntax | Validate query against schema with introspection tool |
2285
+ | "Pagination cursor invalid" | Stale cursor or query change | Reset extraction, verify cursor handling in query |
2286
+ | "Mapping failed: field not found" | Schema mismatch | Run schema validation, update mapping paths |
2287
+ | "SFTP authentication failed" | Invalid credentials | Verify SFTP credentials in activation variables |
2288
+ | "Connection pool exhausted" | Too many concurrent requests | Reduce concurrency, increase pool size |
2289
+ | "KV operation failed" | Versori KV issue | Check Versori platform status, retry operation |
2290
+ | "Job status not found" | Invalid jobId or expired | Verify jobId format, check KV retention policy |
2291
+ | "Memory limit exceeded" | Dataset too large | Reduce maxRecords, enable streaming mode |
2292
+ | "XML generation failed" | Format-specific error | Check XML generation logic, validate output |
2293
+
2294
+ ---