@12-apps/marketplace 1.1.0 → 1.2.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 (75) hide show
  1. package/ADOPTING.md +9 -4
  2. package/README.md +147 -2
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-BggtVFf9.d.ts → adapter-_iuSxvVD.d.ts} +35 -1
  13. package/dist/{chunk-7BYVGNU5.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-NGNEL4HS.js → chunk-CRYFYDQ2.js} +26 -2
  18. package/dist/chunk-CRYFYDQ2.js.map +1 -0
  19. package/dist/{chunk-DVIRN42O.js → chunk-D2X7TOR6.js} +669 -136
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-KrgZ4pA4.d.ts → engine-D-a4mttc.d.ts} +58 -2
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +7 -11
  25. package/dist/ifood/index.js +10 -60
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +56 -352
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +5 -1
  45. package/src/99food/copy.ts +36 -0
  46. package/src/99food/en-US.ts +19 -0
  47. package/src/99food/index.ts +121 -0
  48. package/src/99food/normalize.ts +263 -0
  49. package/src/99food/outbound.ts +220 -0
  50. package/src/99food/pt-BR.ts +23 -0
  51. package/src/core/adapter.ts +17 -1
  52. package/src/core/decisions.ts +16 -4
  53. package/src/core/engine.ts +8 -0
  54. package/src/core/fetch-order.ts +253 -0
  55. package/src/core/inbox.ts +8 -2
  56. package/src/core/ingest.ts +10 -2
  57. package/src/core/integration.ts +30 -1
  58. package/src/core/order-fetch-marks.ts +63 -0
  59. package/src/core/outbound.ts +22 -2
  60. package/src/core/payload-read.ts +101 -0
  61. package/src/core/pipeline.ts +64 -15
  62. package/src/core/types.ts +14 -0
  63. package/src/ifood/normalize.ts +15 -88
  64. package/src/index.ts +9 -1
  65. package/src/rappi/copy.ts +39 -0
  66. package/src/rappi/en-US.ts +14 -0
  67. package/src/rappi/index.ts +155 -0
  68. package/src/rappi/normalize.ts +314 -0
  69. package/src/rappi/outbound.ts +182 -0
  70. package/src/rappi/pt-BR.ts +18 -0
  71. package/src/server/index.ts +1 -0
  72. package/src/server/jobs.ts +35 -2
  73. package/dist/chunk-7BYVGNU5.js.map +0 -1
  74. package/dist/chunk-DVIRN42O.js.map +0 -1
  75. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -80,6 +80,7 @@ function acceptanceData(
80
80
  order: NormalizedMarketplaceOrder,
81
81
  settings: IngestSettings,
82
82
  now: Date,
83
+ clockStartsAt: Date,
83
84
  ): Record<string, unknown> {
84
85
  const accepted = settings.autoAccept;
85
86
  return {
@@ -91,7 +92,7 @@ function acceptanceData(
91
92
  // Who carries a delivery: the merchant's courier or the marketplace's fleet.
92
93
  deliveredBy: order.deliveredBy ?? null,
93
94
  status: accepted ? "ACCEPTED" : "AWAITING",
94
- acknowledgeBy: new Date(now.getTime() + settings.ackSlaSeconds * 1000),
95
+ acknowledgeBy: new Date(clockStartsAt.getTime() + settings.ackSlaSeconds * 1000),
95
96
  acknowledgedAt: accepted ? now : null,
96
97
  externalDueAt: order.deliveryDueAt,
97
98
  commissionCents: order.commissionCents,
@@ -122,10 +123,17 @@ export async function ingestMarketplaceOrder(
122
123
  order: NormalizedMarketplaceOrder;
123
124
  settings: IngestSettings;
124
125
  now?: Date;
126
+ /**
127
+ * When the acceptance window started, if not `now`: the arrival of the
128
+ * event that announced an order fetched later. Moves ONLY the deadline;
129
+ * the liveness stamp and an auto-accept's time stay `now`.
130
+ */
131
+ clockStartsAt?: Date;
125
132
  },
126
133
  ): Promise<IngestResult> {
127
134
  const { clientId, order, settings } = input;
128
135
  const now = input.now ?? ctx.ports.clock.now();
136
+ const clockStartsAt = input.clockStartsAt ?? now;
129
137
 
130
138
  const db = await ctx.ports.db();
131
139
  // Answered from this package's OWN table rather than through a port: the
@@ -148,7 +156,7 @@ export async function ingestMarketplaceOrder(
148
156
  const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
149
157
  const lines = await composeLines(tx, clientId, order, now);
150
158
  const created = await ctx.ports.order.create(clientId, order, lines, tx);
151
- await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now) });
159
+ await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });
152
160
  await markMarketplaceEventSeen(tx, clientId, order.provider, now);
