@fluentcommerce/fc-connect-sdk 0.1.54 β†’ 0.1.56

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 (476) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +11 -0
  3. package/dist/cjs/clients/fluent-client.js +13 -6
  4. package/dist/cjs/utils/pagination-helpers.js +38 -2
  5. package/dist/cjs/versori/fluent-versori-client.js +11 -5
  6. package/dist/esm/clients/fluent-client.js +13 -6
  7. package/dist/esm/utils/pagination-helpers.js +38 -2
  8. package/dist/esm/versori/fluent-versori-client.js +11 -5
  9. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  10. package/dist/tsconfig.tsbuildinfo +1 -1
  11. package/dist/tsconfig.types.tsbuildinfo +1 -1
  12. package/docs/00-START-HERE/EXPORT-VALIDATION.md +158 -158
  13. package/docs/00-START-HERE/cli-analyze-source-structure-guide.md +655 -655
  14. package/docs/00-START-HERE/cli-documentation-index.md +202 -202
  15. package/docs/00-START-HERE/cli-quick-reference.md +252 -252
  16. package/docs/00-START-HERE/decision-tree.md +552 -552
  17. package/docs/00-START-HERE/getting-started.md +1070 -1070
  18. package/docs/00-START-HERE/mapper-quick-decision-guide.md +235 -235
  19. package/docs/00-START-HERE/readme.md +237 -237
  20. package/docs/00-START-HERE/retailerid-configuration.md +404 -404
  21. package/docs/00-START-HERE/sdk-philosophy.md +794 -794
  22. package/docs/00-START-HERE/troubleshooting-quick-reference.md +1086 -1086
  23. package/docs/01-TEMPLATES/faq.md +686 -686
  24. package/docs/01-TEMPLATES/patterns/pattern-templates-guide.md +68 -68
  25. package/docs/01-TEMPLATES/patterns/patterns-csv-schema-validation-and-rejection-report.md +233 -233
  26. package/docs/01-TEMPLATES/patterns/patterns-custom-resolvers.md +407 -407
  27. package/docs/01-TEMPLATES/patterns/patterns-error-handling-retry.md +511 -511
  28. package/docs/01-TEMPLATES/patterns/patterns-field-mapping-universal.md +701 -701
  29. package/docs/01-TEMPLATES/patterns/patterns-large-file-splitting.md +1430 -1430
  30. package/docs/01-TEMPLATES/patterns/patterns-master-data-etl.md +2399 -2399
  31. package/docs/01-TEMPLATES/patterns/patterns-pagination-streaming.md +447 -447
  32. package/docs/01-TEMPLATES/patterns/patterns-state-duplicate-prevention.md +385 -385
  33. package/docs/01-TEMPLATES/readme.md +957 -957
  34. package/docs/01-TEMPLATES/standalone/standalone-asn-inbound-processing.md +1209 -1209
  35. package/docs/01-TEMPLATES/standalone/standalone-graphql-query-export.md +1140 -1140
  36. package/docs/01-TEMPLATES/standalone/standalone-graphql-to-parquet-partitioned-s3.md +432 -432
  37. package/docs/01-TEMPLATES/standalone/standalone-multi-channel-inventory-sync.md +1185 -1185
  38. package/docs/01-TEMPLATES/standalone/standalone-multi-source-aggregation.md +1462 -1462
  39. package/docs/01-TEMPLATES/standalone/standalone-s3-csv-batch-api.md +1390 -1390
  40. package/docs/01-TEMPLATES/standalone/standalone-s3-csv-inventory-to-batch.md +330 -330
  41. package/docs/01-TEMPLATES/standalone/standalone-scripts-guide.md +87 -87
  42. package/docs/01-TEMPLATES/standalone/standalone-sftp-xml-graphql.md +1444 -1444
  43. package/docs/01-TEMPLATES/standalone/standalone-webhook-payload-processing.md +688 -688
  44. package/docs/01-TEMPLATES/versori/business-examples/business-examples-dropship-order-routing.md +193 -193
  45. package/docs/01-TEMPLATES/versori/business-examples/business-examples-graphql-parquet-extraction.md +518 -518
  46. package/docs/01-TEMPLATES/versori/business-examples/business-examples-inter-location-transfers.md +2162 -2162
  47. package/docs/01-TEMPLATES/versori/business-examples/business-examples-pre-order-allocation.md +2226 -2226
  48. package/docs/01-TEMPLATES/versori/business-examples/business-scenarios-guide.md +87 -87
  49. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-connection-validation-pattern.md +656 -656
  50. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-dual-workflow-connector.md +835 -835
  51. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-guide.md +108 -108
  52. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-kv-state-management.md +1533 -1533
  53. package/docs/01-TEMPLATES/versori/patterns/versori-patterns-xml-response-patterns.md +1160 -1160
  54. package/docs/01-TEMPLATES/versori/versori-platform-guide.md +201 -201
  55. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-asn-purchase-order.md +1906 -1906
  56. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-dropship-routing.md +1074 -1074
  57. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-flash-sale-reserve.md +1395 -1395
  58. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-generic-xml-order.md +888 -888
  59. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-payment-gateway-integration.md +2478 -2478
  60. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-rma-returns-comprehensive.md +2240 -2240
  61. package/docs/01-TEMPLATES/versori/webhooks/template-webhook-xml-order-ingestion.md +2029 -2029
  62. package/docs/01-TEMPLATES/versori/webhooks/webhook-templates-guide.md +140 -140
  63. package/docs/01-TEMPLATES/versori/workflows/_examples/sample-data/inventory-mapping.json +20 -20
  64. package/docs/01-TEMPLATES/versori/workflows/_examples/sample-data/products_2025-01-22.csv +11 -11
  65. package/docs/01-TEMPLATES/versori/workflows/_examples/sample-data/sample-data-guide.md +34 -34
  66. package/docs/01-TEMPLATES/versori/workflows/_examples/workflow-examples-guide.md +36 -36
  67. package/docs/01-TEMPLATES/versori/workflows/extraction/extraction-modes-guide.md +1038 -1038
  68. package/docs/01-TEMPLATES/versori/workflows/extraction/extraction-workflows-guide.md +138 -138
  69. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/graphql-extraction-guide.md +63 -63
  70. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-fulfillments-to-sftp-csv.md +2062 -2062
  71. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-fulfillments-to-sftp-xml.md +2294 -2294
  72. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-positions-to-s3-csv.md +2461 -2461
  73. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-positions-to-sftp-xml.md +2529 -2529
  74. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-quantities-to-s3-csv.md +2464 -2464
  75. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-inventory-quantities-to-s3-json.md +1959 -1959
  76. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-orders-to-s3-csv.md +1953 -1953
  77. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-orders-to-sftp-xml.md +2541 -2541
  78. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-products-to-s3-json.md +2384 -2384
  79. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-products-to-sftp-xml.md +2445 -2445
  80. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-virtual-positions-to-s3-csv.md +2355 -2355
  81. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-virtual-positions-to-s3-json.md +2042 -2042
  82. package/docs/01-TEMPLATES/versori/workflows/extraction/graphql-queries/template-extraction-virtual-positions-to-sftp-xml.md +2726 -2726
  83. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/batch-api-guide.md +206 -206
  84. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-cycle-count-reconciliation.md +2030 -2030
  85. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-multi-channel-inventory-sync.md +1882 -1882
  86. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-s3-csv-inventory-batch.md +2827 -2827
  87. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-s3-json-inventory-batch.md +1952 -1952
  88. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-s3-xml-inventory-batch.md +3289 -3289
  89. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-sftp-csv-inventory-batch.md +3064 -3064
  90. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-sftp-json-inventory-batch.md +3238 -3238
  91. package/docs/01-TEMPLATES/versori/workflows/ingestion/batch-api/template-ingestion-sftp-xml-inventory-batch.md +2977 -2977
  92. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/event-api-guide.md +321 -321
  93. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-payload-json-order-cancel-event.md +959 -959
  94. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-payload-xml-order-cancel-event.md +1170 -1170
  95. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-csv-product-event.md +2312 -2312
  96. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-json-product-event.md +2999 -2999
  97. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-parquet-product-event.md +2836 -2836
  98. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-s3-xml-product-event.md +2395 -2395
  99. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-csv-product-event.md +2295 -2295
  100. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-json-product-event.md +2602 -2602
  101. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-parquet-product-event.md +2589 -2589
  102. package/docs/01-TEMPLATES/versori/workflows/ingestion/event-api/template-ingestion-sftp-xml-product-event.md +3578 -3578
  103. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/graphql-mutations-guide.md +93 -93
  104. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-payload-json-order-update-graphql.md +1260 -1260
  105. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-payload-xml-order-update-graphql.md +1472 -1472
  106. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-csv-control-graphql.md +2417 -2417
  107. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-csv-location-graphql.md +2811 -2811
  108. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-csv-price-graphql.md +2619 -2619
  109. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-json-location-graphql.md +2807 -2807
  110. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-s3-xml-location-graphql.md +2373 -2373
  111. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-sftp-csv-control-graphql.md +2740 -2740
  112. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-sftp-csv-location-graphql.md +2760 -2760
  113. package/docs/01-TEMPLATES/versori/workflows/ingestion/graphql-mutations/template-ingestion-sftp-json-location-graphql.md +1710 -1710
  114. package/docs/01-TEMPLATES/versori/workflows/ingestion/ingestion-workflows-guide.md +136 -136
  115. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/rubix-webhooks-guide.md +520 -520
  116. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/template-webhook-rubix-fulfilment-to-sftp-xml-inline.md +1418 -1418
  117. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/template-webhook-rubix-fulfilment-to-sftp-xml-universal-mapper.md +1785 -1785
  118. package/docs/01-TEMPLATES/versori/workflows/rubix-webhooks/template-webhook-rubix-order-attribute-update.md +824 -824
  119. package/docs/01-TEMPLATES/versori/workflows/workflows-overview-guide.md +646 -646
  120. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-batch-archival.md +724 -724
  121. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-job-tracker.md +627 -627
  122. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-partial-batch-recovery.md +561 -561
  123. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-quick-reference.md +367 -367
  124. package/docs/02-CORE-GUIDES/advanced-services/advanced-services-readme.md +407 -407
  125. package/docs/02-CORE-GUIDES/advanced-services/readme.md +49 -49
  126. package/docs/02-CORE-GUIDES/api-reference/api-reference-quick-reference.md +548 -548
  127. package/docs/02-CORE-GUIDES/api-reference/event-api-input-output-reference.md +702 -1171
  128. package/docs/02-CORE-GUIDES/api-reference/examples/client-initialization.ts +286 -286
  129. package/docs/02-CORE-GUIDES/api-reference/graphql-error-classification.md +337 -337
  130. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-01-client-api.md +399 -520
  131. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-03-authentication.md +199 -199
  132. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-04-graphql-mapping.md +925 -925
  133. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-05-services.md +1198 -1198
  134. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-06-data-sources.md +1083 -1083
  135. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-07-parsers.md +1097 -1097
  136. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-08-pagination.md +513 -513
  137. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-08-types.md +545 -597
  138. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-09-error-handling.md +527 -527
  139. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-09-webhook-validation.md +514 -514
  140. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-10-extraction.md +557 -557
  141. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-10-utilities.md +412 -412
  142. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-11-cli-tools.md +423 -423
  143. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-11-error-handling.md +716 -716
  144. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-12-analyze-source-structure.md +518 -518
  145. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-12-partial-responses.md +212 -212
  146. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-12-testing.md +300 -300
  147. package/docs/02-CORE-GUIDES/api-reference/modules/api-reference-13-resolver-builder.md +322 -322
  148. package/docs/02-CORE-GUIDES/api-reference/readme.md +279 -279
  149. package/docs/02-CORE-GUIDES/auto-pagination/auto-pagination-quick-reference.md +351 -351
  150. package/docs/02-CORE-GUIDES/auto-pagination/auto-pagination-readme.md +277 -277
  151. package/docs/02-CORE-GUIDES/auto-pagination/examples/auto-pagination-readme.md +178 -178
  152. package/docs/02-CORE-GUIDES/auto-pagination/examples/common-patterns.ts +351 -351
  153. package/docs/02-CORE-GUIDES/auto-pagination/examples/paginate-products.ts +384 -384
  154. package/docs/02-CORE-GUIDES/auto-pagination/examples/paginate-virtual-positions.ts +308 -308
  155. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-01-foundations.md +470 -470
  156. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-02-quick-start.md +713 -713
  157. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-03-configuration.md +754 -754
  158. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-04-advanced-patterns.md +732 -732
  159. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-05-sdk-integration.md +847 -847
  160. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-06-troubleshooting.md +359 -359
  161. package/docs/02-CORE-GUIDES/auto-pagination/modules/auto-pagination-07-api-reference.md +462 -462
  162. package/docs/02-CORE-GUIDES/auto-pagination/readme.md +54 -54
  163. package/docs/02-CORE-GUIDES/data-sources/data-sources-file-operations-error-handling.md +1487 -1487
  164. package/docs/02-CORE-GUIDES/data-sources/data-sources-quick-reference.md +836 -836
  165. package/docs/02-CORE-GUIDES/data-sources/data-sources-readme.md +276 -276
  166. package/docs/02-CORE-GUIDES/data-sources/data-sources-sftp-credential-access-security.md +553 -553
  167. package/docs/02-CORE-GUIDES/data-sources/examples/common-patterns.ts +409 -409
  168. package/docs/02-CORE-GUIDES/data-sources/examples/data-sources-readme.md +178 -178
  169. package/docs/02-CORE-GUIDES/data-sources/examples/s3-operations.ts +308 -308
  170. package/docs/02-CORE-GUIDES/data-sources/examples/sftp-operations.ts +371 -371
  171. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-01-foundations.md +735 -735
  172. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-02-s3-operations.md +1302 -1302
  173. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-03-sftp-operations.md +1379 -1379
  174. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-04-file-patterns.md +941 -941
  175. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-05-advanced-topics.md +813 -813
  176. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-06-integration-patterns.md +486 -486
  177. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-07-troubleshooting.md +387 -387
  178. package/docs/02-CORE-GUIDES/data-sources/modules/data-sources-08-api-reference.md +417 -417
  179. package/docs/02-CORE-GUIDES/data-sources/readme.md +77 -77
  180. package/docs/02-CORE-GUIDES/error-handling-guide.md +936 -936
  181. package/docs/02-CORE-GUIDES/extraction/examples/02-core-guides-extraction-readme.md +116 -116
  182. package/docs/02-CORE-GUIDES/extraction/examples/common-patterns.ts +428 -428
  183. package/docs/02-CORE-GUIDES/extraction/examples/extract-inventory-basic.ts +187 -187
  184. package/docs/02-CORE-GUIDES/extraction/extraction-quick-reference.md +596 -596
  185. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-01-foundations.md +514 -514
  186. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-02-basic-extraction.md +823 -823
  187. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-03-parquet-processing.md +507 -507
  188. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-04-data-enrichment.md +546 -546
  189. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-05-transformation.md +494 -494
  190. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-06-export-formats.md +458 -458
  191. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-06-performance.md +138 -138
  192. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-07-api-reference.md +148 -148
  193. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-07-optimization.md +692 -692
  194. package/docs/02-CORE-GUIDES/extraction/modules/02-core-guides-extraction-08-extraction-orchestrator.md +1008 -1008
  195. package/docs/02-CORE-GUIDES/extraction/readme.md +151 -151
  196. package/docs/02-CORE-GUIDES/ingestion/examples/_simple-kv-store.ts +40 -40
  197. package/docs/02-CORE-GUIDES/ingestion/examples/error-recovery.ts +728 -728
  198. package/docs/02-CORE-GUIDES/ingestion/examples/event-driven.ts +501 -501
  199. package/docs/02-CORE-GUIDES/ingestion/examples/local-file-ingestion.ts +88 -88
  200. package/docs/02-CORE-GUIDES/ingestion/examples/parquet-ingestion.ts +117 -117
  201. package/docs/02-CORE-GUIDES/ingestion/examples/performance-optimized.ts +647 -647
  202. package/docs/02-CORE-GUIDES/ingestion/examples/s3-csv-ingestion.ts +169 -169
  203. package/docs/02-CORE-GUIDES/ingestion/examples/sftp-csv-ingestion.ts +134 -134
  204. package/docs/02-CORE-GUIDES/ingestion/ingestion-quick-reference.md +546 -546
  205. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-01-introduction.md +626 -626
  206. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-02-quick-start.md +658 -658
  207. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-03-data-sources.md +1052 -1052
  208. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-04-field-mapping.md +763 -763
  209. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-05-advanced-parsers.md +676 -676
  210. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-06-batch-api.md +1295 -1295
  211. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-07-api-reference.md +138 -138
  212. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-07-state-management.md +1037 -1037
  213. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-08-performance-optimization.md +1349 -1349
  214. package/docs/02-CORE-GUIDES/ingestion/modules/02-core-guides-ingestion-09-best-practices.md +1893 -1893
  215. package/docs/02-CORE-GUIDES/ingestion/readme.md +160 -160
  216. package/docs/02-CORE-GUIDES/logging-guide.md +585 -585
  217. package/docs/02-CORE-GUIDES/mapping/error-handling-patterns.md +401 -401
  218. package/docs/02-CORE-GUIDES/mapping/examples/02-core-guides-mapping-readme.md +128 -128
  219. package/docs/02-CORE-GUIDES/mapping/examples/common-patterns.ts +273 -273
  220. package/docs/02-CORE-GUIDES/mapping/examples/csv-location-ingestion.json +36 -36
  221. package/docs/02-CORE-GUIDES/mapping/examples/csv-mapping.ts +242 -242
  222. package/docs/02-CORE-GUIDES/mapping/examples/graphql-to-parquet-extraction.json +36 -36
  223. package/docs/02-CORE-GUIDES/mapping/examples/json-mapping.ts +213 -213
  224. package/docs/02-CORE-GUIDES/mapping/examples/json-product-to-mutation.json +48 -48
  225. package/docs/02-CORE-GUIDES/mapping/examples/xml-mapping.ts +291 -291
  226. package/docs/02-CORE-GUIDES/mapping/examples/xml-order-to-mutation.json +45 -45
  227. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/graphql-mutation-mapping-quick-reference.md +463 -463
  228. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/graphql-mutation-mapping-readme.md +227 -227
  229. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-01-introduction.md +222 -222
  230. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-02-quick-start.md +351 -351
  231. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-03-schema-validation.md +569 -569
  232. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-04-mapping-patterns.md +471 -471
  233. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-05-configuration-reference.md +611 -611
  234. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-06-advanced-xpath.md +148 -148
  235. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-06-path-syntax.md +464 -464
  236. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-07-api-reference.md +94 -94
  237. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-07-array-handling.md +307 -307
  238. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-08-custom-resolvers.md +544 -544
  239. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-09-advanced-patterns.md +427 -427
  240. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-10-hooks-and-variables.md +336 -336
  241. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-11-error-handling.md +488 -488
  242. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-12-arguments-vs-nodes.md +383 -383
  243. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/modules/graphql-mutation-mapping-13-best-practices.md +477 -477
  244. package/docs/02-CORE-GUIDES/mapping/graphql-mutation-mapping/readme.md +62 -62
  245. package/docs/02-CORE-GUIDES/mapping/mapping-format-decision-tree.md +480 -480
  246. package/docs/02-CORE-GUIDES/mapping/mapping-graphql-alias-batching-guide.md +820 -820
  247. package/docs/02-CORE-GUIDES/mapping/mapping-javascript-objects.md +2369 -2369
  248. package/docs/02-CORE-GUIDES/mapping/mapping-mapper-comparison-guide.md +682 -682
  249. package/docs/02-CORE-GUIDES/mapping/modules/02-core-guides-mapping-07-api-reference.md +1327 -1327
  250. package/docs/02-CORE-GUIDES/mapping/modules/02-core-guides-mapping-08-error-handling.md +1142 -1142
  251. package/docs/02-CORE-GUIDES/mapping/modules/mapping-04-use-cases.md +891 -891
  252. package/docs/02-CORE-GUIDES/mapping/modules/mapping-06-helpers-resolvers.md +1126 -1126
  253. package/docs/02-CORE-GUIDES/mapping/modules/mapping-06-sdk-resolvers.md +199 -199
  254. package/docs/02-CORE-GUIDES/mapping/modules/mapping-07-api-reference.md +1319 -1319
  255. package/docs/02-CORE-GUIDES/mapping/readme.md +178 -178
  256. package/docs/02-CORE-GUIDES/mapping/resolver-registration.md +410 -410
  257. package/docs/02-CORE-GUIDES/mapping/resolvers/examples/common-patterns.ts +226 -226
  258. package/docs/02-CORE-GUIDES/mapping/resolvers/examples/custom-resolvers.ts +227 -227
  259. package/docs/02-CORE-GUIDES/mapping/resolvers/examples/sdk-resolvers-usage.ts +203 -203
  260. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-readme.md +274 -274
  261. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-api-reference.md +679 -679
  262. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-cookbook.md +826 -826
  263. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-guide.md +1330 -1330
  264. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-helpers-reference.md +1437 -1437
  265. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-parameters-reference.md +553 -553
  266. package/docs/02-CORE-GUIDES/mapping/resolvers/mapping-resolvers-resolver-troubleshooting.md +854 -854
  267. package/docs/02-CORE-GUIDES/mapping/resolvers/readme.md +75 -75
  268. package/docs/02-CORE-GUIDES/parsers/examples/02-core-guides-parsers-readme.md +161 -161
  269. package/docs/02-CORE-GUIDES/parsers/examples/csv-parser-examples.ts +110 -110
  270. package/docs/02-CORE-GUIDES/parsers/examples/json-parser-examples.ts +33 -33
  271. package/docs/02-CORE-GUIDES/parsers/examples/parquet-parser-examples.ts +47 -47
  272. package/docs/02-CORE-GUIDES/parsers/examples/xml-parser-examples.ts +38 -38
  273. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-01-foundations.md +355 -355
  274. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-02-csv-parser.md +772 -772
  275. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-03-json-parser.md +789 -789
  276. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-04-xml-parser.md +857 -857
  277. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-05-parquet-parser.md +603 -603
  278. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-06-integration-patterns.md +702 -702
  279. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-06-streaming.md +121 -121
  280. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-07-api-reference.md +89 -89
  281. package/docs/02-CORE-GUIDES/parsers/modules/02-core-guides-parsers-07-troubleshooting.md +727 -727
  282. package/docs/02-CORE-GUIDES/parsers/parsers-quick-reference.md +482 -482
  283. package/docs/02-CORE-GUIDES/parsers/parsers-readme.md +258 -258
  284. package/docs/02-CORE-GUIDES/parsers/readme.md +65 -65
  285. package/docs/02-CORE-GUIDES/readme.md +194 -194
  286. package/docs/02-CORE-GUIDES/webhook-validation/examples/basic-validation.ts +108 -108
  287. package/docs/02-CORE-GUIDES/webhook-validation/examples/common-patterns.ts +316 -316
  288. package/docs/02-CORE-GUIDES/webhook-validation/examples/webhook-validation-readme.md +61 -61
  289. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-01-foundations.md +440 -440
  290. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-02-quick-start.md +525 -525
  291. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-03-versori-integration.md +741 -741
  292. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-04-platform-integration.md +629 -629
  293. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-05-configuration.md +535 -535
  294. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-06-error-handling.md +611 -611
  295. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-06-troubleshooting.md +124 -124
  296. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-07-api-reference.md +511 -511
  297. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-08-rubix-webhooks.md +590 -590
  298. package/docs/02-CORE-GUIDES/webhook-validation/modules/webhook-validation-09-rubix-event-vs-http-call.md +432 -432
  299. package/docs/02-CORE-GUIDES/webhook-validation/readme.md +239 -239
  300. package/docs/02-CORE-GUIDES/webhook-validation/webhook-validation-quick-reference.md +392 -392
  301. package/docs/03-PATTERN-GUIDES/connector-scenarios/connector-scenarios-quick-reference.md +498 -498
  302. package/docs/03-PATTERN-GUIDES/connector-scenarios/connector-scenarios-readme.md +313 -313
  303. package/docs/03-PATTERN-GUIDES/connector-scenarios/examples/common-patterns.ts +612 -612
  304. package/docs/03-PATTERN-GUIDES/connector-scenarios/examples/connector-scenarios-readme.md +253 -253
  305. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-01-foundations.md +452 -452
  306. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-02-simple-scenarios.md +681 -681
  307. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-03-intermediate-scenarios.md +637 -637
  308. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-04-advanced-scenarios.md +650 -650
  309. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-05-bidirectional-sync.md +233 -233
  310. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-06-production-patterns.md +442 -442
  311. package/docs/03-PATTERN-GUIDES/connector-scenarios/modules/connector-scenarios-07-reference.md +445 -445
  312. package/docs/03-PATTERN-GUIDES/connector-scenarios/readme.md +31 -31
  313. package/docs/03-PATTERN-GUIDES/enterprise-integration-patterns.md +1528 -1528
  314. package/docs/03-PATTERN-GUIDES/error-handling/comprehensive-error-handling-guide.md +1437 -1437
  315. package/docs/03-PATTERN-GUIDES/error-handling/error-handling-quick-reference.md +390 -390
  316. package/docs/03-PATTERN-GUIDES/error-handling/examples/common-patterns.ts +438 -438
  317. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-01-foundations.md +362 -362
  318. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-02-error-types.md +850 -850
  319. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-03-utf8-handling.md +456 -456
  320. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-04-error-scenarios.md +658 -658
  321. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-05-calling-patterns.md +671 -671
  322. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-06-retry-strategies.md +1034 -1034
  323. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-07-monitoring.md +653 -653
  324. package/docs/03-PATTERN-GUIDES/error-handling/modules/error-handling-08-api-reference.md +847 -847
  325. package/docs/03-PATTERN-GUIDES/error-handling/readme.md +36 -36
  326. package/docs/03-PATTERN-GUIDES/examples/__tests__/readme.md +40 -40
  327. package/docs/03-PATTERN-GUIDES/examples/__tests__/resolver-examples.test.js +282 -282
  328. package/docs/03-PATTERN-GUIDES/examples/test-data/03-pattern-guides-readme.md +110 -110
  329. package/docs/03-PATTERN-GUIDES/examples/test-data/canonical-inventory.json +123 -123
  330. package/docs/03-PATTERN-GUIDES/examples/test-data/canonical-order.json +171 -171
  331. package/docs/03-PATTERN-GUIDES/examples/test-data/readme.md +28 -28
  332. package/docs/03-PATTERN-GUIDES/extraction/extraction-readme.md +15 -15
  333. package/docs/03-PATTERN-GUIDES/extraction/readme.md +25 -25
  334. package/docs/03-PATTERN-GUIDES/file-operations/examples/common-patterns.ts +407 -407
  335. package/docs/03-PATTERN-GUIDES/file-operations/examples/file-operations-readme.md +142 -142
  336. package/docs/03-PATTERN-GUIDES/file-operations/file-operations-quick-reference.md +462 -462
  337. package/docs/03-PATTERN-GUIDES/file-operations/file-operations-readme.md +379 -379
  338. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-01-foundations.md +430 -430
  339. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-02-quick-start.md +484 -484
  340. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-03-s3-operations.md +507 -507
  341. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-04-sftp-operations.md +963 -963
  342. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-05-streaming-performance.md +503 -503
  343. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-06-archive-patterns.md +386 -386
  344. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-06-error-handling.md +117 -117
  345. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-07-api-reference.md +78 -78
  346. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-07-testing-troubleshooting.md +567 -567
  347. package/docs/03-PATTERN-GUIDES/file-operations/modules/file-operations-08-api-reference.md +1055 -1055
  348. package/docs/03-PATTERN-GUIDES/file-operations/readme.md +32 -32
  349. package/docs/03-PATTERN-GUIDES/ingestion/ingestion-readme.md +15 -15
  350. package/docs/03-PATTERN-GUIDES/ingestion/readme.md +25 -25
  351. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/batch-processing.ts +130 -130
  352. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/common-patterns.ts +360 -360
  353. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/delta-sync.ts +130 -130
  354. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/integration-patterns-readme.md +100 -100
  355. package/docs/03-PATTERN-GUIDES/integration-patterns/examples/real-time-webhook.ts +398 -398
  356. package/docs/03-PATTERN-GUIDES/integration-patterns/integration-patterns-quick-reference.md +962 -962
  357. package/docs/03-PATTERN-GUIDES/integration-patterns/integration-patterns-readme.md +134 -134
  358. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-01-real-time-processing.md +991 -991
  359. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-02-batch-processing.md +1547 -1547
  360. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-03-delta-sync.md +1108 -1108
  361. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-04-webhook-patterns.md +1181 -1181
  362. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-05-error-handling.md +1061 -1061
  363. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-06-advanced-integration-services.md +1547 -1547
  364. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-06-performance.md +109 -109
  365. package/docs/03-PATTERN-GUIDES/integration-patterns/modules/integration-patterns-07-api-reference.md +34 -34
  366. package/docs/03-PATTERN-GUIDES/integration-patterns/readme.md +30 -30
  367. package/docs/03-PATTERN-GUIDES/logging-minimal-mode.md +128 -128
  368. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/common-patterns.ts +380 -380
  369. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/multiple-connections-readme.md +139 -139
  370. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/parallel-root-connections.ts +149 -149
  371. package/docs/03-PATTERN-GUIDES/multiple-connections/examples/real-world-scenarios.ts +405 -405
  372. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-01-foundations.md +378 -378
  373. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-02-quick-start.md +566 -566
  374. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-03-targeting-connections.md +659 -659
  375. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-04-parallel-queries.md +656 -656
  376. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-05-best-practices.md +624 -624
  377. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-06-api-reference.md +824 -824
  378. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-06-versori.md +119 -119
  379. package/docs/03-PATTERN-GUIDES/multiple-connections/modules/multiple-connections-07-api-reference.md +87 -87
  380. package/docs/03-PATTERN-GUIDES/multiple-connections/multiple-connections-quick-reference.md +353 -353
  381. package/docs/03-PATTERN-GUIDES/multiple-connections/multiple-connections-readme.md +270 -270
  382. package/docs/03-PATTERN-GUIDES/multiple-connections/readme.md +30 -30
  383. package/docs/03-PATTERN-GUIDES/pagination/pagination-readme.md +14 -14
  384. package/docs/03-PATTERN-GUIDES/pagination/readme.md +24 -24
  385. package/docs/03-PATTERN-GUIDES/parquet/examples/common-patterns.ts +180 -180
  386. package/docs/03-PATTERN-GUIDES/parquet/examples/read-parquet.ts +48 -48
  387. package/docs/03-PATTERN-GUIDES/parquet/examples/write-parquet.ts +65 -65
  388. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-01-introduction.md +393 -393
  389. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-02-quick-start.md +572 -572
  390. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-03-reading-parquet.md +525 -525
  391. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-04-writing-parquet.md +554 -554
  392. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-05-graphql-extraction.md +405 -405
  393. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-06-performance.md +104 -104
  394. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-06-s3-integration.md +511 -511
  395. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-07-api-reference.md +90 -90
  396. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-07-performance-optimization.md +525 -525
  397. package/docs/03-PATTERN-GUIDES/parquet/modules/03-pattern-guides-parquet-08-best-practices.md +712 -712
  398. package/docs/03-PATTERN-GUIDES/parquet/parquet-quick-reference.md +683 -683
  399. package/docs/03-PATTERN-GUIDES/parquet/parquet-readme.md +248 -248
  400. package/docs/03-PATTERN-GUIDES/parquet/readme.md +32 -32
  401. package/docs/03-PATTERN-GUIDES/parsers/parsers-readme.md +12 -12
  402. package/docs/03-PATTERN-GUIDES/parsers/readme.md +24 -24
  403. package/docs/03-PATTERN-GUIDES/readme.md +159 -159
  404. package/docs/03-PATTERN-GUIDES/webhooks/readme.md +24 -24
  405. package/docs/03-PATTERN-GUIDES/webhooks/webhooks-readme.md +8 -8
  406. package/docs/04-REFERENCE/architecture/architecture-01-overview.md +427 -427
  407. package/docs/04-REFERENCE/architecture/architecture-02-client-architecture.md +424 -424
  408. package/docs/04-REFERENCE/architecture/architecture-03-data-flow.md +690 -690
  409. package/docs/04-REFERENCE/architecture/architecture-04-service-layer.md +834 -834
  410. package/docs/04-REFERENCE/architecture/architecture-05-integration-architecture.md +655 -655
  411. package/docs/04-REFERENCE/architecture/architecture-06-state-management.md +653 -653
  412. package/docs/04-REFERENCE/architecture/architecture-adding-new-data-sources.md +686 -686
  413. package/docs/04-REFERENCE/architecture/readme.md +279 -279
  414. package/docs/04-REFERENCE/platforms/deno/readme.md +117 -117
  415. package/docs/04-REFERENCE/platforms/nodejs/readme.md +146 -146
  416. package/docs/04-REFERENCE/platforms/readme.md +135 -135
  417. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-01-introduction.md +398 -398
  418. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-02-quick-start.md +560 -560
  419. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-03-authentication.md +757 -757
  420. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-04-workflows.md +2476 -2476
  421. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-05-connections.md +1167 -1167
  422. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-06-kv-storage.md +990 -990
  423. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-06-state-management.md +121 -121
  424. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-07-api-reference.md +68 -68
  425. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-07-deployment.md +731 -731
  426. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-08-best-practices.md +1111 -1111
  427. package/docs/04-REFERENCE/platforms/versori/modules/platforms-versori-09-signature-reference.md +766 -766
  428. package/docs/04-REFERENCE/platforms/versori/platforms-versori-readme.md +299 -299
  429. package/docs/04-REFERENCE/platforms/versori/platforms-versori-s3-sftp-configuration-guide.md +1425 -1425
  430. package/docs/04-REFERENCE/platforms/versori/platforms-versori-webhook-api-key-security.md +816 -816
  431. package/docs/04-REFERENCE/platforms/versori/platforms-versori-webhook-connection-security.md +681 -681
  432. package/docs/04-REFERENCE/platforms/versori/platforms-versori-workflow-task-types.md +708 -708
  433. package/docs/04-REFERENCE/platforms/versori/readme.md +108 -108
  434. package/docs/04-REFERENCE/readme.md +148 -148
  435. package/docs/04-REFERENCE/resolver-signature/examples/advanced-resolvers.ts +482 -482
  436. package/docs/04-REFERENCE/resolver-signature/examples/async-resolvers.ts +496 -496
  437. package/docs/04-REFERENCE/resolver-signature/examples/basic-resolvers.ts +343 -343
  438. package/docs/04-REFERENCE/resolver-signature/examples/resolver-signature-readme.md +188 -188
  439. package/docs/04-REFERENCE/resolver-signature/examples/testing-resolvers.ts +463 -463
  440. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-01-foundations.md +286 -286
  441. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-02-parameter-reference.md +643 -643
  442. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-03-basic-examples.md +521 -521
  443. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-04-advanced-patterns.md +739 -739
  444. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-05-sdk-resolvers.md +531 -531
  445. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-06-migration-guide.md +650 -650
  446. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-06-testing.md +125 -125
  447. package/docs/04-REFERENCE/resolver-signature/modules/resolver-signature-07-api-reference.md +794 -794
  448. package/docs/04-REFERENCE/resolver-signature/readme.md +64 -64
  449. package/docs/04-REFERENCE/resolver-signature/resolver-signature-quick-reference.md +270 -270
  450. package/docs/04-REFERENCE/resolver-signature/resolver-signature-readme.md +351 -351
  451. package/docs/04-REFERENCE/schema/fluent-commerce-schema.json +764 -764
  452. package/docs/04-REFERENCE/schema/readme.md +141 -141
  453. package/docs/04-REFERENCE/testing/examples/04-reference-testing-readme.md +158 -158
  454. package/docs/04-REFERENCE/testing/examples/fluent-testing.ts +62 -62
  455. package/docs/04-REFERENCE/testing/examples/health-check.ts +155 -155
  456. package/docs/04-REFERENCE/testing/examples/integration-test.ts +119 -119
  457. package/docs/04-REFERENCE/testing/examples/performance-test.ts +183 -183
  458. package/docs/04-REFERENCE/testing/examples/s3-testing.ts +127 -127
  459. package/docs/04-REFERENCE/testing/modules/04-reference-testing-01-foundations.md +267 -267
  460. package/docs/04-REFERENCE/testing/modules/04-reference-testing-02-s3-testing.md +599 -599
  461. package/docs/04-REFERENCE/testing/modules/04-reference-testing-03-fluent-testing.md +589 -589
  462. package/docs/04-REFERENCE/testing/modules/04-reference-testing-04-integration-testing.md +699 -699
  463. package/docs/04-REFERENCE/testing/modules/04-reference-testing-05-debugging.md +478 -478
  464. package/docs/04-REFERENCE/testing/modules/04-reference-testing-06-cicd-integration.md +463 -463
  465. package/docs/04-REFERENCE/testing/modules/04-reference-testing-06-preflight-validation.md +131 -131
  466. package/docs/04-REFERENCE/testing/modules/04-reference-testing-07-best-practices.md +499 -499
  467. package/docs/04-REFERENCE/testing/modules/04-reference-testing-07-coverage-ci.md +165 -165
  468. package/docs/04-REFERENCE/testing/modules/04-reference-testing-08-api-reference.md +634 -634
  469. package/docs/04-REFERENCE/testing/readme.md +86 -86
  470. package/docs/04-REFERENCE/testing/testing-quick-reference.md +667 -667
  471. package/docs/04-REFERENCE/testing/testing-readme.md +286 -286
  472. package/docs/04-REFERENCE/troubleshooting/readme.md +144 -144
  473. package/docs/04-REFERENCE/troubleshooting/troubleshooting-deno-sftp-compatibility.md +392 -392
  474. package/docs/template-loading-matrix.md +242 -242
  475. package/package.json +5 -3
  476. package/docs/02-CORE-GUIDES/api-reference/cli-profile-integration.md +0 -377
