@12-apps/marketplace 1.11.0 → 1.13.0

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 (55) hide show
  1. package/ADOPTING.md +134 -1
  2. package/README.md +49 -3
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CD0SfdVS.d.ts → adapter-CQ4QiZPi.d.ts} +327 -174
  6. package/dist/{chunk-TVZU4HNT.js → chunk-4J2KJ3ZW.js} +1 -1
  7. package/dist/{chunk-TVZU4HNT.js.map → chunk-4J2KJ3ZW.js.map} +1 -1
  8. package/dist/{chunk-YWMEIMO3.js → chunk-CEWTV2TC.js} +176 -40
  9. package/dist/chunk-CEWTV2TC.js.map +1 -0
  10. package/dist/{chunk-DCWOQ5PN.js → chunk-NFJQQWG4.js} +2 -2
  11. package/dist/{chunk-OS4TSIFU.js → chunk-W57TITU4.js} +2 -2
  12. package/dist/{client-11sncog4.d.ts → client-CCSnylou.d.ts} +1 -1
  13. package/dist/{engine-C_3RK8wC.d.ts → engine-1KlJ_8jK.d.ts} +34 -5
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +20 -2
  17. package/dist/ifood/index.js +349 -125
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +162 -65
  21. package/dist/index.js.map +1 -1
  22. package/dist/keeta/index.d.ts +2 -18
  23. package/dist/keeta/index.js +12 -3
  24. package/dist/keeta/index.js.map +1 -1
  25. package/dist/manifest/server.d.ts +2 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +2 -2
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/src/core/adapter.ts +8 -1
  33. package/src/core/connection-stamp.ts +61 -0
  34. package/src/core/courier-port.ts +100 -0
  35. package/src/core/courier.ts +153 -0
  36. package/src/core/engine.ts +4 -1
  37. package/src/core/fetch-order.ts +54 -12
  38. package/src/core/integration.ts +19 -4
  39. package/src/core/lifecycle.ts +27 -4
  40. package/src/core/outbound-queue.ts +24 -11
  41. package/src/core/outbound.ts +8 -6
  42. package/src/core/pickup-code.ts +136 -0
  43. package/src/core/pipeline.ts +15 -6
  44. package/src/core/ports.ts +23 -1
  45. package/src/core/status-store.ts +2 -3
  46. package/src/core/types.ts +56 -4
  47. package/src/ifood/courier.ts +210 -0
  48. package/src/ifood/fetch-order.ts +103 -0
  49. package/src/ifood/index.ts +9 -1
  50. package/src/ifood/normalize.ts +30 -3
  51. package/src/index.ts +16 -0
  52. package/src/keeta/normalize.ts +21 -6
  53. package/dist/chunk-YWMEIMO3.js.map +0 -1
  54. /package/dist/{chunk-DCWOQ5PN.js.map → chunk-NFJQQWG4.js.map} +0 -0
  55. /package/dist/{chunk-OS4TSIFU.js.map → chunk-W57TITU4.js.map} +0 -0
