@12-apps/marketplace 1.6.0 → 1.7.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 (47) hide show
  1. package/dist/99food/index.d.ts +1 -1
  2. package/dist/99food/index.js +7 -4
  3. package/dist/99food/index.js.map +1 -1
  4. package/dist/{adapter-CCWMqt2g.d.ts → adapter-DOjTak1H.d.ts} +37 -2
  5. package/dist/{chunk-RGMSD7S7.js → chunk-L3DCOZUU.js} +7 -1
  6. package/dist/chunk-L3DCOZUU.js.map +1 -0
  7. package/dist/{chunk-NFZT5TWR.js → chunk-SJUKBCVO.js} +17 -13
  8. package/dist/chunk-SJUKBCVO.js.map +1 -0
  9. package/dist/{chunk-4CJ7B5OR.js → chunk-YVUZHXUF.js} +2 -2
  10. package/dist/{engine-w2TgRrlc.d.ts → engine-DG1fg43Y.d.ts} +17 -6
  11. package/dist/hono/index.d.ts +2 -2
  12. package/dist/hono/index.js +2 -2
  13. package/dist/ifood/index.d.ts +1 -1
  14. package/dist/ifood/index.js +38 -4
  15. package/dist/ifood/index.js.map +1 -1
  16. package/dist/index.d.ts +3 -3
  17. package/dist/index.js +17 -7
  18. package/dist/index.js.map +1 -1
  19. package/dist/manifest/server.d.ts +2 -2
  20. package/dist/manifest/server.js +2 -2
  21. package/dist/rappi/index.d.ts +1 -1
  22. package/dist/rappi/index.js +4 -3
  23. package/dist/rappi/index.js.map +1 -1
  24. package/dist/server/index.d.ts +2 -2
  25. package/dist/server/index.js +2 -2
  26. package/package.json +1 -1
  27. package/prisma/marketplace.prisma +3 -3
  28. package/prisma/migrations/20261125180000_marketplace_cancellation_failure_reason_widen/migration.sql +16 -0
  29. package/src/99food/outbound.ts +7 -2
  30. package/src/core/adapter.ts +17 -2
  31. package/src/core/cancellation.ts +4 -1
  32. package/src/core/catalogue.ts +4 -3
  33. package/src/core/decisions.ts +3 -2
  34. package/src/core/fetch-order.ts +2 -2
  35. package/src/core/order-fetch-marks.ts +13 -8
  36. package/src/core/outbound.ts +15 -11
  37. package/src/core/pipeline.ts +13 -1
  38. package/src/core/ports.ts +15 -4
  39. package/src/core/state.ts +1 -1
  40. package/src/core/types.ts +25 -0
  41. package/src/ifood/normalize.ts +53 -0
  42. package/src/ifood/outbound.ts +2 -1
  43. package/src/index.ts +3 -0
  44. package/src/rappi/outbound.ts +2 -1
  45. package/dist/chunk-NFZT5TWR.js.map +0 -1
  46. package/dist/chunk-RGMSD7S7.js.map +0 -1
  47. /package/dist/{chunk-4CJ7B5OR.js.map → chunk-YVUZHXUF.js.map} +0 -0