@@ -1,2295 +1,2295 @@
1
- ---
2
- template_id: tpl-ingest-sftp-csv-to-product-event
3
- canonical_filename: template-ingestion-sftp-csv-product-event.md
4
- version: 2.0.0
5
- sdk_version: ^0.1.39
6
- runtime: versori
7
- direction: ingestion
8
- source: sftp-csv
9
- destination: fluent-event-api
10
- entity: product
11
- format: csv
12
- logging: versori
13
- status: stable
14
- features:
15
- - batched-events
16
- - attribute-transformation
17
- - memory-management
18
- - json-serialization-handling
19
- - enhanced-logging
20
- ---
21
-
22
- # Template: Ingestion - SFTP CSV to Product Event
23
-
24
- **Template Version:** 2.0.0
25
- **SDK Version:** @fluentcommerce/fc-connect-sdk@^0.1.39
26
- **Last Updated:** 2025-01-24
27
- **Deployment Target:** Versori Platform
28
-
29
- **πŸ†• Version 2.0.0 Enhancements:**
30
- - βœ… **Batched Events Support** - UPSERT_PRODUCTS with configurable batch sizes (10x faster for 100+ products)
31
- - βœ… **Attribute Transformation** - Automatic conversion of flat attributes to Fluent Commerce array format
32
- - βœ… **Memory Management** - Configurable batch processing with explicit cleanup (prevents OOM on large CSV files)
33
- - βœ… **JSON Serialization Handling** - Prevents 503 errors from non-serializable webhook responses
34
- - βœ… **Enhanced Event Logging** - Status-prefixed logs (SUCCESS_/ERROR_) with comprehensive metrics and progress tracking
35
-
36
- ---
37
-
38
- ## πŸ“š STEP 1: Load These Docs Into Your AI (Human Checklist)
39
-
40
- 1. REQUIRED (load all)
41
- - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
42
- - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
43
- - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
44
- - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
45
- - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/ingestion/
46
- - [ ] fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
47
-
48
- Copy-paste list (open these):
49
- fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
50
- fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
51
- fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
52
- fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
53
- fc-connect-sdk/docs/03-PATTERN-GUIDES/ingestion/
54
- fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
55
-
56
- ---
57
-
58
- ## πŸ“‹ Implementation Prompt
59
-
60
- ```
61
- I need a Versori scheduled ingestion that:
62
-
63
- 1) Discovers CSV files on SFTP with file tracking to skip duplicates
64
- 2) Downloads and parses CSV (returns array directly - no normalization needed)
65
- 3) Transforms records with UniversalMapper per mapping JSON
66
- 4) Sends UPSERT_PRODUCT events (async) to Fluent Commerce with per-record error handling
67
- 5) Archives files to processed/ or errors/ and writes optional rejection report
68
- 6) Tracks progress with JobTracker and exposes a job-status webhook
69
- 7) Uses native Versori log from context
70
-
71
- Use the loaded docs to fill in SDK specifics and best practices.
72
- Keep the structure identical to the template; only adapt where needed.
73
- ```
74
-
75
- ---
76
-
77
- ## πŸ“‹ Template Overview
78
-
79
- This connector runs on the Versori platform. Most operational settings (Fluent account/connection, SFTP connection, schedule, file patterns/limits) are configured via activation variables. Data shape and logic (mapping JSON, CSV structure, parsing rules, per-record handling) are adjusted in code as needed. It reads product data from SFTP CSV, transforms it, and sends events to the Fluent Commerce Event API.
80
-
81
- ### What This Template Does
82
-
83
- ```
84
- οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
85
- οΏ½ INGESTION WORKFLOW οΏ½
86
- οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
87
-
88
- 1. TRIGGER
89
- οΏ½οΏ½ Scheduled (Cron): Runs automatically every hour
90
- οΏ½οΏ½ Ad hoc (Webhook): Manual trigger for immediate processing
91
- οΏ½οΏ½ Status Query (Webhook): Check job progress
92
-
93
- 2. DISCOVER FILES (SftpDataSource)
94
- οΏ½οΏ½ List files from SFTP directory
95
- οΏ½οΏ½ Filter by pattern (products_*.csv)
96
- οΏ½οΏ½ Check file tracking (skip processed)
97
- "οΏ½ Sort by oldest first
98
-
99
- 3. FOR EACH FILE (Per-File Processing)
100
- οΏ½οΏ½ Process one file completely before moving to next
101
- "οΏ½ Steps 4-6 happen for each file
102
-
103
- 4. PROCESS FILE (Service Function)
104
- οΏ½οΏ½ Download CSV from SFTP
105
- οΏ½οΏ½ Parse CSV to array (CSVParserService)
106
- οΏ½οΏ½ Transform with UniversalMapper
107
- "οΏ½ Return transformed products
108
-
109
- 5. SEND EVENTS (Service Function)
110
- οΏ½οΏ½ Loop through transformed products
111
- οΏ½οΏ½ Send UPSERT_PRODUCT event (async)
112
- οΏ½οΏ½ Track success/failure count
113
- "οΏ½ Continue on individual failures
114
-
115
- 6. ARCHIVE & TRACK (SftpDataSource + KV)
116
- οΏ½οΏ½ Move file to processed/ or errors/
117
- οΏ½οΏ½ Generate timestamped archive name
118
- οΏ½οΏ½ Mark as processed in KV
119
- οΏ½οΏ½ Optional: Write event log
120
- "οΏ½ Store file result
121
-
122
- 7. REPEAT for next file (loop back to step 3)
123
-
124
- 8. COMPLETE JOB (JobTracker)
125
- οΏ½οΏ½ Calculate totals (all files)
126
- οΏ½οΏ½ Store final result in KV
127
- οΏ½οΏ½ Enable status queries via webhook
128
- "οΏ½ Return complete results
129
- ```
130
-
131
- ### Key Features
132
-
133
- - **Service Functions**: Modular design with 3 service functions:
134
- 1. `processFile()` - Downloads, parses, transforms (SftpDataSource + CSVParserService + UniversalMapper)
135
- 2. `sendEvents()` - Loops through products, sends events with per-record error handling
136
- 3. `writeEventLog()` - Writes event logs to SFTP using Buffer (for audit/debugging)
137
-
138
- - **Per-File Processing**: Each file is processed completely (download ? parse ? map ? send ? archive) before moving to next
139
- - **Job Tracking**: JobTracker persists stage/status to Versori KV for visibility and status queries
140
- - **Execution Modes**: Scheduled (cron), ad hoc (webhook), status query (webhook)
141
- - **File Tracking**: KV-based file tracking prevents duplicates; `forceReprocess` bypasses
142
- - **Event API**: Per-record failures don't block other records; optional rejection reports
143
- - **SFTP Cleanup**: Connection disposal in finally block ensures cleanup
144
-
145
- Note: JobTracker recommended for production multi-step flows; can be skipped for trivial single-step utilities.
146
-
147
- ### πŸ“¦ Package Information
148
-
149
- **SDK:** [@fluentcommerce/fc-connect-sdk](https://www.npmjs.com/package/@fluentcommerce/fc-connect-sdk)
150
-
151
- **Installation:**
152
- ```bash
153
- npm install @fluentcommerce/fc-connect-sdk@latest
154
- ```
155
-
156
- **Version:** Use latest SDK version from npm
157
-
158
- ---
159
-
160
- **Templates are designed for direct deployment; customize via activation variables.**
161
-
162
- ---
163
-
164
- ## πŸ“¦ SDK Imports (Verified - Versori Optimized)
165
-
166
- ```typescript
167
- // ? VERIFIED IMPORTS - These match actual SDK exports
168
- import { Buffer } from 'node:buffer';
169
- import {
170
- createClient, // Universal client factory
171
- SftpDataSource, // SFTP operations with connection pooling
172
- CSVParserService, // CSV parsing
173
- UniversalMapper, // Field mapping with SDK resolvers
174
- VersoriFileTracker, // File processing state tracker
175
- JobTracker, // Job status tracking
176
- } from "@fluentcommerce/fc-connect-sdk";
177
-
178
- import type {
179
- FluentClient,
180
- SftpDataSourceConfig,
181
- } from "@fluentcommerce/fc-connect-sdk";
182
-
183
- // Versori platform imports
184
- import { schedule, webhook, http, fn, credentials } from "@versori/run";
185
- ```
186
-
187
- **Note:** All imports are from actual SDK exports - this code compiles and runs as-is.
188
-
189
- **? VERSORI PLATFORM - Use Native Logs:**
190
-
191
- - Use `log` from context: `const { log } = ctx;`
192
- - Native Versori logs are simpler and automatically integrated with platform monitoring
193
-
194
- ---
195
-
196
- ## SFTP Connection Setup
197
-
198
- **Two methods available for accessing SFTP credentials:**
199
-
200
- ### Method 1: activation.connections (Recommended)
201
-
202
- **? BEST PRACTICE - Most Secure & Flexible**
203
-
204
- Store SFTP credentials in a Versori connection and access via `activation.connections`:
205
-
206
- **Connection Configuration:**
207
-
208
- 1. In Versori platform, create a connection named `SFTP`
209
- 2. Set **Authentication Type**: `Basic Auth`
210
- 3. Enter **Username**: Your SFTP username
211
- 4. Enter **Password**: Your SFTP password
212
-
213
- **Access in code:**
214
-
215
- ```typescript
216
- const { activation } = ctx;
217
- const conn = activation.connections.SFTP;
218
- const rawAccessToken = conn.accessToken;
219
- const rawBasicAuth = Buffer.from(rawAccessToken, 'base64').toString('utf-8');
220
- const [username, password] = rawBasicAuth.split(':');
221
- ```
222
-
223
- **Benefits:**
224
- - βœ… Credentials stored securely in Versori vault
225
- - βœ… Connection reusable across workflows
226
- - βœ… Access all connections dynamically
227
- - βœ… No activation variables needed for secrets
228
- - βœ… Easier credential rotation
229
- - βœ… Built-in connection health monitoring
230
-
231
- **Security:** Connections are encrypted at rest and in transit by Versori platform.
232
-
233
- ### Method 2: credentials().get() (Alternative)
234
-
235
- **Alternative approach using credentials API:**
236
-
237
- ```typescript
238
- const { credentials } = ctx;
239
- const conn = credentials().get('SFTP');
240
- const rawAccessToken = conn.accessToken;
241
- const rawBasicAuth = Buffer.from(rawAccessToken, 'base64').toString('utf-8');
242
- const [username, password] = rawBasicAuth.split(':');
243
- ```
244
-
245
- **When to use:**
246
- - Single-connection workflows
247
- - Workflows using `credentials()` API
248
- - Simpler syntax for single credential access
249
-
250
- **Comparison:**
251
-
252
- | Feature | `activation.connections` | `credentials().get()` |
253
- |---------|-------------------------|----------------------|
254
- | **Security** | Same (Versori vault) | Same (Versori vault) |
255
- | **Access Pattern** | Object property | Method call |
256
- | **Multiple Connections** | Enumerate all via `Object.keys()` | Need connection names |
257
- | **Dynamic Discovery** | Yes | Limited |
258
- | **Future-proof** | Yes (recommended API) | Yes (maintained) |
259
-
260
- **πŸ“š Complete guide:** See [SFTP Credential Access Security Guide](../../../../../02-CORE-GUIDES/data-sources/data-sources-sftp-credential-access-security.md) for:
261
- - Detailed security comparison
262
- - Error handling patterns
263
- - Connection validation
264
- - Multi-connection scenarios
265
- - Best practices
266
-
267
- **Template uses:** `activation.connections` (Method 1) throughout - most flexible for production use.
268
-
269
- ## βš™οΈ Activation Variables
270
-
271
- **Configuration is driven by activation variables - modify these instead of code:**
272
-
273
- > **Note:** `sftpUsername` and `sftpPassword` are fetched from the `SFTP` Basic Auth connection (see SFTP Connection Setup above).
274
-
275
- ```bash
276
- # SFTP Configuration
277
- SFTP_HOST=sftp.partner.com
278
- SFTP_PORT=22
279
-
280
- # SFTP Paths
281
- SFTP_REMOTE_PATH=/incoming/products/
282
- SFTP_ARCHIVE_PATH=/archive/products/
283
- SFTP_ERROR_PATH=/errors/products/
284
-
285
- # File Processing
286
- FILE_PATTERN=.csv
287
- MAX_FILES_PER_RUN=10
288
-
289
- # Product Configuration
290
- CATALOGUE_REF=PC:MASTER:2
291
- CATALOGUE_TYPE=MASTER
292
-
293
- # Event API Configuration
294
- EVENT_NAME=UPSERT_PRODUCT
295
- EVENT_MODE=async
296
-
297
- # Fluent Configuration (via Versori connection)
298
- # Connection: fluent_commerce (OAuth2)
299
- FLUENT_RETAILER_ID=1
300
-
301
- # Feature Toggles
302
- ENABLE_FILE_TRACKING=true # Enable/disable file tracking (default: true)
303
-
304
- # Event API Performance
305
- USE_BATCHED_EVENTS=false # Use batched UPSERT_PRODUCTS (10x faster for 100+ products)
306
- MAX_PRODUCTS_UNDER_BATCHED_EVENT=100 # Products per batch (only used when USE_BATCHED_EVENTS=true)
307
- MEMORY_BATCH_SIZE=250 # Products per mapping batch (prevents OOM on large files)
308
- ```
309
-
310
- **Security:**
311
- - **SFTP Authentication:** Credentials stored in Versori connection vault (not in activation variables). See [SFTP Connection Setup](#sftp-connection-setup) section below.
312
- - **Webhook Authentication:** Enforced by Versori connection configuration. Configure your webhook connection with API key authentication in the Versori Dashboard, then reference it in `webhook({ connection: 'webhook-auth' })`.
313
-
314
- ### Variable Explanations
315
-
316
- | Variable | Purpose | Default | Customization Hints |
317
- | ------------------- | --------------------------- | --------------------- | -------------------------------- |
318
- | `FLUENT_RETAILER_ID` | Retailer ID for Event API | - | Required - Fluent retailer ID |
319
- | **SFTP Credentials** | *From Connection* | | *See connection setup above* |
320
- | `SFTP_HOST` | SFTP server hostname | - | Required - your SFTP server |
321
- | `SFTP_PORT` | SFTP server port | `22` | Usually 22, sometimes 2222 |
322
- | `SFTP_REMOTE_PATH` | Incoming files directory | `/incoming/products/` | Where new files arrive |
323
- | `SFTP_ARCHIVE_PATH` | Processed files archive | `/archive/products/` | Where files move after success |
324
- | `SFTP_ERROR_PATH` | Failed files directory | `/errors/products/` | Where files move after errors |
325
- | `FILE_PATTERN` | File name filter | `.csv` | Extension or glob pattern for matching files |
326
- | `CATALOGUE_REF` | Product catalogue reference | `PC:MASTER:2` | Target catalogue in Fluent |
327
- | `CATALOGUE_TYPE` | Catalogue type | `MASTER` | Usually MASTER or STANDARD |
328
- | `EVENT_NAME` | Event to send | `UPSERT_PRODUCT` | Event name from Rubix |
329
- | `EVENT_MODE` | Event processing mode | `async` | async (recommended) or sync |
330
- | `MAX_FILES_PER_RUN` | Max files per execution | `10` | Prevent timeout on large batches (0 = unlimited) |
331
- | `ENABLE_FILE_TRACKING` | Enable file deduplication | `"true"` | `"true"` = skip already processed files, `"false"` = process all files |
332
- | `USE_BATCHED_EVENTS` | Use batched UPSERT_PRODUCTS | `false` | `true` = batched events (10x faster for 100+ products), `false` = individual events |
333
- | `MAX_PRODUCTS_UNDER_BATCHED_EVENT` | Products per batch | `100` | Only used when `USE_BATCHED_EVENTS=true` (default: 100) |
334
- | `MEMORY_BATCH_SIZE` | Products per mapping batch | `250` | Processes products in batches during mapping (prevents OOM on large files) |
335
-
336
- ---
337
-
338
- ## πŸ”’ SDK Automatic Behaviors (v0.1.40+)
339
-
340
- **The SDK automatically validates and retries for improved reliability:**
341
-
342
- ### retailerId Validation
343
- - **SDK validates** `retailerId` before calling `sendEvent()`
344
- - **Checks:** `event.retailerId || client.retailerId`
345
- - **If missing:** Throws `"retailerId is required for Event API..."`
346
- - **Configuration:** Set via `FLUENT_RETAILER_ID` activation variable (recommended)
347
-
348
- ### 401 Auth Retry
349
- - **Automatic retry** for platform auth failures (3 attempts)
350
- - **Delay:** Exponential backoff (1s β†’ 2s β†’ 4s)
351
- - **Applies to:** All `sendEvent()` calls (async and sync modes)
352
- - **Log:** `"[fc-connect-sdk:auth] Platform auth failure (401), retrying..."`
353
-
354
- ### 5xx Server Retry
355
- - **Automatic retry** for transient server errors (3 attempts)
356
- - **Delay:** Exponential backoff (1s β†’ 2s β†’ 4s, capped at 10s)
357
- - **Protects:** Against Fluent API transient failures
358
-
359
- ### No Code Changes Required
360
- - All templates remain compatible
361
- - Retry logic is automatic and transparent
362
- - Better error messages guide configuration
363
-
364
- **See:** [Event API Guide](./event-api-guide.md) for complete details
365
-
366
- ---
367
-
368
- ### πŸ“ File Tracking & Deduplication
369
-
370
- **How file tracking prevents duplicates:**
371
-
372
- 1. **Discovery:** List all files matching `filePattern` from `sftpIncomingPath`
373
- 2. **Filter:** Query VersoriFileTracker to check which files were already processed
374
- 3. **Process:** Only process untracked files (skips duplicates automatically)
375
- 4. **Mark:** Mark file as processed after successful Event API ingestion
376
- 5. **Archive:** Move file to `sftpProcessedPath` (or `sftpErrorPath` on failure)
377
-
378
- **File lifecycle:**
379
-
380
- ```
381
- /incoming/products_20250124_001.csv
382
- ?οΏ½ (discovered)
383
- VersoriFileTracker.wasFileProcessed() ? false
384
- ?οΏ½ (process file)
385
- Parse CSV ? Map to events ? Send to Event API
386
- ?οΏ½ (success)
387
- VersoriFileTracker.markFileProcessed()
388
- ?οΏ½ (archive)
389
- /processed/products_20250124_001-20250124T183045.csv
390
- ```
391
-
392
- **Force reprocess:**
393
-
394
- Set `forceReprocess: true` in webhook payload to bypass file tracker and reprocess files. Useful for:
395
-
396
- - Fixing bad data that was previously ingested
397
- - Reingesting after mapping config changes
398
- - Testing with production files
399
-
400
- **Note:** Force reprocess doesn't prevent marking as processed - files are still tracked after reprocessing.
401
-
402
- ---
403
-
404
- ### πŸ“ SFTP Path vs File Pattern
405
-
406
- **Critical:** Folder paths and file patterns are configured separately.
407
-
408
- - **Folder Paths:** Configured via activation variables:
409
-
410
- - `sftpIncomingPath` - Where new files arrive (e.g., `/products/incoming`)
411
- - `sftpProcessedPath` - Where successful files are archived (e.g., `/products/processed`)
412
- - `sftpErrorPath` - Where failed files are moved (e.g., `/products/errors`)
413
-
414
- - **File Pattern:** Configured via `filePattern` activation variable
415
- - Matches filenames ONLY (not folder paths)
416
- - Supports wildcards: `*.csv`, `products_*.csv`, `urgent_*.csv`
417
-
418
- **How it works:**
419
-
420
- ```typescript
421
- // The workflow lists files like this:
422
- sftp.listFiles({
423
- remotePath: "/products/incoming", // ?οΏ½ Folder from activation variable
424
- filePattern: "products_*.csv", // ?οΏ½ Pattern matches filenames only
425
- });
426
- ```
427
-
428
- **Example:** With these settings:
429
-
430
- ```json
431
- {
432
- "sftpIncomingPath": "/products/incoming",
433
- "filePattern": "products_*.csv"
434
- }
435
- ```
436
-
437
- The workflow will find files like:
438
-
439
- - βœ… `/products/incoming/products_20250124.csv`
440
- - βœ… `/products/incoming/products_urgent.csv`
441
- - ❌ `/products/incoming/orders_20250124.csv` (doesn't match pattern)
442
- - ❌ `/orders/incoming/products_20250124.csv` (wrong folder)
443
-
444
- **Note:** To process files from different folders, change `sftpIncomingPath` (not `filePattern`).
445
-
446
- ---
447
-
448
- ## πŸ“„ Mapping Configuration
449
-
450
- **File:** `config/products.import.csv.json`
451
-
452
- ```json
453
- {
454
- "name": "products.import.csv",
455
- "version": "1.0.0",
456
- "description": "CSV ? Product Event Mapping",
457
- "fields": {
458
- "ref": {
459
- "source": "ref",
460
- "required": true,
461
- "resolver": "sdk.trim"
462
- },
463
- "type": {
464
- "source": "type",
465
- "resolver": "sdk.uppercase",
466
- "defaultValue": "STANDARD"
467
- },
468
- "status": {
469
- "source": "status",
470
- "resolver": "sdk.uppercase",
471
- "defaultValue": "ACTIVE"
472
- },
473
- "gtin": {
474
- "source": "gtin",
475
- "resolver": "sdk.trim"
476
- },
477
- "name": {
478
- "source": "name",
479
- "required": true,
480
- "resolver": "sdk.trim"
481
- },
482
- "summary": {
483
- "source": "summary"
484
- },
485
- "categoryRefs": {
486
- "source": "category_refs",
487
- "resolver": "custom.splitByPipe"
488
- },
489
- "price": {
490
- "resolver": "custom.buildPriceArray"
491
- },
492
- "taxType": {
493
- "resolver": "custom.buildTaxType"
494
- },
495
- "attributes": {
496
- "defaultValue": []
497
- }
498
- }
499
- }
500
- ```
501
-
502
- **Custom Resolvers:**
503
-
504
- ```typescript
505
- const customResolvers = {
506
- /**
507
- * Split pipe-separated string into array
508
- * Example: "CAT1|CAT2|CAT3" ? ["CAT1", "CAT2", "CAT3"]
509
- */
510
- 'custom.splitByPipe': (value: string) => {
511
- if (!value || value.trim() === '') return [];
512
- return value.split('|').map(v => v.trim()).filter(v => v !== '');
513
- },
514
-
515
- /**
516
- * Build price array from flat CSV columns
517
- * Expects: price_default_currency, price_default_value, price_special_currency, price_special_value
518
- */
519
- 'custom.buildPriceArray': (value: any, sourceData: any) => {
520
- const prices = [];
521
-
522
- // Add default price
523
- if (sourceData.price_default_value) {
524
- prices.push({
525
- type: 'DEFAULT',
526
- currency: sourceData.price_default_currency || 'USD',
527
- value: sourceData.price_default_value,
528
- });
529
- }
530
-
531
- // Add special price if exists
532
- if (sourceData.price_special_value) {
533
- prices.push({
534
- type: 'SPECIAL',
535
- currency: sourceData.price_special_currency || 'USD',
536
- value: sourceData.price_special_value,
537
- });
538
- }
539
-
540
- return prices;
541
- },
542
-
543
- /**
544
- * Build tax type object from flat CSV columns
545
- * Expects: tax_country, tax_group, tax_tariff
546
- */
547
- 'custom.buildTaxType': (value: any, sourceData: any) => {
548
- if (!sourceData.tax_country) return undefined;
549
-
550
- return {
551
- country: sourceData.tax_country,
552
- group: sourceData.tax_group,
553
- tariff: sourceData.tax_tariff,
554
- };
555
- },
556
- };
557
- ```
558
-
559
- Note: Adjust fields in the JSON above as needed; prefer built-in resolvers. For advanced patterns, see SDK Universal Mapping guide.
560
-
561
- ### Mapping customization and custom resolvers (how-to)
562
-
563
- (Condensed) Provide custom resolvers via UniversalMapper options if required.
564
-
565
- ### Parse + map
566
-
567
- Handled inside orchestration (download ? parse ? map). No extra helpers needed.
568
-
569
- ---
570
-
571
- ### Error handling & rejection reports
572
-
573
- When moving failed files to errors/, optionally write a JSON rejection report with totals and error list for audit purposes.
574
-
575
- ---
576
-
577
- ## Expected CSV Format
578
-
579
- ```csv
580
- ref,type,status,gtin,name,summary,category_refs,price_default_currency,price_default_value,price_special_currency,price_special_value,tax_country,tax_group,tax_tariff,catalogue_ref,catalogue_type
581
- G_PROD_WITH_NO_STANDARD,VARIANT,ACTIVE,MH01-XS-Orange,Chaz Kangeroo Hoodie-XS-Orange main,<p>test short description</p>,STANDARD_CATEGORY,USD,52.000000,USD,9.000000,AU,Tax Group,Tax Tariff,PC:MASTER:2,MASTER
582
- G_PROD_002,VARIANT,ACTIVE,MH02-M-Blue,Kangeroo Hoodie-M-Blue,<p>Blue variant</p>,STANDARD_CATEGORY|SEASONAL,USD,45.000000,USD,35.000000,AU,Tax Group,Tax Tariff,PC:MASTER:2,MASTER
583
- ```
584
-
585
- ---
586
-
587
- ## Event Sending Configuration
588
-
589
- **Simple Configuration:** One variable controls everything
590
-
591
- ```json
592
- {
593
- "eventConcurrency": 1 // 1 = sequential, 3-10 = parallel
594
- }
595
- ```
596
-
597
- **How it works:**
598
-
599
- - `eventConcurrency: 1` ? Sequential (sends events one at a time, safe default)
600
- - `eventConcurrency: 3` ? Parallel (sends 3 events concurrently)
601
- - `eventConcurrency: 5` ? Parallel (sends 5 events concurrently)
602
- - `eventConcurrency: 10` ? Parallel (sends 10 events concurrently)
603
-
604
- **Configuration Guidelines:**
605
-
606
- - **Conservative:** `1` ? Sequential (safe, predictable, ~1 req/sec)
607
- - **Balanced:** `3-5` ? Parallel (most common, ~3-5 req/sec)
608
- - **Aggressive:** `10` ? Parallel (high-volume, ~10 req/sec)
609
- - **Note:** Fluent API supports concurrent requests - adjust based on your needs
610
-
611
- **Why Single Variable?**
612
-
613
- - **Simpler:** One variable instead of two (`mode` + `concurrency`)
614
- - **Clearer:** `concurrency: 1` = sequential, `concurrency > 1` = parallel
615
- - **Less config:** Fewer activation variables to manage
616
- - **Flexible:** Easy to tune performance (just change the number)
617
-
618
- ---
619
-
620
- ## πŸ”§ Production Implementation
621
-
622
- ### Processing Modes
623
-
624
- | Mode | Default | What happens | When to use |
625
- | ---------- | ------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
626
- | `per-file` | ? | Process one file end-to-end (discover ? parse ? Event API ? archive) before moving on | Recommended for production SFTP feeds and very large files |
627
- | `chunked` | ? | Processes `fileChunkSize` files at a time, completing each chunk before the next | High-volume feeds where per-file would take too long |
628
- | `batch` | ? | Loads every matched file into memory, produces a single Event API job, and archives when complete | Tiny datasets or smoke tests only |
629
-
630
- Set the mode via activation variables:
631
-
632
- ```json
633
- {
634
- "processingMode": "per-file",
635
- "fileChunkSize": "5",
636
- "maxFilesPerRun": "25"
637
- }
638
- ```
639
-
640
- ---
641
-
642
- ## πŸ”§ Complete Production Code
643
-
644
- ### Versori Workflows Structure
645
-
646
- **Key Concept**: Versori workflows are organized by **trigger type** at the first level, then by **specific workflow** with descriptive file names.
647
-
648
- **Trigger Types:**
649
- - **`schedule()`** β†’ Time-based triggers (cron expressions) - NOT exposed as HTTP endpoints
650
- - **`webhook()`** β†’ HTTP-based triggers (event-driven) - Creates HTTP endpoints
651
- - **`workflow()`** β†’ Durable workflows (advanced, rarely used)
652
-
653
- **Execution Steps (chained to triggers):**
654
- - **`http()`** β†’ External API calls (chained from schedule/webhook)
655
- - **`fn()`** β†’ Internal processing (chained from schedule/webhook)
656
-
657
- ### Recommended Project Structure
658
-
659
- ```
660
- product-event-sync/
661
- β”œβ”€β”€ index.ts # Entry point - exports all workflows
662
- └── src/
663
- β”œβ”€β”€ workflows/
664
- β”‚ β”œβ”€β”€ scheduled/
665
- β”‚ β”‚ └── daily-product-sync.ts # Scheduled: Daily product sync
666
- β”‚ β”‚
667
- β”‚ └── webhook/
668
- β”‚ β”œβ”€β”€ adhoc-product-sync.ts # Webhook: Manual trigger
669
- β”‚ └── job-status-check.ts # Webhook: Status query
670
- β”‚
671
- β”œβ”€β”€ services/
672
- β”‚ └── product-sync.service.ts # Shared orchestration logic (reusable)
673
- β”‚
674
- └── types/
675
- └── product.types.ts # Shared type definitions
676
- ```
677
-
678
- **Benefits:**
679
- - βœ… Clear trigger separation (`scheduled/` vs `webhook/`)
680
- - βœ… Descriptive file names (easy to browse and understand)
681
- - βœ… Scalable (add new workflows without cluttering)
682
- - βœ… Reusable code in `services/` (DRY principle)
683
- - βœ… Easy to modify individual workflows without affecting others
684
-
685
- ---
686
-
687
- ## Workflow Files
688
-
689
- ### 1. Scheduled Workflows (`src/workflows/scheduled/`)
690
-
691
- All time-based triggers that run automatically on cron schedules.
692
-
693
- #### `src/workflows/scheduled/daily-product-sync.ts`
694
-
695
- **Purpose**: Automatic Daily product sync
696
- **Trigger**: Cron schedule (`0 2 * * *`)
697
- **Exposed as Endpoint**: ❌ NO - Runs automatically
698
-
699
- ```typescript
700
- import { schedule, http } from '@versori/run';
701
- import { JobTracker } from '@fluentcommerce/fc-connect-sdk';
702
- import { executeProductIngestion } from '../../services/product-sync.service';
703
-
704
- /**
705
- * Scheduled Workflow: Daily Product Sync
706
- *
707
- * Runs automatically daily at 2 AM UTC
708
- * NOT exposed as HTTP endpoint - Versori executes on schedule
709
- *
710
- * Uses shared service: product-sync.service.ts
711
- */
712
- export const dailyProductSync = schedule(
713
- 'product-sync-scheduled',
714
- '0 2 * * *' // Daily at 2 AM UTC
715
- ).then(
716
- http('run-product-sync', { connection: 'fluent_commerce' }, async (ctx: any) => {
717
- const { log, openKv } = ctx;
718
- const executionStartTime = Date.now();
719
- const jobId = `product-sync-${executionStartTime}`;
720
- const tracker = new JobTracker(openKv(':project:'), log);
721
-
722
- log.info('πŸš€ [WORKFLOW] Starting scheduled product sync', { jobId });
723
-
724
- await tracker.createJob(jobId, {
725
- triggeredBy: 'schedule',
726
- stage: 'initialization',
727
- startTime: executionStartTime
728
- });
729
- await tracker.updateJob(jobId, { status: 'processing' });
730
-
731
- try {
732
- // Reuse shared orchestration logic
733
- const result = await executeProductIngestion(ctx, jobId, tracker);
734
-
735
- if (result.success) {
736
- await tracker.markCompleted(jobId, result);
737
- log.info('βœ… [WORKFLOW] Product sync completed successfully', {
738
- jobId,
739
- filesProcessed: result.filesProcessed,
740
- duration: result.duration
741
- });
742
- } else {
743
- await tracker.markFailed(jobId, result.error || 'Unknown error');
744
- log.error('❌ [WORKFLOW] Product sync failed', { jobId, error: result.error });
745
- }
746
-
747
- return { success: true, jobId, ...result };
748
- } catch (e: any) {
749
- const errorMessage = e instanceof Error ? e.message : String(e);
750
- await tracker.markFailed(jobId, errorMessage);
751
- log.error('❌ [WORKFLOW] Product sync failed with exception', {
752
- jobId,
753
- error: errorMessage,
754
- stack: e instanceof Error ? e.stack : undefined
755
- });
756
- return { success: false, jobId, error: errorMessage };
757
- }
758
- })
759
- );
760
- ```
761
-
762
- ---
763
-
764
- ### 2. Webhook Workflows (`src/workflows/webhook/`)
765
-
766
- All HTTP-based triggers that create webhook endpoints.
767
-
768
- #### `src/workflows/webhook/adhoc-product-sync.ts`
769
-
770
- **Purpose**: Manual product sync trigger (on-demand)
771
- **Trigger**: HTTP POST
772
- **Endpoint**: `POST https://{workspace}.versori.run/product-sync-adhoc`
773
- **Use Cases**: Testing, priority processing, ad-hoc runs
774
-
775
- ```typescript
776
- import { webhook, http } from '@versori/run';
777
- import { JobTracker } from '@fluentcommerce/fc-connect-sdk';
778
- import { executeProductIngestion } from '../../services/product-sync.service';
779
-
780
- /**
781
- * Webhook: Manual Product Sync Trigger
782
- *
783
- * Endpoint: POST https://{workspace}.versori.run/product-sync-adhoc
784
- * Request body (optional): { filePattern: "urgent_*.csv", maxFiles: 5 }
785
- *
786
- * Pattern: webhook().then(http()) - needs Fluent API access
787
- * Uses shared service: product-sync.service.ts
788
- *
789
- * SECURITY: Authentication handled via connection parameter
790
- * No manual API key validation needed - Versori manages this via connection auth
791
- */
792
- export const adhocProductSync = webhook('product-sync-adhoc', {
793
- response: { mode: 'sync' }, // βœ… Sync mode: response sent when handler returns
794
- connection: 'product-sync-adhoc', // Versori validates API key
795
- }).then(
796
- http('run-product-sync-adhoc', { connection: 'fluent_commerce' }, async (ctx: any) => {
797
- const { log, openKv, data } = ctx;
798
- const executionStartTime = Date.now();
799
- const jobId = `product-sync-adhoc-${executionStartTime}`;
800
- const tracker = new JobTracker(openKv(':project:'), log);
801
-
802
- const filePattern = data?.filePattern as string;
803
- const maxFiles = data?.maxFiles as number;
804
-
805
- log.info('πŸš€ [WEBHOOK] Adhoc product sync triggered', {
806
- jobId,
807
- filePattern,
808
- maxFiles,
809
- });
810
-
811
- // Create job entry FIRST (awaited to ensure job exists in KV)
812
- await tracker.createJob(jobId, {
813
- triggeredBy: 'webhook',
814
- stage: 'initialization',
815
- status: 'queued',
816
- startTime: executionStartTime,
817
- options: { filePattern, maxFiles },
818
- createdAt: new Date().toISOString(),
819
- });
820
-
821
- // βœ… Fire-and-forget: Start background processing WITHOUT await
822
- // The promise continues execution after we return the response
823
- executeProductIngestion(ctx, jobId, tracker)
824
- .then((result) => {
825
- if (result.success) {
826
- log.info('βœ… [BACKGROUND] Product sync completed successfully', {
827
- jobId,
828
- filesProcessed: result.filesProcessed,
829
- filesFailed: result.filesFailed,
830
- recordsProcessed: result.recordsProcessed,
831
- duration: result.duration,
832
- });
833
- return tracker.markCompleted(jobId, result);
834
- } else {
835
- log.error('❌ [BACKGROUND] Product sync failed', {
836
- jobId,
837
- error: result.error,
838
- });
839
- return tracker.markFailed(jobId, result.error || 'Unknown error');
840
- }
841
- })
842
- .catch((error: unknown) => {
843
- const errorMessage = error instanceof Error ? error.message : String(error);
844
- const errorStack = error instanceof Error ? error.stack : undefined;
845
-
846
- log.error('❌ [BACKGROUND] Product sync failed with exception', {
847
- jobId,
848
- error: errorMessage,
849
- stack: errorStack,
850
- errorType: error instanceof Error ? error.constructor.name : typeof error,
851
- });
852
-
853
- return tracker.markFailed(jobId, errorMessage);
854
- });
855
-
856
- // Return immediately with jobId (response sent with this return value)
857
- return {
858
- success: true,
859
- jobId,
860
- message: 'Product sync started in background',
861
- statusEndpoint: `https://{workspace}.versori.run/product-sync-job-status`,
862
- note: 'Poll the status endpoint with jobId to check progress',
863
- };
864
- })
865
- );
866
- ```
867
-
868
- #### `src/workflows/webhook/job-status-check.ts`
869
-
870
- **Purpose**: Query job status
871
- **Trigger**: HTTP POST
872
- **Endpoint**: `POST https://{workspace}.versori.run/product-sync-job-status`
873
- **Request body**: `{ "jobId": "product-sync-1234567890" }`
874
-
875
- ```typescript
876
- import { webhook, fn } from '@versori/run';
877
- import { JobTracker } from '@fluentcommerce/fc-connect-sdk';
878
-
879
- /**
880
- * Webhook: Job Status Check
881
- *
882
- * Endpoint: POST https://{workspace}.versori.run/product-sync-job-status
883
- * Request body: { "jobId": "product-sync-1234567890" }
884
- *
885
- * Pattern: webhook().then(fn()) - no external API needed, only KV storage
886
- * Lightweight: Only queries KV store, no Fluent API calls
887
- *
888
- * SECURITY: Authentication handled via connection parameter
889
- * No manual API key validation needed - Versori manages this via connection auth
890
- */
891
- export const productSyncJobStatus = webhook('product-sync-job-status', {
892
- response: { mode: 'sync' },
893
- connection: 'product-sync-job-status',
894
- }).then(
895
- fn('status', async ctx => {
896
- const { data, log, openKv } = ctx;
897
- const jobId = data?.jobId as string;
898
-
899
- if (!jobId) {
900
- return { success: false, error: 'jobId required' };
901
- }
902
-
903
- const tracker = new JobTracker(openKv(':project:'), log);
904
- const status = await tracker.getJob(jobId);
905
-
906
- return status
907
- ? { success: true, jobId, ...status }
908
- : { success: false, error: 'Job not found', jobId };
909
- })
910
- );
911
- ```
912
-
913
- ---
914
-
915
- ### 3. Entry Point (`index.ts`)
916
-
917
- **Purpose**: Register all workflows with Versori platform
918
-
919
- ```typescript
920
- /**
921
- * Entry Point - Registers all workflows with Versori platform
922
- *
923
- * Versori automatically discovers and registers exported workflows
924
- *
925
- * File Structure:
926
- * - src/workflows/scheduled/ β†’ Time-based triggers (cron)
927
- * - src/workflows/webhook/ β†’ HTTP-based triggers (webhooks)
928
- */
929
-
930
- // Import scheduled workflows
931
- import { dailyProductSync } from './src/workflows/scheduled/daily-product-sync';
932
-
933
- // Import webhook workflows
934
- import { adhocProductSync } from './src/workflows/webhook/adhoc-product-sync';
935
- import { productSyncJobStatus } from './src/workflows/webhook/job-status-check';
936
-
937
- // Register all workflows
938
- export {
939
- // Scheduled (time-based triggers)
940
- dailyProductSync,
941
-
942
- // Webhooks (HTTP-based triggers)
943
- adhocProductSync,
944
- productSyncJobStatus,
945
- };
946
- ```
947
-
948
- **What Gets Exposed:**
949
- - βœ… `adhocProductSync` β†’ `https://{workspace}.versori.run/product-sync-adhoc`
950
- - βœ… `productSyncJobStatus` β†’ `https://{workspace}.versori.run/product-sync-job-status`
951
- - ❌ `dailyProductSync` β†’ NOT exposed (runs automatically on cron)
952
-
953
- ---
954
-
955
- ### Adding New Workflows
956
-
957
- **To add a scheduled workflow:**
958
- 1. Create file in `src/workflows/scheduled/` with descriptive name (e.g., `hourly-delta-sync.ts`)
959
- 2. Export the workflow from the file
960
- 3. Import and re-export in `index.ts`
961
-
962
- **To add a webhook workflow:**
963
- 1. Create file in `src/workflows/webhook/` with descriptive name (e.g., `error-notification.ts`)
964
- 2. Export the workflow from the file
965
- 3. Import and re-export in `index.ts`
966
-
967
- **Example - Adding hourly delta sync:**
968
-
969
- ```typescript
970
- // src/workflows/scheduled/hourly-delta-sync.ts
971
- export const hourlyDeltaSync = schedule(
972
- 'product-delta-hourly',
973
- '0 * * * *' // Every hour
974
- ).then(
975
- http('run-delta-sync', { connection: 'fluent_commerce' }, async ctx => {
976
- // Delta sync logic (skip BPP)
977
- const result = await runIngestion(ctx, jobId, tracker, { bppEnabled: false });
978
- return result;
979
- })
980
- );
981
-
982
- // index.ts (add to imports and exports)
983
- import { hourlyDeltaSync } from './src/workflows/scheduled/hourly-delta-sync';
984
- export { dailyProductSync, hourlyDeltaSync, ... };
985
- ```
986
-
987
- ---
988
- ## 3. Type Definitions (src/types/product-ingestion.types.ts)
989
-
990
- ```typescript
991
- /**
992
- * Type Definitions for Product Ingestion
993
- *
994
- * Centralized type definitions for product ingestion workflow
995
- */
996
-
997
- import type { FluentClient } from '@fluentcommerce/fc-connect-sdk';
998
-
999
- /**
1000
- * Product interface - represents transformed product data
1001
- */
1002
- export interface Product {
1003
- ref: string;
1004
- type?: string;
1005
- status?: string;
1006
- name: string;
1007
- summary?: string;
1008
- gtin?: string;
1009
- catalogue?: { ref?: string };
1010
- attributes?: Record<string, unknown>;
1011
- }
1012
-
1013
- /**
1014
- * Event configuration
1015
- */
1016
- export interface EventConfig {
1017
- eventName: string;
1018
- catalogueRef: string;
1019
- catalogueType: string;
1020
- eventMode: 'async' | 'sync';
1021
- }
1022
-
1023
- /**
1024
- * Event result - tracks success/failure counts
1025
- */
1026
- export interface EventResult {
1027
- eventsSent: number;
1028
- eventsFailed: number;
1029
- errors: Array<{ productRef: string; error: string }>;
1030
- }
1031
-
1032
- /**
1033
- * Process file result
1034
- */
1035
- export interface ProcessFileResult {
1036
- success: boolean;
1037
- products: Product[];
1038
- error?: string;
1039
- }
1040
-
1041
- /**
1042
- * Versori Context Interface
1043
- * Represents the Versori runtime context passed to workflow functions
1044
- */
1045
- export interface VersoriContext {
1046
- log: {
1047
- info: (message: string, data?: Record<string, unknown>) => void;
1048
- warn: (message: string, data?: Record<string, unknown>) => void;
1049
- error: (message: string, data?: Record<string, unknown>) => void;
1050
- debug?: (message: string, data?: Record<string, unknown>) => void;
1051
- };
1052
- openKv: (namespace: string) => {
1053
- get: (key: string) => Promise<unknown>;
1054
- set: (key: string, value: unknown) => Promise<void>;
1055
- delete: (key: string) => Promise<void>;
1056
- };
1057
- activation: {
1058
- getVariable: (name: string) => string | undefined;
1059
- connections?: Record<string, unknown>;
1060
- };
1061
- connections?: Record<string, unknown>;
1062
- data?: unknown;
1063
- fetch?: typeof fetch;
1064
- }
1065
-
1066
- /**
1067
- * Parameters for ingestion workflow
1068
- */
1069
- export interface ProductIngestionParams {
1070
- jobId: string;
1071
- triggeredBy: 'schedule' | 'webhook';
1072
- filePattern?: string;
1073
- maxFiles?: number;
1074
- forceReprocess?: boolean;
1075
- catalogueRef?: string;
1076
- priority?: 'normal' | 'high';
1077
- }
1078
-
1079
- /**
1080
- * Result from ingestion workflow
1081
- */
1082
- export interface ProductIngestionResult {
1083
- success: boolean;
1084
- jobId: string;
1085
- filesProcessed: number;
1086
- filesFailed: number;
1087
- filesSkipped?: number;
1088
- recordsProcessed: number;
1089
- eventsSent: number;
1090
- eventsFailed: number;
1091
- fileResults: FileProcessingResult[];
1092
- error?: string;
1093
- }
1094
-
1095
- /**
1096
- * Per-file processing result
1097
- */
1098
- export interface FileProcessingResult {
1099
- fileName: string;
1100
- success: boolean;
1101
- skipped?: boolean;
1102
- recordsProcessed: number;
1103
- eventsSent: number;
1104
- eventsFailed: number;
1105
- duration: number;
1106
- error?: string;
1107
- }
1108
- ```
1109
-
1110
- ---
1111
-
1112
- ## 4. Service: Product File Processor (`src/services/product-file-processor.service.ts`)
1113
-
1114
- ```typescript
1115
- /**
1116
- * Product File Processor Service
1117
- *
1118
- * Downloads CSV files from SFTP, parses, and transforms with UniversalMapper.
1119
- * CSV-specific: Returns arrays directly (no normalization needed).
1120
- */
1121
-
1122
- import {
1123
- SftpDataSource,
1124
- CSVParserService,
1125
- UniversalMapper,
1126
- } from '@fluentcommerce/fc-connect-sdk';
1127
- import type { ProcessFileResult, Product } from '../types/product-ingestion.types';
1128
-
1129
- /**
1130
- * Service for processing CSV product files
1131
- */
1132
- export class ProductFileProcessorService {
1133
- constructor(
1134
- private sftp: SftpDataSource,
1135
- private csvParser: CSVParserService,
1136
- private mapper: UniversalMapper,
1137
- private catalogueRef: string
1138
- ) {}
1139
-
1140
- /**
1141
- * Download CSV file from SFTP, parse, and transform with UniversalMapper
1142
- *
1143
- * βœ… PRODUCTION ENHANCEMENT: Memory cleanup pattern
1144
- * - Explicit null assignments after each step
1145
- * - Finally block guarantees cleanup
1146
- * - Prevents OOM errors on large CSV files
1147
- */
1148
- async downloadParseAndTransform(remoteFilePath: string): Promise<ProcessFileResult> {
1149
- // βœ… CRITICAL: Variables for cleanup tracking
1150
- let csvContent: string | null = null;
1151
- let parsed: unknown | null = null;
1152
-
1153
- try {
1154
- // STEP 1: Download CSV content
1155
- csvContent = (await this.sftp.downloadFile(remoteFilePath, {
1156
- encoding: 'utf8',
1157
- })) as string;
1158
-
1159
- // STEP 2: Parse CSV with type safety
1160
- try {
1161
- parsed = await this.csvParser.parse(csvContent);
1162
- } catch (parseError: unknown) {
1163
- const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
1164
- return {
1165
- success: false,
1166
- products: [],
1167
- error: `CSV parse error: ${errorMessage}`,
1168
- };
1169
- }
1170
-
1171
- // βœ… Clear csvContent from memory - no longer needed after parsing
1172
- csvContent = null;
1173
-
1174
- // STEP 3: CSV-SPECIFIC - Returns array directly, no normalization needed
1175
- const rawProducts = Array.isArray(parsed) ? parsed : [];
1176
-
1177
- if (rawProducts.length === 0) {
1178
- return {
1179
- success: false,
1180
- products: [],
1181
- error: 'No products found in CSV',
1182
- };
1183
- }
1184
-
1185
- // βœ… Clear parsed data from memory - only need rawProducts now
1186
- parsed = null;
1187
-
1188
- // STEP 4: Transform with UniversalMapper
1189
- // CSV-SPECIFIC: Merge context using spread pattern (not { inventory: ... })
1190
- const sourceDataWithContext = rawProducts.map(item => ({
1191
- ...item,
1192
- $context: { catalogueRef: this.catalogueRef },
1193
- }));
1194
-
1195
- const mappingResult = await this.mapper.map(sourceDataWithContext);
1196
-
1197
- if (!mappingResult.success) {
1198
- return {
1199
- success: false,
1200
- products: [],
1201
- error: `Mapping validation failed: ${mappingResult.errors?.join(', ')}`,
1202
- };
1203
- }
1204
-
1205
- if (mappingResult.skippedFields && mappingResult.skippedFields.length > 0) {
1206
- this.log.info('ℹ️ [MAPPING] Optional fields skipped (undefined values)', {
1207
- skippedFields: mappingResult.skippedFields,
1208
- note: 'These fields were not present in source data. Add defaultValue to mapping config if they should always appear.',
1209
- });
1210
- }
1211
-
1212
- return {
1213
- success: true,
1214
- products: mappingResult.data as Product[],
1215
- };
1216
- } catch (error: unknown) {
1217
- const errorMessage = error instanceof Error ? error.message : String(error);
1218
- return {
1219
- success: false,
1220
- products: [],
1221
- error: errorMessage,
1222
- };
1223
- } finally {
1224
- // βœ… CRITICAL: Ensure all large objects are cleared even if error occurs
1225
- csvContent = null;
1226
- parsed = null;
1227
- }
1228
- }
1229
- }
1230
- ```
1231
-
1232
- ---
1233
-
1234
- ## 5. Service: Event Sender (`src/services/event-sender.service.ts`)
1235
-
1236
- ```typescript
1237
- /**
1238
- * Event Sender Service
1239
- *
1240
- * Sends product events to Fluent Commerce Event API with per-record error handling.
1241
- * Continues processing on individual failures (Event API best practice).
1242
- * Supports configurable concurrency (sequential or parallel).
1243
- */
1244
-
1245
- import type { FluentClient } from '@fluentcommerce/fc-connect-sdk';
1246
- import type { EventResult, EventConfig, Product } from '../types/product-ingestion.types';
1247
-
1248
- /**
1249
- * Service for sending events to Fluent Commerce Event API
1250
- *
1251
- * βœ… PRODUCTION ENHANCEMENT: Optional logger for detailed progress tracking
1252
- */
1253
- export class EventSenderService {
1254
- constructor(
1255
- private client: FluentClient,
1256
- private log?: any // βœ… Optional logger for progress tracking
1257
- ) {}
1258
-
1259
- /**
1260
- * Send events to Fluent Commerce Event API with configurable concurrency
1261
- *
1262
- * **Performance Characteristics:**
1263
- * - `concurrency: 1` ? Sequential processing (safe default, ~1 event/sec)
1264
- * - `concurrency: 3-5` ? Balanced throughput (~3-5 events/sec, good for most cases)
1265
- * - `concurrency: 10` ? High-volume processing (~10 events/sec, 100+ products)
1266
- *
1267
- * **Implementation Strategy:**
1268
- * - Concurrency = 1: Optimized sequential loop (no Promise.allSettled overhead)
1269
- * - Concurrency > 1: Chunked parallel processing with bounded concurrency
1270
- * - Both modes: Per-record error tracking (failures don't block other events)
1271
- *
1272
- * @param products - Array of products to send as events
1273
- * @param eventConfig - Event configuration (name, catalogue ref, mode)
1274
- * @param concurrency - Number of concurrent event requests (default: 1, min: 1)
1275
- * @returns EventResult with counts (eventsSent/eventsFailed) and error details
1276
- */
1277
- async sendEvents(
1278
- products: Product[],
1279
- eventConfig: EventConfig,
1280
- concurrency: number = 1
1281
- ): Promise<EventResult> {
1282
- // Validate concurrency (guard against invalid values)
1283
- const safeConc = Math.max(1, Math.floor(concurrency));
1284
-
1285
- // Result accumulators
1286
- let eventsSent = 0;
1287
- let eventsFailed = 0;
1288
- const errors: Array<{ productRef: string; error: string }> = [];
1289
-
1290
- // βœ… PRODUCTION ENHANCEMENT: Log event sending start
1291
- if (this.log) {
1292
- this.log.info('πŸ“€ Starting event sending', {
1293
- totalProducts: products.length,
1294
- concurrency: safeConc,
1295
- processingMode: safeConc === 1 ? 'sequential (one at a time)' : `parallel (${safeConc} concurrently)`,
1296
- eventName: eventConfig.eventName,
1297
- catalogueRef: eventConfig.catalogueRef
1298
- });
1299
- }
1300
-
1301
- // Helper: Build event payload (DRY - reused in both modes)
1302
- const buildPayload = (product: Product) => ({
1303
- name: eventConfig.eventName,
1304
- entityRef: eventConfig.catalogueRef,
1305
- entityType: 'PRODUCT_CATALOGUE' as const,
1306
- entitySubtype: eventConfig.catalogueType,
1307
- rootEntityRef: eventConfig.catalogueRef,
1308
- rootEntityType: 'PRODUCT_CATALOGUE' as const,
1309
- attributes: product,
1310
- });
1311
-
1312
- // ============================================================================
1313
- // SEQUENTIAL MODE (concurrency === 1)
1314
- // ============================================================================
1315
- if (safeConc === 1) {
1316
- for (let i = 0; i < products.length; i++) {
1317
- const product = products[i];
1318
-
1319
- // βœ… PRODUCTION ENHANCEMENT: Log progress every 10 products
1320
- if (this.log && i % 10 === 0) {
1321
- this.log.info(`πŸ“€ Sending product ${i + 1}/${products.length}`, {
1322
- productRef: product.ref,
1323
- progress: `${((i / products.length) * 100).toFixed(1)}%`
1324
- });
1325
- }
1326
-
1327
- try {
1328
- await this.client.sendEvent(buildPayload(product), eventConfig.eventMode);
1329
- eventsSent++;
1330
- } catch (err: unknown) {
1331
- eventsFailed++;
1332
- const errorMsg = err instanceof Error ? err.message : String(err);
1333
- errors.push({ productRef: product?.ref || 'unknown', error: errorMsg });
1334
- // Continue processing (failure doesn't block other products)
1335
- }
1336
- }
1337
-
1338
- // βœ… PRODUCTION ENHANCEMENT: Log completion
1339
- if (this.log) {
1340
- this.log.info('βœ… Sequential event sending completed', {
1341
- totalProducts: products.length,
1342
- eventsSent,
1343
- eventsFailed
1344
- });
1345
- }
1346
-
1347
- return { eventsSent, eventsFailed, errors };
1348
- }
1349
-
1350
- // ============================================================================
1351
- // PARALLEL MODE (concurrency > 1)
1352
- // ============================================================================
1353
- const totalChunks = Math.ceil(products.length / safeConc);
1354
-
1355
- for (let i = 0; i < products.length; i += safeConc) {
1356
- const chunk = products.slice(i, i + safeConc);
1357
- const chunkNumber = Math.floor(i / safeConc) + 1;
1358
-
1359
- // βœ… PRODUCTION ENHANCEMENT: Log chunk progress
1360
- if (this.log) {
1361
- this.log.info(`πŸ“¦ Processing chunk ${chunkNumber}/${totalChunks}`, {
1362
- chunkNumber,
1363
- totalChunks,
1364
- productsInChunk: chunk.length,
1365
- productRange: `${i + 1}-${i + chunk.length}`,
1366
- totalProducts: products.length,
1367
- progress: `${((i / products.length) * 100).toFixed(1)}%`
1368
- });
1369
- }
1370
-
1371
- // Fire all requests in chunk concurrently
1372
- const results = await Promise.allSettled(
1373
- chunk.map(product =>
1374
- this.client
1375
- .sendEvent(buildPayload(product), eventConfig.eventMode)
1376
- .then(() => ({ success: true as const, product }))
1377
- .catch(error => ({ success: false as const, product, error }))
1378
- )
1379
- );
1380
-
1381
- // Aggregate chunk results into totals
1382
- let chunkSuccess = 0;
1383
- let chunkFailed = 0;
1384
-
1385
- for (const result of results) {
1386
- if (result.status === 'fulfilled' && result.value.success) {
1387
- eventsSent++;
1388
- chunkSuccess++;
1389
- } else {
1390
- eventsFailed++;
1391
- chunkFailed++;
1392
- const error = result.status === 'fulfilled' ? result.value.error : result.reason;
1393
- const product = result.status === 'fulfilled' ? result.value.product : null;
1394
- errors.push({
1395
- productRef: product?.ref || 'unknown',
1396
- error: error?.message || String(error) || 'unknown error',
1397
- });
1398
- }
1399
- }
1400
-
1401
- // βœ… PRODUCTION ENHANCEMENT: Log chunk completion
1402
- if (this.log) {
1403
- this.log.info(`βœ… Chunk ${chunkNumber}/${totalChunks} completed`, {
1404
- chunkNumber,
1405
- totalChunks,
1406
- chunkSuccess,
1407
- chunkFailed,
1408
- totalSentSoFar: eventsSent,
1409
- totalFailedSoFar: eventsFailed,
1410
- progress: `${(((i + chunk.length) / products.length) * 100).toFixed(1)}%`
1411
- });
1412
- }
1413
- }
1414
-
1415
- // βœ… PRODUCTION ENHANCEMENT: Log parallel completion
1416
- if (this.log) {
1417
- this.log.info('βœ… Parallel event sending completed', {
1418
- totalProducts: products.length,
1419
- totalChunks,
1420
- concurrency: safeConc,
1421
- eventsSent,
1422
- eventsFailed
1423
- });
1424
- }
1425
-
1426
- return { eventsSent, eventsFailed, errors };
1427
- }
1428
- }
1429
- ```
1430
-
1431
- ---
1432
-
1433
- ## 6. Service: Event Logger (`src/services/event-logger.service.ts`)
1434
-
1435
- ```typescript
1436
- /**
1437
- * Event Logger Service
1438
- *
1439
- * Writes event processing logs to SFTP for audit/debugging.
1440
- * Optional - can be used to create rejection reports.
1441
- */
1442
-
1443
- import { Buffer } from 'node:buffer';
1444
- import { SftpDataSource } from '@fluentcommerce/fc-connect-sdk';
1445
-
1446
- /**
1447
- * Service for writing event logs to SFTP
1448
- */
1449
- export class EventLoggerService {
1450
- constructor(private sftp: SftpDataSource) {}
1451
-
1452
- /**
1453
- * Write event log to SFTP
1454
- *
1455
- * @param remotePath - SFTP path for log file
1456
- * @param logData - Log data to write (JSON format)
1457
- */
1458
- async writeEventLog(remotePath: string, logData: unknown): Promise<void> {
1459
- try {
1460
- const logContent = JSON.stringify(logData, null, 2);
1461
- await this.sftp.uploadFile(remotePath, logContent);
1462
- } catch (error: unknown) {
1463
- const errorMessage = error instanceof Error ? error.message : String(error);
1464
- throw new Error(`Failed to write event log: ${errorMessage}`);
1465
- }
1466
- }
1467
- }
1468
- ```
1469
-
1470
- ---
1471
-
1472
- ## 7. Main Orchestration Service (src/services/product-ingestion.service.ts)
1473
-
1474
- ```typescript
1475
- /**
1476
- * MAIN INGESTION ORCHESTRATION SERVICE
1477
- *
1478
- * This is the heart of the ingestion workflow. It coordinates all steps:
1479
- * 1. Initialize clients and services
1480
- * 2. Discover files on SFTP
1481
- * 3. Download and parse CSV files
1482
- * 4. Transform data with UniversalMapper
1483
- * 5. Send events to Fluent Commerce
1484
- * 6. Archive processed files
1485
- * 7. Track file processing state
1486
- * 8. Track job progress with JobTracker
1487
- *
1488
- * NAMING PATTERN (consistent across all use cases):
1489
- * - Interface: {Entity}IngestionParams (e.g., ProductIngestionParams)
1490
- * - Result: {Entity}IngestionResult (e.g., ProductIngestionResult)
1491
- * - Main function: execute{Entity}Ingestion (e.g., executeProductIngestion)
1492
- *
1493
- *
1494
- * - Change entity: Replace "Product" with "Inventory", "Location", etc.
1495
- * - Change format: Replace CSVParserService with XMLParserService/JSONParserService
1496
- * - Change source: Replace SftpDataSource with S3DataSource
1497
- * - Change destination: Replace sendEvent with Batch API or GraphQL mutations
1498
- */
1499
-
1500
- import { Buffer } from 'node:buffer';
1501
- import {
1502
- createClient,
1503
- SftpDataSource,
1504
- CSVParserService,
1505
- UniversalMapper,
1506
- VersoriFileTracker,
1507
- JobTracker,
1508
- } from '@fluentcommerce/fc-connect-sdk';
1509
- import type { FileMetadata } from '@fluentcommerce/fc-connect-sdk';
1510
- import { ProductFileProcessorService } from './product-file-processor.service';
1511
- import { EventSenderService } from './event-sender.service';
1512
- import { EventLoggerService } from './event-logger.service';
1513
- import { extractFileName } from '../utils/sftp-path.utils';
1514
-
1515
- import mappingConfig from '../../config/products.import.csv.json' with { type: 'json' };
1516
-
1517
- // ? VERSORI PLATFORM: Use native log from context, not LoggingService
1518
-
1519
- /**
1520
- * MAIN ORCHESTRATION FUNCTION
1521
- *
1522
- * NAMING: execute{Entity}Ingestion (e.g., executeProductIngestion)
1523
- *
1524
- * This function implements the complete ingestion workflow in 8 steps.
1525
- * Each step is clearly commented for AI understanding.
1526
- *
1527
- * @param ctx - Versori context object containing fetch, connections, log, activation, openKv
1528
- * @param jobId - Job ID for tracking
1529
- * @param tracker - JobTracker instance for job lifecycle management
1530
- */
1531
- export async function executeProductIngestion(
1532
- ctx: any,
1533
- jobId: string,
1534
- tracker: JobTracker
1535
- ) {
1536
- // ? VERSORI PLATFORM: Extract native log from context
1537
- const { log, activation, openKv } = ctx;
1538
- const startTime = Date.now();
1539
-
1540
- log.info('πŸš€ [EXECUTION BOUNDARY] Starting product ingestion', { jobId });
1541
-
1542
- // ⚠️ CRITICAL: Declare SFTP outside try block for double-finally pattern
1543
- let sftp: SftpDataSource | undefined;
1544
-
1545
- try {
1546
- // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1547
- // STEP 1: Initialize Fluent Client
1548
- // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1549
- log.info('πŸ“‘ [STEP 1/7] Initializing Fluent Commerce client', { jobId });
1550
-
1551
- const client = await createClient(ctx);
1552
- log.info('βœ… [DEBUG] Client created successfully');
1553
-
1554
- /**
1555
- * setRetailerId() - REQUIRED for Event/Batch API operations
1556
- *
1557
- * retailerId must be set ONCE on the client after creation.
1558
- * This is required for Event API (sendEvent) operations.
1559
- */
1560
- const fluentRetailerId = activation.getVariable('fluentRetailerId');
1561
- if (!fluentRetailerId) {
1562
- log.error('❌ Missing required fluentRetailerId activation variable');
1563
- return {
1564
- success: false,
1565
- error: 'fluentRetailerId activation variable is required for Event API operations',
1566
- recommendation: 'Please configure fluentRetailerId in the Activation Variables section',
1567
- };
1568
- }
1569
- client.setRetailerId(fluentRetailerId);
1570
- log.info('βœ… Client initialized with retailerId', { retailerId: fluentRetailerId });
1571
-
1572
- // ========================================
1573
- // STEP 2: SFTP CREDENTIAL RETRIEVAL
1574
- // ========================================
1575
-
1576
- log.info('πŸ” [STEP 2/7] Retrieving SFTP credentials from connection');
1577
-
1578
- let sftpUsername: string;
1579
- let sftpPassword: string;
1580
-
1581
- try {
1582
- // Retrieve credentials from the 'SFTP' connection
1583
- const sftpCred = await ctx.credentials().getAccessToken('SFTP');
1584
-
1585
- if (!sftpCred?.accessToken) {
1586
- throw new Error('No SFTP credentials found in connection configuration');
1587
- }
1588
-
1589
- // Decode base64 accessToken to get "username:password"
1590
- const rawBasicAuth = Buffer.from(sftpCred.accessToken, 'base64').toString('utf-8');
1591
-
1592
- // Split on ':' to extract username and password
1593
- const parts = rawBasicAuth.split(':');
1594
-
1595
- if (parts.length !== 2) {
1596
- throw new Error('Invalid SFTP credential format - expected username:password');
1597
- }
1598
-
1599
- sftpUsername = parts[0];
1600
- sftpPassword = parts[1];
1601
-
1602
- log.info('βœ… SFTP credentials retrieved successfully', {
1603
- hasUsername: !!sftpUsername,
1604
- hasPassword: !!sftpPassword,
1605
- });
1606
- } catch (error: any) {
1607
- log.error('❌ Failed to retrieve SFTP credentials', {
1608
- message: error instanceof Error ? error.message : String(error),
1609
- stack: error instanceof Error ? error.stack : undefined,
1610
- });
1611
-
1612
- return {
1613
- success: false,
1614
- error: 'Failed to retrieve SFTP credentials from connection configuration',
1615
- details: error?.message,
1616
- recommendation: 'Please ensure the SFTP connection is configured with Basic Authentication',
1617
- };
1618
- }
1619
-
1620
- // ========================================
1621
- // STEP 3: CONFIGURATION & INITIALIZATION
1622
- // ========================================
1623
-
1624
- log.info('βš™οΈ [STEP 3/7] Configuring SFTP and services', { jobId });
1625
-
1626
- // Configure SFTP
1627
- const sftpConfig = {
1628
- host: activation.getVariable('sftpHost'),
1629
- port: parseInt(activation.getVariable('sftpPort') || '22', 10),
1630
- username: sftpUsername,
1631
- password: sftpPassword,
1632
- remotePath: activation.getVariable('sftpRemotePath') || '/incoming/products/',
1633
- archivePath: activation.getVariable('sftpArchivePath') || '/archive/products/',
1634
- errorPath: activation.getVariable('sftpErrorPath') || '/errors/products/',
1635
- filePattern: activation.getVariable('filePattern') || '.csv',
1636
- enableFileTracking: activation.getVariable('enableFileTracking') !== 'false', // default: true
1637
- };
1638
-
1639
- // Validate SFTP config
1640
- if (!sftpConfig.host) {
1641
- throw new Error('SFTP configuration incomplete: missing host');
1642
- }
1643
-
1644
- // Initialize SFTP data source
1645
- sftp = new SftpDataSource(
1646
- {
1647
- type: 'SFTP_CSV',
1648
- connectionId: 'sftp-product-ingestion',
1649
- name: 'product-sync',
1650
- settings: {
1651
- host: sftpConfig.host,
1652
- port: sftpConfig.port,
1653
- username: sftpUsername,
1654
- password: sftpPassword,
1655
- remotePath: sftpConfig.remotePath,
1656
- archivePath: sftpConfig.archivePath,
1657
- errorPath: sftpConfig.errorPath,
1658
- filePattern: sftpConfig.filePattern,
1659
- encoding: 'utf8',
1660
- requireAbsolutePaths: true,
1661
- },
1662
- },
1663
- log
1664
- );
1665
-
1666
- await sftp.validateConnection();
1667
- log.info('βœ… SFTP connection validated successfully');
1668
-
1669
- // Initialize services
1670
- const csvParser = new CSVParserService();
1671
- const mapper = new UniversalMapper(mappingConfig);
1672
- const kv = openKv(':project:');
1673
- const fileTracker = new VersoriFileTracker(kv, 'sftp-csv-product-sync');
1674
-
1675
- // Initialize class-based services
1676
- const fileProcessor = new ProductFileProcessorService(
1677
- sftp,
1678
- csvParser,
1679
- mapper,
1680
- activation.getVariable('catalogueRef') || 'PC:MASTER:2'
1681
- );
1682
- // βœ… PRODUCTION ENHANCEMENT: Pass log to EventSenderService for detailed progress tracking
1683
- const eventSender = new EventSenderService(client, log);
1684
- const eventLogger = new EventLoggerService(sftp);
1685
-
1686
- // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1687
- // STEP 4: DISCOVER FILES ON SFTP
1688
- // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1689
-
1690
- log.info('πŸ“‚ [STEP 4/7] Discovering files on SFTP', {
1691
- jobId,
1692
- remotePath: sftpConfig.remotePath,
1693
- filePattern: sftpConfig.filePattern,
1694
- });
1695
-
1696
- await tracker.updateJob(jobId, {
1697
- status: 'processing',
1698
- stage: 'file_discovery',
1699
- message: 'Discovering files on SFTP',
1700
- });
1701
-
1702
- // List files from SFTP
1703
- const files = await sftp.listFiles({
1704
- remotePath: sftpConfig.remotePath,
1705
- filePattern: sftpConfig.filePattern,
1706
- });
1707
-
1708
- const maxFilesPerRun = parseInt(activation.getVariable('maxFilesPerRun') || '10', 10);
1709
- const csvFiles = maxFilesPerRun > 0 ? files.slice(0, maxFilesPerRun) : files;
1710
-
1711
- log.info(`βœ… Found ${csvFiles.length} CSV files matching pattern`);
1712
-
1713
- if (csvFiles.length === 0) {
1714
- log.info('ℹ️ No files to process');
1715
-
1716
- return {
1717
- success: true,
1718
- message: 'No files to process',
1719
- filesProcessed: 0,
1720
- filesFailed: 0,
1721
- recordsProcessed: 0,
1722
- eventsSent: 0,
1723
- eventsFailed: 0,
1724
- results: [],
1725
- duration: Date.now() - startTime,
1726
- };
1727
- }
1728
-
1729
- log.info(`πŸ“‹ Processing ${csvFiles.length} files`);
1730
-
1731
- // ========================================
1732
- // STEP 5: PROCESS FILES
1733
- // ========================================
1734
-
1735
- const results: any[] = [];
1736
- const eventConfig = {
1737
- catalogueRef: activation.getVariable('catalogueRef') || 'PC:MASTER:2',
1738
- catalogueType: activation.getVariable('catalogueType') || 'MASTER',
1739
- eventName: activation.getVariable('eventName') || 'UPSERT_PRODUCT',
1740
- eventMode: (activation.getVariable('eventMode') || 'async') as 'async' | 'sync',
1741
- };
1742
-
1743
- // Get event sending configuration
1744
- const eventConcurrency = Math.max(
1745
- 1,
1746
- parseInt(activation.getVariable('eventConcurrency') || '1', 10)
1747
- );
1748
- // Validate: Ensure concurrency is at least 1 (sequential) or higher (parallel)
1749
- // concurrency: 1 = sequential, concurrency > 1 = parallel
1750
-
1751
- log.info(`Event concurrency: ${eventConcurrency}`, {
1752
- mode: eventConcurrency === 1 ? 'sequential' : 'parallel',
1753
- concurrentRequests: eventConcurrency === 1 ? 'N/A' : eventConcurrency,
1754
- });
1755
-
1756
- for (const file of csvFiles) {
1757
- const fileStartTime = Date.now();
1758
- const fileName = extractFileName(file.name);
1759
-
1760
- try {
1761
- // Check if already processed (file tracking)
1762
- if (sftpConfig.enableFileTracking && (await fileTracker.wasFileProcessed(fileName))) {
1763
- log.info(`⏭️ Skipping already processed: ${fileName}`);
1764
- results.push({ file: fileName, success: true, skipped: true });
1765
- continue;
1766
- }
1767
-
1768
- log.info(`πŸ”„ Processing file: ${fileName}`);
1769
-
1770
- // Download and parse
1771
- const csvContent = (await sftp.downloadFile(file.path, { encoding: 'utf8' })) as string;
1772
- const records = await csvParser.parse(csvContent);
1773
- const products: any[] = Array.isArray(records) ? records : records ? [records] : [];
1774
-
1775
- log.info(`πŸ“Š Parsed ${products.length} products from ${fileName}`);
1776
-
1777
- if (products.length === 0) {
1778
- await sftp.moveFile(file.path, `${sftpConfig.archivePath}${fileName}`, true);
1779
- results.push({ file: fileName, success: true, recordCount: 0 });
1780
- continue;
1781
- }
1782
-
1783
- // Transform with UniversalMapper
1784
- const mapped = await mapper.map(products);
1785
- if (!mapped.success) {
1786
- throw new Error(`Mapping failed: ${mapped.errors?.join(', ')}`);
1787
- }
1788
-
1789
- log.info(`βœ… Transformed ${mapped.data.length} products for ${fileName}`);
1790
-
1791
- // ═══════════════════════════════════════════════════════════
1792
- // STEP 6: Send Events
1793
- // ═══════════════════════════════════════════════════════════
1794
- log.info(`πŸ“€ [STEP 6/7] Sending events for ${fileName}`);
1795
-
1796
- // βœ… Enhanced: Extract context for progress logging
1797
- const sampleProductRefs = mapped.data.slice(0, 5).map((p: any) => p.ref || p.skuRef);
1798
- const eventType = eventConfig.eventName || 'UPSERT_PRODUCT';
1799
-
1800
- // βœ… Enhanced: Start logging with context
1801
- log.info(`[EventSender] Sending events for file "${fileName}"`, {
1802
- totalProducts: mapped.data.length,
1803
- eventType,
1804
- concurrency: eventConcurrency === 1 ? 'sequential' : `parallel (${eventConcurrency})`,
1805
- sampleProductRefs: sampleProductRefs.join(', '),
1806
- eventMode: eventConfig.eventMode || 'async'
1807
- });
1808
-
1809
- const eventResult = await eventSender.sendEvents(
1810
- mapped.data,
1811
- eventConfig,
1812
- eventConcurrency
1813
- );
1814
-
1815
- const eventsSent = eventResult.eventsSent;
1816
- const eventsFailed = eventResult.eventsFailed;
1817
-
1818
- log.info(`βœ… Events sent for ${fileName}`, {
1819
- successful: eventsSent,
1820
- failed: eventsFailed
1821
- });
1822
-
1823
- // βœ… Enhanced: Completion logging with summary
1824
- log.info(`[EventSender] Event submission completed for file "${fileName}"`, {
1825
- totalProducts: mapped.data.length,
1826
- eventsSent,
1827
- eventsFailed,
1828
- successRate: mapped.data.length > 0 ? `${Math.round((eventsSent / mapped.data.length) * 100)}%` : '0%',
1829
- eventType
1830
- });
1831
-
1832
- // Archive file and mark as processed
1833
- log.info(`πŸ“¦ [STEP 7/7] Archiving file: ${fileName}`);
1834
- await sftp.moveFile(file.path, `${sftpConfig.archivePath}${fileName}`, true);
1835
-
1836
- if (sftpConfig.enableFileTracking) {
1837
- await fileTracker.markFileProcessed(fileName, {
1838
- recordCount: products.length,
1839
- eventsSent,
1840
- eventsFailed,
1841
- });
1842
- }
1843
-
1844
- results.push({
1845
- file: fileName,
1846
- success: true,
1847
- recordCount: products.length,
1848
- eventsSent,
1849
- eventsFailed,
1850
- duration: Date.now() - fileStartTime,
1851
- });
1852
-
1853
- log.info(`βœ… Successfully processed ${fileName}`, {
1854
- recordCount: products.length,
1855
- eventsSent,
1856
- eventsFailed,
1857
- duration: Date.now() - fileStartTime,
1858
- });
1859
- } catch (error: any) {
1860
- log.error(`❌ Error processing ${fileName}:`, {
1861
- message: error?.message || 'Unknown error',
1862
- stack: error?.stack,
1863
- });
1864
-
1865
- // Move to error directory
1866
- try {
1867
- await sftp.moveFile(file.path, `${sftpConfig.errorPath}${fileName}`, true);
1868
- } catch (moveError) {
1869
- log.error(`❌ Failed to move error file: ${fileName}`);
1870
- }
1871
-
1872
- results.push({ file: fileName, success: false, error: error.message });
1873
- }
1874
- }
1875
-
1876
- // ========================================
1877
- // STEP 6: CLEANUP
1878
- // ========================================
1879
-
1880
- try {
1881
- await sftp.dispose();
1882
- log.info('βœ… [EXECUTION BOUNDARY] SFTP connection disposed successfully');
1883
- } catch (disposeError: any) {
1884
- log.error('⚠️ Failed to dispose SFTP connection', {
1885
- message: disposeError instanceof Error ? disposeError.message : String(disposeError),
1886
- });
1887
- }
1888
-
1889
- const duration = Date.now() - startTime;
1890
- const filesProcessed = results.filter(r => r.success && !r.skipped).length;
1891
- const filesFailed = results.filter(r => !r.success).length;
1892
- const filesSkipped = results.filter(r => r.skipped).length;
1893
-
1894
- log.info('πŸŽ‰ [EXECUTION BOUNDARY] Product ingestion completed', {
1895
- jobId,
1896
- filesProcessed,
1897
- filesFailed,
1898
- filesSkipped,
1899
- duration,
1900
- });
1901
-
1902
- return {
1903
- success: true,
1904
- filesProcessed,
1905
- filesSkipped,
1906
- filesFailed,
1907
- results,
1908
- duration,
1909
- };
1910
- } catch (error: any) {
1911
- log.error('πŸ’₯ [EXECUTION BOUNDARY] Product ingestion failed', {
1912
- jobId,
1913
- message: error instanceof Error ? error.message : String(error),
1914
- stack: error instanceof Error ? error.stack : undefined,
1915
- });
1916
-
1917
- return {
1918
- success: false,
1919
- error: error.message,
1920
- duration: Date.now() - startTime,
1921
- };
1922
- }
1923
- }
1924
- ```
1925
-
1926
- ---
1927
-
1928
- ## 8. Utility Functions (src/utils/)
1929
-
1930
- ### SFTP Path Helpers (src/utils/sftp-path.utils.ts)
1931
-
1932
- ```typescript
1933
- /**
1934
- * SFTP Path Utilities
1935
- *
1936
- * Helper functions for SFTP path operations.
1937
- */
1938
-
1939
- /**
1940
- * Extract base filename from full SFTP path
1941
- *
1942
- * @param filePath - Full SFTP path or filename
1943
- * @returns Base filename only
1944
- *
1945
- * @example
1946
- * ```typescript
1947
- * extractFileName('/products/incoming/products_20250101.csv')
1948
- * // Returns: 'products_20250101.csv'
1949
- *
1950
- * extractFileName('products_20250101.csv')
1951
- * // Returns: 'products_20250101.csv'
1952
- * ```
1953
- */
1954
- export function extractFileName(filePath: string): string {
1955
- return filePath.split('/').pop() || filePath;
1956
- }
1957
- ```
1958
-
1959
- ---
1960
-
1961
- ### Job ID Generator (src/utils/job-id-generator.ts)
1962
-
1963
- ```typescript
1964
- /**
1965
- * Job ID Generator
1966
- *
1967
- * Generates unique job IDs for tracking ingestion workflows
1968
- *
1969
- * FORMAT: {TYPE}_{ENTITY}_{YYYYMMDD}_{HHMMSS}_{RANDOM}
1970
- * Example: SCHEDULED_PRD_20251024_183045_a1b2c3
1971
- *
1972
- * NAMING: generate{Entity}JobId or generateJobId (generic)
1973
- */
1974
-
1975
- /**
1976
- * Generate unique job ID
1977
- *
1978
- * @param type - Job trigger type (SCHEDULED, ADHOC, MANUAL)
1979
- * @param entity - Entity abbreviation (VP, IP, ORD, PRD)
1980
- * @returns Unique job ID string
1981
- */
1982
- export function generateJobId(type: string, entity: string): string {
1983
- const now = new Date();
1984
-
1985
- // Format: YYYYMMDD
1986
- const dateStr = now.toISOString().slice(0, 10).replace(/-/g, "");
1987
-
1988
- // Format: HHMMSS
1989
- const timeStr = now.toISOString().slice(11, 19).replace(/:/g, "");
1990
-
1991
- // Random suffix (6 chars)
1992
- const randomStr = Math.random().toString(36).substring(2, 8);
1993
-
1994
- return `${type}_${entity}_${dateStr}_${timeStr}_${randomStr}`;
1995
- }
1996
-
1997
- /**
1998
- * Parse job ID components
1999
- *
2000
- * @param jobId - Job ID to parse
2001
- * @returns Parsed components or null if invalid
2002
- */
2003
- export function parseJobId(
2004
- jobId: string
2005
- ): {
2006
- type: string;
2007
- entity: string;
2008
- date: string;
2009
- time: string;
2010
- random: string;
2011
- } | null {
2012
- const parts = jobId.split("_");
2013
-
2014
- if (parts.length !== 5) {
2015
- return null;
2016
- }
2017
-
2018
- return {
2019
- type: parts[0],
2020
- entity: parts[1],
2021
- date: parts[2],
2022
- time: parts[3],
2023
- random: parts[4],
2024
- };
2025
- }
2026
- ```
2027
-
2028
- ---
2029
-
2030
- ## 5. Package Configuration
2031
-
2032
- ### package.json
2033
-
2034
- ```json
2035
- {
2036
- "name": "sftp-csv-product-event",
2037
- "version": "1.2.0",
2038
- "description": "Ingest product CSV files from SFTP and send to Fluent Commerce Event API",
2039
- "type": "module",
2040
- "main": "src/index.ts",
2041
- "scripts": {
2042
- "dev": "versori dev",
2043
- "build": "versori build",
2044
- "deploy": "versori deploy"
2045
- },
2046
- "dependencies": {
2047
- "@fluentcommerce/fc-connect-sdk": "^0.1.39",
2048
- "@versori/run": "latest"
2049
- },
2050
- "devDependencies": {
2051
- "@types/node": "^20.0.0",
2052
- "typescript": "^5.0.0"
2053
- }
2054
- }
2055
- ```
2056
-
2057
- ### tsconfig.json
2058
-
2059
- ```json
2060
- {
2061
- "compilerOptions": {
2062
- "module": "ES2022",
2063
- "target": "ES2024",
2064
- "moduleResolution": "node"
2065
- }
2066
- }
2067
- ```
2068
-
2069
- ---
2070
-
2071
- ## 6. Deployment Instructions
2072
-
2073
- ### Deploy to Versori
2074
-
2075
- ```bash
2076
- # 1. Install dependencies
2077
- npm install
2078
-
2079
- # 2. Test locally (if using Versori CLI)
2080
- npm run dev
2081
-
2082
- # 3. Deploy to Versori platform
2083
- npm run deploy
2084
- ```
2085
-
2086
- ### Configure Activation Variables
2087
-
2088
- In Versori platform settings, configure:
2089
-
2090
- ```json
2091
- {
2092
- "sftpHost": "sftp.partner.com",
2093
- "sftpPort": 22,
2094
- "sftpPrivateKey": "",
2095
- "sftpIncomingPath": "/products/incoming",
2096
- "sftpProcessedPath": "/products/processed",
2097
- "sftpErrorPath": "/products/errors",
2098
- "filePattern": "products_*.csv",
2099
- "catalogueRef": "PC:MASTER:2",
2100
- "catalogueType": "MASTER",
2101
- "eventName": "UPSERT_PRODUCT",
2102
- "eventMode": "async",
2103
- "maxFilesPerRun": 10,
2104
- "requireAbsolutePaths": "true"
2105
- }
2106
- ```
2107
-
2108
- > **Note:** `sftpUsername` and `sftpPassword` are fetched from the `versori_ftp_server` Basic Auth connection.
2109
-
2110
- ---
2111
-
2112
- ## 7. Performance Notes
2113
-
2114
- - **Event sending:** Sequential processing (<100 records) is simple and reliable; consider parallel batches (Promise.allSettled) for 100-1000 records
2115
- - **Batch API threshold:** For high volumes (>1000 records), use Batch API instead of Event API for better throughput
2116
- - **File concurrency:** Files process sequentially by default; for very high volumes, consider processing 3-5 files in parallel if SFTP limits allow
2117
- - **Rate limiting:** If 429 throttling is observed, add small backoff/delay or switch to Batch API
2118
-
2119
- ---
2120
-
2121
- ## 8. Testing
2122
-
2123
- ### Test Scheduled Ingestion
2124
-
2125
- Upload a test CSV file to SFTP incoming directory and wait for the scheduled run.
2126
-
2127
- **Check logs:**
2128
-
2129
- ```
2130
- [STEP 1/8] Initializing job tracking
2131
- [STEP 2/8] Initializing Fluent Commerce client and SFTP
2132
- [STEP 3/8] Discovering files on SFTP
2133
- [FILE 1/1] Processing file: products_20250124.csv
2134
- [STEP 4/8] Downloading and parsing: products_20250124.csv
2135
- [STEP 5/8] Transforming 5 products from products_20250124.csv
2136
- [STEP 6/8] Sending 5 events to Fluent Commerce
2137
- [STEP 7/8] Archiving file: products_20250124.csv
2138
- [STEP 8/8] Completing job and calculating totals
2139
- ```
2140
-
2141
- ### Test Ad hoc Ingestion
2142
-
2143
- ```bash
2144
- # Process all pending files
2145
- curl -X POST https://api.versori.com/webhooks/product-ingestion-adhoc \
2146
- -H "Content-Type: application/json" \
2147
- -d '{}'
2148
-
2149
- # Process specific pattern
2150
- curl -X POST https://api.versori.com/webhooks/product-ingestion-adhoc \
2151
- -H "Content-Type: application/json" \
2152
- -d '{
2153
- "filePattern": "urgent_*.csv", }'
2154
- ```
2155
-
2156
- ### Test Job Status Query
2157
-
2158
- ```bash
2159
- curl -X POST https://api.versori.com/webhooks/product-ingestion-job-status \
2160
- -H "Content-Type: application/json" \
2161
- -d '{
2162
- "jobId": "ADHOC_PROD_20251024_183045_abc123"
2163
- }'
2164
- ```
2165
-
2166
- ---
2167
-
2168
- ## Monitoring
2169
-
2170
- ### Success Response
2171
-
2172
- ```json
2173
- {
2174
- "success": true,
2175
- "filesProcessed": 1,
2176
- "filesSkipped": 0,
2177
- "filesFailed": 0,
2178
- "totalRecords": 50,
2179
- "eventsSent": 50,
2180
- "eventsFailed": 0,
2181
- "results": [
2182
- {
2183
- "file": "products_2025-01-22.csv",
2184
- "success": true,
2185
- "recordsProcessed": 50,
2186
- "eventsSent": 50,
2187
- "eventsFailed": 0
2188
- }
2189
- ],
2190
- "duration": 12345
2191
- }
2192
- ```
2193
-
2194
- ### Partial Success Response
2195
-
2196
- ```json
2197
- {
2198
- "success": true,
2199
- "filesProcessed": 1,
2200
- "filesSkipped": 0,
2201
- "filesFailed": 0,
2202
- "totalRecords": 50,
2203
- "eventsSent": 45,
2204
- "eventsFailed": 5,
2205
- "results": [
2206
- {
2207
- "file": "products_2025-01-22.csv",
2208
- "success": true,
2209
- "recordsProcessed": 50,
2210
- "eventsSent": 45,
2211
- "eventsFailed": 5,
2212
- "errors": ["PRD-001: Invalid SKU format", "PRD-002: Missing required field"]
2213
- }
2214
- ],
2215
- "duration": 12345
2216
- }
2217
- ```
2218
-
2219
- ### Error Response
2220
-
2221
- ```json
2222
- {
2223
- "success": false,
2224
- "filesProcessed": 0,
2225
- "filesFailed": 1,
2226
- "totalRecords": 0,
2227
- "eventsSent": 0,
2228
- "eventsFailed": 0,
2229
- "results": [
2230
- {
2231
- "file": "products_2025-01-22.csv",
2232
- "success": false,
2233
- "error": "CSV parse error: Invalid structure"
2234
- }
2235
- ],
2236
- "duration": 876
2237
- }
2238
- ```
2239
-
2240
- ### Monitoring Metrics
2241
-
2242
- Monitor these metrics via Versori logs filtered by `jobId` or `stage`:
2243
-
2244
- - **Files Processed** - Total files successfully processed
2245
- - **Events Sent** - Total events sent to Fluent Commerce
2246
- - **Events Failed** - Events that failed (check rejection reports)
2247
- - **Processing Duration** - Time taken for complete workflow
2248
- - **Rate Limiting** - Watch for 429 errors indicating throttling
2249
-
2250
- Use the status webhook for dashboards and automated monitoring.
2251
-
2252
- ---
2253
-
2254
- **To replicate this template for other entities/formats:**
2255
-
2256
- 1. **File Naming:** Replace `product`, `PRD` with your entity name across all files
2257
- 2. **CSV Structure:** Update expected CSV format and parsing logic
2258
- 3. **Mapping Config:** Create new mapping file in `config/` with correct field paths
2259
- 4. **Event Name:** Update event name (e.g., `UPSERT_INVENTORY`, `CREATE_LOCATION`)
2260
- 5. **Workflows:** Rename workflow exports to match entity (e.g., `scheduledInventoryIngestion`)
2261
- 6. **Service Function:** Rename main function (e.g., `executeInventoryIngestion`)
2262
- 7. **File Pattern:** Update SFTP file pattern (e.g., `inventory_*.csv`)
2263
- 8. **Data Source:** For S3 use `S3DataSource`, for XML use `XMLParserService`
2264
-
2265
- ---
2266
-
2267
- ## 10. Template summary
2268
-
2269
- This template provides:
2270
-
2271
- - SFTP ? Fluent Commerce ingestion workflow
2272
- - File discovery and tracking (VersoriFileTracker)
2273
- - CSV parsing and transformation (CSVParserService + UniversalMapper)
2274
- - Event API integration with per-record error handling
2275
- - File archival (success/error paths)
2276
- - Job tracking (scheduled, ad hoc, status query modes)
2277
- - SFTP connection cleanup and retry logic
2278
-
2279
- ---
2280
-
2281
- ## πŸ”§ Troubleshooting (quick)
2282
-
2283
- - No files found: Check `sftpIncomingPath` and `filePattern` (names only).
2284
- - CSV parse failed: Move to errors/; validate CSV structure and encoding.
2285
- - High event failures: Inspect rejection report; consider Batch API for very high volumes.
2286
- - 429 throttling: Add small backoff/delay or use Batch API.
2287
-
2288
- ## πŸ—ΊοΈ Mapping tips (compact)
2289
-
2290
- - Required fields: mark in mapping JSON; failed items won't be sent.
2291
- - Arrays: use custom resolver `custom.splitByPipe` for pipe-separated values.
2292
- - Nested objects: use custom resolvers `custom.buildPriceArray` and `custom.buildTaxType`.
2293
- - Resolvers: prefer SDK built-ins (trim, uppercase, parseFloat).
2294
-
2295
- ---
1
+ ---
2
+ template_id: tpl-ingest-sftp-csv-to-product-event
3
+ canonical_filename: template-ingestion-sftp-csv-product-event.md
4
+ version: 2.0.0
5
+ sdk_version: ^0.1.39
6
+ runtime: versori
7
+ direction: ingestion
8
+ source: sftp-csv
9
+ destination: fluent-event-api
10
+ entity: product
11
+ format: csv
12
+ logging: versori
13
+ status: stable
14
+ features:
15
+ - batched-events
16
+ - attribute-transformation
17
+ - memory-management
18
+ - json-serialization-handling
19
+ - enhanced-logging
20
+ ---
21
+
22
+ # Template: Ingestion - SFTP CSV to Product Event
23
+
24
+ **Template Version:** 2.0.0
25
+ **SDK Version:** @fluentcommerce/fc-connect-sdk@^0.1.39
26
+ **Last Updated:** 2025-01-24
27
+ **Deployment Target:** Versori Platform
28
+
29
+ **πŸ†• Version 2.0.0 Enhancements:**
30
+ - βœ… **Batched Events Support** - UPSERT_PRODUCTS with configurable batch sizes (10x faster for 100+ products)
31
+ - βœ… **Attribute Transformation** - Automatic conversion of flat attributes to Fluent Commerce array format
32
+ - βœ… **Memory Management** - Configurable batch processing with explicit cleanup (prevents OOM on large CSV files)
33
+ - βœ… **JSON Serialization Handling** - Prevents 503 errors from non-serializable webhook responses
34
+ - βœ… **Enhanced Event Logging** - Status-prefixed logs (SUCCESS_/ERROR_) with comprehensive metrics and progress tracking
35
+
36
+ ---
37
+
38
+ ## πŸ“š STEP 1: Load These Docs Into Your AI (Human Checklist)
39
+
40
+ 1. REQUIRED (load all)
41
+ - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
42
+ - [ ] fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
43
+ - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
44
+ - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
45
+ - [ ] fc-connect-sdk/docs/03-PATTERN-GUIDES/ingestion/
46
+ - [ ] fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
47
+
48
+ Copy-paste list (open these):
49
+ fc-connect-sdk/docs/02-CORE-GUIDES/api-reference/
50
+ fc-connect-sdk/docs/02-CORE-GUIDES/mapping/
51
+ fc-connect-sdk/docs/03-PATTERN-GUIDES/data-sources/
52
+ fc-connect-sdk/docs/03-PATTERN-GUIDES/parsers/
53
+ fc-connect-sdk/docs/03-PATTERN-GUIDES/ingestion/
54
+ fc-connect-sdk/docs/04-REFERENCE/platforms/versori/
55
+
56
+ ---
57
+
58
+ ## πŸ“‹ Implementation Prompt
59
+
60
+ ```
61
+ I need a Versori scheduled ingestion that:
62
+
63
+ 1) Discovers CSV files on SFTP with file tracking to skip duplicates
64
+ 2) Downloads and parses CSV (returns array directly - no normalization needed)
65
+ 3) Transforms records with UniversalMapper per mapping JSON
66
+ 4) Sends UPSERT_PRODUCT events (async) to Fluent Commerce with per-record error handling
67
+ 5) Archives files to processed/ or errors/ and writes optional rejection report
68
+ 6) Tracks progress with JobTracker and exposes a job-status webhook
69
+ 7) Uses native Versori log from context
70
+
71
+ Use the loaded docs to fill in SDK specifics and best practices.
72
+ Keep the structure identical to the template; only adapt where needed.
73
+ ```
74
+
75
+ ---
76
+
77
+ ## πŸ“‹ Template Overview
78
+
79
+ This connector runs on the Versori platform. Most operational settings (Fluent account/connection, SFTP connection, schedule, file patterns/limits) are configured via activation variables. Data shape and logic (mapping JSON, CSV structure, parsing rules, per-record handling) are adjusted in code as needed. It reads product data from SFTP CSV, transforms it, and sends events to the Fluent Commerce Event API.
80
+
81
+ ### What This Template Does
82
+
83
+ ```
84
+ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
85
+ οΏ½ INGESTION WORKFLOW οΏ½
86
+ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
87
+
88
+ 1. TRIGGER
89
+ οΏ½οΏ½ Scheduled (Cron): Runs automatically every hour
90
+ οΏ½οΏ½ Ad hoc (Webhook): Manual trigger for immediate processing
91
+ οΏ½οΏ½ Status Query (Webhook): Check job progress
92
+
93
+ 2. DISCOVER FILES (SftpDataSource)
94
+ οΏ½οΏ½ List files from SFTP directory
95
+ οΏ½οΏ½ Filter by pattern (products_*.csv)
96
+ οΏ½οΏ½ Check file tracking (skip processed)
97
+ "οΏ½ Sort by oldest first
98
+
99
+ 3. FOR EACH FILE (Per-File Processing)
100
+ οΏ½οΏ½ Process one file completely before moving to next
101
+ "οΏ½ Steps 4-6 happen for each file
102
+
103
+ 4. PROCESS FILE (Service Function)
104
+ οΏ½οΏ½ Download CSV from SFTP
105
+ οΏ½οΏ½ Parse CSV to array (CSVParserService)
106
+ οΏ½οΏ½ Transform with UniversalMapper
107
+ "οΏ½ Return transformed products
108
+
109
+ 5. SEND EVENTS (Service Function)
110
+ οΏ½οΏ½ Loop through transformed products
111
+ οΏ½οΏ½ Send UPSERT_PRODUCT event (async)
112
+ οΏ½οΏ½ Track success/failure count
113
+ "οΏ½ Continue on individual failures
114
+
115
+ 6. ARCHIVE & TRACK (SftpDataSource + KV)
116
+ οΏ½οΏ½ Move file to processed/ or errors/
117
+ οΏ½οΏ½ Generate timestamped archive name
118
+ οΏ½οΏ½ Mark as processed in KV
119
+ οΏ½οΏ½ Optional: Write event log
120
+ "οΏ½ Store file result
121
+
122
+ 7. REPEAT for next file (loop back to step 3)
123
+
124
+ 8. COMPLETE JOB (JobTracker)
125
+ οΏ½οΏ½ Calculate totals (all files)
126
+ οΏ½οΏ½ Store final result in KV
127
+ οΏ½οΏ½ Enable status queries via webhook
128
+ "οΏ½ Return complete results
129
+ ```
130
+
131
+ ### Key Features
132
+
133
+ - **Service Functions**: Modular design with 3 service functions:
134
+ 1. `processFile()` - Downloads, parses, transforms (SftpDataSource + CSVParserService + UniversalMapper)
135
+ 2. `sendEvents()` - Loops through products, sends events with per-record error handling
136
+ 3. `writeEventLog()` - Writes event logs to SFTP using Buffer (for audit/debugging)
137
+
138
+ - **Per-File Processing**: Each file is processed completely (download ? parse ? map ? send ? archive) before moving to next
139
+ - **Job Tracking**: JobTracker persists stage/status to Versori KV for visibility and status queries
140
+ - **Execution Modes**: Scheduled (cron), ad hoc (webhook), status query (webhook)
141
+ - **File Tracking**: KV-based file tracking prevents duplicates; `forceReprocess` bypasses
142
+ - **Event API**: Per-record failures don't block other records; optional rejection reports
143
+ - **SFTP Cleanup**: Connection disposal in finally block ensures cleanup
144
+
145
+ Note: JobTracker recommended for production multi-step flows; can be skipped for trivial single-step utilities.
146
+
147
+ ### πŸ“¦ Package Information
148
+
149
+ **SDK:** [@fluentcommerce/fc-connect-sdk](https://www.npmjs.com/package/@fluentcommerce/fc-connect-sdk)
150
+
151
+ **Installation:**
152
+ ```bash
153
+ npm install @fluentcommerce/fc-connect-sdk@latest
154
+ ```
155
+
156
+ **Version:** Use latest SDK version from npm
157
+
158
+ ---
159
+
160
+ **Templates are designed for direct deployment; customize via activation variables.**
161
+
162
+ ---
163
+
164
+ ## πŸ“¦ SDK Imports (Verified - Versori Optimized)
165
+
166
+ ```typescript
167
+ // ? VERIFIED IMPORTS - These match actual SDK exports
168
+ import { Buffer } from 'node:buffer';
169
+ import {
170
+ createClient, // Universal client factory
171
+ SftpDataSource, // SFTP operations with connection pooling
172
+ CSVParserService, // CSV parsing
173
+ UniversalMapper, // Field mapping with SDK resolvers
174
+ VersoriFileTracker, // File processing state tracker
175
+ JobTracker, // Job status tracking
176
+ } from "@fluentcommerce/fc-connect-sdk";
177
+
178
+ import type {
179
+ FluentClient,
180
+ SftpDataSourceConfig,
181
+ } from "@fluentcommerce/fc-connect-sdk";
182
+
183
+ // Versori platform imports
184
+ import { schedule, webhook, http, fn, credentials } from "@versori/run";
185
+ ```
186
+
187
+ **Note:** All imports are from actual SDK exports - this code compiles and runs as-is.
188
+
189
+ **? VERSORI PLATFORM - Use Native Logs:**
190
+
191
+ - Use `log` from context: `const { log } = ctx;`
192
+ - Native Versori logs are simpler and automatically integrated with platform monitoring
193
+
194
+ ---
195
+
196
+ ## SFTP Connection Setup
197
+
198
+ **Two methods available for accessing SFTP credentials:**
199
+
200
+ ### Method 1: activation.connections (Recommended)
201
+
202
+ **? BEST PRACTICE - Most Secure & Flexible**
203
+
204
+ Store SFTP credentials in a Versori connection and access via `activation.connections`:
205
+
206
+ **Connection Configuration:**
207
+
208
+ 1. In Versori platform, create a connection named `SFTP`
209
+ 2. Set **Authentication Type**: `Basic Auth`
210
+ 3. Enter **Username**: Your SFTP username
211
+ 4. Enter **Password**: Your SFTP password
212
+
213
+ **Access in code:**
214
+
215
+ ```typescript
216
+ const { activation } = ctx;
217
+ const conn = activation.connections.SFTP;
218
+ const rawAccessToken = conn.accessToken;
219
+ const rawBasicAuth = Buffer.from(rawAccessToken, 'base64').toString('utf-8');
220
+ const [username, password] = rawBasicAuth.split(':');
221
+ ```
222
+
223
+ **Benefits:**
224
+ - βœ… Credentials stored securely in Versori vault
225
+ - βœ… Connection reusable across workflows
226
+ - βœ… Access all connections dynamically
227
+ - βœ… No activation variables needed for secrets
228
+ - βœ… Easier credential rotation
229
+ - βœ… Built-in connection health monitoring
230
+
231
+ **Security:** Connections are encrypted at rest and in transit by Versori platform.
232
+
233
+ ### Method 2: credentials().get() (Alternative)
234
+
235
+ **Alternative approach using credentials API:**
236
+
237
+ ```typescript
238
+ const { credentials } = ctx;
239
+ const conn = credentials().get('SFTP');
240
+ const rawAccessToken = conn.accessToken;
241
+ const rawBasicAuth = Buffer.from(rawAccessToken, 'base64').toString('utf-8');
242
+ const [username, password] = rawBasicAuth.split(':');
243
+ ```
244
+
245
+ **When to use:**
246
+ - Single-connection workflows
247
+ - Workflows using `credentials()` API
248
+ - Simpler syntax for single credential access
249
+
250
+ **Comparison:**
251
+
252
+ | Feature | `activation.connections` | `credentials().get()` |
253
+ |---------|-------------------------|----------------------|
254
+ | **Security** | Same (Versori vault) | Same (Versori vault) |
255
+ | **Access Pattern** | Object property | Method call |
256
+ | **Multiple Connections** | Enumerate all via `Object.keys()` | Need connection names |
257
+ | **Dynamic Discovery** | Yes | Limited |
258
+ | **Future-proof** | Yes (recommended API) | Yes (maintained) |
259
+
260
+ **πŸ“š Complete guide:** See [SFTP Credential Access Security Guide](../../../../../02-CORE-GUIDES/data-sources/data-sources-sftp-credential-access-security.md) for:
261
+ - Detailed security comparison
262
+ - Error handling patterns
263
+ - Connection validation
264
+ - Multi-connection scenarios
265
+ - Best practices
266
+
267
+ **Template uses:** `activation.connections` (Method 1) throughout - most flexible for production use.
268
+
269
+ ## βš™οΈ Activation Variables
270
+
271
+ **Configuration is driven by activation variables - modify these instead of code:**
272
+
273
+ > **Note:** `sftpUsername` and `sftpPassword` are fetched from the `SFTP` Basic Auth connection (see SFTP Connection Setup above).
274
+
275
+ ```bash
276
+ # SFTP Configuration
277
+ SFTP_HOST=sftp.partner.com
278
+ SFTP_PORT=22
279
+
280
+ # SFTP Paths
281
+ SFTP_REMOTE_PATH=/incoming/products/
282
+ SFTP_ARCHIVE_PATH=/archive/products/
283
+ SFTP_ERROR_PATH=/errors/products/
284
+
285
+ # File Processing
286
+ FILE_PATTERN=.csv
287
+ MAX_FILES_PER_RUN=10
288
+
289
+ # Product Configuration
290
+ CATALOGUE_REF=PC:MASTER:2
291
+ CATALOGUE_TYPE=MASTER
292
+
293
+ # Event API Configuration
294
+ EVENT_NAME=UPSERT_PRODUCT
295
+ EVENT_MODE=async
296
+
297
+ # Fluent Configuration (via Versori connection)
298
+ # Connection: fluent_commerce (OAuth2)
299
+ FLUENT_RETAILER_ID=1
300
+
301
+ # Feature Toggles
302
+ ENABLE_FILE_TRACKING=true # Enable/disable file tracking (default: true)
303
+
304
+ # Event API Performance
305
+ USE_BATCHED_EVENTS=false # Use batched UPSERT_PRODUCTS (10x faster for 100+ products)
306
+ MAX_PRODUCTS_UNDER_BATCHED_EVENT=100 # Products per batch (only used when USE_BATCHED_EVENTS=true)
307
+ MEMORY_BATCH_SIZE=250 # Products per mapping batch (prevents OOM on large files)
308
+ ```
309
+
310
+ **Security:**
311
+ - **SFTP Authentication:** Credentials stored in Versori connection vault (not in activation variables). See [SFTP Connection Setup](#sftp-connection-setup) section below.
312
+ - **Webhook Authentication:** Enforced by Versori connection configuration. Configure your webhook connection with API key authentication in the Versori Dashboard, then reference it in `webhook({ connection: 'webhook-auth' })`.
313
+
314
+ ### Variable Explanations
315
+
316
+ | Variable | Purpose | Default | Customization Hints |
317
+ | ------------------- | --------------------------- | --------------------- | -------------------------------- |
318
+ | `FLUENT_RETAILER_ID` | Retailer ID for Event API | - | Required - Fluent retailer ID |
319
+ | **SFTP Credentials** | *From Connection* | | *See connection setup above* |
320
+ | `SFTP_HOST` | SFTP server hostname | - | Required - your SFTP server |
321
+ | `SFTP_PORT` | SFTP server port | `22` | Usually 22, sometimes 2222 |
322
+ | `SFTP_REMOTE_PATH` | Incoming files directory | `/incoming/products/` | Where new files arrive |
323
+ | `SFTP_ARCHIVE_PATH` | Processed files archive | `/archive/products/` | Where files move after success |
324
+ | `SFTP_ERROR_PATH` | Failed files directory | `/errors/products/` | Where files move after errors |
325
+ | `FILE_PATTERN` | File name filter | `.csv` | Extension or glob pattern for matching files |
326
+ | `CATALOGUE_REF` | Product catalogue reference | `PC:MASTER:2` | Target catalogue in Fluent |
327
+ | `CATALOGUE_TYPE` | Catalogue type | `MASTER` | Usually MASTER or STANDARD |
328
+ | `EVENT_NAME` | Event to send | `UPSERT_PRODUCT` | Event name from Rubix |
329
+ | `EVENT_MODE` | Event processing mode | `async` | async (recommended) or sync |
330
+ | `MAX_FILES_PER_RUN` | Max files per execution | `10` | Prevent timeout on large batches (0 = unlimited) |
331
+ | `ENABLE_FILE_TRACKING` | Enable file deduplication | `"true"` | `"true"` = skip already processed files, `"false"` = process all files |
332
+ | `USE_BATCHED_EVENTS` | Use batched UPSERT_PRODUCTS | `false` | `true` = batched events (10x faster for 100+ products), `false` = individual events |
333
+ | `MAX_PRODUCTS_UNDER_BATCHED_EVENT` | Products per batch | `100` | Only used when `USE_BATCHED_EVENTS=true` (default: 100) |
334
+ | `MEMORY_BATCH_SIZE` | Products per mapping batch | `250` | Processes products in batches during mapping (prevents OOM on large files) |
335
+
336
+ ---
337
+
338
+ ## πŸ”’ SDK Automatic Behaviors (v0.1.40+)
339
+
340
+ **The SDK automatically validates and retries for improved reliability:**
341
+
342
+ ### retailerId Validation
343
+ - **SDK validates** `retailerId` before calling `sendEvent()`
344
+ - **Checks:** `event.retailerId || client.retailerId`
345
+ - **If missing:** Throws `"retailerId is required for Event API..."`
346
+ - **Configuration:** Set via `FLUENT_RETAILER_ID` activation variable (recommended)
347
+
348
+ ### 401 Auth Retry
349
+ - **Automatic retry** for platform auth failures (3 attempts)
350
+ - **Delay:** Exponential backoff (1s β†’ 2s β†’ 4s)
351
+ - **Applies to:** All `sendEvent()` calls (async and sync modes)
352
+ - **Log:** `"[fc-connect-sdk:auth] Platform auth failure (401), retrying..."`
353
+
354
+ ### 5xx Server Retry
355
+ - **Automatic retry** for transient server errors (3 attempts)
356
+ - **Delay:** Exponential backoff (1s β†’ 2s β†’ 4s, capped at 10s)
357
+ - **Protects:** Against Fluent API transient failures
358
+
359
+ ### No Code Changes Required
360
+ - All templates remain compatible
361
+ - Retry logic is automatic and transparent
362
+ - Better error messages guide configuration
363
+
364
+ **See:** [Event API Guide](./event-api-guide.md) for complete details
365
+
366
+ ---
367
+
368
+ ### πŸ“ File Tracking & Deduplication
369
+
370
+ **How file tracking prevents duplicates:**
371
+
372
+ 1. **Discovery:** List all files matching `filePattern` from `sftpIncomingPath`
373
+ 2. **Filter:** Query VersoriFileTracker to check which files were already processed
374
+ 3. **Process:** Only process untracked files (skips duplicates automatically)
375
+ 4. **Mark:** Mark file as processed after successful Event API ingestion
376
+ 5. **Archive:** Move file to `sftpProcessedPath` (or `sftpErrorPath` on failure)
377
+
378
+ **File lifecycle:**
379
+
380
+ ```
381
+ /incoming/products_20250124_001.csv
382
+ ?οΏ½ (discovered)
383
+ VersoriFileTracker.wasFileProcessed() ? false
384
+ ?οΏ½ (process file)
385
+ Parse CSV ? Map to events ? Send to Event API
386
+ ?οΏ½ (success)
387
+ VersoriFileTracker.markFileProcessed()
388
+ ?οΏ½ (archive)
389
+ /processed/products_20250124_001-20250124T183045.csv
390
+ ```
391
+
392
+ **Force reprocess:**
393
+
394
+ Set `forceReprocess: true` in webhook payload to bypass file tracker and reprocess files. Useful for:
395
+
396
+ - Fixing bad data that was previously ingested
397
+ - Reingesting after mapping config changes
398
+ - Testing with production files
399
+
400
+ **Note:** Force reprocess doesn't prevent marking as processed - files are still tracked after reprocessing.
401
+
402
+ ---
403
+
404
+ ### πŸ“ SFTP Path vs File Pattern
405
+
406
+ **Critical:** Folder paths and file patterns are configured separately.
407
+
408
+ - **Folder Paths:** Configured via activation variables:
409
+
410
+ - `sftpIncomingPath` - Where new files arrive (e.g., `/products/incoming`)
411
+ - `sftpProcessedPath` - Where successful files are archived (e.g., `/products/processed`)
412
+ - `sftpErrorPath` - Where failed files are moved (e.g., `/products/errors`)
413
+
414
+ - **File Pattern:** Configured via `filePattern` activation variable
415
+ - Matches filenames ONLY (not folder paths)
416
+ - Supports wildcards: `*.csv`, `products_*.csv`, `urgent_*.csv`
417
+
418
+ **How it works:**
419
+
420
+ ```typescript
421
+ // The workflow lists files like this:
422
+ sftp.listFiles({
423
+ remotePath: "/products/incoming", // ?οΏ½ Folder from activation variable
424
+ filePattern: "products_*.csv", // ?οΏ½ Pattern matches filenames only
425
+ });
426
+ ```
427
+
428
+ **Example:** With these settings:
429
+
430
+ ```json
431
+ {
432
+ "sftpIncomingPath": "/products/incoming",
433
+ "filePattern": "products_*.csv"
434
+ }
435
+ ```
436
+
437
+ The workflow will find files like:
438
+
439
+ - βœ… `/products/incoming/products_20250124.csv`
440
+ - βœ… `/products/incoming/products_urgent.csv`
441
+ - ❌ `/products/incoming/orders_20250124.csv` (doesn't match pattern)
442
+ - ❌ `/orders/incoming/products_20250124.csv` (wrong folder)
443
+
444
+ **Note:** To process files from different folders, change `sftpIncomingPath` (not `filePattern`).
445
+
446
+ ---
447
+
448
+ ## πŸ“„ Mapping Configuration
449
+
450
+ **File:** `config/products.import.csv.json`
451
+
452
+ ```json
453
+ {
454
+ "name": "products.import.csv",
455
+ "version": "1.0.0",
456
+ "description": "CSV ? Product Event Mapping",
457
+ "fields": {
458
+ "ref": {
459
+ "source": "ref",
460
+ "required": true,
461
+ "resolver": "sdk.trim"
462
+ },
463
+ "type": {
464
+ "source": "type",
465
+ "resolver": "sdk.uppercase",
466
+ "defaultValue": "STANDARD"
467
+ },
468
+ "status": {
469
+ "source": "status",
470
+ "resolver": "sdk.uppercase",
471
+ "defaultValue": "ACTIVE"
472
+ },
473
+ "gtin": {
474
+ "source": "gtin",
475
+ "resolver": "sdk.trim"
476
+ },
477
+ "name": {
478
+ "source": "name",
479
+ "required": true,
480
+ "resolver": "sdk.trim"
481
+ },
482
+ "summary": {
483
+ "source": "summary"
484
+ },
485
+ "categoryRefs": {
486
+ "source": "category_refs",
487
+ "resolver": "custom.splitByPipe"
488
+ },
489
+ "price": {
490
+ "resolver": "custom.buildPriceArray"
491
+ },
492
+ "taxType": {
493
+ "resolver": "custom.buildTaxType"
494
+ },
495
+ "attributes": {
496
+ "defaultValue": []
497
+ }
498
+ }
499
+ }
500
+ ```
501
+
502
+ **Custom Resolvers:**
503
+
504
+ ```typescript
505
+ const customResolvers = {
506
+ /**
507
+ * Split pipe-separated string into array
508
+ * Example: "CAT1|CAT2|CAT3" ? ["CAT1", "CAT2", "CAT3"]
509
+ */
510
+ 'custom.splitByPipe': (value: string) => {
511
+ if (!value || value.trim() === '') return [];
512
+ return value.split('|').map(v => v.trim()).filter(v => v !== '');
513
+ },
514
+
515
+ /**
516
+ * Build price array from flat CSV columns
517
+ * Expects: price_default_currency, price_default_value, price_special_currency, price_special_value
518
+ */
519
+ 'custom.buildPriceArray': (value: any, sourceData: any) => {
520
+ const prices = [];
521
+
522
+ // Add default price
523
+ if (sourceData.price_default_value) {
524
+ prices.push({
525
+ type: 'DEFAULT',
526
+ currency: sourceData.price_default_currency || 'USD',
527
+ value: sourceData.price_default_value,
528
+ });
529
+ }
530
+
531
+ // Add special price if exists
532
+ if (sourceData.price_special_value) {
533
+ prices.push({
534
+ type: 'SPECIAL',
535
+ currency: sourceData.price_special_currency || 'USD',
536
+ value: sourceData.price_special_value,
537
+ });
538
+ }
539
+
540
+ return prices;
541
+ },
542
+
543
+ /**
544
+ * Build tax type object from flat CSV columns
545
+ * Expects: tax_country, tax_group, tax_tariff
546
+ */
547
+ 'custom.buildTaxType': (value: any, sourceData: any) => {
548
+ if (!sourceData.tax_country) return undefined;
549
+
550
+ return {
551
+ country: sourceData.tax_country,
552
+ group: sourceData.tax_group,
553
+ tariff: sourceData.tax_tariff,
554
+ };
555
+ },
556
+ };
557
+ ```
558
+
559
+ Note: Adjust fields in the JSON above as needed; prefer built-in resolvers. For advanced patterns, see SDK Universal Mapping guide.
560
+
561
+ ### Mapping customization and custom resolvers (how-to)
562
+
563
+ (Condensed) Provide custom resolvers via UniversalMapper options if required.
564
+
565
+ ### Parse + map
566
+
567
+ Handled inside orchestration (download ? parse ? map). No extra helpers needed.
568
+
569
+ ---
570
+
571
+ ### Error handling & rejection reports
572
+
573
+ When moving failed files to errors/, optionally write a JSON rejection report with totals and error list for audit purposes.
574
+
575
+ ---
576
+
577
+ ## Expected CSV Format
578
+
579
+ ```csv
580
+ ref,type,status,gtin,name,summary,category_refs,price_default_currency,price_default_value,price_special_currency,price_special_value,tax_country,tax_group,tax_tariff,catalogue_ref,catalogue_type
581
+ G_PROD_WITH_NO_STANDARD,VARIANT,ACTIVE,MH01-XS-Orange,Chaz Kangeroo Hoodie-XS-Orange main,<p>test short description</p>,STANDARD_CATEGORY,USD,52.000000,USD,9.000000,AU,Tax Group,Tax Tariff,PC:MASTER:2,MASTER
582
+ G_PROD_002,VARIANT,ACTIVE,MH02-M-Blue,Kangeroo Hoodie-M-Blue,<p>Blue variant</p>,STANDARD_CATEGORY|SEASONAL,USD,45.000000,USD,35.000000,AU,Tax Group,Tax Tariff,PC:MASTER:2,MASTER
583
+ ```
584
+
585
+ ---
586
+
587
+ ## Event Sending Configuration
588
+
589
+ **Simple Configuration:** One variable controls everything
590
+
591
+ ```json
592
+ {
593
+ "eventConcurrency": 1 // 1 = sequential, 3-10 = parallel
594
+ }
595
+ ```
596
+
597
+ **How it works:**
598
+
599
+ - `eventConcurrency: 1` ? Sequential (sends events one at a time, safe default)
600
+ - `eventConcurrency: 3` ? Parallel (sends 3 events concurrently)
601
+ - `eventConcurrency: 5` ? Parallel (sends 5 events concurrently)
602
+ - `eventConcurrency: 10` ? Parallel (sends 10 events concurrently)
603
+
604
+ **Configuration Guidelines:**
605
+
606
+ - **Conservative:** `1` ? Sequential (safe, predictable, ~1 req/sec)
607
+ - **Balanced:** `3-5` ? Parallel (most common, ~3-5 req/sec)
608
+ - **Aggressive:** `10` ? Parallel (high-volume, ~10 req/sec)
609
+ - **Note:** Fluent API supports concurrent requests - adjust based on your needs
610
+
611
+ **Why Single Variable?**
612
+
613
+ - **Simpler:** One variable instead of two (`mode` + `concurrency`)
614
+ - **Clearer:** `concurrency: 1` = sequential, `concurrency > 1` = parallel
615
+ - **Less config:** Fewer activation variables to manage
616
+ - **Flexible:** Easy to tune performance (just change the number)
617
+
618
+ ---
619
+
620
+ ## πŸ”§ Production Implementation
621
+
622
+ ### Processing Modes
623
+
624
+ | Mode | Default | What happens | When to use |
625
+ | ---------- | ------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
626
+ | `per-file` | ? | Process one file end-to-end (discover ? parse ? Event API ? archive) before moving on | Recommended for production SFTP feeds and very large files |
627
+ | `chunked` | ? | Processes `fileChunkSize` files at a time, completing each chunk before the next | High-volume feeds where per-file would take too long |
628
+ | `batch` | ? | Loads every matched file into memory, produces a single Event API job, and archives when complete | Tiny datasets or smoke tests only |
629
+
630
+ Set the mode via activation variables:
631
+
632
+ ```json
633
+ {
634
+ "processingMode": "per-file",
635
+ "fileChunkSize": "5",
636
+ "maxFilesPerRun": "25"
637
+ }
638
+ ```
639
+
640
+ ---
641
+
642
+ ## πŸ”§ Complete Production Code
643
+
644
+ ### Versori Workflows Structure
645
+
646
+ **Key Concept**: Versori workflows are organized by **trigger type** at the first level, then by **specific workflow** with descriptive file names.
647
+
648
+ **Trigger Types:**
649
+ - **`schedule()`** β†’ Time-based triggers (cron expressions) - NOT exposed as HTTP endpoints
650
+ - **`webhook()`** β†’ HTTP-based triggers (event-driven) - Creates HTTP endpoints
651
+ - **`workflow()`** β†’ Durable workflows (advanced, rarely used)
652
+
653
+ **Execution Steps (chained to triggers):**
654
+ - **`http()`** β†’ External API calls (chained from schedule/webhook)
655
+ - **`fn()`** β†’ Internal processing (chained from schedule/webhook)
656
+
657
+ ### Recommended Project Structure
658
+
659
+ ```
660
+ product-event-sync/
661
+ β”œβ”€β”€ index.ts # Entry point - exports all workflows
662
+ └── src/
663
+ β”œβ”€β”€ workflows/
664
+ β”‚ β”œβ”€β”€ scheduled/
665
+ β”‚ β”‚ └── daily-product-sync.ts # Scheduled: Daily product sync
666
+ β”‚ β”‚
667
+ β”‚ └── webhook/
668
+ β”‚ β”œβ”€β”€ adhoc-product-sync.ts # Webhook: Manual trigger
669
+ β”‚ └── job-status-check.ts # Webhook: Status query
670
+ β”‚
671
+ β”œβ”€β”€ services/
672
+ β”‚ └── product-sync.service.ts # Shared orchestration logic (reusable)
673
+ β”‚
674
+ └── types/
675
+ └── product.types.ts # Shared type definitions
676
+ ```
677
+
678
+ **Benefits:**
679
+ - βœ… Clear trigger separation (`scheduled/` vs `webhook/`)
680
+ - βœ… Descriptive file names (easy to browse and understand)
681
+ - βœ… Scalable (add new workflows without cluttering)
682
+ - βœ… Reusable code in `services/` (DRY principle)
683
+ - βœ… Easy to modify individual workflows without affecting others
684
+
685
+ ---
686
+
687
+ ## Workflow Files
688
+
689
+ ### 1. Scheduled Workflows (`src/workflows/scheduled/`)
690
+
691
+ All time-based triggers that run automatically on cron schedules.
692
+
693
+ #### `src/workflows/scheduled/daily-product-sync.ts`
694
+
695
+ **Purpose**: Automatic Daily product sync
696
+ **Trigger**: Cron schedule (`0 2 * * *`)
697
+ **Exposed as Endpoint**: ❌ NO - Runs automatically
698
+
699
+ ```typescript
700
+ import { schedule, http } from '@versori/run';
701
+ import { JobTracker } from '@fluentcommerce/fc-connect-sdk';
702
+ import { executeProductIngestion } from '../../services/product-sync.service';
703
+
704
+ /**
705
+ * Scheduled Workflow: Daily Product Sync
706
+ *
707
+ * Runs automatically daily at 2 AM UTC
708
+ * NOT exposed as HTTP endpoint - Versori executes on schedule
709
+ *
710
+ * Uses shared service: product-sync.service.ts
711
+ */
712
+ export const dailyProductSync = schedule(
713
+ 'product-sync-scheduled',
714
+ '0 2 * * *' // Daily at 2 AM UTC
715
+ ).then(
716
+ http('run-product-sync', { connection: 'fluent_commerce' }, async (ctx: any) => {
717
+ const { log, openKv } = ctx;
718
+ const executionStartTime = Date.now();
719
+ const jobId = `product-sync-${executionStartTime}`;
720
+ const tracker = new JobTracker(openKv(':project:'), log);
721
+
722
+ log.info('πŸš€ [WORKFLOW] Starting scheduled product sync', { jobId });
723
+
724
+ await tracker.createJob(jobId, {
725
+ triggeredBy: 'schedule',
726
+ stage: 'initialization',
727
+ startTime: executionStartTime
728
+ });
729
+ await tracker.updateJob(jobId, { status: 'processing' });
730
+
731
+ try {
732
+ // Reuse shared orchestration logic
733
+ const result = await executeProductIngestion(ctx, jobId, tracker);
734
+
735
+ if (result.success) {
736
+ await tracker.markCompleted(jobId, result);
737
+ log.info('βœ… [WORKFLOW] Product sync completed successfully', {
738
+ jobId,
739
+ filesProcessed: result.filesProcessed,
740
+ duration: result.duration
741
+ });
742
+ } else {
743
+ await tracker.markFailed(jobId, result.error || 'Unknown error');
744
+ log.error('❌ [WORKFLOW] Product sync failed', { jobId, error: result.error });
745
+ }
746
+
747
+ return { success: true, jobId, ...result };
748
+ } catch (e: any) {
749
+ const errorMessage = e instanceof Error ? e.message : String(e);
750
+ await tracker.markFailed(jobId, errorMessage);
751
+ log.error('❌ [WORKFLOW] Product sync failed with exception', {
752
+ jobId,
753
+ error: errorMessage,
754
+ stack: e instanceof Error ? e.stack : undefined
755
+ });
756
+ return { success: false, jobId, error: errorMessage };
757
+ }
758
+ })
759
+ );
760
+ ```
761
+
762
+ ---
763
+
764
+ ### 2. Webhook Workflows (`src/workflows/webhook/`)
765
+
766
+ All HTTP-based triggers that create webhook endpoints.
767
+
768
+ #### `src/workflows/webhook/adhoc-product-sync.ts`
769
+
770
+ **Purpose**: Manual product sync trigger (on-demand)
771
+ **Trigger**: HTTP POST
772
+ **Endpoint**: `POST https://{workspace}.versori.run/product-sync-adhoc`
773
+ **Use Cases**: Testing, priority processing, ad-hoc runs
774
+
775
+ ```typescript
776
+ import { webhook, http } from '@versori/run';
777
+ import { JobTracker } from '@fluentcommerce/fc-connect-sdk';
778
+ import { executeProductIngestion } from '../../services/product-sync.service';
779
+
780
+ /**
781
+ * Webhook: Manual Product Sync Trigger
782
+ *
783
+ * Endpoint: POST https://{workspace}.versori.run/product-sync-adhoc
784
+ * Request body (optional): { filePattern: "urgent_*.csv", maxFiles: 5 }
785
+ *
786
+ * Pattern: webhook().then(http()) - needs Fluent API access
787
+ * Uses shared service: product-sync.service.ts
788
+ *
789
+ * SECURITY: Authentication handled via connection parameter
790
+ * No manual API key validation needed - Versori manages this via connection auth
791
+ */
792
+ export const adhocProductSync = webhook('product-sync-adhoc', {
793
+ response: { mode: 'sync' }, // βœ… Sync mode: response sent when handler returns
794
+ connection: 'product-sync-adhoc', // Versori validates API key
795
+ }).then(
796
+ http('run-product-sync-adhoc', { connection: 'fluent_commerce' }, async (ctx: any) => {
797
+ const { log, openKv, data } = ctx;
798
+ const executionStartTime = Date.now();
799
+ const jobId = `product-sync-adhoc-${executionStartTime}`;
800
+ const tracker = new JobTracker(openKv(':project:'), log);
801
+
802
+ const filePattern = data?.filePattern as string;
803
+ const maxFiles = data?.maxFiles as number;
804
+
805
+ log.info('πŸš€ [WEBHOOK] Adhoc product sync triggered', {
806
+ jobId,
807
+ filePattern,
808
+ maxFiles,
809
+ });
810
+
811
+ // Create job entry FIRST (awaited to ensure job exists in KV)
812
+ await tracker.createJob(jobId, {
813
+ triggeredBy: 'webhook',
814
+ stage: 'initialization',
815
+ status: 'queued',
816
+ startTime: executionStartTime,
817
+ options: { filePattern, maxFiles },
818
+ createdAt: new Date().toISOString(),
819
+ });
820
+
821
+ // βœ… Fire-and-forget: Start background processing WITHOUT await
822
+ // The promise continues execution after we return the response
823
+ executeProductIngestion(ctx, jobId, tracker)
824
+ .then((result) => {
825
+ if (result.success) {
826
+ log.info('βœ… [BACKGROUND] Product sync completed successfully', {
827
+ jobId,
828
+ filesProcessed: result.filesProcessed,
829
+ filesFailed: result.filesFailed,
830
+ recordsProcessed: result.recordsProcessed,
831
+ duration: result.duration,
832
+ });
833
+ return tracker.markCompleted(jobId, result);
834
+ } else {
835
+ log.error('❌ [BACKGROUND] Product sync failed', {
836
+ jobId,
837
+ error: result.error,
838
+ });
839
+ return tracker.markFailed(jobId, result.error || 'Unknown error');
840
+ }
841
+ })
842
+ .catch((error: unknown) => {
843
+ const errorMessage = error instanceof Error ? error.message : String(error);
844
+ const errorStack = error instanceof Error ? error.stack : undefined;
845
+
846
+ log.error('❌ [BACKGROUND] Product sync failed with exception', {
847
+ jobId,
848
+ error: errorMessage,
849
+ stack: errorStack,
850
+ errorType: error instanceof Error ? error.constructor.name : typeof error,
851
+ });
852
+
853
+ return tracker.markFailed(jobId, errorMessage);
854
+ });
855
+
856
+ // Return immediately with jobId (response sent with this return value)
857
+ return {
858
+ success: true,
859
+ jobId,
860
+ message: 'Product sync started in background',
861
+ statusEndpoint: `https://{workspace}.versori.run/product-sync-job-status`,
862
+ note: 'Poll the status endpoint with jobId to check progress',
863
+ };
864
+ })
865
+ );
866
+ ```
867
+
868
+ #### `src/workflows/webhook/job-status-check.ts`
869
+
870
+ **Purpose**: Query job status
871
+ **Trigger**: HTTP POST
872
+ **Endpoint**: `POST https://{workspace}.versori.run/product-sync-job-status`
873
+ **Request body**: `{ "jobId": "product-sync-1234567890" }`
874
+
875
+ ```typescript
876
+ import { webhook, fn } from '@versori/run';
877
+ import { JobTracker } from '@fluentcommerce/fc-connect-sdk';
878
+
879
+ /**
880
+ * Webhook: Job Status Check
881
+ *
882
+ * Endpoint: POST https://{workspace}.versori.run/product-sync-job-status
883
+ * Request body: { "jobId": "product-sync-1234567890" }
884
+ *
885
+ * Pattern: webhook().then(fn()) - no external API needed, only KV storage
886
+ * Lightweight: Only queries KV store, no Fluent API calls
887
+ *
888
+ * SECURITY: Authentication handled via connection parameter
889
+ * No manual API key validation needed - Versori manages this via connection auth
890
+ */
891
+ export const productSyncJobStatus = webhook('product-sync-job-status', {
892
+ response: { mode: 'sync' },
893
+ connection: 'product-sync-job-status',
894
+ }).then(
895
+ fn('status', async ctx => {
896
+ const { data, log, openKv } = ctx;
897
+ const jobId = data?.jobId as string;
898
+
899
+ if (!jobId) {
900
+ return { success: false, error: 'jobId required' };
901
+ }
902
+
903
+ const tracker = new JobTracker(openKv(':project:'), log);
904
+ const status = await tracker.getJob(jobId);
905
+
906
+ return status
907
+ ? { success: true, jobId, ...status }
908
+ : { success: false, error: 'Job not found', jobId };
909
+ })
910
+ );
911
+ ```
912
+
913
+ ---
914
+
915
+ ### 3. Entry Point (`index.ts`)
916
+
917
+ **Purpose**: Register all workflows with Versori platform
918
+
919
+ ```typescript
920
+ /**
921
+ * Entry Point - Registers all workflows with Versori platform
922
+ *
923
+ * Versori automatically discovers and registers exported workflows
924
+ *
925
+ * File Structure:
926
+ * - src/workflows/scheduled/ β†’ Time-based triggers (cron)
927
+ * - src/workflows/webhook/ β†’ HTTP-based triggers (webhooks)
928
+ */
929
+
930
+ // Import scheduled workflows
931
+ import { dailyProductSync } from './src/workflows/scheduled/daily-product-sync';
932
+
933
+ // Import webhook workflows
934
+ import { adhocProductSync } from './src/workflows/webhook/adhoc-product-sync';
935
+ import { productSyncJobStatus } from './src/workflows/webhook/job-status-check';
936
+
937
+ // Register all workflows
938
+ export {
939
+ // Scheduled (time-based triggers)
940
+ dailyProductSync,
941
+
942
+ // Webhooks (HTTP-based triggers)
943
+ adhocProductSync,
944
+ productSyncJobStatus,
945
+ };
946
+ ```
947
+
948
+ **What Gets Exposed:**
949
+ - βœ… `adhocProductSync` β†’ `https://{workspace}.versori.run/product-sync-adhoc`
950
+ - βœ… `productSyncJobStatus` β†’ `https://{workspace}.versori.run/product-sync-job-status`
951
+ - ❌ `dailyProductSync` β†’ NOT exposed (runs automatically on cron)
952
+
953
+ ---
954
+
955
+ ### Adding New Workflows
956
+
957
+ **To add a scheduled workflow:**
958
+ 1. Create file in `src/workflows/scheduled/` with descriptive name (e.g., `hourly-delta-sync.ts`)
959
+ 2. Export the workflow from the file
960
+ 3. Import and re-export in `index.ts`
961
+
962
+ **To add a webhook workflow:**
963
+ 1. Create file in `src/workflows/webhook/` with descriptive name (e.g., `error-notification.ts`)
964
+ 2. Export the workflow from the file
965
+ 3. Import and re-export in `index.ts`
966
+
967
+ **Example - Adding hourly delta sync:**
968
+
969
+ ```typescript
970
+ // src/workflows/scheduled/hourly-delta-sync.ts
971
+ export const hourlyDeltaSync = schedule(
972
+ 'product-delta-hourly',
973
+ '0 * * * *' // Every hour
974
+ ).then(
975
+ http('run-delta-sync', { connection: 'fluent_commerce' }, async ctx => {
976
+ // Delta sync logic (skip BPP)
977
+ const result = await runIngestion(ctx, jobId, tracker, { bppEnabled: false });
978
+ return result;
979
+ })
980
+ );
981
+
982
+ // index.ts (add to imports and exports)
983
+ import { hourlyDeltaSync } from './src/workflows/scheduled/hourly-delta-sync';
984
+ export { dailyProductSync, hourlyDeltaSync, ... };
985
+ ```
986
+
987
+ ---
988
+ ## 3. Type Definitions (src/types/product-ingestion.types.ts)
989
+
990
+ ```typescript
991
+ /**
992
+ * Type Definitions for Product Ingestion
993
+ *
994
+ * Centralized type definitions for product ingestion workflow
995
+ */
996
+
997
+ import type { FluentClient } from '@fluentcommerce/fc-connect-sdk';
998
+
999
+ /**
1000
+ * Product interface - represents transformed product data
1001
+ */
1002
+ export interface Product {
1003
+ ref: string;
1004
+ type?: string;
1005
+ status?: string;
1006
+ name: string;
1007
+ summary?: string;
1008
+ gtin?: string;
1009
+ catalogue?: { ref?: string };
1010
+ attributes?: Record<string, unknown>;
1011
+ }
1012
+
1013
+ /**
1014
+ * Event configuration
1015
+ */
1016
+ export interface EventConfig {
1017
+ eventName: string;
1018
+ catalogueRef: string;
1019
+ catalogueType: string;
1020
+ eventMode: 'async' | 'sync';
1021
+ }
1022
+
1023
+ /**
1024
+ * Event result - tracks success/failure counts
1025
+ */
1026
+ export interface EventResult {
1027
+ eventsSent: number;
1028
+ eventsFailed: number;
1029
+ errors: Array<{ productRef: string; error: string }>;
1030
+ }
1031
+
1032
+ /**
1033
+ * Process file result
1034
+ */
1035
+ export interface ProcessFileResult {
1036
+ success: boolean;
1037
+ products: Product[];
1038
+ error?: string;
1039
+ }
1040
+
1041
+ /**
1042
+ * Versori Context Interface
1043
+ * Represents the Versori runtime context passed to workflow functions
1044
+ */
1045
+ export interface VersoriContext {
1046
+ log: {
1047
+ info: (message: string, data?: Record<string, unknown>) => void;
1048
+ warn: (message: string, data?: Record<string, unknown>) => void;
1049
+ error: (message: string, data?: Record<string, unknown>) => void;
1050
+ debug?: (message: string, data?: Record<string, unknown>) => void;
1051
+ };
1052
+ openKv: (namespace: string) => {
1053
+ get: (key: string) => Promise<unknown>;
1054
+ set: (key: string, value: unknown) => Promise<void>;
1055
+ delete: (key: string) => Promise<void>;
1056
+ };
1057
+ activation: {
1058
+ getVariable: (name: string) => string | undefined;
1059
+ connections?: Record<string, unknown>;
1060
+ };
1061
+ connections?: Record<string, unknown>;
1062
+ data?: unknown;
1063
+ fetch?: typeof fetch;
1064
+ }
1065
+
1066
+ /**
1067
+ * Parameters for ingestion workflow
1068
+ */
1069
+ export interface ProductIngestionParams {
1070
+ jobId: string;
1071
+ triggeredBy: 'schedule' | 'webhook';
1072
+ filePattern?: string;
1073
+ maxFiles?: number;
1074
+ forceReprocess?: boolean;
1075
+ catalogueRef?: string;
1076
+ priority?: 'normal' | 'high';
1077
+ }
1078
+
1079
+ /**
1080
+ * Result from ingestion workflow
1081
+ */
1082
+ export interface ProductIngestionResult {
1083
+ success: boolean;
1084
+ jobId: string;
1085
+ filesProcessed: number;
1086
+ filesFailed: number;
1087
+ filesSkipped?: number;
1088
+ recordsProcessed: number;
1089
+ eventsSent: number;
1090
+ eventsFailed: number;
1091
+ fileResults: FileProcessingResult[];
1092
+ error?: string;
1093
+ }
1094
+
1095
+ /**
1096
+ * Per-file processing result
1097
+ */
1098
+ export interface FileProcessingResult {
1099
+ fileName: string;
1100
+ success: boolean;
1101
+ skipped?: boolean;
1102
+ recordsProcessed: number;
1103
+ eventsSent: number;
1104
+ eventsFailed: number;
1105
+ duration: number;
1106
+ error?: string;
1107
+ }
1108
+ ```
1109
+
1110
+ ---
1111
+
1112
+ ## 4. Service: Product File Processor (`src/services/product-file-processor.service.ts`)
1113
+
1114
+ ```typescript
1115
+ /**
1116
+ * Product File Processor Service
1117
+ *
1118
+ * Downloads CSV files from SFTP, parses, and transforms with UniversalMapper.
1119
+ * CSV-specific: Returns arrays directly (no normalization needed).
1120
+ */
1121
+
1122
+ import {
1123
+ SftpDataSource,
1124
+ CSVParserService,
1125
+ UniversalMapper,
1126
+ } from '@fluentcommerce/fc-connect-sdk';
1127
+ import type { ProcessFileResult, Product } from '../types/product-ingestion.types';
1128
+
1129
+ /**
1130
+ * Service for processing CSV product files
1131
+ */
1132
+ export class ProductFileProcessorService {
1133
+ constructor(
1134
+ private sftp: SftpDataSource,
1135
+ private csvParser: CSVParserService,
1136
+ private mapper: UniversalMapper,
1137
+ private catalogueRef: string
1138
+ ) {}
1139
+
1140
+ /**
1141
+ * Download CSV file from SFTP, parse, and transform with UniversalMapper
1142
+ *
1143
+ * βœ… PRODUCTION ENHANCEMENT: Memory cleanup pattern
1144
+ * - Explicit null assignments after each step
1145
+ * - Finally block guarantees cleanup
1146
+ * - Prevents OOM errors on large CSV files
1147
+ */
1148
+ async downloadParseAndTransform(remoteFilePath: string): Promise<ProcessFileResult> {
1149
+ // βœ… CRITICAL: Variables for cleanup tracking
1150
+ let csvContent: string | null = null;
1151
+ let parsed: unknown | null = null;
1152
+
1153
+ try {
1154
+ // STEP 1: Download CSV content
1155
+ csvContent = (await this.sftp.downloadFile(remoteFilePath, {
1156
+ encoding: 'utf8',
1157
+ })) as string;
1158
+
1159
+ // STEP 2: Parse CSV with type safety
1160
+ try {
1161
+ parsed = await this.csvParser.parse(csvContent);
1162
+ } catch (parseError: unknown) {
1163
+ const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
1164
+ return {
1165
+ success: false,
1166
+ products: [],
1167
+ error: `CSV parse error: ${errorMessage}`,
1168
+ };
1169
+ }
1170
+
1171
+ // βœ… Clear csvContent from memory - no longer needed after parsing
1172
+ csvContent = null;
1173
+
1174
+ // STEP 3: CSV-SPECIFIC - Returns array directly, no normalization needed
1175
+ const rawProducts = Array.isArray(parsed) ? parsed : [];
1176
+
1177
+ if (rawProducts.length === 0) {
1178
+ return {
1179
+ success: false,
1180
+ products: [],
1181
+ error: 'No products found in CSV',
1182
+ };
1183
+ }
1184
+
1185
+ // βœ… Clear parsed data from memory - only need rawProducts now
1186
+ parsed = null;
1187
+
1188
+ // STEP 4: Transform with UniversalMapper
1189
+ // CSV-SPECIFIC: Merge context using spread pattern (not { inventory: ... })
1190
+ const sourceDataWithContext = rawProducts.map(item => ({
1191
+ ...item,
1192
+ $context: { catalogueRef: this.catalogueRef },
1193
+ }));
1194
+
1195
+ const mappingResult = await this.mapper.map(sourceDataWithContext);
1196
+
1197
+ if (!mappingResult.success) {
1198
+ return {
1199
+ success: false,
1200
+ products: [],
1201
+ error: `Mapping validation failed: ${mappingResult.errors?.join(', ')}`,
1202
+ };
1203
+ }
1204
+
1205
+ if (mappingResult.skippedFields && mappingResult.skippedFields.length > 0) {
1206
+ this.log.info('ℹ️ [MAPPING] Optional fields skipped (undefined values)', {
1207
+ skippedFields: mappingResult.skippedFields,
1208
+ note: 'These fields were not present in source data. Add defaultValue to mapping config if they should always appear.',
1209
+ });
1210
+ }
1211
+
1212
+ return {
1213
+ success: true,
1214
+ products: mappingResult.data as Product[],
1215
+ };
1216
+ } catch (error: unknown) {
1217
+ const errorMessage = error instanceof Error ? error.message : String(error);
1218
+ return {
1219
+ success: false,
1220
+ products: [],
1221
+ error: errorMessage,
1222
+ };
1223
+ } finally {
1224
+ // βœ… CRITICAL: Ensure all large objects are cleared even if error occurs
1225
+ csvContent = null;
1226
+ parsed = null;
1227
+ }
1228
+ }
1229
+ }
1230
+ ```
1231
+
1232
+ ---
1233
+
1234
+ ## 5. Service: Event Sender (`src/services/event-sender.service.ts`)
1235
+
1236
+ ```typescript
1237
+ /**
1238
+ * Event Sender Service
1239
+ *
1240
+ * Sends product events to Fluent Commerce Event API with per-record error handling.
1241
+ * Continues processing on individual failures (Event API best practice).
1242
+ * Supports configurable concurrency (sequential or parallel).
1243
+ */
1244
+
1245
+ import type { FluentClient } from '@fluentcommerce/fc-connect-sdk';
1246
+ import type { EventResult, EventConfig, Product } from '../types/product-ingestion.types';
1247
+
1248
+ /**
1249
+ * Service for sending events to Fluent Commerce Event API
1250
+ *
1251
+ * βœ… PRODUCTION ENHANCEMENT: Optional logger for detailed progress tracking
1252
+ */
1253
+ export class EventSenderService {
1254
+ constructor(
1255
+ private client: FluentClient,
1256
+ private log?: any // βœ… Optional logger for progress tracking
1257
+ ) {}
1258
+
1259
+ /**
1260
+ * Send events to Fluent Commerce Event API with configurable concurrency
1261
+ *
1262
+ * **Performance Characteristics:**
1263
+ * - `concurrency: 1` ? Sequential processing (safe default, ~1 event/sec)
1264
+ * - `concurrency: 3-5` ? Balanced throughput (~3-5 events/sec, good for most cases)
1265
+ * - `concurrency: 10` ? High-volume processing (~10 events/sec, 100+ products)
1266
+ *
1267
+ * **Implementation Strategy:**
1268
+ * - Concurrency = 1: Optimized sequential loop (no Promise.allSettled overhead)
1269
+ * - Concurrency > 1: Chunked parallel processing with bounded concurrency
1270
+ * - Both modes: Per-record error tracking (failures don't block other events)
1271
+ *
1272
+ * @param products - Array of products to send as events
1273
+ * @param eventConfig - Event configuration (name, catalogue ref, mode)
1274
+ * @param concurrency - Number of concurrent event requests (default: 1, min: 1)
1275
+ * @returns EventResult with counts (eventsSent/eventsFailed) and error details
1276
+ */
1277
+ async sendEvents(
1278
+ products: Product[],
1279
+ eventConfig: EventConfig,
1280
+ concurrency: number = 1
1281
+ ): Promise<EventResult> {
1282
+ // Validate concurrency (guard against invalid values)
1283
+ const safeConc = Math.max(1, Math.floor(concurrency));
1284
+
1285
+ // Result accumulators
1286
+ let eventsSent = 0;
1287
+ let eventsFailed = 0;
1288
+ const errors: Array<{ productRef: string; error: string }> = [];
1289
+
1290
+ // βœ… PRODUCTION ENHANCEMENT: Log event sending start
1291
+ if (this.log) {
1292
+ this.log.info('πŸ“€ Starting event sending', {
1293
+ totalProducts: products.length,
1294
+ concurrency: safeConc,
1295
+ processingMode: safeConc === 1 ? 'sequential (one at a time)' : `parallel (${safeConc} concurrently)`,
1296
+ eventName: eventConfig.eventName,
1297
+ catalogueRef: eventConfig.catalogueRef
1298
+ });
1299
+ }
1300
+
1301
+ // Helper: Build event payload (DRY - reused in both modes)
1302
+ const buildPayload = (product: Product) => ({
1303
+ name: eventConfig.eventName,
1304
+ entityRef: eventConfig.catalogueRef,
1305
+ entityType: 'PRODUCT_CATALOGUE' as const,
1306
+ entitySubtype: eventConfig.catalogueType,
1307
+ rootEntityRef: eventConfig.catalogueRef,
1308
+ rootEntityType: 'PRODUCT_CATALOGUE' as const,
1309
+ attributes: product,
1310
+ });
1311
+
1312
+ // ============================================================================
1313
+ // SEQUENTIAL MODE (concurrency === 1)
1314
+ // ============================================================================
1315
+ if (safeConc === 1) {
1316
+ for (let i = 0; i < products.length; i++) {
1317
+ const product = products[i];
1318
+
1319
+ // βœ… PRODUCTION ENHANCEMENT: Log progress every 10 products
1320
+ if (this.log && i % 10 === 0) {
1321
+ this.log.info(`πŸ“€ Sending product ${i + 1}/${products.length}`, {
1322
+ productRef: product.ref,
1323
+ progress: `${((i / products.length) * 100).toFixed(1)}%`
1324
+ });
1325
+ }
1326
+
1327
+ try {
1328
+ await this.client.sendEvent(buildPayload(product), eventConfig.eventMode);
1329
+ eventsSent++;
1330
+ } catch (err: unknown) {
1331
+ eventsFailed++;
1332
+ const errorMsg = err instanceof Error ? err.message : String(err);
1333
+ errors.push({ productRef: product?.ref || 'unknown', error: errorMsg });
1334
+ // Continue processing (failure doesn't block other products)
1335
+ }
1336
+ }
1337
+
1338
+ // βœ… PRODUCTION ENHANCEMENT: Log completion
1339
+ if (this.log) {
1340
+ this.log.info('βœ… Sequential event sending completed', {
1341
+ totalProducts: products.length,
1342
+ eventsSent,
1343
+ eventsFailed
1344
+ });
1345
+ }
1346
+
1347
+ return { eventsSent, eventsFailed, errors };
1348
+ }
1349
+
1350
+ // ============================================================================
1351
+ // PARALLEL MODE (concurrency > 1)
1352
+ // ============================================================================
1353
+ const totalChunks = Math.ceil(products.length / safeConc);
1354
+
1355
+ for (let i = 0; i < products.length; i += safeConc) {
1356
+ const chunk = products.slice(i, i + safeConc);
1357
+ const chunkNumber = Math.floor(i / safeConc) + 1;
1358
+
1359
+ // βœ… PRODUCTION ENHANCEMENT: Log chunk progress
1360
+ if (this.log) {
1361
+ this.log.info(`πŸ“¦ Processing chunk ${chunkNumber}/${totalChunks}`, {
1362
+ chunkNumber,
1363
+ totalChunks,
1364
+ productsInChunk: chunk.length,
1365
+ productRange: `${i + 1}-${i + chunk.length}`,
1366
+ totalProducts: products.length,
1367
+ progress: `${((i / products.length) * 100).toFixed(1)}%`
1368
+ });
1369
+ }
1370
+
1371
+ // Fire all requests in chunk concurrently
1372
+ const results = await Promise.allSettled(
1373
+ chunk.map(product =>
1374
+ this.client
1375
+ .sendEvent(buildPayload(product), eventConfig.eventMode)
1376
+ .then(() => ({ success: true as const, product }))
1377
+ .catch(error => ({ success: false as const, product, error }))
1378
+ )
1379
+ );
1380
+
1381
+ // Aggregate chunk results into totals
1382
+ let chunkSuccess = 0;
1383
+ let chunkFailed = 0;
1384
+
1385
+ for (const result of results) {
1386
+ if (result.status === 'fulfilled' && result.value.success) {
1387
+ eventsSent++;
1388
+ chunkSuccess++;
1389
+ } else {
1390
+ eventsFailed++;
1391
+ chunkFailed++;
1392
+ const error = result.status === 'fulfilled' ? result.value.error : result.reason;
1393
+ const product = result.status === 'fulfilled' ? result.value.product : null;
1394
+ errors.push({
1395
+ productRef: product?.ref || 'unknown',
1396
+ error: error?.message || String(error) || 'unknown error',
1397
+ });
1398
+ }
1399
+ }
1400
+
1401
+ // βœ… PRODUCTION ENHANCEMENT: Log chunk completion
1402
+ if (this.log) {
1403
+ this.log.info(`βœ… Chunk ${chunkNumber}/${totalChunks} completed`, {
1404
+ chunkNumber,
1405
+ totalChunks,
1406
+ chunkSuccess,
1407
+ chunkFailed,
1408
+ totalSentSoFar: eventsSent,
1409
+ totalFailedSoFar: eventsFailed,
1410
+ progress: `${(((i + chunk.length) / products.length) * 100).toFixed(1)}%`
1411
+ });
1412
+ }
1413
+ }
1414
+
1415
+ // βœ… PRODUCTION ENHANCEMENT: Log parallel completion
1416
+ if (this.log) {
1417
+ this.log.info('βœ… Parallel event sending completed', {
1418
+ totalProducts: products.length,
1419
+ totalChunks,
1420
+ concurrency: safeConc,
1421
+ eventsSent,
1422
+ eventsFailed
1423
+ });
1424
+ }
1425
+
1426
+ return { eventsSent, eventsFailed, errors };
1427
+ }
1428
+ }
1429
+ ```
1430
+
1431
+ ---
1432
+
1433
+ ## 6. Service: Event Logger (`src/services/event-logger.service.ts`)
1434
+
1435
+ ```typescript
1436
+ /**
1437
+ * Event Logger Service
1438
+ *
1439
+ * Writes event processing logs to SFTP for audit/debugging.
1440
+ * Optional - can be used to create rejection reports.
1441
+ */
1442
+
1443
+ import { Buffer } from 'node:buffer';
1444
+ import { SftpDataSource } from '@fluentcommerce/fc-connect-sdk';
1445
+
1446
+ /**
1447
+ * Service for writing event logs to SFTP
1448
+ */
1449
+ export class EventLoggerService {
1450
+ constructor(private sftp: SftpDataSource) {}
1451
+
1452
+ /**
1453
+ * Write event log to SFTP
1454
+ *
1455
+ * @param remotePath - SFTP path for log file
1456
+ * @param logData - Log data to write (JSON format)
1457
+ */
1458
+ async writeEventLog(remotePath: string, logData: unknown): Promise<void> {
1459
+ try {
1460
+ const logContent = JSON.stringify(logData, null, 2);
1461
+ await this.sftp.uploadFile(remotePath, logContent);
1462
+ } catch (error: unknown) {
1463
+ const errorMessage = error instanceof Error ? error.message : String(error);
1464
+ throw new Error(`Failed to write event log: ${errorMessage}`);
1465
+ }
1466
+ }
1467
+ }
1468
+ ```
1469
+
1470
+ ---
1471
+
1472
+ ## 7. Main Orchestration Service (src/services/product-ingestion.service.ts)
1473
+
1474
+ ```typescript
1475
+ /**
1476
+ * MAIN INGESTION ORCHESTRATION SERVICE
1477
+ *
1478
+ * This is the heart of the ingestion workflow. It coordinates all steps:
1479
+ * 1. Initialize clients and services
1480
+ * 2. Discover files on SFTP
1481
+ * 3. Download and parse CSV files
1482
+ * 4. Transform data with UniversalMapper
1483
+ * 5. Send events to Fluent Commerce
1484
+ * 6. Archive processed files
1485
+ * 7. Track file processing state
1486
+ * 8. Track job progress with JobTracker
1487
+ *
1488
+ * NAMING PATTERN (consistent across all use cases):
1489
+ * - Interface: {Entity}IngestionParams (e.g., ProductIngestionParams)
1490
+ * - Result: {Entity}IngestionResult (e.g., ProductIngestionResult)
1491
+ * - Main function: execute{Entity}Ingestion (e.g., executeProductIngestion)
1492
+ *
1493
+ *
1494
+ * - Change entity: Replace "Product" with "Inventory", "Location", etc.
1495
+ * - Change format: Replace CSVParserService with XMLParserService/JSONParserService
1496
+ * - Change source: Replace SftpDataSource with S3DataSource
1497
+ * - Change destination: Replace sendEvent with Batch API or GraphQL mutations
1498
+ */
1499
+
1500
+ import { Buffer } from 'node:buffer';
1501
+ import {
1502
+ createClient,
1503
+ SftpDataSource,
1504
+ CSVParserService,
1505
+ UniversalMapper,
1506
+ VersoriFileTracker,
1507
+ JobTracker,
1508
+ } from '@fluentcommerce/fc-connect-sdk';
1509
+ import type { FileMetadata } from '@fluentcommerce/fc-connect-sdk';
1510
+ import { ProductFileProcessorService } from './product-file-processor.service';
1511
+ import { EventSenderService } from './event-sender.service';
1512
+ import { EventLoggerService } from './event-logger.service';
1513
+ import { extractFileName } from '../utils/sftp-path.utils';
1514
+
1515
+ import mappingConfig from '../../config/products.import.csv.json' with { type: 'json' };
1516
+
1517
+ // ? VERSORI PLATFORM: Use native log from context, not LoggingService
1518
+
1519
+ /**
1520
+ * MAIN ORCHESTRATION FUNCTION
1521
+ *
1522
+ * NAMING: execute{Entity}Ingestion (e.g., executeProductIngestion)
1523
+ *
1524
+ * This function implements the complete ingestion workflow in 8 steps.
1525
+ * Each step is clearly commented for AI understanding.
1526
+ *
1527
+ * @param ctx - Versori context object containing fetch, connections, log, activation, openKv
1528
+ * @param jobId - Job ID for tracking
1529
+ * @param tracker - JobTracker instance for job lifecycle management
1530
+ */
1531
+ export async function executeProductIngestion(
1532
+ ctx: any,
1533
+ jobId: string,
1534
+ tracker: JobTracker
1535
+ ) {
1536
+ // ? VERSORI PLATFORM: Extract native log from context
1537
+ const { log, activation, openKv } = ctx;
1538
+ const startTime = Date.now();
1539
+
1540
+ log.info('πŸš€ [EXECUTION BOUNDARY] Starting product ingestion', { jobId });
1541
+
1542
+ // ⚠️ CRITICAL: Declare SFTP outside try block for double-finally pattern
1543
+ let sftp: SftpDataSource | undefined;
1544
+
1545
+ try {
1546
+ // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1547
+ // STEP 1: Initialize Fluent Client
1548
+ // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1549
+ log.info('πŸ“‘ [STEP 1/7] Initializing Fluent Commerce client', { jobId });
1550
+
1551
+ const client = await createClient(ctx);
1552
+ log.info('βœ… [DEBUG] Client created successfully');
1553
+
1554
+ /**
1555
+ * setRetailerId() - REQUIRED for Event/Batch API operations
1556
+ *
1557
+ * retailerId must be set ONCE on the client after creation.
1558
+ * This is required for Event API (sendEvent) operations.
1559
+ */
1560
+ const fluentRetailerId = activation.getVariable('fluentRetailerId');
1561
+ if (!fluentRetailerId) {
1562
+ log.error('❌ Missing required fluentRetailerId activation variable');
1563
+ return {
1564
+ success: false,
1565
+ error: 'fluentRetailerId activation variable is required for Event API operations',
1566
+ recommendation: 'Please configure fluentRetailerId in the Activation Variables section',
1567
+ };
1568
+ }
1569
+ client.setRetailerId(fluentRetailerId);
1570
+ log.info('βœ… Client initialized with retailerId', { retailerId: fluentRetailerId });
1571
+
1572
+ // ========================================
1573
+ // STEP 2: SFTP CREDENTIAL RETRIEVAL
1574
+ // ========================================
1575
+
1576
+ log.info('πŸ” [STEP 2/7] Retrieving SFTP credentials from connection');
1577
+
1578
+ let sftpUsername: string;
1579
+ let sftpPassword: string;
1580
+
1581
+ try {
1582
+ // Retrieve credentials from the 'SFTP' connection
1583
+ const sftpCred = await ctx.credentials().getAccessToken('SFTP');
1584
+
1585
+ if (!sftpCred?.accessToken) {
1586
+ throw new Error('No SFTP credentials found in connection configuration');
1587
+ }
1588
+
1589
+ // Decode base64 accessToken to get "username:password"
1590
+ const rawBasicAuth = Buffer.from(sftpCred.accessToken, 'base64').toString('utf-8');
1591
+
1592
+ // Split on ':' to extract username and password
1593
+ const parts = rawBasicAuth.split(':');
1594
+
1595
+ if (parts.length !== 2) {
1596
+ throw new Error('Invalid SFTP credential format - expected username:password');
1597
+ }
1598
+
1599
+ sftpUsername = parts[0];
1600
+ sftpPassword = parts[1];
1601
+
1602
+ log.info('βœ… SFTP credentials retrieved successfully', {
1603
+ hasUsername: !!sftpUsername,
1604
+ hasPassword: !!sftpPassword,
1605
+ });
1606
+ } catch (error: any) {
1607
+ log.error('❌ Failed to retrieve SFTP credentials', {
1608
+ message: error instanceof Error ? error.message : String(error),
1609
+ stack: error instanceof Error ? error.stack : undefined,
1610
+ });
1611
+
1612
+ return {
1613
+ success: false,
1614
+ error: 'Failed to retrieve SFTP credentials from connection configuration',
1615
+ details: error?.message,
1616
+ recommendation: 'Please ensure the SFTP connection is configured with Basic Authentication',
1617
+ };
1618
+ }
1619
+
1620
+ // ========================================
1621
+ // STEP 3: CONFIGURATION & INITIALIZATION
1622
+ // ========================================
1623
+
1624
+ log.info('βš™οΈ [STEP 3/7] Configuring SFTP and services', { jobId });
1625
+
1626
+ // Configure SFTP
1627
+ const sftpConfig = {
1628
+ host: activation.getVariable('sftpHost'),
1629
+ port: parseInt(activation.getVariable('sftpPort') || '22', 10),
1630
+ username: sftpUsername,
1631
+ password: sftpPassword,
1632
+ remotePath: activation.getVariable('sftpRemotePath') || '/incoming/products/',
1633
+ archivePath: activation.getVariable('sftpArchivePath') || '/archive/products/',
1634
+ errorPath: activation.getVariable('sftpErrorPath') || '/errors/products/',
1635
+ filePattern: activation.getVariable('filePattern') || '.csv',
1636
+ enableFileTracking: activation.getVariable('enableFileTracking') !== 'false', // default: true
1637
+ };
1638
+
1639
+ // Validate SFTP config
1640
+ if (!sftpConfig.host) {
1641
+ throw new Error('SFTP configuration incomplete: missing host');
1642
+ }
1643
+
1644
+ // Initialize SFTP data source
1645
+ sftp = new SftpDataSource(
1646
+ {
1647
+ type: 'SFTP_CSV',
1648
+ connectionId: 'sftp-product-ingestion',
1649
+ name: 'product-sync',
1650
+ settings: {
1651
+ host: sftpConfig.host,
1652
+ port: sftpConfig.port,
1653
+ username: sftpUsername,
1654
+ password: sftpPassword,
1655
+ remotePath: sftpConfig.remotePath,
1656
+ archivePath: sftpConfig.archivePath,
1657
+ errorPath: sftpConfig.errorPath,
1658
+ filePattern: sftpConfig.filePattern,
1659
+ encoding: 'utf8',
1660
+ requireAbsolutePaths: true,
1661
+ },
1662
+ },
1663
+ log
1664
+ );
1665
+
1666
+ await sftp.validateConnection();
1667
+ log.info('βœ… SFTP connection validated successfully');
1668
+
1669
+ // Initialize services
1670
+ const csvParser = new CSVParserService();
1671
+ const mapper = new UniversalMapper(mappingConfig);
1672
+ const kv = openKv(':project:');
1673
+ const fileTracker = new VersoriFileTracker(kv, 'sftp-csv-product-sync');
1674
+
1675
+ // Initialize class-based services
1676
+ const fileProcessor = new ProductFileProcessorService(
1677
+ sftp,
1678
+ csvParser,
1679
+ mapper,
1680
+ activation.getVariable('catalogueRef') || 'PC:MASTER:2'
1681
+ );
1682
+ // βœ… PRODUCTION ENHANCEMENT: Pass log to EventSenderService for detailed progress tracking
1683
+ const eventSender = new EventSenderService(client, log);
1684
+ const eventLogger = new EventLoggerService(sftp);
1685
+
1686
+ // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1687
+ // STEP 4: DISCOVER FILES ON SFTP
1688
+ // οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
1689
+
1690
+ log.info('πŸ“‚ [STEP 4/7] Discovering files on SFTP', {
1691
+ jobId,
1692
+ remotePath: sftpConfig.remotePath,
1693
+ filePattern: sftpConfig.filePattern,
1694
+ });
1695
+
1696
+ await tracker.updateJob(jobId, {
1697
+ status: 'processing',
1698
+ stage: 'file_discovery',
1699
+ message: 'Discovering files on SFTP',
1700
+ });
1701
+
1702
+ // List files from SFTP
1703
+ const files = await sftp.listFiles({
1704
+ remotePath: sftpConfig.remotePath,
1705
+ filePattern: sftpConfig.filePattern,
1706
+ });
1707
+
1708
+ const maxFilesPerRun = parseInt(activation.getVariable('maxFilesPerRun') || '10', 10);
1709
+ const csvFiles = maxFilesPerRun > 0 ? files.slice(0, maxFilesPerRun) : files;
1710
+
1711
+ log.info(`βœ… Found ${csvFiles.length} CSV files matching pattern`);
1712
+
1713
+ if (csvFiles.length === 0) {
1714
+ log.info('ℹ️ No files to process');
1715
+
1716
+ return {
1717
+ success: true,
1718
+ message: 'No files to process',
1719
+ filesProcessed: 0,
1720
+ filesFailed: 0,
1721
+ recordsProcessed: 0,
1722
+ eventsSent: 0,
1723
+ eventsFailed: 0,
1724
+ results: [],
1725
+ duration: Date.now() - startTime,
1726
+ };
1727
+ }
1728
+
1729
+ log.info(`πŸ“‹ Processing ${csvFiles.length} files`);
1730
+
1731
+ // ========================================
1732
+ // STEP 5: PROCESS FILES
1733
+ // ========================================
1734
+
1735
+ const results: any[] = [];
1736
+ const eventConfig = {
1737
+ catalogueRef: activation.getVariable('catalogueRef') || 'PC:MASTER:2',
1738
+ catalogueType: activation.getVariable('catalogueType') || 'MASTER',
1739
+ eventName: activation.getVariable('eventName') || 'UPSERT_PRODUCT',
1740
+ eventMode: (activation.getVariable('eventMode') || 'async') as 'async' | 'sync',
1741
+ };
1742
+
1743
+ // Get event sending configuration
1744
+ const eventConcurrency = Math.max(
1745
+ 1,
1746
+ parseInt(activation.getVariable('eventConcurrency') || '1', 10)
1747
+ );
1748
+ // Validate: Ensure concurrency is at least 1 (sequential) or higher (parallel)
1749
+ // concurrency: 1 = sequential, concurrency > 1 = parallel
1750
+
1751
+ log.info(`Event concurrency: ${eventConcurrency}`, {
1752
+ mode: eventConcurrency === 1 ? 'sequential' : 'parallel',
1753
+ concurrentRequests: eventConcurrency === 1 ? 'N/A' : eventConcurrency,
1754
+ });
1755
+
1756
+ for (const file of csvFiles) {
1757
+ const fileStartTime = Date.now();
1758
+ const fileName = extractFileName(file.name);
1759
+
1760
+ try {
1761
+ // Check if already processed (file tracking)
1762
+ if (sftpConfig.enableFileTracking && (await fileTracker.wasFileProcessed(fileName))) {
1763
+ log.info(`⏭️ Skipping already processed: ${fileName}`);
1764
+ results.push({ file: fileName, success: true, skipped: true });
1765
+ continue;
1766
+ }
1767
+
1768
+ log.info(`πŸ”„ Processing file: ${fileName}`);
1769
+
1770
+ // Download and parse
1771
+ const csvContent = (await sftp.downloadFile(file.path, { encoding: 'utf8' })) as string;
1772
+ const records = await csvParser.parse(csvContent);
1773
+ const products: any[] = Array.isArray(records) ? records : records ? [records] : [];
1774
+
1775
+ log.info(`πŸ“Š Parsed ${products.length} products from ${fileName}`);
1776
+
1777
+ if (products.length === 0) {
1778
+ await sftp.moveFile(file.path, `${sftpConfig.archivePath}${fileName}`, true);
1779
+ results.push({ file: fileName, success: true, recordCount: 0 });
1780
+ continue;
1781
+ }
1782
+
1783
+ // Transform with UniversalMapper
1784
+ const mapped = await mapper.map(products);
1785
+ if (!mapped.success) {
1786
+ throw new Error(`Mapping failed: ${mapped.errors?.join(', ')}`);
1787
+ }
1788
+
1789
+ log.info(`βœ… Transformed ${mapped.data.length} products for ${fileName}`);
1790
+
1791
+ // ═══════════════════════════════════════════════════════════
1792
+ // STEP 6: Send Events
1793
+ // ═══════════════════════════════════════════════════════════
1794
+ log.info(`πŸ“€ [STEP 6/7] Sending events for ${fileName}`);
1795
+
1796
+ // βœ… Enhanced: Extract context for progress logging
1797
+ const sampleProductRefs = mapped.data.slice(0, 5).map((p: any) => p.ref || p.skuRef);
1798
+ const eventType = eventConfig.eventName || 'UPSERT_PRODUCT';
1799
+
1800
+ // βœ… Enhanced: Start logging with context
1801
+ log.info(`[EventSender] Sending events for file "${fileName}"`, {
1802
+ totalProducts: mapped.data.length,
1803
+ eventType,
1804
+ concurrency: eventConcurrency === 1 ? 'sequential' : `parallel (${eventConcurrency})`,
1805
+ sampleProductRefs: sampleProductRefs.join(', '),
1806
+ eventMode: eventConfig.eventMode || 'async'
1807
+ });
1808
+
1809
+ const eventResult = await eventSender.sendEvents(
1810
+ mapped.data,
1811
+ eventConfig,
1812
+ eventConcurrency
1813
+ );
1814
+
1815
+ const eventsSent = eventResult.eventsSent;
1816
+ const eventsFailed = eventResult.eventsFailed;
1817
+
1818
+ log.info(`βœ… Events sent for ${fileName}`, {
1819
+ successful: eventsSent,
1820
+ failed: eventsFailed
1821
+ });
1822
+
1823
+ // βœ… Enhanced: Completion logging with summary
1824
+ log.info(`[EventSender] Event submission completed for file "${fileName}"`, {
1825
+ totalProducts: mapped.data.length,
1826
+ eventsSent,
1827
+ eventsFailed,
1828
+ successRate: mapped.data.length > 0 ? `${Math.round((eventsSent / mapped.data.length) * 100)}%` : '0%',
1829
+ eventType
1830
+ });
1831
+
1832
+ // Archive file and mark as processed
1833
+ log.info(`πŸ“¦ [STEP 7/7] Archiving file: ${fileName}`);
1834
+ await sftp.moveFile(file.path, `${sftpConfig.archivePath}${fileName}`, true);
1835
+
1836
+ if (sftpConfig.enableFileTracking) {
1837
+ await fileTracker.markFileProcessed(fileName, {
1838
+ recordCount: products.length,
1839
+ eventsSent,
1840
+ eventsFailed,
1841
+ });
1842
+ }
1843
+
1844
+ results.push({
1845
+ file: fileName,
1846
+ success: true,
1847
+ recordCount: products.length,
1848
+ eventsSent,
1849
+ eventsFailed,
1850
+ duration: Date.now() - fileStartTime,
1851
+ });
1852
+
1853
+ log.info(`βœ… Successfully processed ${fileName}`, {
1854
+ recordCount: products.length,
1855
+ eventsSent,
1856
+ eventsFailed,
1857
+ duration: Date.now() - fileStartTime,
1858
+ });
1859
+ } catch (error: any) {
1860
+ log.error(`❌ Error processing ${fileName}:`, {
1861
+ message: error?.message || 'Unknown error',
1862
+ stack: error?.stack,
1863
+ });
1864
+
1865
+ // Move to error directory
1866
+ try {
1867
+ await sftp.moveFile(file.path, `${sftpConfig.errorPath}${fileName}`, true);
1868
+ } catch (moveError) {
1869
+ log.error(`❌ Failed to move error file: ${fileName}`);
1870
+ }
1871
+
1872
+ results.push({ file: fileName, success: false, error: error.message });
1873
+ }
1874
+ }
1875
+
1876
+ // ========================================
1877
+ // STEP 6: CLEANUP
1878
+ // ========================================
1879
+
1880
+ try {
1881
+ await sftp.dispose();
1882
+ log.info('βœ… [EXECUTION BOUNDARY] SFTP connection disposed successfully');
1883
+ } catch (disposeError: any) {
1884
+ log.error('⚠️ Failed to dispose SFTP connection', {
1885
+ message: disposeError instanceof Error ? disposeError.message : String(disposeError),
1886
+ });
1887
+ }
1888
+
1889
+ const duration = Date.now() - startTime;
1890
+ const filesProcessed = results.filter(r => r.success && !r.skipped).length;
1891
+ const filesFailed = results.filter(r => !r.success).length;
1892
+ const filesSkipped = results.filter(r => r.skipped).length;
1893
+
1894
+ log.info('πŸŽ‰ [EXECUTION BOUNDARY] Product ingestion completed', {
1895
+ jobId,
1896
+ filesProcessed,
1897
+ filesFailed,
1898
+ filesSkipped,
1899
+ duration,
1900
+ });
1901
+
1902
+ return {
1903
+ success: true,
1904
+ filesProcessed,
1905
+ filesSkipped,
1906
+ filesFailed,
1907
+ results,
1908
+ duration,
1909
+ };
1910
+ } catch (error: any) {
1911
+ log.error('πŸ’₯ [EXECUTION BOUNDARY] Product ingestion failed', {
1912
+ jobId,
1913
+ message: error instanceof Error ? error.message : String(error),
1914
+ stack: error instanceof Error ? error.stack : undefined,
1915
+ });
1916
+
1917
+ return {
1918
+ success: false,
1919
+ error: error.message,
1920
+ duration: Date.now() - startTime,
1921
+ };
1922
+ }
1923
+ }
1924
+ ```
1925
+
1926
+ ---
1927
+
1928
+ ## 8. Utility Functions (src/utils/)
1929
+
1930
+ ### SFTP Path Helpers (src/utils/sftp-path.utils.ts)
1931
+
1932
+ ```typescript
1933
+ /**
1934
+ * SFTP Path Utilities
1935
+ *
1936
+ * Helper functions for SFTP path operations.
1937
+ */
1938
+
1939
+ /**
1940
+ * Extract base filename from full SFTP path
1941
+ *
1942
+ * @param filePath - Full SFTP path or filename
1943
+ * @returns Base filename only
1944
+ *
1945
+ * @example
1946
+ * ```typescript
1947
+ * extractFileName('/products/incoming/products_20250101.csv')
1948
+ * // Returns: 'products_20250101.csv'
1949
+ *
1950
+ * extractFileName('products_20250101.csv')
1951
+ * // Returns: 'products_20250101.csv'
1952
+ * ```
1953
+ */
1954
+ export function extractFileName(filePath: string): string {
1955
+ return filePath.split('/').pop() || filePath;
1956
+ }
1957
+ ```
1958
+
1959
+ ---
1960
+
1961
+ ### Job ID Generator (src/utils/job-id-generator.ts)
1962
+
1963
+ ```typescript
1964
+ /**
1965
+ * Job ID Generator
1966
+ *
1967
+ * Generates unique job IDs for tracking ingestion workflows
1968
+ *
1969
+ * FORMAT: {TYPE}_{ENTITY}_{YYYYMMDD}_{HHMMSS}_{RANDOM}
1970
+ * Example: SCHEDULED_PRD_20251024_183045_a1b2c3
1971
+ *
1972
+ * NAMING: generate{Entity}JobId or generateJobId (generic)
1973
+ */
1974
+
1975
+ /**
1976
+ * Generate unique job ID
1977
+ *
1978
+ * @param type - Job trigger type (SCHEDULED, ADHOC, MANUAL)
1979
+ * @param entity - Entity abbreviation (VP, IP, ORD, PRD)
1980
+ * @returns Unique job ID string
1981
+ */
1982
+ export function generateJobId(type: string, entity: string): string {
1983
+ const now = new Date();
1984
+
1985
+ // Format: YYYYMMDD
1986
+ const dateStr = now.toISOString().slice(0, 10).replace(/-/g, "");
1987
+
1988
+ // Format: HHMMSS
1989
+ const timeStr = now.toISOString().slice(11, 19).replace(/:/g, "");
1990
+
1991
+ // Random suffix (6 chars)
1992
+ const randomStr = Math.random().toString(36).substring(2, 8);
1993
+
1994
+ return `${type}_${entity}_${dateStr}_${timeStr}_${randomStr}`;
1995
+ }
1996
+
1997
+ /**
1998
+ * Parse job ID components
1999
+ *
2000
+ * @param jobId - Job ID to parse
2001
+ * @returns Parsed components or null if invalid
2002
+ */
2003
+ export function parseJobId(
2004
+ jobId: string
2005
+ ): {
2006
+ type: string;
2007
+ entity: string;
2008
+ date: string;
2009
+ time: string;
2010
+ random: string;
2011
+ } | null {
2012
+ const parts = jobId.split("_");
2013
+
2014
+ if (parts.length !== 5) {
2015
+ return null;
2016
+ }
2017
+
2018
+ return {
2019
+ type: parts[0],
2020
+ entity: parts[1],
2021
+ date: parts[2],
2022
+ time: parts[3],
2023
+ random: parts[4],
2024
+ };
2025
+ }
2026
+ ```
2027
+
2028
+ ---
2029
+
2030
+ ## 5. Package Configuration
2031
+
2032
+ ### package.json
2033
+
2034
+ ```json
2035
+ {
2036
+ "name": "sftp-csv-product-event",
2037
+ "version": "1.2.0",
2038
+ "description": "Ingest product CSV files from SFTP and send to Fluent Commerce Event API",
2039
+ "type": "module",
2040
+ "main": "src/index.ts",
2041
+ "scripts": {
2042
+ "dev": "versori dev",
2043
+ "build": "versori build",
2044
+ "deploy": "versori deploy"
2045
+ },
2046
+ "dependencies": {
2047
+ "@fluentcommerce/fc-connect-sdk": "^0.1.39",
2048
+ "@versori/run": "latest"
2049
+ },
2050
+ "devDependencies": {
2051
+ "@types/node": "^20.0.0",
2052
+ "typescript": "^5.0.0"
2053
+ }
2054
+ }
2055
+ ```
2056
+
2057
+ ### tsconfig.json
2058
+
2059
+ ```json
2060
+ {
2061
+ "compilerOptions": {
2062
+ "module": "ES2022",
2063
+ "target": "ES2024",
2064
+ "moduleResolution": "node"
2065
+ }
2066
+ }
2067
+ ```
2068
+
2069
+ ---
2070
+
2071
+ ## 6. Deployment Instructions
2072
+
2073
+ ### Deploy to Versori
2074
+
2075
+ ```bash
2076
+ # 1. Install dependencies
2077
+ npm install
2078
+
2079
+ # 2. Test locally (if using Versori CLI)
2080
+ npm run dev
2081
+
2082
+ # 3. Deploy to Versori platform
2083
+ npm run deploy
2084
+ ```
2085
+
2086
+ ### Configure Activation Variables
2087
+
2088
+ In Versori platform settings, configure:
2089
+
2090
+ ```json
2091
+ {
2092
+ "sftpHost": "sftp.partner.com",
2093
+ "sftpPort": 22,
2094
+ "sftpPrivateKey": "",
2095
+ "sftpIncomingPath": "/products/incoming",
2096
+ "sftpProcessedPath": "/products/processed",
2097
+ "sftpErrorPath": "/products/errors",
2098
+ "filePattern": "products_*.csv",
2099
+ "catalogueRef": "PC:MASTER:2",
2100
+ "catalogueType": "MASTER",
2101
+ "eventName": "UPSERT_PRODUCT",
2102
+ "eventMode": "async",
2103
+ "maxFilesPerRun": 10,
2104
+ "requireAbsolutePaths": "true"
2105
+ }
2106
+ ```
2107
+
2108
+ > **Note:** `sftpUsername` and `sftpPassword` are fetched from the `versori_ftp_server` Basic Auth connection.
2109
+
2110
+ ---
2111
+
2112
+ ## 7. Performance Notes
2113
+
2114
+ - **Event sending:** Sequential processing (<100 records) is simple and reliable; consider parallel batches (Promise.allSettled) for 100-1000 records
2115
+ - **Batch API threshold:** For high volumes (>1000 records), use Batch API instead of Event API for better throughput
2116
+ - **File concurrency:** Files process sequentially by default; for very high volumes, consider processing 3-5 files in parallel if SFTP limits allow
2117
+ - **Rate limiting:** If 429 throttling is observed, add small backoff/delay or switch to Batch API
2118
+
2119
+ ---
2120
+
2121
+ ## 8. Testing
2122
+
2123
+ ### Test Scheduled Ingestion
2124
+
2125
+ Upload a test CSV file to SFTP incoming directory and wait for the scheduled run.
2126
+
2127
+ **Check logs:**
2128
+
2129
+ ```
2130
+ [STEP 1/8] Initializing job tracking
2131
+ [STEP 2/8] Initializing Fluent Commerce client and SFTP
2132
+ [STEP 3/8] Discovering files on SFTP
2133
+ [FILE 1/1] Processing file: products_20250124.csv
2134
+ [STEP 4/8] Downloading and parsing: products_20250124.csv
2135
+ [STEP 5/8] Transforming 5 products from products_20250124.csv
2136
+ [STEP 6/8] Sending 5 events to Fluent Commerce
2137
+ [STEP 7/8] Archiving file: products_20250124.csv
2138
+ [STEP 8/8] Completing job and calculating totals
2139
+ ```
2140
+
2141
+ ### Test Ad hoc Ingestion
2142
+
2143
+ ```bash
2144
+ # Process all pending files
2145
+ curl -X POST https://api.versori.com/webhooks/product-ingestion-adhoc \
2146
+ -H "Content-Type: application/json" \
2147
+ -d '{}'
2148
+
2149
+ # Process specific pattern
2150
+ curl -X POST https://api.versori.com/webhooks/product-ingestion-adhoc \
2151
+ -H "Content-Type: application/json" \
2152
+ -d '{
2153
+ "filePattern": "urgent_*.csv", }'
2154
+ ```
2155
+
2156
+ ### Test Job Status Query
2157
+
2158
+ ```bash
2159
+ curl -X POST https://api.versori.com/webhooks/product-ingestion-job-status \
2160
+ -H "Content-Type: application/json" \
2161
+ -d '{
2162
+ "jobId": "ADHOC_PROD_20251024_183045_abc123"
2163
+ }'
2164
+ ```
2165
+
2166
+ ---
2167
+
2168
+ ## Monitoring
2169
+
2170
+ ### Success Response
2171
+
2172
+ ```json
2173
+ {
2174
+ "success": true,
2175
+ "filesProcessed": 1,
2176
+ "filesSkipped": 0,
2177
+ "filesFailed": 0,
2178
+ "totalRecords": 50,
2179
+ "eventsSent": 50,
2180
+ "eventsFailed": 0,
2181
+ "results": [
2182
+ {
2183
+ "file": "products_2025-01-22.csv",
2184
+ "success": true,
2185
+ "recordsProcessed": 50,
2186
+ "eventsSent": 50,
2187
+ "eventsFailed": 0
2188
+ }
2189
+ ],
2190
+ "duration": 12345
2191
+ }
2192
+ ```
2193
+
2194
+ ### Partial Success Response
2195
+
2196
+ ```json
2197
+ {
2198
+ "success": true,
2199
+ "filesProcessed": 1,
2200
+ "filesSkipped": 0,
2201
+ "filesFailed": 0,
2202
+ "totalRecords": 50,
2203
+ "eventsSent": 45,
2204
+ "eventsFailed": 5,
2205
+ "results": [
2206
+ {
2207
+ "file": "products_2025-01-22.csv",
2208
+ "success": true,
2209
+ "recordsProcessed": 50,
2210
+ "eventsSent": 45,
2211
+ "eventsFailed": 5,
2212
+ "errors": ["PRD-001: Invalid SKU format", "PRD-002: Missing required field"]
2213
+ }
2214
+ ],
2215
+ "duration": 12345
2216
+ }
2217
+ ```
2218
+
2219
+ ### Error Response
2220
+
2221
+ ```json
2222
+ {
2223
+ "success": false,
2224
+ "filesProcessed": 0,
2225
+ "filesFailed": 1,
2226
+ "totalRecords": 0,
2227
+ "eventsSent": 0,
2228
+ "eventsFailed": 0,
2229
+ "results": [
2230
+ {
2231
+ "file": "products_2025-01-22.csv",
2232
+ "success": false,
2233
+ "error": "CSV parse error: Invalid structure"
2234
+ }
2235
+ ],
2236
+ "duration": 876
2237
+ }
2238
+ ```
2239
+
2240
+ ### Monitoring Metrics
2241
+
2242
+ Monitor these metrics via Versori logs filtered by `jobId` or `stage`:
2243
+
2244
+ - **Files Processed** - Total files successfully processed
2245
+ - **Events Sent** - Total events sent to Fluent Commerce
2246
+ - **Events Failed** - Events that failed (check rejection reports)
2247
+ - **Processing Duration** - Time taken for complete workflow
2248
+ - **Rate Limiting** - Watch for 429 errors indicating throttling
2249
+
2250
+ Use the status webhook for dashboards and automated monitoring.
2251
+
2252
+ ---
2253
+
2254
+ **To replicate this template for other entities/formats:**
2255
+
2256
+ 1. **File Naming:** Replace `product`, `PRD` with your entity name across all files
2257
+ 2. **CSV Structure:** Update expected CSV format and parsing logic
2258
+ 3. **Mapping Config:** Create new mapping file in `config/` with correct field paths
2259
+ 4. **Event Name:** Update event name (e.g., `UPSERT_INVENTORY`, `CREATE_LOCATION`)
2260
+ 5. **Workflows:** Rename workflow exports to match entity (e.g., `scheduledInventoryIngestion`)
2261
+ 6. **Service Function:** Rename main function (e.g., `executeInventoryIngestion`)
2262
+ 7. **File Pattern:** Update SFTP file pattern (e.g., `inventory_*.csv`)
2263
+ 8. **Data Source:** For S3 use `S3DataSource`, for XML use `XMLParserService`
2264
+
2265
+ ---
2266
+
2267
+ ## 10. Template summary
2268
+
2269
+ This template provides:
2270
+
2271
+ - SFTP ? Fluent Commerce ingestion workflow
2272
+ - File discovery and tracking (VersoriFileTracker)
2273
+ - CSV parsing and transformation (CSVParserService + UniversalMapper)
2274
+ - Event API integration with per-record error handling
2275
+ - File archival (success/error paths)
2276
+ - Job tracking (scheduled, ad hoc, status query modes)
2277
+ - SFTP connection cleanup and retry logic
2278
+
2279
+ ---
2280
+
2281
+ ## πŸ”§ Troubleshooting (quick)
2282
+
2283
+ - No files found: Check `sftpIncomingPath` and `filePattern` (names only).
2284
+ - CSV parse failed: Move to errors/; validate CSV structure and encoding.
2285
+ - High event failures: Inspect rejection report; consider Batch API for very high volumes.
2286
+ - 429 throttling: Add small backoff/delay or use Batch API.
2287
+
2288
+ ## πŸ—ΊοΈ Mapping tips (compact)
2289
+
2290
+ - Required fields: mark in mapping JSON; failed items won't be sent.
2291
+ - Arrays: use custom resolver `custom.splitByPipe` for pipe-separated values.
2292
+ - Nested objects: use custom resolvers `custom.buildPriceArray` and `custom.buildTaxType`.
2293
+ - Resolvers: prefer SDK built-ins (trim, uppercase, parseFloat).
2294
+
2295
+ ---