@12-apps/marketplace 1.15.1 → 1.17.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 (73) hide show
  1. package/ADOPTING.md +146 -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-CxzF-qGx.d.ts} +185 -2
  5. package/dist/{chunk-TRUK5ZBE.js → chunk-7IYUO2KC.js} +2 -2
  6. package/dist/{chunk-BTKVZAJI.js → chunk-CF5BSXE5.js} +1 -1
  7. package/dist/chunk-CF5BSXE5.js.map +1 -0
  8. package/dist/{chunk-DJIMUEHT.js → chunk-EABVLQKK.js} +79 -7
  9. package/dist/chunk-EABVLQKK.js.map +1 -0
  10. package/dist/{chunk-H2VQRD3B.js → chunk-KKFMDV5K.js} +1 -1
  11. package/dist/chunk-KKFMDV5K.js.map +1 -0
  12. package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
  13. package/dist/chunk-LO7OKO6V.js.map +1 -0
  14. package/dist/{chunk-TICWLBSA.js → chunk-UZO2NILN.js} +365 -6
  15. package/dist/chunk-UZO2NILN.js.map +1 -0
  16. package/dist/{client-DgzCkl8u.d.ts → client-C-4QvVq3.d.ts} +1 -1
  17. package/dist/{engine-DSRj7qnC.d.ts → engine-Y6Rpf5p7.d.ts} +430 -185
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +4 -4
  20. package/dist/ifood/index.d.ts +65 -2
  21. package/dist/ifood/index.js +374 -23
  22. package/dist/ifood/index.js.map +1 -1
  23. package/dist/index.d.ts +21 -4
  24. package/dist/index.js +381 -42
  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 +69 -1
  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/src/core/adapter.ts +12 -1
  41. package/src/core/app-linking.ts +396 -0
  42. package/src/core/dispute-engine.ts +32 -0
  43. package/src/core/dispute-job.ts +142 -0
  44. package/src/core/dispute-port.ts +133 -0
  45. package/src/core/dispute-store.ts +203 -0
  46. package/src/core/disputes.ts +263 -0
  47. package/src/core/engine.ts +4 -55
  48. package/src/core/integration.ts +3 -1
  49. package/src/core/link-engine.ts +176 -0
  50. package/src/core/link-store.ts +15 -0
  51. package/src/core/linking-port.ts +35 -1
  52. package/src/core/linking.ts +8 -0
  53. package/src/core/outbound-sweep.ts +9 -1
  54. package/src/core/pipeline.ts +8 -3
  55. package/src/core/ports.ts +15 -0
  56. package/src/core/types.ts +8 -0
  57. package/src/ifood/app-linking.ts +119 -0
  58. package/src/ifood/disputes.ts +209 -0
  59. package/src/ifood/index.ts +25 -1
  60. package/src/ifood/logistics.ts +195 -0
  61. package/src/ifood/normalize.ts +3 -0
  62. package/src/ifood/outbound.ts +1 -1
  63. package/src/index.ts +34 -0
  64. package/src/server/jobs.ts +51 -3
  65. package/src/server/link-routes.ts +56 -4
  66. package/src/server/mcp-link.ts +44 -2
  67. package/src/server/mcp.ts +2 -1
  68. package/dist/chunk-BTKVZAJI.js.map +0 -1
  69. package/dist/chunk-DJIMUEHT.js.map +0 -1
  70. package/dist/chunk-H2VQRD3B.js.map +0 -1
  71. package/dist/chunk-SGOTN5PX.js.map +0 -1
  72. package/dist/chunk-TICWLBSA.js.map +0 -1
  73. /package/dist/{chunk-TRUK5ZBE.js.map → chunk-7IYUO2KC.js.map} +0 -0
@@ -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,9 @@ 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";
6
7
  import { ifoodFetchOrder } from "./fetch-order";
8
+ import { IFOOD_APP_LINKING } from "./app-linking";
7
9
  import { IFOOD_LINKING } from "./linking";
8
10
  import { normalizeIfoodEvent, readIfoodPresence, verifyIfoodSignature } from "./normalize";
9
11
  import {
@@ -85,6 +87,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
85
87
  marketplaceConfirms: true,
86
88
  // A step is told only once iFood took the confirm (FUT-5673).
87
89
  statusAfterConfirm: true,
90
+ // The Negotiation Platform (FUT-6099): HSD / HSS events, answered through `disputes`.
91
+ disputes: true,
88
92
  },
89
93
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
90
94
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
@@ -107,10 +111,16 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
107
111
  orderCancellationReasons: ifoodOrderCancellationReasons,