@@ -10,7 +10,7 @@ import {
10
10
  import { readOutboundConnection, type OutboundConnection } from "./integration";
11
11
  import type { OutboundJobPayload } from "./outbound-queue";
12
12
  import { failAsTimeout } from "./outbound-sweep";
13
- import type { EngineContext } from "./ports";
13
+ import type { CancellationFailureReason, EngineContext } from "./ports";
14
14
  import { resolveReason } from "./registry";
15
15
 
16
16
  /**
@@ -133,15 +133,16 @@ async function stampCancellation(
133
133
  row: OutboundRow,
134
134
  status: "REQUESTED" | "CONFIRMED" | "FAILED",
135
135
  clientId: string,
136
+ failure: CancellationFailureReason = "REFUSED",
136
137
  ): Promise<void> {
137
138
  if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
138
139
  const db = await ctx.ports.db();
139
- const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
140
+ const data = status === "FAILED" ? failedRequestData(failure) : { cancellationStatus: status };
140
141
  const moved = await db.marketplaceAcceptance.updateMany({
141
142
  where: { orderId: row.orderId, cancellationStatus: "PENDING" },
142
143
  data,
143
144
  });
144
- if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
145
+ if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, failure);
145
146
  }
146
147
 
147
148
  /**
@@ -218,7 +219,7 @@ async function settle(
218
219
  result: OutboundResult,
219
220
  attempt: OutboundAttempt,
220
221
  succeed: () => Promise<void>,
221
- fail: () => Promise<void>,
222
+ fail: (reason: CancellationFailureReason) => Promise<void>,
222
223
  ): Promise<OutboundOutcome> {
223
224
  if (result.kind === "accepted") {
224
225
  await succeed();
@@ -229,7 +230,9 @@ async function settle(
229
230
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
230
231
  throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);
231
232
  }
232
- await fail();
233
+ // A refusal that is the marketplace's judgement is REFUSED; anything else (our
234
+ // own refusal, retries that ran out) never got one.
235
+ await fail(result.kind === "refused" && !result.own ? "REFUSED" : "UNREACHABLE");
233
236
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);
234
237
  ctx.ports.publishChanged(payload.clientId);
235
238
  return { kind: "failed", action: payload.action, reason };
@@ -248,7 +251,7 @@ async function runConfirm(
248
251
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
249
252
  const result: OutboundResult =
250
253
  typeof connection === "string"
251
- ? { kind: "refused", status: 0, message: connection }
254
+ ? { kind: "refused", status: 0, message: connection, own: true }
252
255
  : await adapter.confirm(
253
256
  { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
254
257
  refOf(row),
@@ -299,8 +302,9 @@ async function runCancellation(
299
302
  const reason = resolveReason(adapter, row.cancellationReasonCode);
300
303
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
301
304
  let result: OutboundResult;
302
- if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's" };
303
- else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection };
305
+ // A stored reason that is not the marketplace's own was never sent: our side (UNREACHABLE).
306
+ if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's", own: true };
307
+ else if (typeof connection === "string") result = { kind: "refused", status: 0, message: connection, own: true };
304
308
  else {
305
309
  result = await adapter.requestCancellation(
306
310
  { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
@@ -316,7 +320,7 @@ async function runCancellation(
316
320
  result,
317
321
  attempt,
318
322
  () => stampCancellation(ctx, row, taken, payload.clientId),
319
- () => stampCancellation(ctx, row, "FAILED", payload.clientId),
323
+ (failure) => stampCancellation(ctx, row, "FAILED", payload.clientId, failure),
320
324
  );
321
325
  }
322
326
 
@@ -335,12 +339,12 @@ async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobP
335
339
  })
336
340
  : db.marketplaceAcceptance.updateMany({
337
341
  where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
338
- data: failedRequestData("REFUSED"),
342
+ data: failedRequestData("UNREACHABLE"),
339
343
  }));
340
344
  ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
341
345
  ctx.ports.publishChanged(payload.clientId);
342
346
  if (payload.action === "requestCancellation" && moved.count > 0) {
343
- await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
347
+ await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "UNREACHABLE");
344
348
  }
345
349
  return { kind: "failed", action: payload.action, reason };
346
350
  }
@@ -4,7 +4,7 @@ import { awaitOrderBody, merchantMismatch, requeueOwedFetch } from "./fetch-orde
4
4
  import { deferInboxEvent, recordInboxEvent, settleInboxEvent } from "./inbox";
5
5
  import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
6
6
  import { connectionMerchantId, resolveIngestionTarget } from "./integration";
7
- import { markCancelledBeforeIngest } from "./order-fetch-marks";
7
+ import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest, markCancelledBeforeIngest } from "./order-fetch-marks";
8
8
  import type { EngineContext } from "./ports";
9
9
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
10
10
 
@@ -190,7 +190,19 @@ async function ingestCarried(
190
190
  ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);
191
191
  return { kind: "failed", reason: mismatch };
192
192
  }
193
+ // A CANCELLED that found nothing to cancel left its marker (an earlier
194
+ // NEW_ORDER FAILED, so no acceptance existed). The retry sweep re-runs that
195
+ // row: ingesting it now would send a cancelled order to the kitchen.
196
+ if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
197
+ await settleInboxEvent(ctx, inboxId, "IGNORED", CANCELLED_BEFORE_INGEST_REASON);
198
+ return { kind: "ignored", reason: CANCELLED_BEFORE_INGEST_REASON };
199
+ }
193
200
  const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });
201
+ // A CANCELLED that read the acceptances while this ingest's transaction was
202
+ // still open found none and left its marker: honour it now, through the
203
+ // ordinary cancel path (the order is cancelled; no confirm is owed).
204
+ const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };
205
+ if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);
194
206
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
195
207
  return { kind: "ingested", orderId: result.orderId, unmappedSkus: result.unmappedSkus };
196
208
  }
package/src/core/ports.ts CHANGED
@@ -146,11 +146,22 @@ export type MarketplaceAdmissionResult =
146
146
  export type MarketplaceRefusal = "REJECTED" | "EXPIRED" | "CANCELLED";
147
147
 
148
148
  /**
149
- * Why the store's own cancellation request FAILED: REFUSED (the marketplace
150
- * said no, or every attempt failed) or TIMEOUT (no answer inside the
151
- * marketplace's cancellation window). Vocabulary, not copy.
149
+ * Why the store's own cancellation request FAILED. Vocabulary, not copy.
150
+ *
151
+ * - `REFUSED`: the marketplace judged the request and denied it: its denial
152
+ * event, an answer that is its business refusal, or an adapter that has no
153
+ * cancellation API to call. An adapter that cannot tell a business 4xx from
154
+ * a malformed request (iFood, Rappi) reports every final 4xx as REFUSED.
155
+ * - `UNREACHABLE`: our own request never got a judgement: no credentials or
156
+ * ones that do not open, a token the marketplace did not grant, a request
157
+ * the marketplace calls malformed (99Food's 400), or every attempt failed
158
+ * on the network or a 5xx. Retrying, or fixing the connection, can help.
159
+ * - `TIMEOUT`: no answer inside the marketplace's cancellation window.
160
+ *
161
+ * A host written before `UNREACHABLE` existed treats an unknown value as it
162
+ * treats REFUSED: the order stays and a person finishes in the marketplace's app.
152
163
  */
153
- export type CancellationFailureReason = "REFUSED" | "TIMEOUT";
164
+ export type CancellationFailureReason = "REFUSED" | "UNREACHABLE" | "TIMEOUT";
154
165
 
155
166
  /**
156
167
  * The host's domain, as five questions the engine asks and never answers.
package/src/core/state.ts CHANGED
@@ -17,7 +17,7 @@ export interface MarketplaceOrderState {
17
17
  confirmFailedAt: Date | null;
18
18
  cancellation: CancellationStatus | null;
19
19
  cancellationReasonCode: string | null;
20
- /** Why the request FAILED (REFUSED or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */
20
+ /** Why the request FAILED (REFUSED, UNREACHABLE or TIMEOUT); null unless `cancellation` is FAILED, and on rows from before it. */
21
21
  cancellationFailure: CancellationFailureReason | null;
22
22
  /** The adapter's app link, or null when no adapter is registered for it. */
23
23
  appUrl: string | null;
package/src/core/types.ts CHANGED
@@ -69,6 +69,18 @@ export type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
69
69
  /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
70
70
  export type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
71
71
 
72
+ /** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */
73
+ export type MarketplaceDiscountSponsor = "MERCHANT" | "MARKETPLACE" | "OTHER";
74
+
75
+ /** One discount on an order, as the part one sponsor pays. */
76
+ export interface NormalizedOrderDiscount {
77
+ /** The discount's value in the smallest currency unit. */
78
+ cents: number;
79
+ sponsor: MarketplaceDiscountSponsor;
80
+ /** What the marketplace called the campaign, when it says. */
81
+ name?: string;
82
+ }
83
+
72
84
  /** An incoming marketplace order, normalized. */
73
85
  export interface NormalizedMarketplaceOrder {
74
86
  provider: MarketplaceProvider;
@@ -96,6 +108,19 @@ export interface NormalizedMarketplaceOrder {
96
108
  deliveredBy?: MarketplaceDeliveredBy | null;
97
109
  /** Null on a take-out and when unstated. */
98
110
  deliveryAddress?: NormalizedAddress | null;
111
+ /**
112
+ * OPTIONAL. The delivery fee the buyer was charged, in the smallest currency
113
+ * unit. 0 is a free delivery; null or absent is "did not say".
114
+ */
115
+ deliveryFeeCents?: number | null;
116
+ /** OPTIONAL. The items' sum as the marketplace states it, before fees and discounts. Null or absent is "did not say". */
117
+ subtotalCents?: number | null;
118
+ /**
119
+ * OPTIONAL. The discounts on the order, one entry per sponsor's share, so a
120
+ * host can tell what the store gave from what the marketplace paid for.
121
+ * Absent is "did not say"; an empty array is "no discount".
122
+ */
123
+ discounts?: NormalizedOrderDiscount[];
99
124
  /**
100
125
  * OPTIONAL. The merchant the order names, when its body says (Open
101
126
  * Delivery's `merchant.id`). A fetched order naming another merchant than
@@ -1,10 +1,12 @@
1
1
  import type {
2
2
  MarketplaceDeliveredBy,
3
+ MarketplaceDiscountSponsor,
3
4
  MarketplaceOrderType,
4
5
  NormalizedAddress,
5
6
  NormalizedBuyer,
6
7
  NormalizedEvent,
7
8
  NormalizedMarketplaceOrder,
9
+ NormalizedOrderDiscount,
8
10
  NormalizedOrderLine,
9
11
  } from "../core/types";
10
12
  import {
@@ -13,6 +15,7 @@ import {
13
15
  firstDate,
14
16
  firstString,
15
17
  pick,
18
+ toCents,
16
19
  verifyHmacSha256Hex,
17
20
  } from "../core/payload-read";
18
21
 
@@ -112,6 +115,45 @@ function readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {
112
115
  return stated === "MERCHANT" ? "MERCHANT" : null;
113
116
  }
114
117
 
118
+ /**
119
+ * iFood's sponsor names as who pays. ESTIMATED: the names are the ones iFood's
120
+ * order-details guide documents for `benefits[].sponsorshipValues[].name`, but
121
+ * no recorded payload in this repo carries them; confirm against a real order
122
+ * (https://developer.ifood.com.br/en-US/docs/guides/order/details).
123
+ */
124
+ function sponsorOf(name: string | null): MarketplaceDiscountSponsor {
125
+ const stated = name?.toUpperCase();
126
+ if (stated === "IFOOD") return "MARKETPLACE";
127
+ return stated === "MERCHANT" ? "MERCHANT" : "OTHER";
128
+ }
129
+
130
+ /**
131
+ * The discounts on an order, one per sponsor's share of each benefit.
132
+ * ESTIMATED shape (see {@link sponsorOf}): `benefits[]` with a `value` and
133
+ * `sponsorshipValues[{ name, value, description? }]`. A benefit that names no
134
+ * sponsor is the whole `value` under OTHER; a share with no usable amount is
135
+ * skipped. Absent `benefits` is undefined ("did not say").
136
+ */
137
+ function readDiscounts(order: unknown): NormalizedOrderDiscount[] | undefined {
138
+ const benefits = pick(order, "benefits");
139
+ if (!Array.isArray(benefits)) return undefined;
140
+ return benefits.flatMap((benefit): NormalizedOrderDiscount[] => {
141
+ const shares = pick(benefit, "sponsorshipValues");
142
+ const parts = Array.isArray(shares)
143
+ ? shares.map((share) => ({
144
+ cents: toCents(pick(share, "value")),
145
+ sponsor: sponsorOf(firstString(share, [["name"]])),
146
+ name: firstString(share, [["description"]]),
147
+ }))
148
+ : [{ cents: toCents(pick(benefit, "value")), sponsor: "OTHER" as const, name: null }];
149
+ return parts.flatMap((part) =>
150
+ part.cents === null || part.cents <= 0
151
+ ? []
152
+ : [{ cents: part.cents, sponsor: part.sponsor, ...(part.name === null ? {} : { name: part.name }) }],
153
+ );
154
+ });
155
+ }
156
+
115
157
  /**
116
158
  * Where a delivery goes. The street is what a courier cannot find a door
117
159
  * without, so an address with none is none; a missing number reads as the
@@ -135,6 +177,11 @@ function readAddress(order: unknown, missingStreetNumber: string): NormalizedAdd
135
177
  };
136
178
  }
137
179
 
180
+ /** `{ key: value }` unless the value is undefined, so an unstated field is absent rather than `undefined`. */
181
+ function optional<K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } {
182
+ return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });
183
+ }
184
+
138
185
  /** The order body of a placed-order event, or null when it carries none. */
