@12-apps/marketplace 1.16.0 → 1.18.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 (79) hide show
  1. package/ADOPTING.md +185 -0
  2. package/dist/99food/index.d.ts +2 -2
  3. package/dist/99food/index.js +2 -2
  4. package/dist/{adapter-CjVdMhZ2.d.ts → adapter-ZpAWKoCk.d.ts} +300 -3
  5. package/dist/{chunk-TRUK5ZBE.js → chunk-3B5EULS6.js} +2 -2
  6. package/dist/{chunk-DJIMUEHT.js → chunk-BLHZ3MRB.js} +79 -7
  7. package/dist/chunk-BLHZ3MRB.js.map +1 -0
  8. package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
  9. package/dist/chunk-LO7OKO6V.js.map +1 -0
  10. package/dist/{chunk-TICWLBSA.js → chunk-MDEIRGNL.js} +1372 -823
  11. package/dist/chunk-MDEIRGNL.js.map +1 -0
  12. package/dist/{chunk-H2VQRD3B.js → chunk-Q5RMVNU5.js} +1 -1
  13. package/dist/chunk-Q5RMVNU5.js.map +1 -0
  14. package/dist/{chunk-BTKVZAJI.js → chunk-ZT6TZTLD.js} +1 -1
  15. package/dist/chunk-ZT6TZTLD.js.map +1 -0
  16. package/dist/{client-DgzCkl8u.d.ts → client-DpEq0yXb.d.ts} +1 -1
  17. package/dist/{engine-DSRj7qnC.d.ts → engine-DRRhAjZK.d.ts} +566 -293
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +4 -4
  20. package/dist/ifood/index.d.ts +14 -2
  21. package/dist/ifood/index.js +406 -120
  22. package/dist/ifood/index.js.map +1 -1
  23. package/dist/index.d.ts +21 -4
  24. package/dist/index.js +453 -43
  25. package/dist/index.js.map +1 -1
  26. package/dist/keeta/index.d.ts +2 -2
  27. package/dist/keeta/index.js +2 -2
  28. package/dist/manifest/index.d.ts +78 -0
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +6 -2
  31. package/dist/manifest/server.js +4 -4
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/index.d.ts +93 -7
  35. package/dist/server/index.js +4 -4
  36. package/package.json +1 -1
  37. package/prisma/marketplace.prisma +70 -2
  38. package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
  39. package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
  40. package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
  41. package/src/core/adapter.ts +14 -2
  42. package/src/core/app-linking.ts +396 -0
  43. package/src/core/delivery-code.ts +119 -0
  44. package/src/core/dispute-engine.ts +32 -0
  45. package/src/core/dispute-job.ts +142 -0
  46. package/src/core/dispute-port.ts +133 -0
  47. package/src/core/dispute-store.ts +203 -0
  48. package/src/core/disputes.ts +263 -0
  49. package/src/core/engine.ts +12 -55
  50. package/src/core/integration.ts +3 -1
  51. package/src/core/link-engine.ts +176 -0
  52. package/src/core/link-store.ts +15 -0
  53. package/src/core/linking-port.ts +35 -1
  54. package/src/core/linking.ts +8 -0
  55. package/src/core/logistics.ts +388 -0
  56. package/src/core/outbound-queue.ts +6 -1
  57. package/src/core/outbound-sweep.ts +19 -6
  58. package/src/core/outbound.ts +4 -5
  59. package/src/core/pipeline.ts +14 -4
  60. package/src/core/ports.ts +20 -2
  61. package/src/core/status-job.ts +3 -0
  62. package/src/core/status-store.ts +2 -1
  63. package/src/core/types.ts +10 -0
  64. package/src/ifood/app-linking.ts +119 -0
  65. package/src/ifood/disputes.ts +209 -0
  66. package/src/ifood/index.ts +15 -1
  67. package/src/ifood/logistics.ts +38 -0
  68. package/src/ifood/normalize.ts +14 -1
  69. package/src/index.ts +44 -0
  70. package/src/server/jobs.ts +51 -3
  71. package/src/server/link-routes.ts +56 -4
  72. package/src/server/mcp-link.ts +44 -2
  73. package/src/server/mcp.ts +2 -1
  74. package/dist/chunk-BTKVZAJI.js.map +0 -1
  75. package/dist/chunk-DJIMUEHT.js.map +0 -1
  76. package/dist/chunk-H2VQRD3B.js.map +0 -1
  77. package/dist/chunk-SGOTN5PX.js.map +0 -1
  78. package/dist/chunk-TICWLBSA.js.map +0 -1
  79. /package/dist/{chunk-TRUK5ZBE.js.map → chunk-3B5EULS6.js.map} +0 -0
package/src/core/types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { NormalizedDisputeEvent } from "./dispute-port";
2
+
1
3
  /**
2
4
  * The canonical shape every marketplace adapter normalizes INTO.
3
5
  *
@@ -348,4 +350,12 @@ export interface NormalizedEvent {
348
350
  * host's admit, with no confirm sent back. Carries no order body.
349
351
  */