108
112
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
109
113
  availability: IFOOD_AVAILABILITY,
110
- // The distributed-app authorization: a store links the software's own app (FUT-5613).
114
+ // The CENTRALIZED app (FUT-5798): a store authorizes the software's app on the portal and picks
115
+ // its store from the app's list; iFood's webhook serves centralized apps only. It wins at every
116
+ // entry point. The distributed half (FUT-5613) stays declared: a store linked through it keeps
117
+ // refreshing its own token until it links again.
118
+ appLinking: IFOOD_APP_LINKING,
111
119
  linking: IFOOD_LINKING,
112
120
  // iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).
113
121
  courier: IFOOD_COURIER,
122
+ // The buyer's disputes: accept, reject with iFood's reason, or one of its alternatives (FUT-6099).
123
+ disputes: IFOOD_DISPUTES,
114
124
  // No per-order deep link is known, so the portal, where a live order is
115
125
  // on the first screen.
116
126
  appLink: () => IFOOD_PORTAL_URL,
@@ -123,6 +133,20 @@ export { ifoodFetchOrder } from "./fetch-order";
123
133
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
124
134
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
125
135
  export { IFOOD_LINKING } from "./linking";
136
+ export { IFOOD_APP_LINKING, IFOOD_APPS_PORTAL_URL, ifoodAddressLine } from "./app-linking";
126
137
  export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
127
138
  export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
128
139
  export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