153
161
  return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
154
162
  });
@@ -168,6 +168,26 @@ export interface IngestionTarget {
168
168
  autoAccept: boolean;
169
169
  ackSlaSeconds: number;
170
170
  webhookSecret: string | null;
171
+ /** The merchant the store connected; a fetched order naming another is refused. */
172
+ externalMerchantId: string | null;
173
+ }
174
+
175
+ /**
176
+ * The merchant id a store's live connection states, read alone: no
177
+ * credentials are opened. Null when it states none, or when there is no live
178
+ * connection (archived or absent).
179
+ */
180
+ export async function connectionMerchantId(
181
+ ctx: EngineContext,
182
+ clientId: string,
183
+ provider: MarketplaceProvider,
184
+ ): Promise<string | null> {
185
+ const db = await ctx.ports.db();
186
+ const row = (await db.marketplaceIntegration.findUnique({
187
+ where: { clientId_provider: { clientId, provider } },
188
+ select: { externalMerchantId: true, archivedAt: true },
189
+ })) as { externalMerchantId: string | null; archivedAt: Date | null } | null;
190
+ return row && !row.archivedAt ? (row.externalMerchantId ?? null) : null;
171
191
  }
172
192
 
173
193
  /**
@@ -188,8 +208,16 @@ export async function resolveIngestionTarget(
188
208
  const db = await ctx.ports.db();
189
209
  const row = (await db.marketplaceIntegration.findUnique({
190
210
  where: { clientId_provider: { clientId, provider } },
191
- select: { enabled: true, autoAccept: true, ackSlaSeconds: true, credentials: true, archivedAt: true },
211
+ select: {
212
+ enabled: true,
213
+ autoAccept: true,
214
+ ackSlaSeconds: true,
215
+ credentials: true,
216
+ archivedAt: true,
217
+ externalMerchantId: true,
218
+ },
192
219
  })) as {
220
+ externalMerchantId: string | null;
193
221
  enabled: boolean;
194
222
  autoAccept: boolean;
195
223
  ackSlaSeconds: number;
@@ -202,6 +230,7 @@ export async function resolveIngestionTarget(
202
230
  enabled: row.enabled,
203
231
  autoAccept: row.autoAccept,
204
232
  ackSlaSeconds: row.ackSlaSeconds,
233
+ externalMerchantId: row.externalMerchantId ?? null,
205
234
  // An unopenable blob must not read as "no secret configured" — that would
206
235
  // turn a key-rotation problem into an endpoint that accepts unsigned
207
236
  // deliveries. The secrets port throws instead, and the caller answers 401.
@@ -0,0 +1,63 @@
1
+ import type { EngineContext } from "./ports";
2
+ import type { MarketplaceProvider } from "./types";
3
+
4
+ /**
5
+ * A cancellation that outran its order's body.
6
+ *
7
+ * For a marketplace whose events only announce an order (`fetchOrder`), the
8
+ * marketplace's CANCELLED can arrive while the fetch is still queued, held or
9
+ * retrying, and the fetched body (Open Delivery's `Order` has no status) cannot
10
+ * say the order was cancelled. Without a trace the fetch would then ingest a
11
+ * cancelled order, send it to the kitchen and confirm it.
12
+ *
13
+ * So when a cancellation finds no acceptance to cancel, it leaves a MARKER: an
14
+ * IGNORED inbox row under a key derived from the order (`engine:cancelled:<id>`),
15
+ * found again through the inbox's own unique `(provider, eventId)` index, with
16
+ * no new column or table. The fetch reads it before it ingests.
17
+ */
18
+
19
+ const MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
20
+
21
+ const markerId = (externalOrderId: string): string => `engine:cancelled:${externalOrderId}`;
22
+
23
+ /** Leave the marker, for an adapter that fetches its orders. Idempotent. */
24
+ export async function markCancelledBeforeIngest(
25
+ ctx: EngineContext,
26
+ input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
27
+ ): Promise<void> {
28
+ if (!ctx.registry.get(input.provider)?.fetchOrder) return;
29
+ const db = await ctx.ports.db();
30
+ try {
31
+ await db.marketplaceInboxEvent.create({
32
+ data: {
33
+ clientId: input.clientId,
34
+ provider: input.provider,
35
+ eventId: markerId(input.externalOrderId),
36
+ eventType: MARKER_TYPE,
37
+ externalOrderId: input.externalOrderId,
38
+ payload: {},
39
+ status: "IGNORED",
40
+ error: "cancelled before the order was ingested",
41
+ receivedAt: ctx.ports.clock.now(),
42
+ processedAt: ctx.ports.clock.now(),
43
+ },
44
+ select: { id: true },
45
+ });
46
+ } catch (error) {
47
+ // A redelivered cancellation: the marker is already there.
48
+ if ((error as { code?: string }).code !== "P2002") throw error;
49
+ }
50
+ }
51
+
52
+ /** Whether this store's order was cancelled before it was ingested. */
53
+ export async function cancelledBeforeIngest(
54
+ ctx: EngineContext,
55
+ input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
56
+ ): Promise<boolean> {
57
+ const db = await ctx.ports.db();
58
+ const row = (await db.marketplaceInboxEvent.findUnique({
59
+ where: { provider_eventId: { provider: input.provider, eventId: markerId(input.externalOrderId) } },
60
+ select: { clientId: true },
61
+ })) as { clientId: string | null } | null;
62
+ return row !== null && row.clientId === input.clientId;
63
+ }
@@ -144,6 +144,22 @@ async function stampCancellation(
144
144
  if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
145
145
  }