350
352
  marketplaceConfirmed?: boolean;
353
+ /** The marketplace asked the customer's delivery code for the order (FUT-6167). */
354
+ deliveryCodeRequested?: boolean;
355
+ /**
356
+ * OPTIONAL (FUT-6099). A dispute the marketplace opened or closed on this
357
+ * order (iFood's HSD / HSS). Carries no order body, and never moves the
358
+ * order or its acceptance.
359
+ */
360
+ dispute?: NormalizedDisputeEvent | null;
351
361
  }
@@ -0,0 +1,119 @@
1
+ import type { AdapterCallContext, MarketplaceHttpResponse } from "../core/adapter";
2
+ import { outboundResultOf } from "../core/adapter";
3
+ import type { AppLinkCallContext, LinkResult, LinkedMerchant, MarketplaceAppLinking } from "../core/linking-port";
4
+ import { asString, pick } from "../core/payload-read";
5
+ import { IFOOD_API, withIfoodToken } from "./outbound";
6
+
7
+ /**
8
+ * iFood's CENTRALIZED-APP linking, the wire format only (FUT-5798).
9
+ *
10
+ * The store authorizes the software's app on iFood's Portal do Parceiro; the
11
+ * app's own `client_credentials` token then lists that store with the others
12
+ * that authorized it, and the store picks its own. iFood offers its webhook
13
+ * only to centralized apps, which is why the software links this way.
14
+ *
15
+ * - `GET /merchant/v1.0/merchants?page=&size=` (size default 100) → 200
16
+ * `[{ id, name, corporateName }]`: every store the app may act for.
17
+ * - `GET /merchant/v1.0/merchants/{merchantId}` → 200 with `address`
18
+ * (sandbox, 2026-12-02: `id, name, corporateName, description,
19
+ * averageTicket, type, createdAt, test, status, address, operations`).
20
+ * Neither carries a CNPJ.
21
+ *
22
+ * The token is the one every outbound call of the app uses, from the same
23
+ * cache key: bought once, renewed only when expired or answered 401.
24
+ *
25
+ * ESTIMATED, not settled by iFood's pages: the address fields' names
26
+ * (`street`/`streetName`, `number`/`streetNumber`, `district`/`neighborhood`),
27
+ * read with fallbacks; and the portal's apps page as the place to authorize.
28
+ */
29
+
30
+ const MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
31
+ /** One page of the merchant list; iFood's documented default. */
32
+ const MERCHANT_PAGE_SIZE = 100;
33
+ /** A ceiling on pages read, so a misbehaving answer cannot loop. */
34
+ const MAX_MERCHANT_PAGES = 20;
35
+ /** Where a store authorizes the software's app: the Portal do Parceiro's apps page. */
36
+ export const IFOOD_APPS_PORTAL_URL = "https://portal.ifood.com.br/apps";
37
+
38
+ function json(body: string): unknown {
39
+ try {
40
+ return body === "" ? null : (JSON.parse(body) as unknown);
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ const adapterContext = (ctx: AppLinkCallContext): AdapterCallContext => ({
47
+ http: ctx.http,
48
+ credentials: ctx.credentials,
49
+ environment: ctx.environment,
50
+ tokens: ctx.tokens,
51
+ now: ctx.now,
52
+ });
53
+
54
+ /** One GET with the app's token; its 2xx body read by `read`. */
55
+ async function get<T>(ctx: AppLinkCallContext, url: string, read: (body: unknown) => T | null): Promise<LinkResult<T>> {
56
+ try {
57
+ const response = await withIfoodToken(adapterContext(ctx), (token) =>
58
+ ctx.http({ method: "GET", url, headers: { Authorization: `Bearer ${token}` } }),
59
+ );
60
+ if (response === null) return { kind: "refused", status: 401, message: "iFood refused the app's token" };
61
+ if ("kind" in response) return response.kind === "accepted" ? { kind: "retry", reason: "no answer" } : response;
62
+ const result = outboundResultOf(response as MarketplaceHttpResponse);
63
+ if (result.kind !== "accepted") return result;
64
+ const value = read(json(response.body));
65
+ return value === null ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" } : { kind: "ok", value };
66
+ } catch (error) {
67
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
68
+ }
69
+ }
70
+
71
+ function merchantsOf(body: unknown): LinkedMerchant[] | null {
72
+ if (!Array.isArray(body)) return null;
73
+ return body.flatMap((raw: unknown) => {
74
+ const id = asString(pick(raw, "id"));
75
+ return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
76
+ });
77
+ }
78
+
79
+ const first = (raw: unknown, ...keys: string[]): string | null => {
80
+ for (const key of keys) {
81
+ const value = pick(raw, key);
82
+ const text = typeof value === "number" ? String(value) : asString(value);
83
+ if (text && text.trim() !== "") return text.trim();
84
+ }
85
+ return null;
86
+ };
87
+
88
+ /** "Rua Pernambuco, 1000 · Savassi": the street and number, then the district; null when the detail carries no street. */
89
+ export function ifoodAddressLine(body: unknown): string | null {
90
+ const address = pick(body, "address");
91
+ const street = first(address, "street", "streetName");
92
+ if (!street) return null;
93
+ const number = first(address, "number", "streetNumber");
94
+ const district = first(address, "district", "neighborhood");
95
+ // The sandbox's street already carries the number and the district ("Ramal Bujari, 122, Bujari"): never twice.
96
+ const line = number && !street.includes(number) ? `${street}, ${number}` : street;
97
+ return district && !line.includes(district) ? `${line} · ${district}` : line;
98
+ }
99
+
100
+ /** Every store the app may act for, page by page until a short page. */
101
+ async function listMerchants(ctx: AppLinkCallContext): Promise<LinkResult<LinkedMerchant[]>> {
102
+ const all: LinkedMerchant[] = [];
103
+ for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
104
+ const answer = await get(ctx, `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`, merchantsOf);
105
+ if (answer.kind !== "ok") return answer;
106
+ all.push(...answer.value);
107
+ if (answer.value.length < MERCHANT_PAGE_SIZE) break;
108
+ }
109
+ return { kind: "ok", value: all };
110
+ }
111
+
112
+ /** The iFood adapter's centralized linking half. */
113
+ export const IFOOD_APP_LINKING: MarketplaceAppLinking = {
114
+ portalUrl: IFOOD_APPS_PORTAL_URL,
115
+ merchants: listMerchants,
116
+ address: (ctx, merchantId) => get(ctx, `${MERCHANTS_URL}/${encodeURIComponent(merchantId)}`, (body) => (body === null ? null : { line: ifoodAddressLine(body) })).then(
117
+ (answer) => (answer.kind === "ok" ? { kind: "ok", value: answer.value.line } : answer),
118
+ ),
119
+ };
@@ -0,0 +1,209 @@
1
+ import { answered, outboundResultOf, type AdapterCallContext } from "../core/adapter";
2
+ import type {
3
+ DisputeAlternative,
4
+ DisputeAnswer,
5
+ DisputeAnswerResult,
6
+ DisputeFailureCode,
7
+ DisputeItem,
8
+ DisputeOutcome,
9
+ DisputeReason,
10
+ MarketplaceDisputeApi,
11
+ NormalizedDisputeEvent,
12
+ } from "../core/dispute-port";
13
+ import { asString, firstDate, firstString, pick } from "../core/payload-read";
14
+ import { IFOOD_API, withIfoodToken } from "./outbound";
15
+
16
+ /**
17
+ * iFood's Negotiation Platform ("Plataforma de Negociação", handshake
18
+ * disputes; FUT-6099): the events that open and close a dispute, and the
19
+ * three answers.
20
+ *
21
+ * ESTIMATED, every name in this file. iFood's developer portal answers 403
22
+ * behind Cloudflare to our reader (2026-12-02, curl and WebFetch), so the
23
+ * shapes below are the ones four independent public write-ups of iFood's
24
+ * handshake guide agree on, not read off iFood's page. They sit in this one
25
+ * file so the homologation run corrects one place:
26
+ * - `HANDSHAKE_DISPUTE` (HSD) opens, `HANDSHAKE_SETTLEMENT` (HSS) closes, each
27
+ * naming the order (`orderId`) and carrying the dispute in `metadata`;
28
+ * - money is `{ value, currency }` with `value` in CENTS (a string or a number);
29
+ * - `POST /order/v1.0/disputes/{disputeId}/accept` and `/reject` (`{ reason }`);
30
+ * - the proposal: `POST …/disputes/{disputeId}/alternatives/{alternativeId}` with
31
+ * `{ type, metadata }` (the sources disagree; the other reading is
32
+ * `POST …/alternative` with the type in the body: ADOPTING §15.3, U1);
33
+ * - whether accept takes a reason (U2): sent only when iFood lists accept
34
+ * reasons for the dispute, the first of them.
35
+ */
36
+
37
+ const DISPUTE_OPENED = new Set(["HSD", "HANDSHAKE_DISPUTE"]);
38
+ const DISPUTE_SETTLED = new Set(["HSS", "HANDSHAKE_SETTLEMENT"]);
39
+ const OUTCOMES: ReadonlySet<string> = new Set<DisputeOutcome>(["ACCEPTED", "REJECTED", "EXPIRED", "ALTERNATIVE_REPLIED"]);
40
+
41
+ /** `{ value }` in cents (a string or a number), or a bare value; null when not a whole number. */
42
+ function centsOf(money: unknown): number | null {
43
+ const raw = typeof money === "object" && money !== null ? pick(money, "value") : money;
44
+ const numeric = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : raw;
45
+ return typeof numeric === "number" && Number.isInteger(numeric) && numeric >= 0 ? numeric : null;
46
+ }
47
+
48
+ function listOf(source: unknown, key: string): unknown[] {
49
+ const value = pick(source, key);
50
+ return Array.isArray(value) ? value : [];
51
+ }
52
+
53
+ /** A reason as iFood lists it: a bare code, or `{ code | reason, description }`. */
54
+ function readReason(entry: unknown): DisputeReason[] {
55
+ if (typeof entry === "string") return entry ? [{ code: entry, description: entry }] : [];
56
+ const code = firstString(entry, [["code"], ["reason"], ["id"]]);
57
+ if (!code) return [];
58
+ return [{ code, description: firstString(entry, [["description"], ["label"], ["name"]]) ?? code }];
59
+ }
60
+
61
+ function readItem(entry: unknown): DisputeItem[] {
62
+ const name = firstString(entry, [["name"], ["description"]]);
63
+ if (!name) return [];
64
+ const quantity = Number(pick(entry, "quantity") ?? 1);
65
+ return [
66
+ {
67
+ name,
68
+ quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,
69
+ amountCents: centsOf(pick(entry, "amount")) ?? centsOf(pick(entry, "totalPrice")),
70
+ },
71
+ ];
72
+ }
73
+
74
+ const ALTERNATIVE_TYPES: ReadonlySet<string> = new Set(["REFUND", "BENEFIT", "ADDITIONAL_TIME"]);
75
+
76
+ function readAlternative(entry: unknown): DisputeAlternative[] {
77
+ const id = firstString(entry, [["id"]]);
78
+ const type = firstString(entry, [["type"]])?.toUpperCase();
79
+ if (!id || !type || !ALTERNATIVE_TYPES.has(type)) return [];
80
+ const metadata = pick(entry, "metadata");
81
+ const stated = pick(metadata, "maxAmount");
82
+ const maxAmountCents = centsOf(stated);
83
+ // A cap iFood stated and we cannot read is never "no cap": the alternative is not offered.
84
+ if (stated !== undefined && stated !== null && maxAmountCents === null) return [];
85
+ const minutes = listOf(metadata, "allowedsAdditionalTimeInMinutes")
86
+ .map(Number)
87
+ .filter((value) => Number.isInteger(value) && value > 0);
88
+ return [
89
+ {
90
+ id,
91
+ type: type as DisputeAlternative["type"],
92
+ maxAmountCents,
93
+ allowedMinutes: minutes,
94
+ },
95
+ ];
96
+ }
97
+
98
+ /** The https photos the buyer sent; any other scheme is dropped. */
99
+ function readEvidences(metadata: unknown): string[] {
100
+ return listOf(metadata, "evidences")
101
+ .map((entry) => (typeof entry === "string" ? entry : asString(pick(entry, "url"))))
102
+ .filter((url): url is string => typeof url === "string" && url.startsWith("https://"));
103
+ }
104
+
105
+ function sumOf(items: readonly DisputeItem[]): number | null {
106
+ const amounts = items.map((item) => item.amountCents);
107
+ return amounts.length > 0 && amounts.every((value) => value !== null) ? amounts.reduce((a, b) => a! + b!, 0) : null;
108
+ }
109
+
110
+ function readOpened(payload: unknown, metadata: unknown, disputeId: string): NormalizedDisputeEvent {
111
+ const items = listOf(metadata, "garnishItems").flatMap(readItem);
112
+ return {
113
+ kind: "opened",
114
+ dispute: {
115
+ disputeId,
116
+ action: firstString(metadata, [["action"]]) ?? "UNKNOWN",
117
+ handshakeType: firstString(metadata, [["handshakeType"]]),
118
+ reason: firstString(metadata, [["reason"], ["handshakeGroup"]]),
119
+ message: firstString(metadata, [["message"]]),
120
+ evidenceUrls: readEvidences(metadata),
121
+ items,
122
+ requestedAmountCents: centsOf(pick(metadata, "amount")) ?? sumOf(items),
123
+ expiresAt: firstDate(metadata, [["expiresAt"]]),
124
+ openedAt: firstDate(metadata, [["createdAt"]]) ?? firstDate(payload, [["createdAt"]]),
125
+ timeoutAction: firstString(metadata, [["timeoutAction"]]),
126
+ alternatives: listOf(metadata, "alternatives").flatMap(readAlternative),
127
+ rejectReasons: listOf(metadata, "negotiationReasons").flatMap(readReason),
128
+ acceptReasons: listOf(metadata, "acceptCancellationReasons").flatMap(readReason),
129
+ },
130
+ };
131
+ }
132
+
133
+ function readSettled(payload: unknown, metadata: unknown, disputeId: string): NormalizedDisputeEvent {
134
+ const status = firstString(metadata, [["status"]])?.toUpperCase() ?? "";
135
+ const selected = pick(metadata, "selectedDisputeAlternative");
136
+ return {
137
+ kind: "settled",
138
+ settlement: {
139
+ disputeId,
140
+ outcome: OUTCOMES.has(status) ? (status as DisputeOutcome) : "OTHER",
141
+ at: firstDate(metadata, [["createdAt"]]) ?? firstDate(payload, [["createdAt"]]),
142
+ amountCents: centsOf(pick(selected, "metadata", "amount")) ?? centsOf(pick(metadata, "amount")),
143
+ },
144
+ };
145
+ }
146
+
147
+ /** The dispute an iFood delivery opens or closes, or null for any other event. */
148
+ export function readIfoodDispute(payload: unknown, eventType: string): NormalizedDisputeEvent | null {
149
+ const code = eventType.toUpperCase();
150
+ const opened = DISPUTE_OPENED.has(code);
151
+ if (!opened && !DISPUTE_SETTLED.has(code)) return null;
152
+ const metadata = pick(payload, "metadata");
153
+ const disputeId = firstString(metadata, [["disputeId"], ["id"]]);
154
+ if (!disputeId) return null;
155
+ return opened ? readOpened(payload, metadata, disputeId) : readSettled(payload, metadata, disputeId);
156
+ }
157
+
158
+ /** The path and body of one answer. */
159
+ function requestOf(answer: DisputeAnswer): { path: string; body: unknown } {
160
+ if (answer.kind === "ACCEPT") return { path: "accept", body: answer.reasonCode ? { reason: answer.reasonCode } : undefined };
161
+ if (answer.kind === "REJECT") return { path: "reject", body: { reason: answer.reasonCode } };
162
+ const { alternative } = answer;
163
+ const metadata =
164
+ alternative.type === "ADDITIONAL_TIME"
165
+ ? { additionalTimeInMinutes: answer.minutes }
166
+ : { amount: { value: String(answer.amountCents), currency: "BRL" } };
167
+ return { path: `alternatives/${encodeURIComponent(alternative.id)}`, body: { type: alternative.type, metadata } };
168
+ }
169
+
170
+ /** iFood's refusal codes, as the engine names them; any other final 4xx is REFUSED. */
171
+ const FAILURE_OF: readonly [string, DisputeFailureCode][] = [
172
+ ["DISPUTE_ALREADY_ANSWERED", "ALREADY_ANSWERED"],
173
+ ["DISPUTE_NOT_FOUND", "NOT_FOUND"],
174
+ ["INVALID_REASON", "INVALID_REASON"],
175
+ ["INVALID_AMOUNT", "INVALID_AMOUNT"],
176
+ ];
177
+
178
+ function failureOf(status: number, message: string): DisputeFailureCode {
179
+ const named = FAILURE_OF.find(([code]) => message.includes(code));
180
+ if (named) return named[1];
181
+ if (status === 422) return "ALREADY_ANSWERED";
182
+ return status === 404 ? "NOT_FOUND" : "REFUSED";
183
+ }
184
+
185
+ /** Send one answer. */
186
+ async function answerIfoodDispute(
187
+ ctx: AdapterCallContext,
188
+ target: { externalOrderId: string; disputeId: string },
189
+ answer: DisputeAnswer,
190
+ ): Promise<DisputeAnswerResult> {
191
+ const { path, body } = requestOf(answer);
192
+ const result = await answered(async () => {
193
+ const response = await withIfoodToken(ctx, (token) =>
194
+ ctx.http({
195
+ method: "POST",
196
+ url: `${IFOOD_API}/order/v1.0/disputes/${encodeURIComponent(target.disputeId)}/${path}`,
197
+ headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
198
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
199
+ }),
200
+ );
201
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
202
+ return "kind" in response ? response : outboundResultOf(response);
203
+ });
204
+ if (result.kind !== "refused") return result;
205
+ return { kind: "refused", status: result.status, message: result.message, code: result.own ? "REFUSED" : failureOf(result.status, result.message) };
206
+ }
207
+
208
+ /** iFood's disputes API. */
209
+ export const IFOOD_DISPUTES: MarketplaceDisputeApi = { answer: answerIfoodDispute };
@@ -3,7 +3,10 @@ import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
5
  import { IFOOD_COURIER } from "./courier";
6
+ import { IFOOD_DISPUTES } from "./disputes";
7
+ import { IFOOD_LOGISTICS } from "./logistics";
6
8
  import { ifoodFetchOrder } from "./fetch-order";
9
+ import { IFOOD_APP_LINKING } from "./app-linking";
7
10
  import { IFOOD_LINKING } from "./linking";
8
11
  import { normalizeIfoodEvent, readIfoodPresence, verifyIfoodSignature } from "./normalize";
9
12
  import {
@@ -85,6 +88,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
85
88
  marketplaceConfirms: true,
86
89
  // A step is told only once iFood took the confirm (FUT-5673).
87
90
  statusAfterConfirm: true,
91
+ // The Negotiation Platform (FUT-6099): HSD / HSS events, answered through `disputes`.
92
+ disputes: true,
88
93
  },
89
94
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
90
95
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
@@ -107,10 +112,17 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
107
112
  orderCancellationReasons: ifoodOrderCancellationReasons,
108
113
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
109
114
  availability: IFOOD_AVAILABILITY,
110
- // The distributed-app authorization: a store links the software's own app (FUT-5613).
115
+ // The CENTRALIZED app (FUT-5798): a store authorizes the software's app on the portal and picks
116
+ // its store from the app's list; iFood's webhook serves centralized apps only. It wins at every
117
+ // entry point. The distributed half (FUT-5613) stays declared: a store linked through it keeps
118
+ // refreshing its own token until it links again.
119
+ appLinking: IFOOD_APP_LINKING,
111
120
  linking: IFOOD_LINKING,
112
121
  // iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).
113
122
  courier: IFOOD_COURIER,
123
+ // The buyer's disputes: accept, reject with iFood's reason, or one of its alternatives (FUT-6099).
124
+ disputes: IFOOD_DISPUTES,
125
+ logistics: IFOOD_LOGISTICS,
114
126
  // No per-order deep link is known, so the portal, where a live order is
115
127
  // on the first screen.
116
128
  appLink: () => IFOOD_PORTAL_URL,
@@ -123,10 +135,12 @@ export { ifoodFetchOrder } from "./fetch-order";
123
135
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
124
136
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
125
137
  export { IFOOD_LINKING } from "./linking";
138
+ export { IFOOD_APP_LINKING, IFOOD_APPS_PORTAL_URL, ifoodAddressLine } from "./app-linking";
126
139
  export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
127
140
  export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
128
141
  export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
129
142
  export {
143
+ IFOOD_LOGISTICS,
130
144
  IFOOD_LOGISTICS_STEPS,
131
145
  IFOOD_LOGISTICS_VEHICLES,
132
146
  ifoodLogisticsAssignDriver,
@@ -1,3 +1,4 @@
1
+ import type { DeliveryCodeAnswer, LogisticsVehicle, MarketplaceLogistics } from "../core/logistics";
1
2
  import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
2
3
  import { IFOOD_API, withIfoodToken } from "./outbound";
3
4
 
@@ -193,3 +194,40 @@ export async function ifoodLogisticsVerifyDeliveryCode(
193
194
  if (result.kind === "refused" && result.status === 412) return { kind: "not-requested" };
194
195
  return result;
195
196
  }
197
+
198
+ /** The engine's vehicles, as iFood names them. */
199
+ const VEHICLE: Readonly<Record<LogisticsVehicle, IfoodLogisticsVehicle>> = {
200
+ MOTORCYCLE: "MOTORCYCLE",
201
+ CAR: "CAR",
202
+ BICYCLE: "BICYCLE",
203
+ ON_FOOT: "ONFOOT",
204
+ SCOOTER: "PATINETE",
205
+ };
206
+
207
+ /**
208
+ * The adapter's Logistics half (FUT-6166): the engine's steps on iFood's
209
+ * wire. An invalid driver is answered as the engine's `invalid`.
210
+ */
211
+ export const IFOOD_LOGISTICS: MarketplaceLogistics = {
212
+ assignDriver: (ctx, order, driver) =>
213
+ ifoodLogisticsAssignDriver(ctx, order.externalOrderId, { name: driver.name, phone: driver.phone, vehicle: VEHICLE[driver.vehicle] }),
214
+ step: (ctx, order, step) => ifoodLogisticsStep(ctx, order.externalOrderId, step),
215
+ verifyDeliveryCode: async (ctx, order, code) => deliveryCodeAnswerOf(await ifoodLogisticsVerifyDeliveryCode(ctx, order.externalOrderId, code)),
216
+ };
217
+
218
+ /** iFood's answer to a code, as the engine's closed set (FUT-6167). */
219
+ function deliveryCodeAnswerOf(result: IfoodDeliveryCodeResult): DeliveryCodeAnswer {
220
+ switch (result.kind) {
221
+ case "verified":
222
+ return { kind: "VERIFIED" };
223
+ case "wrong-code":
224
+ case "invalid":
225
+ return { kind: "WRONG_CODE" };
226
+ case "not-requested":
227
+ return { kind: "NOT_REQUESTED" };
228
+ case "refused":
229
+ return { kind: "UNAVAILABLE", reason: `refused ${result.status}` };
230
+ default:
231
+ return { kind: "UNAVAILABLE", reason: result.reason };
232
+ }
233
+ }
@@ -21,6 +21,7 @@ import {
21
21
  verifyHmacSha256Hex,
22
22
  } from "../core/payload-read";
23
23
  import { readIfoodCourierEvent } from "./courier";
24
+ import { readIfoodDispute } from "./disputes";
24
25
  import { readIfoodAdditionalFees, readIfoodBuyerDocument, readIfoodOptions, readIfoodPayments } from "./order-details";
25
26
 
26
27
  /**
@@ -42,6 +43,16 @@ const ORDER_PLACED = new Set(["PLC", "PLACED", "ORDER_PLACED"]);
42
43
  const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
43
44
  /** The store accepted the order on iFood's own app (FUT-5653). Also the echo of our own confirm. */
44
45
  const ORDER_CONFIRMED = new Set(["CFM", "CONFIRMED"]);
46
+ /** iFood asked the customer's delivery code (FUT-6167), by its code or its full code. */
47
+ const DELIVERY_CODE_REQUESTED = new Set(["DDCR", "DELIVERY_DROP_CODE_REQUESTED"]);
48
+ /** The event's yes-or-no facts, present only when true. */
49
+ function flagsOf(code: string): Pick<NormalizedEvent, "marketplaceConfirmed" | "deliveryCodeRequested"> {
50
+ return {
51
+ ...(ORDER_CONFIRMED.has(code) ? { marketplaceConfirmed: true } : {}),
52
+ ...(DELIVERY_CODE_REQUESTED.has(code) ? { deliveryCodeRequested: true } : {}),
53
+ };
54
+ }
55
+
45
56
  /** iFood's presence heartbeat (FUT-5984, `presence.md`): every 30 s, naming no order. */
46
57
  const KEEPALIVE = "KEEPALIVE";
47
58
  /** iFood refused the store's own cancellation request. */
@@ -322,7 +333,9 @@ export function normalizeIfoodEvent(
322
333
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
323
334
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
324
335
  ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
325
- ...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),
336
+ ...flagsOf(eventType.toUpperCase()),
337
+ // The Negotiation Platform's HSD / HSS (FUT-6099): a dispute opened or closed, never an order body.
338
+ ...optional("dispute", readIfoodDispute(payload, eventType) ?? undefined),
326
339
  };
327
340
  }