140
+ export {
141
+ IFOOD_LOGISTICS_STEPS,
142
+ IFOOD_LOGISTICS_VEHICLES,
143
+ ifoodLogisticsAssignDriver,
144
+ ifoodLogisticsStep,
145
+ ifoodLogisticsStepsTo,
146
+ ifoodLogisticsVerifyDeliveryCode,
147
+ type IfoodDeliveryCodeResult,
148
+ type IfoodLogisticsDriver,
149
+ type IfoodLogisticsInvalid,
150
+ type IfoodLogisticsStep,
151
+ type IfoodLogisticsVehicle,
152
+ } from "./logistics";
@@ -0,0 +1,195 @@
1
+ import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
2
+ import { IFOOD_API, withIfoodToken } from "./outbound";
3
+
4
+ /**
5
+ * iFood's LOGISTICS module (FUT-5988): the store's own motoboy carries an
6
+ * iFood order, and the software reports each step of that delivery to iFood,
7
+ * so the customer follows it in the iFood app.
8
+ *
9
+ * Wire format only, like `./outbound.ts`: the URLs, the bodies and how each
10
+ * answer reads. Which step is sent when, and the job that sends it, are the
11
+ * caller's. Read off iFood's Logistics guides on 2026-12-01 (the ticket's
12
+ * comment lists the pages):
13
+ *
14
+ * - base `https://merchant-api.ifood.com.br/logistics/v1.0`;
15
+ * - `POST /orders/{id}/assignDriver` with `workerName`, `workerPhone`,
16
+ * `workerVehicleType`;
17
+ * - `POST /orders/{id}/goingToOrigin`, `/arrivedAtOrigin`, `/dispatch`,
18
+ * `/arrivedAtDestination`, no body;
19
+ * - `POST /orders/{id}/verifyDeliveryCode` with `code`, answering `success`;
20
+ * - the steps go in a strict order: out of order is 409, verifying before the
21
+ * code was requested (`DELIVERY_DROP_CODE_REQUESTED`) is 412, a wrong code
22
+ * is 422. The step calls are asynchronous (202): their outcome is an event.
23
+ *
24
+ * Logistics is a SEPARATE iFood app (category Logística, centralized), so the
25
+ * context carries THAT app's credentials, never the store's PDV app: its
26
+ * token is cached under its own client id by `bearer`, apart from the PDV
27
+ * app's. No GPS: the guides have no endpoint for the motoboy's position.
28
+ *
29
+ * Tests never reach iFood: the HTTP client is the host's port.
30
+ */
31
+
32
+ const logisticsUrl = (externalOrderId: string, action: string): string =>
33
+ `${IFOOD_API}/logistics/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;
34
+
35
+ /** The vehicles iFood takes in `workerVehicleType`. */
36
+ export const IFOOD_LOGISTICS_VEHICLES = [
37
+ "BICYCLE",
38
+ "ONFOOT",
39
+ "PATINETE",
40
+ "EBIKE",
41
+ "SUPERBIKE",
42
+ "CAR",
43
+ "MOTORCYCLE",
44
+ "MOTORBIKE",
45
+ ] as const;
46
+
47
+ export type IfoodLogisticsVehicle = (typeof IFOOD_LOGISTICS_VEHICLES)[number];
48
+
49
+ /** The steps after the driver is assigned, in the one order iFood accepts them. */
50
+ export const IFOOD_LOGISTICS_STEPS = ["GOING_TO_ORIGIN", "ARRIVED_AT_ORIGIN", "DISPATCHED", "ARRIVED_AT_DESTINATION"] as const;
51
+
52
+ export type IfoodLogisticsStep = (typeof IFOOD_LOGISTICS_STEPS)[number];
53
+
54
+ const STEP_ACTION: Readonly<Record<IfoodLogisticsStep, string>> = {
55
+ GOING_TO_ORIGIN: "goingToOrigin",
56
+ ARRIVED_AT_ORIGIN: "arrivedAtOrigin",
57
+ DISPATCHED: "dispatch",
58
+ ARRIVED_AT_DESTINATION: "arrivedAtDestination",
59
+ };
60
+
61
+ /**
62
+ * The steps still owed, in order, to reach `target` when `lastSent` is the
63
+ * last one iFood took (null: only the driver was assigned). Empty when the
64
+ * target was already passed: iFood answers a repeated or earlier step with
65
+ * 409, so it is never sent.
66
+ */
67
+ export function ifoodLogisticsStepsTo(lastSent: IfoodLogisticsStep | null, target: IfoodLogisticsStep): IfoodLogisticsStep[] {
68
+ const from = lastSent === null ? 0 : IFOOD_LOGISTICS_STEPS.indexOf(lastSent) + 1;
69
+ const to = IFOOD_LOGISTICS_STEPS.indexOf(target);
70
+ return to < from ? [] : IFOOD_LOGISTICS_STEPS.slice(from, to + 1);
71
+ }
72
+
73
+ /** Who carries the order, as iFood shows them to the customer. */
74
+ export interface IfoodLogisticsDriver {
75
+ name: string;
76
+ /**
77
+ * Digits only once sent; anything else in it (spaces, `+`, dashes) is
78
+ * dropped. 10 to 13 digits is this client's own bound, not iFood's.
79
+ */
80
+ phone: string;
81
+ vehicle: IfoodLogisticsVehicle;
82
+ }
83
+
84
+ /** A call refused here, before reaching iFood: nothing was sent. */
85
+ export interface IfoodLogisticsInvalid {
86
+ kind: "invalid";
87
+ reason: "DRIVER_NAME" | "DRIVER_PHONE" | "DRIVER_VEHICLE" | "CODE";
88
+ }
89
+
90
+ /**
91
+ * The context a Logistics call runs on: the Logistics app's own credentials,
92
+ * always through a client-credentials grant. A linked store's grant is the
93
+ * PDV app's, so it is dropped here, never used (and never forgotten on a 401).
94
+ */
95
+ function logisticsApp(ctx: AdapterCallContext): AdapterCallContext {
96
+ return { http: ctx.http, credentials: ctx.credentials, environment: ctx.environment, tokens: ctx.tokens, now: ctx.now };
97
+ }
98
+
99
+ /**
100
+ * A result with iFood's answer body left out: a validation answer may echo the
101
+ * motoboy's phone or the customer's code, and a result's text reaches logs.
102
+ */
103
+ function redacted(result: OutboundResult, status: number): OutboundResult {
104
+ if (result.kind === "refused") return { ...result, message: `iFood Logistics answered ${status}` };
105
+ if (result.kind === "retry") return { kind: "retry", reason: `iFood Logistics answered ${status}` };
106
+ return result;
107
+ }
108
+
109
+ function post(ctx: AdapterCallContext, url: string, body?: unknown): Promise<{ result: OutboundResult; body: string }> {
110
+ let answer = "";
111
+ return answered(async () => {
112
+ const response = await withIfoodToken(logisticsApp(ctx), (token) =>
113
+ ctx.http({
114
+ method: "POST",
115
+ url,
116
+ headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
117
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
118
+ }),
119
+ );
120
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
121
+ if ("kind" in response) return response;
122
+ answer = response.body;
123
+ return redacted(outboundResultOf(response), response.status);
124
+ }).then((result) => ({ result, body: answer }));
125
+ }
126
+
127
+ /**
128
+ * `assignDriver`: the store's motoboy takes the order. A second assignment of
129
+ * the same order is iFood's 409, answered as `refused` like any final 4xx.
130
+ */
131
+ export async function ifoodLogisticsAssignDriver(
132
+ ctx: AdapterCallContext,
133
+ externalOrderId: string,
134
+ driver: IfoodLogisticsDriver,
135
+ ): Promise<OutboundResult | IfoodLogisticsInvalid> {
136
+ const name = driver.name.trim();
137
+ const phone = driver.phone.replace(/\D/g, "");
138
+ if (name === "") return { kind: "invalid", reason: "DRIVER_NAME" };
139
+ if (phone.length < 10 || phone.length > 13) return { kind: "invalid", reason: "DRIVER_PHONE" };
140
+ if (!(IFOOD_LOGISTICS_VEHICLES as readonly string[]).includes(driver.vehicle)) return { kind: "invalid", reason: "DRIVER_VEHICLE" };
141
+ const { result } = await post(ctx, logisticsUrl(externalOrderId, "assignDriver"), {
142
+ workerName: name,
143
+ workerPhone: phone,
144
+ workerVehicleType: driver.vehicle,
145
+ });
146
+ return result;
147
+ }
148
+
149
+ /** One step of the delivery. iFood takes it asynchronously: `accepted` means the request was taken. */
150
+ export async function ifoodLogisticsStep(ctx: AdapterCallContext, externalOrderId: string, step: IfoodLogisticsStep): Promise<OutboundResult> {
151
+ const { result } = await post(ctx, logisticsUrl(externalOrderId, STEP_ACTION[step]));
152
+ return result;
153
+ }
154
+
155
+ /** What iFood said of the customer's delivery code. */
156
+ export type IfoodDeliveryCodeResult =
157
+ | { kind: "verified" }
158
+ /** iFood's `success: false`, or its 422: the motoboy may type it again. */
159
+ | { kind: "wrong-code" }
160
+ /** iFood's 412: the order never asked for a code (no `DELIVERY_DROP_CODE_REQUESTED`). */
161
+ | { kind: "not-requested" }
162
+ | Exclude<OutboundResult, { kind: "accepted" }>
163
+ | IfoodLogisticsInvalid;
164
+
165
+ function successOf(body: string): boolean | null {
166
+ try {
167
+ const parsed = JSON.parse(body) as { success?: unknown } | null;
168
+ return typeof parsed?.success === "boolean" ? parsed.success : null;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * `verifyDeliveryCode`: the code the customer reads from the iFood app,
176
+ * typed by the motoboy at the door. The code is in the request body only, and
177
+ * no result carries iFood's answer body, so nothing here puts it in a log.
178
+ */
179
+ export async function ifoodLogisticsVerifyDeliveryCode(
180
+ ctx: AdapterCallContext,
181
+ externalOrderId: string,
182
+ code: string,
183
+ ): Promise<IfoodDeliveryCodeResult> {
184
+ const typed = code.replace(/\s/g, "");
185
+ if (!/^[0-9A-Za-z]{1,12}$/.test(typed)) return { kind: "invalid", reason: "CODE" };
186
+ const { result, body } = await post(ctx, logisticsUrl(externalOrderId, "verifyDeliveryCode"), { code: typed });
187
+ if (result.kind === "accepted") {
188
+ const success = successOf(body);
189
+ if (success === null) return { kind: "retry", reason: "iFood answered the delivery code without `success`" };
190
+ return success ? { kind: "verified" } : { kind: "wrong-code" };
191
+ }
192
+ if (result.kind === "refused" && result.status === 422) return { kind: "wrong-code" };
193
+ if (result.kind === "refused" && result.status === 412) return { kind: "not-requested" };
194
+ return result;
195
+ }
@@ -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
  /**
@@ -323,6 +324,8 @@ export function normalizeIfoodEvent(
323
324
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
324
325
  ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
325
326
  ...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),
327
+ // The Negotiation Platform's HSD / HSS (FUT-6099): a dispute opened or closed, never an order body.
328
+ ...optional("dispute", readIfoodDispute(payload, eventType) ?? undefined),
326
329
  };
327
330
  }
328
331
 
@@ -96,7 +96,7 @@ export async function bearer(ctx: AdapterCallContext): Promise<{ token: string }
96
96
  * (iFood: "Prepare seu aplicativo para solicitar um novo token quando receber
97
97
  * status 401"). A second 401 forgets that one too and answers `null`.
98
98
  */
99
- async function withIfoodToken(
99
+ export async function withIfoodToken(
100
100
  ctx: AdapterCallContext,
101
101
  call: (token: string) => Promise<MarketplaceHttpResponse>,
102
102
  ): Promise<MarketplaceHttpResponse | OutboundResult | null> {
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,17 @@ 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";
@@ -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>;