146
146
 
147
+ /**
148
+ * Which rows a synchronous "cancelled" answers: the request still waiting or
149
+ * FAILED, or the tombstone an accept left of THIS request (no status, the
150
+ * same `cancellation_requested_at` the job read) on an order STILL ACCEPTED.
151
+ * A later request of the store carries a new instant and a status of its own,
152
+ * so it is never mistaken for it; and once the marketplace's own cancel event
153
+ * has moved the order to REJECTED (and told the host), the tombstone answers
154
+ * nothing more, so the host is never told twice.
155
+ */
156
+ function answerableRequest(row: OutboundRow): Record<string, unknown>[] {
157
+ const waiting = { cancellationStatus: { in: ["PENDING", "FAILED"] } };
158
+ if (row.cancellationRequestedAt === null) return [waiting];
159
+ const tombstone = { status: "ACCEPTED", cancellationStatus: null, cancellationRequestedAt: row.cancellationRequestedAt };
160
+ return [waiting, tombstone];
161
+ }
162
+
147
163
  /**
148
164
  * A marketplace that confirms in its answer: the same stamps as its
149
165
  * CANCELLED event (`cancelAcceptance`) — CONFIRMED and REJECTED in one
@@ -157,9 +173,13 @@ async function stampConfirmedCancellation(ctx: EngineContext, row: OutboundRow,
157
173
  // From FAILED too: the sweep may have timed the request out while this
158
174
  // call was in flight, and a marketplace that answers in the response sends
159
175
  // no event — its "cancelled" is the only word that it did (the event path's
160
- // own rule: a confirmation after a TIMEOUT still confirms).
176
+ // own rule: a confirmation after a TIMEOUT still confirms). And from the
177
+ // TOMBSTONE of this same request (FUT-4765, R3-N2): the store may have
178
+ // accepted the order once the request timed out, which clears the request
179
+ // but keeps its `cancellation_requested_at`. The order is cancelled on the
180
+ // marketplace, so it is cancelled here too, and the host hears it.
161
181
  const confirmed = await tx.marketplaceAcceptance.updateMany({
162
- where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "FAILED"] } },
182
+ where: { orderId: row.orderId, OR: answerableRequest(row) },
163
183
  data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null },
164
184
  });
165
185
  if (confirmed.count === 0) return false;
@@ -0,0 +1,101 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ /**
4
+ * The defensive readers every adapter's normalizer is built from.
5
+ *
6
+ * A marketplace payload is UNTRUSTED: a documented shape and the shape that
7
+ * actually arrives drift, and a `TypeError` reading a missing field would
8
+ * reject a paid order at the door. Every reader here produces a value or
9
+ * null, never a throw. They are wire-format-neutral (no marketplace's key
10
+ * names), which is why they live beside the engine rather than in an adapter.
11
+ */
12
+
13
+ /** Read a nested value without asserting the shape of anything on the way. */
14
+ export function pick(source: unknown, ...path: string[]): unknown {
15
+ let cursor: unknown = source;
16
+ for (const key of path) {
17
+ if (typeof cursor !== "object" || cursor === null) return undefined;
18
+ cursor = (cursor as Record<string, unknown>)[key];
19
+ }
20
+ return cursor;
21
+ }
22
+
23
+ /** A non-blank string (trimmed), a finite number as text, or null. */
24
+ export function asString(value: unknown): string | null {
25
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
26
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
27
+ return null;
28
+ }
29
+
30
+ /**
31
+ * The first of several candidate paths that yields a string.
32
+ *
33
+ * A marketplace states the same fact under different keys depending on which
34
+ * API version delivered it, so nearly every read is a fallback chain. Expressed
35
+ * as data rather than as `??` so a chain grows by one entry, not one branch.
36
+ */
37
+ export function firstString(source: unknown, paths: string[][]): string | null {
38
+ for (const path of paths) {
39
+ const found = asString(pick(source, ...path));
40
+ if (found !== null) return found;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ /**
46
+ * Money stated in DECIMAL units (`12.9`) → integer cents.
47
+ *
48
+ * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,
49
+ * so truncation loses a cent on ordinary prices, always in the store's
50
+ * disfavour.
51
+ */
52
+ export function toCents(value: unknown): number | null {
53
+ const numeric = typeof value === "string" ? Number(value) : value;
54
+ if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
55
+ return Math.round(numeric * 100);
56
+ }
57
+
58
+ /** {@link firstString} for money. */
59
+ export function firstCents(source: unknown, paths: string[][]): number | null {
60
+ for (const path of paths) {
61
+ const found = toCents(pick(source, ...path));
62
+ if (found !== null) return found;
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /** An ISO timestamp → a Date, or null when absent or unparseable. */
68
+ function toDate(value: unknown): Date | null {
69
+ const raw = asString(value);
70
+ if (!raw) return null;
71
+ const parsed = new Date(raw);
72
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
73
+ }
74
+
75
+ /** {@link firstString} for timestamps. */
76
+ export function firstDate(source: unknown, paths: string[][]): Date | null {
77
+ for (const path of paths) {
78
+ const found = toDate(pick(source, ...path));
79
+ if (found !== null) return found;
80
+ }
81
+ return null;
82
+ }
83
+
84
+ /**
85
+ * Verify a lowercase-hex HMAC-SHA256 of the raw body (an optional `sha256=`
86
+ * prefix tolerated), keyed by `secret`.
87
+ *
88
+ * Unsigned deliveries are refused whenever a secret is CONFIGURED; a store
89
+ * that has not set one yet is accepted, and that state is visible on the
90
+ * connection screen rather than silent. Compared in constant time over bytes:
91
+ * an early-exit `===` on a hex digest leaks the prefix a forger already got
92
+ * right, one request at a time.
93
+ */
94
+ export function verifyHmacSha256Hex(rawBody: string, signature: string | null, secret: string | null): boolean {
95
+ if (!secret) return true;
96
+ if (!signature) return false;
97
+ const expected = createHmac("sha256", secret).update(rawBody, "utf8").digest("hex");
98
+ const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, ""), "utf8");
99
+ const mine = Buffer.from(expected, "utf8");
100
+ return given.length === mine.length && timingSafeEqual(given, mine);
101
+ }
@@ -1,10 +1,12 @@
1
1
  import { cancelAcceptance } from "./acceptance";
2
2
  import { failCancellationRequest } from "./cancellation";
3
+ import { awaitOrderBody, merchantMismatch, requeueOwedFetch } from "./fetch-order";
3
4
  import { deferInboxEvent, recordInboxEvent, settleInboxEvent } from "./inbox";
4
5
  import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
5
- import { resolveIngestionTarget } from "./integration";
6
+ import { connectionMerchantId, resolveIngestionTarget } from "./integration";
7
+ import { markCancelledBeforeIngest } from "./order-fetch-marks";
6
8
  import type { EngineContext } from "./ports";
7
- import type { MarketplaceProvider, NormalizedEvent } from "./types";
9
+ import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
8
10
 
9
11
  /**
10
12
  * One delivery, start to finish: normalize → inbox → ingest.
@@ -34,6 +36,8 @@ export type DeliveryOutcome =
34
36
  | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
35
37
  | { kind: "cancelled" }
36
38
  | { kind: "cancellationFailed" }
39
+ /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
40
+ | { kind: "awaitingOrder" }
37
41
  | { kind: "duplicate" }
38
42
  | { kind: "ignored"; reason: string }
39
43
  | { kind: "failed"; reason: string };
@@ -88,6 +92,28 @@ export async function processDelivery(
88
92
  }
89
93
  }
90
94
 
95
+ /** The event names an order whose body the marketplace serves apart (`orderToFetch`). */
96
+ function announcesOrderToFetch(event: NormalizedEvent): boolean {
97
+ return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;
98
+ }
99
+
100
+ /**
101
+ * Why an order the event CARRIES must not be ingested for this store: it names
102
+ * another merchant than the connection's (a wrong webhook URL, a replay), the
103
+ * rule a fetched order is held to. Read only for an order that names its
104
+ * merchant (an adapter that sets `externalMerchantId` on the order); an order
105
+ * that names none costs no read.
106
+ */
107
+ async function carriedOrderMismatch(
108
+ ctx: EngineContext,
109
+ clientId: string,
110
+ order: NormalizedMarketplaceOrder,
111
+ ): Promise<string | null> {
112
+ if (!order.externalMerchantId) return null;
113
+ // The one column, never the whole target: no credentials opened per order.
114
+ return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));
115
+ }
116
+
91
117
  /**
92
118
  * Act on one recorded delivery: cancel, ingest, or deliberately nothing.
93
119
  *
@@ -118,16 +144,22 @@ async function applyEvent(
118
144
  }
119
145
 
120
146
  if (event.cancelled && event.externalOrderId) {
121
- await cancelAcceptance(ctx, {
122
- clientId,
123
- provider: event.provider,
124
- externalOrderId: event.externalOrderId,
125
- now,
126
- });
147
+ const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };
148
+ // A cancellation that outran a fetched order's body leaves its marker, so
149
+ // the fetch that follows ingests nothing.
150
+ if (!(await cancelAcceptance(ctx, { ...order, now }))) await markCancelledBeforeIngest(ctx, order);
127
151
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
128
152
  return { kind: "cancelled" };
129
153
  }
130
154
 
155
+ if (announcesOrderToFetch(event)) {
156
+ // The event announces an order whose body the marketplace serves apart.
157
+ // Fetching is a call to the marketplace, so it is a job's, never this
158
+ // request's: the row waits PENDING and the fetch is queued.
159
+ await awaitOrderBody(ctx, clientId, inboxId);
160
+ return { kind: "awaitingOrder" };
161
+ }
162
+
131
163
  if (!event.order) {
132
164
  // An event type this ingestion does not act on. Marketplaces emit a wide
133
165
  // stream (dispatched, concluded, driver assigned…) and most of it is not an
@@ -138,12 +170,27 @@ async function applyEvent(
138
170
  return { kind: "ignored", reason };
139
171
  }
140
172
 
141
- const result = await ingestMarketplaceOrder(ctx, {
142
- clientId,
143
- order: event.order,
144
- settings,
145
- now,
146
- });
173
+ return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);
174
+ }
175
+
176
+ /** Ingest the order an event carries, unless it names another merchant than the connection's. */
177
+ async function ingestCarried(
178
+ ctx: EngineContext,
179
+ inboxId: string,
180
+ clientId: string,
181
+ order: NormalizedMarketplaceOrder,
182
+ settings: IngestSettings,
183
+ now: Date | undefined,
184
+ ): Promise<DeliveryOutcome> {
185
+ const mismatch = await carriedOrderMismatch(ctx, clientId, order);
186
+ if (mismatch) {
187
+ // FAILED, so the reconciliation sweep retries it once the connection's
188
+ // merchant id is corrected, within the inbox's attempt bound.
189
+ await settleInboxEvent(ctx, inboxId, "FAILED", mismatch);
190
+ ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);
191
+ return { kind: "failed", reason: mismatch };
192
+ }
193
+ const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });
147
194
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
148
195
  return { kind: "ingested", orderId: result.orderId, unmappedSkus: result.unmappedSkus };