328
341
 
package/src/index.ts CHANGED
@@ -162,6 +162,37 @@ export type {
162
162
  PickupCodeValidation,
163
163
  ValidatePickupCodeInput,
164
164
  } from "./core/courier-port";
165
+ export type {
166
+ DisputeAlternative,
167
+ DisputeAlternativeType,
168
+ DisputeAnswer,
169
+ DisputeAnswerResult,
170
+ DisputeFailureCode,
171
+ DisputeItem,
172
+ DisputeOutcome,
173
+ DisputeReason,
174
+ MarketplaceDisputeApi,
175
+ MarketplaceDisputeChange,
176
+ MarketplaceDisputeDelegate,
177
+ NormalizedDisputeEvent,
178
+ NormalizedDisputeOpened,
179
+ NormalizedDisputeSettled,
180
+ } from "./core/dispute-port";
181
+ export {
182
+ MARKETPLACE_DISPUTE_ANSWER_JOB,
183
+ disputeView,
184
+ type DisputeAnswerView,
185
+ type DisputeRow,
186
+ type DisputeStatus,
187
+ type MarketplaceDisputeView,
188
+ } from "./core/dispute-store";
189
+ export type { AnswerDisputeResult, DisputeAnswerInput, DisputeRefusalCode } from "./core/disputes";
190
+ export type { MarketplaceDisputeEngine } from "./core/dispute-engine";
191
+ export {
192
+ DisputeAnswerRetryError,
193
+ type DisputeAnswerJobPayload,
194
+ type DisputeAnswerOutcome,
195
+ } from "./core/dispute-job";
165
196
  export {
166
197
  FetchOrderRetryError,
167
198
  MARKETPLACE_FETCH_ORDER_JOB,
@@ -261,14 +292,27 @@ export {
261
292
  } from "./core/pause-store";
262
293
  export type { AvailabilitySweepResult } from "./core/pause-sweep";
263
294
  export type {
295
+ AppLinkCallContext,
264
296
  LinkCallContext,
265
297
  LinkCode,
266
298
  LinkGrant,
267
299
  LinkResult,
268
300
  LinkedMerchant,
269
301
  MarketplaceAppCredentialsPort,
302
+ MarketplaceAppLinking,
270
303
  MarketplaceLinkAttemptDelegate,
271
304
  MarketplaceLinking,
272
305
  } from "./core/linking-port";
306
+ export { MARKETPLACE_LINK_CHECK_JOB, ATTEMPT_MINUTES as LINK_ATTEMPT_MINUTES, CHECK_EVERY_SECONDS as LINK_CHECK_EVERY_SECONDS, type AppLinkPendingView } from "./core/app-linking";
273
307
  export type { LinkFailure, LinkFinished, LinkPendingView, LinkRefusalCode } from "./core/linking";
274
308
  export type { MarketplaceAuthMode } from "./core/link-store";
309
+ export type { MarketplaceDeliveryCodeEngine, VerifyDeliveryCodeInput } from "./core/delivery-code";
310
+ export {
311
+ LOGISTICS_STEPS,
312
+ type DeliveryCodeAnswer,
313
+ type InformLogisticsInput,
314
+ type LogisticsDriver,
315
+ type LogisticsStep,
316
+ type LogisticsVehicle,
317
+ type MarketplaceLogistics,
318
+ } from "./core/logistics";
@@ -8,10 +8,11 @@ import { CancellationReasonsRetryError, type CancellationReasonsJobPayload } fro
8
8
  import { OutboundRetryError } from "../core/outbound";
9
9
  import type { OutboundJobPayload } from "../core/outbound-queue";
10
10
  import { AvailabilityRetryError } from "../core/pause-job";
11
+ import { DisputeAnswerRetryError, type DisputeAnswerJobPayload } from "../core/dispute-job";
11
12
  import type { AvailabilityJobPayload } from "../core/pause-store";
12
13
 
13
14
  /**
14
- * The engine's ten jobs, declared here because every number in them is the
15
+ * The engine's eleven jobs, declared here because every number in them is the
15
16
  * engine's knowledge, not a host's:
16
17
  *
17
18
  * - `expire-acceptances`, every minute: the unit being measured is minutes (a
@@ -42,6 +43,9 @@ import type { AvailabilityJobPayload } from "../core/pause-store";
42
43
  * - `availability`, on demand: brings one marketplace in line with the host's
43
44
  * last pause or resume ask for one store (FUT-4851). Three attempts with
44
45
  * backoff; the last one stamps FAILED with a failure code.
46
+ * - `dispute-answer`, on demand: sends one store's answer to a buyer's
47
+ * dispute (FUT-6099). Three attempts with backoff; the last gives the
48
+ * answer back OPEN, and the outbound sweep re-queues one still owed.
45
49
  * - `availability-sweep`, every five minutes: resumes a pause past its
46
50
  * `until` (the host stopped renewing it), re-queues an ask still owed, and
47
51
  * gives up on one older than a day.
@@ -53,8 +57,9 @@ import type { AvailabilityJobPayload } from "../core/pause-store";
53
57
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
54
58
  * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.acknowledge`,
55
59
  * `marketplace.cancellation-reasons`, `marketplace.catalogue`,
56
- * `marketplace.outbound-sweep`, `marketplace.availability` and
57
- * `marketplace.availability-sweep`.
60
+ * `marketplace.outbound-sweep`, `marketplace.availability`,
61
+ * `marketplace.availability-sweep`, `marketplace.link-check` and
62
+ * `marketplace.dispute-answer`.
58
63
  */
59
64
 
60
65
  /** What the host closes over at bind time: the mounted engine. */
@@ -73,6 +78,8 @@ export interface MarketplaceJobDeps {
73
78
  | "sweepOutbound"
74
79
  | "runAvailability"
75
80
  | "sweepAvailability"
81
+ | "sweepLinks"
82
+ | "runDisputeAnswer"
76
83
  >;
77
84
  }
78
85
 
@@ -290,6 +297,45 @@ const availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
290
297
  },