139
186
  function readOrder(
140
187
  payload: unknown,
@@ -168,6 +215,12 @@ function readOrder(
168
215
  orderType: readOrderType(order),
169
216
  deliveredBy: readDeliveredBy(order),
170
217
  deliveryAddress: readAddress(order, missingStreetNumber),
218
+ // ESTIMATED names (iFood's order-details guide: `total.deliveryFee`,
219
+ // `total.subTotal`, `benefits[]`). Fee and subtotal are null when unstated,
220
+ // never 0; `discounts` is absent when `benefits` is.
221
+ deliveryFeeCents: firstCents(order, [["total", "deliveryFee"]]),
222
+ subtotalCents: firstCents(order, [["total", "subTotal"]]),
223
+ ...optional("discounts", readDiscounts(order)),
171
224
  };
172
225
  }
173
226
 
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  answered,
3
3
  outboundResultOf,
4
+ tokenGrantResultOf,
4
5
  type AdapterCallContext,
5
6
  type CancellationRequestInput,
6
7
  type OutboundOrderRef,
@@ -70,7 +71,7 @@ export async function bearer(ctx: AdapterCallContext): Promise<{ token: string }
70
71
  clientSecret: ctx.credentials.clientSecret,
71
72
  }).toString(),
72
73
  });
73
- if (response.status < 200 || response.status >= 300) return outboundResultOf(response);
74
+ if (response.status < 200 || response.status >= 300) return tokenGrantResultOf(response);
74
75
  const token = tokenOf(response.body);