@@ -0,0 +1,153 @@
1
+ import type { OutboundOrderRef } from "./adapter";
2
+ import type { CourierTrackingResult, MarketplaceCourierAnswer, MarketplaceCourierEngine } from "./courier-port";
3
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
4
+ import type { IngestSettings } from "./ingest";
5
+ import { readOutboundConnection } from "./integration";
6
+ import { followLifecycle } from "./lifecycle";
7
+ import { validatePickupCode } from "./pickup-code";
8
+ import type { DeliveryOutcome } from "./pipeline";
9
+ import type { EngineContext } from "./ports";
10
+ import type { MarketplaceDeliveredBy, MarketplaceCourierStep, NormalizedEvent } from "./types";
11
+
12
+ /**
13
+ * The marketplace's own courier (FUT-5665), the engine's half: courier events
14
+ * reach the host's `onCourier`, and the host's job reads the tracking.
15
+ *
16
+ * A courier event moves nothing: it is a fact the host stores (who is coming,
17
+ * when they arrived, the bag coming back). The one that also moves the order,
18
+ * `COLLECTED`, names the lifecycle too and goes through `followLifecycle`
19
+ * like a `DISPATCHED`, after the host stored its facts.
20
+ */
21
+
22
+ interface CourierAcceptance {
23
+ orderId: string;
24
+ status: string;
25
+ deliveredBy: string | null;
26
+ }
27
+
28
+ /** What the courier half made of an event, before the inbox row is settled. */
29
+ type CourierStepOutcome =
30
+ | { kind: "deferred" }
31
+ | { kind: "stopped"; reason: string }
32
+ | { kind: "recorded"; orderId: string; step: MarketplaceCourierStep };
33
+
34
+ function deliveredByOf(value: string | null): MarketplaceDeliveredBy | null {
35
+ return value === "MERCHANT" || value === "MARKETPLACE" ? value : null;
36
+ }
37
+
38
+ function reasonOf(answer: MarketplaceCourierAnswer, step: MarketplaceCourierStep): string {
39
+ if (answer === "unchanged") return `nothing to record for ${step}`;
40
+ return answer === "recorded" ? "" : answer.reason;
41
+ }
42
+
43
+ /** Hand the courier's facts to the host, or null when this host or this event has none. */
44
+ async function followCourier(ctx: EngineContext, clientId: string, event: NormalizedEvent): Promise<CourierStepOutcome | null> {
45
+ const hook = ctx.ports.order.onCourier;
46
+ const courier = event.courier;
47
+ if (!hook || !courier || !event.externalOrderId) return null;
48
+ const db = await ctx.ports.db();
49
+ const held = (await db.marketplaceAcceptance.findFirst({
50
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
51
+ select: { orderId: true, status: true, deliveredBy: true },
52
+ })) as CourierAcceptance | null;
53
+ if (!held) return { kind: "deferred" };
54
+ if (held.status !== "ACCEPTED") return { kind: "stopped", reason: `the order is ${held.status}, not ACCEPTED` };
55
+ const facts = { deliveredBy: deliveredByOf(held.deliveredBy), at: courier.at ?? ctx.ports.clock.now() };
56
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, courier, facts);
57
+ if (answer === "recorded") return { kind: "recorded", orderId: held.orderId, step: courier.step };
58
+ return { kind: "stopped", reason: reasonOf(answer, courier.step) };
59
+ }
60
+
61
+ /** Settle the inbox row for a courier event that named no lifecycle the host moved on. */
62
+ async function settleCourier(
63
+ ctx: EngineContext,
64
+ inboxId: string,
65
+ clientId: string,
66
+ outcome: CourierStepOutcome,
67
+ ): Promise<DeliveryOutcome> {
68
+ if (outcome.kind === "recorded") {
69
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
70
+ ctx.ports.publishChanged(clientId);
71
+ return { kind: "courier", orderId: outcome.orderId, step: outcome.step };
72
+ }
73
+ if (outcome.kind === "deferred") {
74
+ const reason = "courier event before its order";
75
+ await deferInboxEvent(ctx, inboxId, reason);
76
+ return { kind: "ignored", reason };
77
+ }
78
+ await settleInboxEvent(ctx, inboxId, "IGNORED", outcome.reason);
79
+ return { kind: "ignored", reason: outcome.reason };
80
+ }
81
+
82
+ /**
83
+ * The courier's facts first, then the lifecycle the event names: null when
84
+ * neither applies (the caller then does what it did before). A lifecycle that
85
+ * moved the order answers for the row; one that moved nothing (already past
86
+ * it, an echo) leaves the row to the courier's facts when they were recorded.
87
+ */
88
+ export async function followCourierAndLifecycle(
89
+ ctx: EngineContext,
90
+ inboxId: string,
91
+ clientId: string,
92
+ event: NormalizedEvent,
93
+ settings: IngestSettings,
94
+ ): Promise<DeliveryOutcome | null> {
95
+ const courier = await followCourier(ctx, clientId, event);
96
+ const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
97
+ const recorded = courier?.kind === "recorded";
98
+ if (followed && !(recorded && followed.kind === "ignored")) return followed;
99
+ return courier ? settleCourier(ctx, inboxId, clientId, courier) : null;
100
+ }
101
+
102
+ interface TrackedAcceptance {
103
+ orderId: string;
104
+ provider: string;
105
+ externalOrderId: string;
106
+ externalDisplayId: string | null;
107
+ deliveredBy: string | null;
108
+ createdAt: Date;
109
+ }
110
+
111
+ /**
112
+ * Read where the marketplace's courier is (FUT-5665). Calls the marketplace at
113
+ * once, so the host runs it in a job, never on a tap or a screen load, and at
114
+ * the marketplace's own rate (iFood: at most once per 30 s). `notYet` before a
115
+ * courier is assigned; `unsupported` with no call for an order the engine does
116
+ * not hold, a marketplace with no tracking, or a bag the store carries itself.
117
+ */
118
+ async function readCourierTracking(
119
+ ctx: EngineContext,
120
+ input: { clientId: string; orderId: string },
121
+ ): Promise<CourierTrackingResult> {
122
+ const db = await ctx.ports.db();
123
+ const row = (await db.marketplaceAcceptance.findFirst({
124
+ where: { clientId: input.clientId, orderId: input.orderId },
125
+ select: { orderId: true, provider: true, externalOrderId: true, externalDisplayId: true, deliveredBy: true, createdAt: true },
126
+ })) as TrackedAcceptance | null;
127
+ if (!row) return { kind: "unsupported", reason: "no marketplace order with this id" };
128
+ const api = ctx.registry.get(row.provider)?.courier;
129
+ if (!api) return { kind: "unsupported", reason: `${row.provider} has no courier tracking` };
130
+ if (row.deliveredBy !== "MARKETPLACE") return { kind: "unsupported", reason: "the order is not carried by the marketplace's courier" };
131
+ let connection;
132
+ try {
133
+ connection = await readOutboundConnection(ctx, input.clientId, row.provider);
134
+ } catch (error) {
135
+ return { kind: "refused", status: 0, message: `credentials do not open: ${error instanceof Error ? error.message : String(error)}`, own: true };
136
+ }
137
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
138
+ const ref: OutboundOrderRef = {
139
+ externalOrderId: row.externalOrderId,
140
+ externalDisplayId: row.externalDisplayId,
141
+ hostOrderCode: row.orderId,
142
+ placedAt: row.createdAt,
143
+ };
144
+ return api.tracking({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, ref);
145
+ }
146
+
147
+ /** The engine's courier calls, bound to its context. */
148
+ export function courierEngine(ctx: EngineContext): MarketplaceCourierEngine {
149
+ return {
150
+ validatePickupCode: (input) => validatePickupCode(ctx, input),
151
+ courierTracking: (input) => readCourierTracking(ctx, input),
152
+ };
153
+ }
@@ -35,6 +35,8 @@ import type { CatalogueMenuOptions } from "./catalogue-port";
35
35
  import { readMarketplaceCatalogue } from "./catalogue-read";
36
36
  import type { CatalogueReadResult } from "./catalogue-read-port";
37
37
  import type { CataloguePublicationView } from "./catalogue-store";
38
+ import { courierEngine } from "./courier";
39
+ import type { MarketplaceCourierEngine } from "./courier-port";
38
40
  import {
39
41
  runFetchOrder,
40
42
  type FetchOrderJobPayload,
@@ -97,7 +99,7 @@ import { readOrderStates, type MarketplaceOrderState } from "./state";
97
99
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
98
100
 
99
101
  /** Everything the mounted engine can do, with the ports and adapters bound in. */
100
- export interface MarketplaceEngine {
102
+ export interface MarketplaceEngine extends MarketplaceCourierEngine {
101
103
  /** Every registered marketplace, in registration order. */
102
104
  providers(): readonly MarketplaceProvider[];
103
105
  /** Whether a provider id (a URL segment, a body field) names a registered adapter. */
@@ -375,6 +377,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
375
377
  runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
376
378
  runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
377
379
  informStatus: (input) => informStatus(ctx, input),
380
+ ...courierEngine(ctx),
378
381
 
379
382
  // Null too when the host bound no catalogue port: nothing could be published.
380
383
  catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
@@ -1,6 +1,7 @@
1
1
  import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
2
  import { ingestMarketplaceOrder } from "./ingest";
3
- import { readOutboundConnection, resolveIngestionTarget } from "./integration";
3
+ import { markCredentialsAccepted, markCredentialsRefused } from "./connection-stamp";
4
+ import { readSealedOutboundConnection, resolveIngestionTarget } from "./integration";
4
5
  import type { FetchOrderResult } from "./adapter";
5
6
  import { cancelAcceptance } from "./acceptance";
6
7
  import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest } from "./order-fetch-marks";
@@ -131,30 +132,37 @@ async function owedFetch(
131
132
  return { row, event };
132
133
  }
133
134
 
135
+ /** What one call to the adapter answered, and the sealed credentials it was made with (null: no call). */
136
+ interface AdapterFetch {
137
+ result: FetchOrderResult;
138
+ sealed: string | null;
139
+ }
140
+
134
141
  /** One call to the adapter, or the refusal that stands in for it. */
135
142
  async function fetchThroughAdapter(
136
143
  ctx: EngineContext,
137
144
  clientId: string,
138
145
  provider: MarketplaceProvider,
139
146
  externalOrderId: string,
140
- ): Promise<FetchOrderResult> {
147
+ ): Promise<AdapterFetch> {
141
148
  const adapter = ctx.registry.get(provider);
142
- if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
143
- let connection;
149
+ if (!adapter?.fetchOrder) return { result: { kind: "refused", status: 0, message: `${provider} cannot fetch an order` }, sealed: null };
150
+ let opened;
144
151
  try {
145
- connection = await readOutboundConnection(ctx, clientId, provider);
152
+ opened = await readSealedOutboundConnection(ctx, clientId, provider);
146
153
  } catch (error) {
147
154
  const reason = error instanceof Error ? error.message : String(error);
148
- return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
155
+ return { result: { kind: "refused", status: 0, message: `credentials do not open: ${reason}` }, sealed: null };
149
156
  }
150
- if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
157
+ if (!opened) return { result: { kind: "refused", status: 0, message: "no credentials on file" }, sealed: null };
151
158
  try {
152
- return await adapter.fetchOrder(
153
- { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
159
+ const result = await adapter.fetchOrder(
160
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...opened.connection },
154
161
  { externalOrderId },
155
162
  );
163
+ return { result, sealed: opened.sealed };
156
164
  } catch (error) {
157
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
165
+ return { result: { kind: "retry", reason: error instanceof Error ? error.message : String(error) }, sealed: opened.sealed };
158
166
  }
159
167
  }
160
168
 
@@ -222,6 +230,11 @@ async function ingestFetched(
222
230
  return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
223
231
  }
224
232
 
233
+ /** A final refusal of our own credentials by the marketplace (a 4xx, not a local "no credentials"). */
234
+ function credentialsRefused(result: FetchOrderResult): boolean {
235
+ return result.kind === "refused" && result.own === true && result.status >= 400 && result.status < 500;
236
+ }
237
+
225
238
  /**
226
239
  * Run one queued fetch. Returns what it did; throws {@link FetchOrderRetryError}
227
240
  * for an answer worth retrying before the last attempt. A refusal, or the last
@@ -241,12 +254,41 @@ export async function runFetchOrder(
241
254
  await deferInboxEvent(ctx, row.id, "integration is not enabled");
242
255
  return { kind: "skipped", reason: "integration is not enabled" };
243
256
  }
244
- const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
245
- if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
257
+ const { result, sealed } = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
258
+ const stamp = sealed === null ? null : { clientId: payload.clientId, provider: event.provider, sealed };
259
+ if (result.kind === "order") {
260
+ // The credentials worked: a FAILED stamp left by an earlier refusal of these same ones is lifted.
261
+ if (stamp) await markCredentialsAccepted(ctx, stamp);
262
+ return ingestFetched(ctx, row, payload.clientId, result.order, target);
263
+ }
264
+ return endUnfetched(ctx, { row, event, result, attempt, stamp });
265
+ }
266
+
267
+ /**
268
+ * A fetch that brought no order: rethrown for the queue while a retry is worth
269
+ * it, else the row settles FAILED. Our credentials refused (a 401 that a fresh
270
+ * token did not cure, a refused token grant) are never retried by the queue:
271
+ * the connection reads FAILED, and the reconciliation sweep's next pass,
272
+ * minutes away and within the row's attempt bound, is the only re-try, so a
273
+ * revoked app never loops.
274
+ */
275
+ async function endUnfetched(
276
+ ctx: EngineContext,
277
+ input: {
278
+ row: InboxRow;
279
+ event: NormalizedEvent;
280
+ result: Exclude<FetchOrderResult, { kind: "order" }>;
281
+ attempt: { attempt: number; maxAttempts: number };
282
+ /** The connection and the sealed credentials the call was made with; null when no call was made. */
283
+ stamp: { clientId: string; provider: MarketplaceProvider; sealed: string } | null;
284
+ },
285
+ ): Promise<FetchOrderOutcome> {
286
+ const { row, event, result, attempt } = input;
246
287
  const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
247
288
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
248
289
  throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
249
290
  }
291
+ if (input.stamp && credentialsRefused(result)) await markCredentialsRefused(ctx, input.stamp);
250
292
  await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
251
293
  ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
252
294
  return { kind: "failed", reason };
@@ -357,18 +357,33 @@ export async function readOutboundConnection(
357
357
  clientId: string,
358
358
  provider: MarketplaceProvider,
359
359
  ): Promise<OutboundConnection | null> {
360
+ return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
361
+ }
362
+
363
+ /**
364
+ * {@link readOutboundConnection}, with the sealed blob it was opened from: a
365
+ * caller that stamps the connection afterwards (`./fetch-order.ts`) guards
366
+ * the stamp on it, so a call made with credentials since replaced never
367
+ * judges the new ones. The blob never reaches an adapter.
368
+ */
369
+ export async function readSealedOutboundConnection(
370
+ ctx: EngineContext,
371
+ clientId: string,
372
+ provider: MarketplaceProvider,
373
+ ): Promise<{ connection: OutboundConnection; sealed: string } | null> {
360
374
  const db = await ctx.ports.db();
361
375
  const row = (await db.marketplaceIntegration.findUnique({
362
376
  where: { clientId_provider: { clientId, provider } },
363
377
  select: { environment: true, credentials: true, authMode: true },
364
378
  })) as { environment: string; credentials: string; authMode?: string } | null;
365
379
  if (!row || row.credentials === "") return null;
380
+ const sealed = row.credentials;
366
381
  const environment = environmentOf(row.environment);
367
- if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
382
+ if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
368
383
  // Linked: the software's app speaks for the store, with the store's refresh token.
369
384
  const app = await appCredentialsOf(ctx, provider, environment);
370
385
  if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
371
- const refreshToken = openLinkRefreshToken(ctx, row.credentials);
372
- const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
373
- return { environment, credentials: app, grant: linkGrant(ctx, link) };
386
+ const refreshToken = openLinkRefreshToken(ctx, sealed);
387
+ const link = { clientId, provider, environment, refreshToken, app, sealed };
388
+ return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
374
389
  }
@@ -2,7 +2,7 @@ import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
2
  import type { IngestSettings } from "./ingest";
3
3
  import type { DeliveryOutcome } from "./pipeline";
4
4
  import type { EngineContext } from "./ports";
5
- import { readStatusRows, noteMarketplaceStep, statusTable } from "./status-store";
5
+ import { readStatusRows, noteMarketplaceStep, statusTable, type StatusRowStep } from "./status-store";
6
6
  import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } from "./types";
7
7
 
8
8
  /**
@@ -20,7 +20,7 @@ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } fr
20
20
  * 3. a cancellation request standing (PENDING or REQUESTED) is the store's
21
21
  * last word and nothing here contradicts it;
22
22
  * 4. an event that answers a step WE informed (a STORE row for DISPATCHED, or
23
- * for HANDED_OVER when the event is CONCLUDED) is an echo: the failure case
23
+ * for HANDED_OVER when the event is COLLECTED or CONCLUDED) is an echo: the failure case
24
24
  * of forward-only alone is the store's undo, where the echo would
25
25
  * dispatch a card again with no courier.
26
26
  *
@@ -36,9 +36,23 @@ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } fr
36
36
  /** The step of the table an event's echo is looked for under. */
37
37
  const ECHO_OF: Record<MarketplaceLifecycle, "DISPATCHED" | "HANDED_OVER"> = {
38
38
  DISPATCHED: "DISPATCHED",
39
+ // The courier holding the bag answers the store's hand-over (FUT-5665).
40
+ COLLECTED: "HANDED_OVER",
39
41
  CONCLUDED: "HANDED_OVER",
40
42
  };
41
43
 
44
+ /**
45
+ * The step the marketplace's word is NOTED under. `COLLECTED` is the
46
+ * hand-over seen from the marketplace's side, so it is noted as HANDED_OVER:
47
+ * the table's vocabulary (its CHECK) is unchanged, and our own job never
48
+ * informs a hand-over the marketplace already announced.
49
+ */
50
+ const NOTED_AS: Record<MarketplaceLifecycle, StatusRowStep> = {
51
+ DISPATCHED: "DISPATCHED",
52
+ COLLECTED: "HANDED_OVER",
53
+ CONCLUDED: "CONCLUDED",
54
+ };
55
+
42
56
  interface HeldAcceptance {
43
57
  orderId: string;
44
58
  status: string;
@@ -62,6 +76,15 @@ function refusal(held: HeldAcceptance): string | null {
62
76
  return null;
63
77
  }
64
78
 
79
+ /**
80
+ * A COLLECTED is the marketplace's courier taking the bag (FUT-5665): for a
81
+ * bag the store carries it moves nothing and is never noted, so it cannot
82
+ * stand in for the store's own HANDED_OVER (a merchant bag's "delivered").
83
+ */
84
+ function notTheFleets(lifecycle: MarketplaceLifecycle, held: HeldAcceptance): string | null {
85
+ return lifecycle === "COLLECTED" && held.deliveredBy !== "MARKETPLACE" ? "COLLECTED of a bag the marketplace does not carry" : null;
86
+ }
87
+
65
88
  function deliveredByOf(held: HeldAcceptance): MarketplaceDeliveredBy | null {
66
89
  return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
67
90
  }
@@ -108,7 +131,7 @@ export async function followLifecycle(
108
131
  await deferInboxEvent(ctx, inboxId, reason);
109
132
  return { kind: "ignored", reason };
110
133
  }
111
- const stopped = refusal(held);
134
+ const stopped = refusal(held) ?? notTheFleets(lifecycle, held);
112
135
  if (stopped) return ignored(ctx, inboxId, stopped);
113
136
 
114
137
  const echo = ECHO_OF[lifecycle];
@@ -121,7 +144,7 @@ export async function followLifecycle(
121
144
  // FAILED and logged): the marketplace's state and ours already agree, and a stricter ordering
122
145
  // would put a write before the host's answer on every event.
123
146
  const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
124
- await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
147
+ await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: NOTED_AS[lifecycle] });
125
148
  if (answer === "moved") {
126
149
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
127
150
  ctx.ports.publishChanged(clientId);
@@ -1,4 +1,4 @@
1
- import type { StatusStep } from "./adapter";
1
+ import type { MarketplaceAdapter, StatusStep } from "./adapter";
2
2
  import type { EngineContext } from "./ports";
3
3
  import type { MarketplaceProvider } from "./types";
4
4
 
@@ -16,10 +16,11 @@ import type { MarketplaceProvider } from "./types";
16
16
  export const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
17
17
 
18
18
  /**
19
- * What goes out: the store's aceite, the store's cancellation request, or a
20
- * step of the order the store reached (`status`, FUT-4653).
19
+ * What goes out: the store's aceite, the store's cancellation request, a
20
+ * step of the order the store reached (`status`, FUT-4653), or the pickup code
21
+ * the store checked at the hand-over (`validatePickupCode`, FUT-5665).
21
22
  */
22
- export type OutboundAction = "confirm" | "requestCancellation" | "status";
23
+ export type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode";
23
24
 
24
25
  /** The outbound job's payload. Identifiers only. */
25
26
  export interface OutboundJobPayload {
@@ -33,6 +34,12 @@ export interface OutboundJobPayload {
33
34
  * belongs to: the owner of its SENDING claim. Absent on every other action.
34
35
  */
35
36
  claimKey?: string;
37
+ /**
38
+ * OPTIONAL. The pickup code a `validatePickupCode` call sends; absent on every
39
+ * other action. The one non-identifier in the payload: a short-lived code the
40
+ * job needs to send, which no log line prints.
41
+ */
42
+ code?: string;
36
43
  }
37
44
 
38
45
  /** The dedupe key: at most one queued call per (order, action). */
@@ -45,6 +52,18 @@ export function statusDedupeKey(step: StatusStep, orderId: string, at: Date): st
45
52
  return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
46
53
  }
47
54
 
55
+ /** Whether the adapter's marketplace can take this call at all. */
56
+ function ableTo(adapter: MarketplaceAdapter, payload: OutboundJobPayload): boolean {
57
+ switch (payload.action) {
58
+ case "status":
59
+ return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
60
+ case "confirm":
61
+ return adapter.capabilities.apiConfirm;
62
+ default:
63
+ return adapter.capabilities.apiCancel;
64
+ }
65
+ }
66
+
48
67
  /**
49
68
  * Queue one outbound call, when the marketplace's API can take it at all.
50
69
  *
@@ -65,13 +84,7 @@ export async function enqueueOutbound(
65
84
  ): Promise<boolean> {
66
85
  const adapter = ctx.registry.get(provider);
67
86
  if (!adapter) return false;
68
- const able =
69
- payload.action === "status"
70
- ? Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step))
71
- : payload.action === "confirm"
72
- ? adapter.capabilities.apiConfirm
73
- : adapter.capabilities.apiCancel;
74
- if (!able) return false;
87
+ if (!ableTo(adapter, payload)) return false;
75
88
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
76
89
  if (!outcome.enqueued) {
77
90
  ctx.ports.logger.warn(
@@ -9,6 +9,7 @@ import {
9
9
  } from "./cancellation-outcome";
10
10
  import { readOutboundConnection, type OutboundConnection } from "./integration";
11
11
  import type { OutboundJobPayload } from "./outbound-queue";
12
+ import { runPickupCode, tellPickupCode } from "./pickup-code";
12
13
  import { failStatusRow, runStatus } from "./status-job";
13
14
  import { failAsTimeout } from "./outbound-sweep";
14
15
  import type { CancellationFailureReason, EngineContext } from "./ports";
@@ -334,9 +335,10 @@ async function runCancellation(
334
335
  */
335
336
  async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
336
337
  const reason = error instanceof Error ? error.message : String(error);
337
- if (payload.action === "status") {
338
- await failStatusRow(ctx, payload);
339
- ctx.ports.logger.error(`marketplace.outbound: status ${payload.step ?? ""} for order ${payload.orderId} failed: ${reason}`);
338
+ if (payload.action === "status" || payload.action === "validatePickupCode") {
339
+ if (payload.action === "status") await failStatusRow(ctx, payload);
340
+ else await tellPickupCode(ctx, payload, "UNVERIFIED");
341
+ ctx.ports.logger.error(`marketplace.outbound: ${payload.action}${payload.step ? ` ${payload.step}` : ""} for order ${payload.orderId} failed: ${reason}`);
340
342
  return { kind: "failed", action: payload.action, reason };
341
343
  }
342
344
  const db = await ctx.ports.db();
@@ -366,9 +368,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
366
368
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
367
369
  const adapter = ctx.registry.get(row.provider);
368
370
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
369
- if (payload.action === "status") {
370
- return runStatus(ctx, payload, row, adapter, { attempt, ref: refOf(row), retryError: (m) => new OutboundRetryError(m) });
371
- }
371
+ const deps = { attempt, ref: refOf(row), retryError: (m: string) => new OutboundRetryError(m) };
372
+ if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
373
+ if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
372
374
  return payload.action === "confirm"
373
375
  ? runConfirm(ctx, payload, row, adapter, attempt)
374
376
  : runCancellation(ctx, payload, row, adapter, attempt);
@@ -0,0 +1,136 @@
1
+ import type { MarketplaceAdapter, OutboundOrderRef } from "./adapter";
2
+ import type { PickupCodeCallResult, PickupCodeValidation, ValidatePickupCodeInput } from "./courier-port";
3
+ import { readOutboundConnection } from "./integration";
4
+ import { MARKETPLACE_OUTBOUND_JOB, type OutboundJobPayload } from "./outbound-queue";
5
+ import type { EngineContext } from "./ports";
6
+
7
+ /**
8
+ * The pickup-code check's engine half (FUT-5665): the store checked the code
9
+ * the marketplace's courier stated, locally, and handed the bag over; then the
10
+ * host calls {@link validatePickupCode}, one enqueue, and the
11
+ * `marketplace.outbound` job (action `validatePickupCode`) tells the
12
+ * marketplace and hands its verdict to the host's `onPickupCodeValidated`.
13
+ *
14
+ * No row: the verdict is the host's to keep (it warns on `INVALID`, it moves
15
+ * nothing). A retry after a verdict could ask again; that is harmless, the
16
+ * check being a question with the same answer. A queue that refuses the job
17
+ * answers false and nothing re-queues it: the hand-over has happened and the
18
+ * marketplace's own check is its half, never a gate on ours.
19
+ */
20
+
21
+ /** One enqueue, never throws: no statement and no call. True when the queue took it. */
22
+ export async function validatePickupCode(ctx: EngineContext, input: ValidatePickupCodeInput): Promise<boolean> {
23
+ const payload: OutboundJobPayload = {
24
+ clientId: input.clientId,
25
+ orderId: input.orderId,
26
+ action: "validatePickupCode",
27
+ code: input.code,
28
+ };
29
+ const dedupeKey = `${MARKETPLACE_OUTBOUND_JOB}:validatePickupCode:${input.orderId}:${input.at.getTime()}`;
30
+ const notQueued = (why: string): false => {
31
+ ctx.ports.logger.warn(`${MARKETPLACE_OUTBOUND_JOB}: validatePickupCode for order ${input.orderId} was not queued${why}`);
32
+ return false;
33
+ };
34
+ try {
35
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
36
+ return outcome.enqueued || notQueued(outcome.reason ? ` (${outcome.reason})` : "");
37
+ } catch (error) {
38
+ return notQueued(`: ${error instanceof Error ? error.message : String(error)}`);
39
+ }
40
+ }
41
+
42
+ /** What the job reads of the acceptance row. */
43
+ interface PickupCodeRow {
44
+ orderId: string;
45
+ provider: string;
46
+ status: string;
47
+ deliveredBy: string | null;
48
+ }
49
+
50
+ type PickupCodeOutcome =
51
+ | { kind: "skipped"; reason: string }
52
+ | { kind: "done"; action: "validatePickupCode" }
53
+ | { kind: "failed"; action: "validatePickupCode"; reason: string };
54
+
55
+ interface PickupCodeDeps {
56
+ attempt: { attempt: number; maxAttempts: number };
57
+ ref: OutboundOrderRef;
58
+ retryError: (message: string) => Error;
59
+ }
60
+
61
+ /** Hand the verdict to the host. Its throw is logged: the job never re-asks the marketplace for it. */
62
+ export async function tellPickupCode(
63
+ ctx: EngineContext,
64
+ payload: OutboundJobPayload,
65
+ validation: PickupCodeValidation,
66
+ ): Promise<void> {
67
+ const hook = ctx.ports.order.onPickupCodeValidated;
68
+ const log = validation === "VALID" ? ctx.ports.logger.info : ctx.ports.logger.warn;
69
+ log.call(ctx.ports.logger, `marketplace.outbound: pickup code of order ${payload.orderId}: ${validation}`);
70
+ if (!hook) return;
71
+ try {
72
+ await hook.call(ctx.ports.order, payload.clientId, payload.orderId, validation);
73
+ } catch (error) {
74
+ ctx.ports.logger.error(
75
+ `marketplace.outbound: the host's half of the pickup-code verdict for order ${payload.orderId} failed: ` +
76
+ (error instanceof Error ? error.message : String(error)),
77
+ );
78
+ }
79
+ }
80
+
81
+ /** Why the check is not sent, or null when it is. */
82
+ function skipOf(payload: OutboundJobPayload, row: PickupCodeRow, adapter: MarketplaceAdapter): string | null {
83
+ if (!adapter.courier) return "the marketplace has no pickup-code check";
84
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
85
+ if (row.deliveredBy !== "MARKETPLACE") return "the order is not carried by the marketplace's courier";
86
+ return payload.code ? null : "no pickup code to send";
87
+ }
88
+
89
+ /** The call's answer, or the reason no call could be made. */
90
+ async function call(
91
+ ctx: EngineContext,
92
+ payload: OutboundJobPayload,
93
+ row: PickupCodeRow,
94
+ adapter: MarketplaceAdapter,
95
+ ref: OutboundOrderRef,
96
+ ): Promise<PickupCodeCallResult> {
97
+ let connection;
98
+ try {
99
+ connection = await readOutboundConnection(ctx, payload.clientId, row.provider);
100
+ } catch (error) {
101
+ const message = `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
102
+ return { kind: "refused", status: 0, message, own: true };
103
+ }
104
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
105
+ return adapter.courier!.validatePickupCode(
106
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
107
+ ref,
108
+ { code: payload.code! },
109
+ );
110
+ }
111
+
112
+ /** The job's body: skip, call, hand the verdict over; a retry throws until the last attempt. */
113
+ export async function runPickupCode(
114
+ ctx: EngineContext,
115
+ payload: OutboundJobPayload,
116
+ row: PickupCodeRow,
117
+ adapter: MarketplaceAdapter,
118
+ deps: PickupCodeDeps,
119
+ ): Promise<PickupCodeOutcome> {
120
+ const skip = skipOf(payload, row, adapter);
121
+ if (skip) return { kind: "skipped", reason: skip };
122
+ const result = await call(ctx, payload, row, adapter, deps.ref);
123
+ if (result.kind === "answered") {
124
+ await tellPickupCode(ctx, payload, result.valid ? "VALID" : "INVALID");
125
+ ctx.ports.publishChanged(payload.clientId);
126
+ return { kind: "done", action: "validatePickupCode" };
127
+ }
128
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
129
+ if (result.kind === "retry" && deps.attempt.attempt < deps.attempt.maxAttempts) {
130
+ throw deps.retryError(`validatePickupCode for order ${row.orderId}: ${reason}`);
131
+ }
132
+ ctx.ports.logger.error(`marketplace.outbound: validatePickupCode for order ${row.orderId} failed: ${reason}`);
133
+ await tellPickupCode(ctx, payload, "UNVERIFIED");
134
+ ctx.ports.publishChanged(payload.clientId);
135
+ return { kind: "failed", action: "validatePickupCode", reason };
136
+ }