291
298
  };
292
299
 
300
+ /**
301
+ * `link-check` (FUT-5798), each minute and once more half a minute later
302
+ * (queued by the tick, only while a store waits): every centralized link
303
+ * attempt still waiting asks the app's list, and a store whose authorization
304
+ * arrived is hinted. Never retried: the next pass re-finds it from the rows.
305
+ */
306
+ const linkCheck: WireJobBlueprint<{ half?: boolean } | undefined, MarketplaceJobDeps> = {
307
+ name: "link-check",
308
+ queue: MARKETPLACE_SWEEP_QUEUE,
309
+ concurrency: 1,
310
+ schedule: { pattern: "* * * * *", timezone: "UTC" },
311
+ attempts: 1,
312
+ lease: { ttlMs: SWEEP_LEASE_MS },
313
+ handle: async (payload, deps, context) => {
314
+ const result = await deps.engine.sweepLinks({ half: payload?.half === true });
315
+ if (result.seen.length === 0) return;
316
+ context.logger.info(`marketplace.link-check: saw the authorization of ${result.seen.length} store(s); ${result.waiting} still waiting.`);
317
+ },
318
+ };
319
+
320
+ /** The dispute answer's attempts: the last one gives the answer back for a person to send again. */
321
+ const MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS = 3;
322
+
323
+ const disputeAnswer: WireJobBlueprint<DisputeAnswerJobPayload, MarketplaceJobDeps> = {
324
+ name: "dispute-answer",
325
+ attempts: MARKETPLACE_DISPUTE_ANSWER_ATTEMPTS,
326
+ // Short: the marketplace's deadline is minutes, and a person waits on the card.
327
+ backoff: { type: "exponential", delayMs: 10_000 },
328
+ handle: async (payload, deps, context) => {
329
+ try {
330
+ const outcome = await deps.engine.runDisputeAnswer(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });
331
+ if (outcome.kind === "skipped") context.logger.info(`marketplace.dispute-answer: ${payload.disputeId} skipped: ${outcome.reason}`);
332
+ } catch (error) {
333
+ if (error instanceof DisputeAnswerRetryError) context.logger.warn(`marketplace.dispute-answer: ${error.message}`);
334
+ throw error;
335
+ }
336
+ },
337
+ };
338
+
293
339
  /** The jobs contribution. */
294
340
  export const MARKETPLACE_JOBS = {
295
341
  namespace: "marketplace",
@@ -304,5 +350,7 @@ export const MARKETPLACE_JOBS = {
304
350
  "outbound-sweep": outboundSweep,
305
351
  availability,
306
352
  "availability-sweep": availabilitySweep,
353
+ "link-check": linkCheck,
354
+ "dispute-answer": disputeAnswer,
307
355
  },
308
356
  } as const satisfies JobsContribution<MarketplaceJobDeps>;