75
76
  if (!token) return { kind: "retry", reason: "iFood answered the token grant without a token" };
76
77
  ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ export { stableUuid } from "./core/catalogue-ids";
25
25
  export {
26
26
  answered,
27
27
  outboundResultOf,
28
+ tokenGrantResultOf,
28
29
  type AdapterCallContext,
29
30
  type AdapterTokenCache,
30
31
  type CancellationReason,
@@ -70,12 +71,14 @@ export {
70
71
  PROVIDER_ID_PATTERN,
71
72
  type CancellationOutcome,
72
73
  type MarketplaceDeliveredBy,
74
+ type MarketplaceDiscountSponsor,
73
75
  type MarketplaceOrderType,
74
76
  type MarketplaceProvider,
75
77
  type NormalizedAddress,
76
78
  type NormalizedBuyer,
77
79
  type NormalizedEvent,
78
80
  type NormalizedMarketplaceOrder,
81
+ type NormalizedOrderDiscount,
79
82
  type NormalizedOrderLine,
80
83
  } from "./core/types";
81
84
  export type {
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  answered,
3
3
  outboundResultOf,
4
+ tokenGrantResultOf,
4
5
  type AdapterCallContext,
5
6
  type CancellationRequestInput,
6
7
  type MarketplaceHttpResponse,
@@ -96,7 +97,7 @@ export async function bearer(
96
97
  body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret }),
97
98
  });
98
99
  if (response.status < 200 || response.status >= 300) {
99
- const result = outboundResultOf(response);
100
+ const result = tokenGrantResultOf(response);
100
101
  return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
101
102
  }
102
103
  const token = tokenOf(response.body);