149
196
  }
@@ -158,7 +205,7 @@ async function applyEvent(
158
205
  */
159
206
  export async function reprocessStoredDelivery(
160
207
  ctx: EngineContext,
161
- input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown },
208
+ input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown; receivedAt?: Date | null },
162
209
  ): Promise<DeliveryOutcome> {
163
210
  const event = normalizeEvent(ctx, input.provider, input.payload);
164
211
  if (!event) {
@@ -176,6 +223,8 @@ export async function reprocessStoredDelivery(
176
223
  await deferInboxEvent(ctx, input.id, reason);
177
224
  return { kind: "ignored", reason };
178
225
  }
226
+ // A row waiting for its order body is the fetch job's: re-queued, never fetched here.
227
+ if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);
179
228
  try {
180
229
  return await applyEvent(
181
230
  ctx,
package/src/core/types.ts CHANGED
@@ -96,6 +96,12 @@ export interface NormalizedMarketplaceOrder {
96
96
  deliveredBy?: MarketplaceDeliveredBy | null;
97
97
  /** Null on a take-out and when unstated. */
98
98
  deliveryAddress?: NormalizedAddress | null;
99
+ /**
100
+ * OPTIONAL. The merchant the order names, when its body says (Open
101
+ * Delivery's `merchant.id`). A fetched order naming another merchant than
102
+ * the connection's is refused.
103
+ */
104
+ externalMerchantId?: string | null;
99
105
  }
100
106
 
101
107
  /**
@@ -128,4 +134,12 @@ export interface NormalizedEvent {
128
134
  * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
129
135
  */
130
136
  cancellationOutcome?: CancellationOutcome | null;
137
+ /**
138
+ * OPTIONAL. This event announces an order whose body the marketplace serves
139
+ * separately (Open Delivery's `CREATED` carries only the order's id): the
140
+ * engine fetches it through the adapter's `fetchOrder`, in the
141
+ * `marketplace.fetch-order` job, never inside the request that delivered
142
+ * the event. Ignored when `order` is present.
143
+ */
144
+ orderToFetch?: boolean;
131
145
  }
@@ -1,5 +1,3 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
2
-
3
1
  import type {
4
2
  MarketplaceDeliveredBy,
5
3
  MarketplaceOrderType,
@@ -9,6 +7,14 @@ import type {
9
7
  NormalizedMarketplaceOrder,
10
8
  NormalizedOrderLine,
11
9
  } from "../core/types";
10
+ import {
11
+ asString,
12
+ firstCents,
13
+ firstDate,
14
+ firstString,
15
+ pick,
16
+ verifyHmacSha256Hex,
17
+ } from "../core/payload-read";
12
18
 
13
19
  /**
14
20
  * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.
@@ -30,99 +36,20 @@ const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
30
36
  /** iFood refused the store's own cancellation request. */
31
37
  const CANCELLATION_REQUEST_FAILED = new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
32
38
 
33
- /** Read a nested value without asserting the shape of anything on the way. */
34
- function pick(source: unknown, ...path: string[]): unknown {
35
- let cursor: unknown = source;
36
- for (const key of path) {
37
- if (typeof cursor !== "object" || cursor === null) return undefined;
38
- cursor = (cursor as Record<string, unknown>)[key];
39
- }
40
- return cursor;
41
- }
42
-
43
- function asString(value: unknown): string | null {
44
- if (typeof value === "string" && value.trim() !== "") return value.trim();
45
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
46
- return null;
47
- }
48
-
49
- /**
50
- * The first of several candidate paths that yields a string.
51
- *
52
- * iFood states the same fact under different keys depending on which API
53
- * version delivered the order, so nearly every read here is a fallback chain.
54
- * Expressed as data rather than as `??` so a chain can grow by one entry
55
- * instead of by one branch.
56
- */
57
- function firstString(source: unknown, paths: string[][]): string | null {
58
- for (const path of paths) {
59
- const found = asString(pick(source, ...path));
60
- if (found !== null) return found;
61
- }
62
- return null;
63
- }
64
-
65
- /** {@link firstString} for money. Same reason, same shape. */
66
- function firstCents(source: unknown, paths: string[][]): number | null {
67
- for (const path of paths) {
68
- const found = toCents(pick(source, ...path));
69
- if (found !== null) return found;
70
- }
71
- return null;
72
- }
73
-
74
39
  /**
75
- * iFood states money in DECIMAL reais (`12.9`), this app in integer cents.
76
- *
77
- * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,
78
- * so truncation loses a cent on ordinary prices — per line, on every order,
79
- * always in the store's disfavour.
80
- */
81
- function toCents(value: unknown): number | null {
82
- const numeric = typeof value === "string" ? Number(value) : value;
83
- if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
84
- return Math.round(numeric * 100);
85
- }
86
-
87
- function toDate(value: unknown): Date | null {
88
- const raw = asString(value);
89
- if (!raw) return null;
90
- const parsed = new Date(raw);
91
- return Number.isNaN(parsed.getTime()) ? null : parsed;
92
- }
93
-
94
- /** {@link firstString} for timestamps. */
95
- function firstDate(source: unknown, paths: string[][]): Date | null {
96
- for (const path of paths) {
97
- const found = toDate(pick(source, ...path));
98
- if (found !== null) return found;
99
- }
100
- return null;
101
- }
102
-
103
- /**
104
- * Verify a delivery against the merchant's webhook secret.
105
- *
106
- * Unsigned deliveries are refused whenever a secret is CONFIGURED. A store that
107
- * has not set one yet is accepted — iFood's own onboarding issues the secret
108
- * after the merchant is certified, so refusing before then would make the
109
- * connection untestable — and that state is visible on the integration screen
110
- * rather than silent.
111
- *
112
- * Compared in constant time over bytes: an early-exit `===` on a hex digest
113
- * leaks the prefix a forger already got right, one request at a time.
40
+ * Verify a delivery against the merchant's webhook secret: iFood signs the raw
41
+ * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one
42
+ * refuses an unsigned delivery; constant-time compare) is the engine's
43
+ * {@link verifyHmacSha256Hex}. iFood's own onboarding issues the secret after
44
+ * the merchant is certified, so refusing before then would make the
45
+ * connection untestable.
114
46
  */
115
47
  export function verifyIfoodSignature(
116
48
  rawBody: string,
117
49
  signature: string | null,
118
50
  webhookSecret: string | null,
119
51
  ): boolean {
120
- if (!webhookSecret) return true;
121
- if (!signature) return false;
122
- const expected = createHmac("sha256", webhookSecret).update(rawBody, "utf8").digest("hex");
123
- const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, ""), "utf8");
124
- const mine = Buffer.from(expected, "utf8");
125
- return given.length === mine.length && timingSafeEqual(given, mine);
52
+ return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
126
53
  }
127
54
 
128
55
  /** The buyer, as much of them as iFood discloses on the order. */
package/src/index.ts CHANGED
@@ -12,7 +12,8 @@
12
12
  * So: the engine (this entry) holds the inbox, the pipeline, ingest, the
13
13
  * acceptance clock and its sweep, the SKU map, the integration settings and
14
14
  * the outbound engine, and knows no marketplace by name. Each marketplace is
15
- * an adapter at its own subpath (`@12-apps/marketplace/ifood`), registered at
15
+ * an adapter at its own subpath (`@12-apps/marketplace/ifood`,
16
+ * `@12-apps/marketplace/99food`, `@12-apps/marketplace/rappi`), registered at
16
17
  * mount. The wiring manifests are at `./manifest` and `./manifest/server`.
17
18
  *
18
19
  * Everything the engine needs from its host is a required port with no
@@ -27,6 +28,7 @@ export {
27
28
  type AdapterTokenCache,
28
29
  type CancellationReason,
29
30
  type CancellationRequestInput,
31
+ type FetchOrderResult,
30
32
  type MarketplaceAdapter,
31
33
  type MarketplaceCapabilities,
32
34
  type MarketplaceCredentials,
@@ -120,4 +122,10 @@ export {
120
122
  type OutboundJobPayload,
121
123
  } from "./core/outbound-queue";
122
124
  export type { DeliveryOutcome } from "./core/pipeline";
125
+ export {
126
+ FetchOrderRetryError,
127
+ MARKETPLACE_FETCH_ORDER_JOB,
128
+ type FetchOrderJobPayload,
129
+ type FetchOrderOutcome,
130
+ } from "./core/fetch-order";
123
131
  export type { MarketplaceOrderState } from "./core/state";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The words the Rappi adapter needs from its host, and nothing else.
3
+ *
4
+ * Required and defaultless, like every copy port in this repo: the adapter
5
+ * ships no language of its own. Two packs sit beside it (`./pt-BR`,
6
+ * `./en-US`); a host passes one by hand, or its own.
7
+ */
8
+
9
+ /**
10
+ * The `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,
11
+ * verbatim from Rappi's public API reference (dev-portal.rappi.com,
12
+ * api-reference/orders, "PUT orders/{orderId}/reject"). Pinned by the portal,
13
+ * not estimated.
14
+ */
15
+ export const RAPPI_REASON_CODES = [
16
+ "ITEM_OUT_OF_STOCK",
17
+ "ITEM_NOT_FOUND",
18
+ "ITEM_WRONG_PRICE",
19
+ "ORDER_MISSING_INFORMATION",
20
+ "ORDER_MISSING_ADDRESS_INFORMATION",
21
+ "ORDER_TOTAL_INCORRECT",
22
+ ] as const;
23
+
24
+ export type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];
25
+
26
+ /**
27
+ * The codes with which the portal REQUIRES the offending items ("If the value
28
+ * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,
29
+ * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the
30
+ * offending items").
31
+ */
32
+ export const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[] = ["ITEM_OUT_OF_STOCK", "ITEM_NOT_FOUND", "ITEM_WRONG_PRICE"];
33
+
34
+ export interface RappiAdapterCopy {
35
+ /** One label per reason code. Sent as the reject's required `reason` text. */
36
+ reasonLabels: Readonly<Record<RappiReasonCode, string>>;
37
+ /** What an address with no street number says instead. */
38
+ missingStreetNumber: string;
39
+ }
@@ -0,0 +1,14 @@
1
+ import type { RappiAdapterCopy } from "./copy";
2
+
3
+ /** The Rappi adapter's en-US pack: the same reasons, in English. */
4
+ export const RAPPI_ADAPTER_COPY_EN_US = {
5
+ reasonLabels: {
6
+ ITEM_OUT_OF_STOCK: "Item unavailable",
7
+ ITEM_NOT_FOUND: "Item not found",
8
+ ITEM_WRONG_PRICE: "Wrong item price",
9
+ ORDER_MISSING_INFORMATION: "Order information missing",
10
+ ORDER_MISSING_ADDRESS_INFORMATION: "Address information missing",
11
+ ORDER_TOTAL_INCORRECT: "Order total incorrect",
12
+ },
13
+ missingStreetNumber: "no number",
14
+ } as const satisfies RappiAdapterCopy;