@12-apps/marketplace 1.10.0 → 1.12.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.
- package/ADOPTING.md +126 -1
- package/README.md +100 -1
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CYJzu1c9.d.ts → adapter-nUyZpLzz.d.ts} +448 -173
- package/dist/{chunk-2BA2EHNF.js → chunk-45ZVN5XI.js} +316 -42
- package/dist/chunk-45ZVN5XI.js.map +1 -0
- package/dist/{chunk-PYHNM47K.js → chunk-L6FG6T4S.js} +2 -2
- package/dist/{chunk-HEXLCTOG.js → chunk-LACBT6NC.js} +1 -1
- package/dist/chunk-LACBT6NC.js.map +1 -0
- package/dist/{chunk-WVZ2IXFH.js → chunk-MIPNQ7X5.js} +190 -12
- package/dist/chunk-MIPNQ7X5.js.map +1 -0
- package/dist/chunk-SGOTN5PX.js +345 -0
- package/dist/chunk-SGOTN5PX.js.map +1 -0
- package/dist/{client-B4EQCRD_.d.ts → client-Ctas7WCS.d.ts} +1 -1
- package/dist/{engine-DK3iV_Kk.d.ts → engine-CIy9P7Cq.d.ts} +149 -8
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +10 -2
- package/dist/ifood/index.js +297 -25
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +23 -4
- package/dist/index.js +424 -84
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -18
- package/dist/keeta/index.js +12 -3
- package/dist/keeta/index.js.map +1 -1
- package/dist/manifest/index.d.ts +219 -1
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/en-US.d.ts +13 -0
- package/dist/server/en-US.js +13 -0
- package/dist/server/en-US.js.map +1 -1
- package/dist/server/index.d.ts +241 -7
- package/dist/server/index.js +3 -3
- package/dist/server/pt-BR.d.ts +13 -0
- package/dist/server/pt-BR.js +13 -0
- package/dist/server/pt-BR.js.map +1 -1
- package/package.json +1 -1
- package/prisma/marketplace.prisma +41 -0
- package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
- package/src/core/adapter.ts +27 -0
- package/src/core/bulk.ts +43 -8
- package/src/core/courier-port.ts +100 -0
- package/src/core/courier.ts +153 -0
- package/src/core/engine.ts +63 -4
- package/src/core/integration.ts +60 -32
- package/src/core/lifecycle.ts +27 -4
- package/src/core/link-store.ts +170 -0
- package/src/core/linking-port.ts +100 -0
- package/src/core/linking.ts +363 -0
- package/src/core/merchant-claim.ts +106 -0
- package/src/core/outbound-queue.ts +24 -11
- package/src/core/outbound.ts +8 -6
- package/src/core/pickup-code.ts +136 -0
- package/src/core/pipeline.ts +15 -6
- package/src/core/ports.ts +26 -1
- package/src/core/status-store.ts +2 -3
- package/src/core/types.ts +56 -4
- package/src/ifood/courier.ts +210 -0
- package/src/ifood/index.ts +8 -0
- package/src/ifood/linking.ts +170 -0
- package/src/ifood/normalize.ts +7 -0
- package/src/ifood/outbound.ts +10 -3
- package/src/index.ts +30 -0
- package/src/keeta/normalize.ts +21 -6
- package/src/server/copy.ts +20 -2
- package/src/server/en-US.ts +13 -0
- package/src/server/index.ts +1 -1
- package/src/server/link-routes.ts +140 -0
- package/src/server/mcp-link.ts +103 -0
- package/src/server/mcp.ts +6 -2
- package/src/server/pt-BR.ts +13 -0
- package/src/server/routes.ts +5 -2
- package/src/server/webhook.ts +86 -0
- package/dist/chunk-2BA2EHNF.js.map +0 -1
- package/dist/chunk-HEXLCTOG.js.map +0 -1
- package/dist/chunk-WVZ2IXFH.js.map +0 -1
- package/dist/chunk-ZO4S3LF4.js +0 -254
- package/dist/chunk-ZO4S3LF4.js.map +0 -1
- /package/dist/{chunk-PYHNM47K.js.map → chunk-L6FG6T4S.js.map} +0 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { MarketplaceAdapter, OutboundOrderRef } from "./adapter";
|
|
2
|
+
import type { PickupCodeCallResult, PickupCodeValidation, ValidatePickupCodeInput } from "./courier-port";
|
|
3
|
+
import { readOutboundConnection } from "./integration";
|
|
4
|
+
import { MARKETPLACE_OUTBOUND_JOB, type OutboundJobPayload } from "./outbound-queue";
|
|
5
|
+
import type { EngineContext } from "./ports";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The pickup-code check's engine half (FUT-5665): the store checked the code
|
|
9
|
+
* the marketplace's courier stated, locally, and handed the bag over; then the
|
|
10
|
+
* host calls {@link validatePickupCode}, one enqueue, and the
|
|
11
|
+
* `marketplace.outbound` job (action `validatePickupCode`) tells the
|
|
12
|
+
* marketplace and hands its verdict to the host's `onPickupCodeValidated`.
|
|
13
|
+
*
|
|
14
|
+
* No row: the verdict is the host's to keep (it warns on `INVALID`, it moves
|
|
15
|
+
* nothing). A retry after a verdict could ask again; that is harmless, the
|
|
16
|
+
* check being a question with the same answer. A queue that refuses the job
|
|
17
|
+
* answers false and nothing re-queues it: the hand-over has happened and the
|
|
18
|
+
* marketplace's own check is its half, never a gate on ours.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** One enqueue, never throws: no statement and no call. True when the queue took it. */
|
|
22
|
+
export async function validatePickupCode(ctx: EngineContext, input: ValidatePickupCodeInput): Promise<boolean> {
|
|
23
|
+
const payload: OutboundJobPayload = {
|
|
24
|
+
clientId: input.clientId,
|
|
25
|
+
orderId: input.orderId,
|
|
26
|
+
action: "validatePickupCode",
|
|
27
|
+
code: input.code,
|
|
28
|
+
};
|
|
29
|
+
const dedupeKey = `${MARKETPLACE_OUTBOUND_JOB}:validatePickupCode:${input.orderId}:${input.at.getTime()}`;
|
|
30
|
+
const notQueued = (why: string): false => {
|
|
31
|
+
ctx.ports.logger.warn(`${MARKETPLACE_OUTBOUND_JOB}: validatePickupCode for order ${input.orderId} was not queued${why}`);
|
|
32
|
+
return false;
|
|
33
|
+
};
|
|
34
|
+
try {
|
|
35
|
+
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
|
|
36
|
+
return outcome.enqueued || notQueued(outcome.reason ? ` (${outcome.reason})` : "");
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return notQueued(`: ${error instanceof Error ? error.message : String(error)}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** What the job reads of the acceptance row. */
|
|
43
|
+
interface PickupCodeRow {
|
|
44
|
+
orderId: string;
|
|
45
|
+
provider: string;
|
|
46
|
+
status: string;
|
|
47
|
+
deliveredBy: string | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type PickupCodeOutcome =
|
|
51
|
+
| { kind: "skipped"; reason: string }
|
|
52
|
+
| { kind: "done"; action: "validatePickupCode" }
|
|
53
|
+
| { kind: "failed"; action: "validatePickupCode"; reason: string };
|
|
54
|
+
|
|
55
|
+
interface PickupCodeDeps {
|
|
56
|
+
attempt: { attempt: number; maxAttempts: number };
|
|
57
|
+
ref: OutboundOrderRef;
|
|
58
|
+
retryError: (message: string) => Error;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Hand the verdict to the host. Its throw is logged: the job never re-asks the marketplace for it. */
|
|
62
|
+
export async function tellPickupCode(
|
|
63
|
+
ctx: EngineContext,
|
|
64
|
+
payload: OutboundJobPayload,
|
|
65
|
+
validation: PickupCodeValidation,
|
|
66
|
+
): Promise<void> {
|
|
67
|
+
const hook = ctx.ports.order.onPickupCodeValidated;
|
|
68
|
+
const log = validation === "VALID" ? ctx.ports.logger.info : ctx.ports.logger.warn;
|
|
69
|
+
log.call(ctx.ports.logger, `marketplace.outbound: pickup code of order ${payload.orderId}: ${validation}`);
|
|
70
|
+
if (!hook) return;
|
|
71
|
+
try {
|
|
72
|
+
await hook.call(ctx.ports.order, payload.clientId, payload.orderId, validation);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
ctx.ports.logger.error(
|
|
75
|
+
`marketplace.outbound: the host's half of the pickup-code verdict for order ${payload.orderId} failed: ` +
|
|
76
|
+
(error instanceof Error ? error.message : String(error)),
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Why the check is not sent, or null when it is. */
|
|
82
|
+
function skipOf(payload: OutboundJobPayload, row: PickupCodeRow, adapter: MarketplaceAdapter): string | null {
|
|
83
|
+
if (!adapter.courier) return "the marketplace has no pickup-code check";
|
|
84
|
+
if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
|
|
85
|
+
if (row.deliveredBy !== "MARKETPLACE") return "the order is not carried by the marketplace's courier";
|
|
86
|
+
return payload.code ? null : "no pickup code to send";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The call's answer, or the reason no call could be made. */
|
|
90
|
+
async function call(
|
|
91
|
+
ctx: EngineContext,
|
|
92
|
+
payload: OutboundJobPayload,
|
|
93
|
+
row: PickupCodeRow,
|
|
94
|
+
adapter: MarketplaceAdapter,
|
|
95
|
+
ref: OutboundOrderRef,
|
|
96
|
+
): Promise<PickupCodeCallResult> {
|
|
97
|
+
let connection;
|
|
98
|
+
try {
|
|
99
|
+
connection = await readOutboundConnection(ctx, payload.clientId, row.provider);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
const message = `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
|
|
102
|
+
return { kind: "refused", status: 0, message, own: true };
|
|
103
|
+
}
|
|
104
|
+
if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
|
|
105
|
+
return adapter.courier!.validatePickupCode(
|
|
106
|
+
{ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
|
|
107
|
+
ref,
|
|
108
|
+
{ code: payload.code! },
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The job's body: skip, call, hand the verdict over; a retry throws until the last attempt. */
|
|
113
|
+
export async function runPickupCode(
|
|
114
|
+
ctx: EngineContext,
|
|
115
|
+
payload: OutboundJobPayload,
|
|
116
|
+
row: PickupCodeRow,
|
|
117
|
+
adapter: MarketplaceAdapter,
|
|
118
|
+
deps: PickupCodeDeps,
|
|
119
|
+
): Promise<PickupCodeOutcome> {
|
|
120
|
+
const skip = skipOf(payload, row, adapter);
|
|
121
|
+
if (skip) return { kind: "skipped", reason: skip };
|
|
122
|
+
const result = await call(ctx, payload, row, adapter, deps.ref);
|
|
123
|
+
if (result.kind === "answered") {
|
|
124
|
+
await tellPickupCode(ctx, payload, result.valid ? "VALID" : "INVALID");
|
|
125
|
+
ctx.ports.publishChanged(payload.clientId);
|
|
126
|
+
return { kind: "done", action: "validatePickupCode" };
|
|
127
|
+
}
|
|
128
|
+
const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
|
|
129
|
+
if (result.kind === "retry" && deps.attempt.attempt < deps.attempt.maxAttempts) {
|
|
130
|
+
throw deps.retryError(`validatePickupCode for order ${row.orderId}: ${reason}`);
|
|
131
|
+
}
|
|
132
|
+
ctx.ports.logger.error(`marketplace.outbound: validatePickupCode for order ${row.orderId} failed: ${reason}`);
|
|
133
|
+
await tellPickupCode(ctx, payload, "UNVERIFIED");
|
|
134
|
+
ctx.ports.publishChanged(payload.clientId);
|
|
135
|
+
return { kind: "failed", action: "validatePickupCode", reason };
|
|
136
|
+
}
|
package/src/core/pipeline.ts
CHANGED
|
@@ -6,8 +6,14 @@ import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
|
|
|
6
6
|
import { connectionMerchantId, resolveIngestionTarget } from "./integration";
|
|
7
7
|
import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest, markCancelledBeforeIngest } from "./order-fetch-marks";
|
|
8
8
|
import type { EngineContext } from "./ports";
|
|
9
|
-
import type {
|
|
10
|
-
|
|
9
|
+
import type {
|
|
10
|
+
MarketplaceCourierStep,
|
|
11
|
+
MarketplaceLifecycle,
|
|
12
|
+
MarketplaceProvider,
|
|
13
|
+
NormalizedEvent,
|
|
14
|
+
NormalizedMarketplaceOrder,
|
|
15
|
+
} from "./types";
|
|
16
|
+
import { followCourierAndLifecycle } from "./courier";
|
|
11
17
|
|
|
12
18
|
/**
|
|
13
19
|
* One delivery, start to finish: normalize → inbox → ingest.
|
|
@@ -37,6 +43,8 @@ export type DeliveryOutcome =
|
|
|
37
43
|
| { kind: "ingested"; orderId: string; unmappedSkus: string[] }
|
|
38
44
|
/** A lifecycle event moved the order forward, through the host's `onLifecycle` (FUT-4653). */
|
|
39
45
|
| { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
|
|
46
|
+
/** A courier event's facts were stored by the host's `onCourier` (FUT-5665). */
|
|
47
|
+
| { kind: "courier"; orderId: string; step: MarketplaceCourierStep }
|
|
40
48
|
| { kind: "cancelled" }
|
|
41
49
|
| { kind: "cancellationFailed" }
|
|
42
50
|
/** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
|
|
@@ -163,10 +171,11 @@ async function applyEvent(
|
|
|
163
171
|
return { kind: "awaitingOrder" };
|
|
164
172
|
}
|
|
165
173
|
|
|
166
|
-
// A
|
|
167
|
-
//
|
|
168
|
-
//
|
|
169
|
-
|
|
174
|
+
// A courier event (FUT-5665) reaches a host that binds `onCourier`; a
|
|
175
|
+
// lifecycle event (dispatched, collected, concluded) of an order we hold:
|
|
176
|
+
// with the connection's switch ON and a host that binds the hook, the order
|
|
177
|
+
// follows. Anything else falls through to "understood, nothing to do", as before.
|
|
178
|
+
const followed = await followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
|
|
170
179
|
if (followed) return followed;
|
|
171
180
|
return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
|
|
172
181
|
}
|
package/src/core/ports.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import type { AdapterRegistry } from "./registry";
|
|
2
2
|
import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
|
|
3
3
|
import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
|
|
4
|
+
import type { MarketplaceCourierAnswer, MarketplaceCourierFacts, PickupCodeValidation } from "./courier-port";
|
|
4
5
|
import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
|
|
6
|
+
import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
|
|
5
7
|
import type {
|
|
6
8
|
CancellationFailureReason,
|
|
7
9
|
MarketplaceAdmission,
|
|
@@ -10,7 +12,7 @@ import type {
|
|
|
10
12
|
MarketplaceRefusal,
|
|
11
13
|
ResolvedOrderLine,
|
|
12
14
|
} from "./order-types";
|
|
13
|
-
import type { NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
15
|
+
import type { NormalizedCourierEvent, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
14
16
|
|
|
15
17
|
export type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
|
|
16
18
|
export type {
|
|
@@ -110,6 +112,7 @@ export interface MarketplaceDb {
|
|
|
110
112
|
create(args: unknown): Promise<unknown>;
|
|
111
113
|
updateMany(args: unknown): Promise<{ count: number }>;
|
|
112
114
|
};
|
|
115
|
+
marketplaceLinkAttempt?: MarketplaceLinkAttemptDelegate; // OPTIONAL, as above; absent: no linking (FUT-5613).
|
|
113
116
|
}
|
|
114
117
|
|
|
115
118
|
/** One decision as the host's admission sees it, BEFORE the claim commits. */
|
|
@@ -220,6 +223,27 @@ export interface MarketplaceOrderPort {
|
|
|
220
223
|
* Absent: the engine cannot tell, and sends nothing.
|
|
221
224
|
*/
|
|
222
225
|
statusHolds?(clientId: string, orderId: string, step: StatusStep): Promise<boolean>;
|
|
226
|
+
/**
|
|
227
|
+
* OPTIONAL (FUT-5665). The marketplace's courier moved: named, on the way,
|
|
228
|
+
* at the counter, holding the bag, or bringing it back. Store the facts on
|
|
229
|
+
* the order; never move it (a `COLLECTED` moves through `onLifecycle`).
|
|
230
|
+
* Idempotent: a redelivery is deduped, but the reconcile pass re-runs a
|
|
231
|
+
* FAILED row. Asked for an ACCEPTED order only, whatever the connection's
|
|
232
|
+
* `followStatus`. Absent: courier events are understood and ignored.
|
|
233
|
+
*/
|
|
234
|
+
onCourier?(
|
|
235
|
+
clientId: string,
|
|
236
|
+
orderId: string,
|
|
237
|
+
event: NormalizedCourierEvent,
|
|
238
|
+
facts: MarketplaceCourierFacts,
|
|
239
|
+
): Promise<MarketplaceCourierAnswer>;
|
|
240
|
+
/**
|
|
241
|
+
* OPTIONAL (FUT-5665). The marketplace's verdict on the pickup code the host
|
|
242
|
+
* sent with `engine.validatePickupCode`. Called once per job, after the
|
|
243
|
+
* hand-over has committed: `INVALID` warns, it moves nothing. A throw is
|
|
244
|
+
* logged. Absent: the verdict is only logged.
|
|
245
|
+
*/
|
|
246
|
+
onPickupCodeValidated?(clientId: string, orderId: string, validation: PickupCodeValidation): Promise<void>;
|
|
223
247
|
/** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
|
|
224
248
|
summarize(
|
|
225
249
|
clientId: string,
|
|
@@ -333,6 +357,7 @@ export interface MarketplacePorts {
|
|
|
333
357
|
* catalogue. Absent: every catalogue call answers `UNSUPPORTED`.
|
|
334
358
|
*/
|
|
335
359
|
catalogue?: MarketplaceCataloguePort;
|
|
360
|
+
appCredentials?: MarketplaceAppCredentialsPort; // OPTIONAL. The software's own app, to link a store (FUT-5613).
|
|
336
361
|
/** The acceptance window a connection gets when it does not state its own. */
|
|
337
362
|
defaultAckSlaSeconds: number;
|
|
338
363
|
/** How many stored deliveries one reconciliation pass re-runs. */
|
package/src/core/status-store.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { StatusStep } from "./adapter";
|
|
2
2
|
import type { EngineContext, MarketplaceDb } from "./ports";
|
|
3
|
-
import type { MarketplaceLifecycle } from "./types";
|
|
4
3
|
|
|
5
4
|
/**
|
|
6
5
|
* The engine's memory of what was said about an order's steps, in
|
|
@@ -11,7 +10,7 @@ import type { MarketplaceLifecycle } from "./types";
|
|
|
11
10
|
*/
|
|
12
11
|
|
|
13
12
|
/** A step as the table holds it: the three the store informs, and the one only a marketplace announces. */
|
|
14
|
-
export type StatusRowStep = StatusStep |
|
|
13
|
+
export type StatusRowStep = StatusStep | "CONCLUDED";
|
|
15
14
|
|
|
16
15
|
/** Where a row stands. */
|
|
17
16
|
export type StatusRowState = "SENDING" | "SENT" | "FAILED" | "NOTED";
|
|
@@ -65,7 +64,7 @@ export async function insertStatusRow(
|
|
|
65
64
|
/** Remember a step the marketplace announced, so our own job never informs it back. */
|
|
66
65
|
export async function noteMarketplaceStep(
|
|
67
66
|
ctx: EngineContext,
|
|
68
|
-
row: { clientId: string; orderId: string; provider: string; step:
|
|
67
|
+
row: { clientId: string; orderId: string; provider: string; step: StatusRowStep },
|
|
69
68
|
): Promise<void> {
|
|
70
69
|
const table = statusTable(await ctx.ports.db());
|
|
71
70
|
if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
|
package/src/core/types.ts
CHANGED
|
@@ -127,6 +127,14 @@ export interface NormalizedMarketplaceOrder {
|
|
|
127
127
|
* the connection's is refused.
|
|
128
128
|
*/
|
|
129
129
|
externalMerchantId?: string | null;
|
|
130
|
+
/**
|
|
131
|
+
* OPTIONAL (FUT-5665). The code the marketplace's courier states at the
|
|
132
|
+
* counter to collect the bag (iFood's `delivery.pickupCode`), for the host
|
|
133
|
+
* to check locally at the hand-over. Null or absent: the marketplace asks
|
|
134
|
+
* none for this order (the check is off for the store, or the store carries
|
|
135
|
+
* the bag itself).
|
|
136
|
+
*/
|
|
137
|
+
pickupCode?: string | null;
|
|
130
138
|
}
|
|
131
139
|
|
|
132
140
|
/**
|
|
@@ -138,11 +146,49 @@ export type CancellationOutcome = "CONFIRMED" | "FAILED";
|
|
|
138
146
|
|
|
139
147
|
/**
|
|
140
148
|
* A step of the order's life a marketplace announces about an order it
|
|
141
|
-
* already has (FUT-4653): the courier left (`DISPATCHED`)
|
|
142
|
-
*
|
|
143
|
-
*
|
|
149
|
+
* already has (FUT-4653): the courier left (`DISPATCHED`), the marketplace's
|
|
150
|
+
* courier has the bag (`COLLECTED`, FUT-5665: for a fleet bag it is the same
|
|
151
|
+
* hand-over as `DISPATCHED`) or the order is finished (`CONCLUDED`). An event
|
|
152
|
+
* that names one moves nothing by itself; the engine asks the host to move the
|
|
153
|
+
* order forward (`onLifecycle`).
|
|
144
154
|
*/
|
|
145
|
-
export type MarketplaceLifecycle = "DISPATCHED" | "CONCLUDED";
|
|
155
|
+
export type MarketplaceLifecycle = "DISPATCHED" | "COLLECTED" | "CONCLUDED";
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Where the marketplace's own courier is with a bag (FUT-5665), provider-
|
|
159
|
+
* neutral: named (`ASSIGNED`), on the way to the store (`GOING_TO_ORIGIN`),
|
|
160
|
+
* at the counter (`ARRIVED_AT_ORIGIN`), holding the bag (`COLLECTED`), or
|
|
161
|
+
* bringing it back (`RETURNING_TO_ORIGIN`, then `RETURNED_TO_ORIGIN`).
|
|
162
|
+
*/
|
|
163
|
+
export type MarketplaceCourierStep =
|
|
164
|
+
| "ASSIGNED"
|
|
165
|
+
| "GOING_TO_ORIGIN"
|
|
166
|
+
| "ARRIVED_AT_ORIGIN"
|
|
167
|
+
| "COLLECTED"
|
|
168
|
+
| "RETURNING_TO_ORIGIN"
|
|
169
|
+
| "RETURNED_TO_ORIGIN";
|
|
170
|
+
|
|
171
|
+
/** What the courier rides, as a closed set the host has words for. `OTHER`: stated, and none of these. */
|
|
172
|
+
export type MarketplaceCourierVehicle = "MOTORCYCLE" | "BICYCLE" | "CAR" | "OTHER";
|
|
173
|
+
|
|
174
|
+
/** Who the marketplace sent, as much as it says. */
|
|
175
|
+
export interface MarketplaceCourier {
|
|
176
|
+
name: string | null;
|
|
177
|
+
/** An https URL of the courier's photo, or null (any other scheme is dropped). */
|
|
178
|
+
photoUrl: string | null;
|
|
179
|
+
vehicle: MarketplaceCourierVehicle | null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One courier event, normalized (FUT-5665). */
|
|
183
|
+
export interface NormalizedCourierEvent {
|
|
184
|
+
step: MarketplaceCourierStep;
|
|
185
|
+
/** When the marketplace says it happened; null when it does not (the engine then hands the host its clock). */
|
|
186
|
+
at: Date | null;
|
|
187
|
+
/** Who is coming: on `ASSIGNED`, when the marketplace names them; null otherwise. */
|
|
188
|
+
courier: MarketplaceCourier | null;
|
|
189
|
+
/** The bag is coming back (`RETURNING`) or is back (`RETURNED`); null on every other step. */
|
|
190
|
+
returning: "RETURNING" | "RETURNED" | null;
|
|
191
|
+
}
|
|
146
192
|
|
|
147
193
|
/** What an adapter makes of one inbound delivery. */
|
|
148
194
|
export interface NormalizedEvent {
|
|
@@ -181,4 +227,10 @@ export interface NormalizedEvent {
|
|
|
181
227
|
* names one carries no order body.
|
|
182
228
|
*/
|
|
183
229
|
lifecycle?: MarketplaceLifecycle | null;
|
|
230
|
+
/**
|
|
231
|
+
* OPTIONAL (FUT-5665). Where the marketplace's courier is, when this event
|
|
232
|
+
* says. A `COLLECTED` names the lifecycle too. Absent or null: the event
|
|
233
|
+
* names no courier step.
|
|
234
|
+
*/
|
|
235
|
+
courier?: NormalizedCourierEvent | null;
|
|
184
236
|
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { outboundResultOf, type AdapterCallContext, type OutboundOrderRef } from "../core/adapter";
|
|
2
|
+
import type {
|
|
3
|
+
CourierTrackingCallResult,
|
|
4
|
+
MarketplaceCourierApi,
|
|
5
|
+
MarketplaceCourierTracking,
|
|
6
|
+
PickupCodeCallResult,
|
|
7
|
+
} from "../core/courier-port";
|
|
8
|
+
import { firstDate, firstString, pick } from "../core/payload-read";
|
|
9
|
+
import type { MarketplaceCourier, MarketplaceCourierStep, MarketplaceCourierVehicle, NormalizedCourierEvent } from "../core/types";
|
|
10
|
+
import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* iFood's own fleet (FUT-5665), both halves: the courier events of iFood's
|
|
14
|
+
* stream, and the two calls about the courier (the pickup-code check and the
|
|
15
|
+
* tracking read). Only for an order iFood's fleet carries
|
|
16
|
+
* (`delivery.deliveredBy = IFOOD`); the engine never calls either for another.
|
|
17
|
+
*
|
|
18
|
+
* Source: the iFood research of 2026-11-26 (Levantamento, lines 95-115),
|
|
19
|
+
* marked confirmed there against iFood's Order module docs; what it could not
|
|
20
|
+
* confirm is marked ESTIMATED below, in this file only.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* iFood's courier event codes, short and long. The four short codes and every
|
|
25
|
+
* long form are confirmed; the two return events have no documented short
|
|
26
|
+
* code, so only their long forms are read (ESTIMATED: none is guessed).
|
|
27
|
+
*/
|
|
28
|
+
const COURIER_STEP_OF: Readonly<Record<string, MarketplaceCourierStep>> = {
|
|
29
|
+
ADR: "ASSIGNED",
|
|
30
|
+
ASSIGN_DRIVER: "ASSIGNED",
|
|
31
|
+
GTO: "GOING_TO_ORIGIN",
|
|
32
|
+
GOING_TO_ORIGIN: "GOING_TO_ORIGIN",
|
|
33
|
+
AAO: "ARRIVED_AT_ORIGIN",
|
|
34
|
+
ARRIVED_AT_ORIGIN: "ARRIVED_AT_ORIGIN",
|
|
35
|
+
CLT: "COLLECTED",
|
|
36
|
+
COLLECTED: "COLLECTED",
|
|
37
|
+
DELIVERY_RETURNING_TO_ORIGIN: "RETURNING_TO_ORIGIN",
|
|
38
|
+
DELIVERY_RETURNED_TO_ORIGIN: "RETURNED_TO_ORIGIN",
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* `workerVehicleType` as the host's closed set. ESTIMATED: the field is
|
|
43
|
+
* confirmed, its values are not documented in the research; these are the
|
|
44
|
+
* words a vehicle is plausibly named with, and anything else stated is OTHER.
|
|
45
|
+
*/
|
|
46
|
+
const VEHICLE_OF: Readonly<Record<string, MarketplaceCourierVehicle>> = {
|
|
47
|
+
MOTORCYCLE: "MOTORCYCLE",
|
|
48
|
+
MOTORBIKE: "MOTORCYCLE",
|
|
49
|
+
MOTO: "MOTORCYCLE",
|
|
50
|
+
BICYCLE: "BICYCLE",
|
|
51
|
+
BIKE: "BICYCLE",
|
|
52
|
+
CAR: "CAR",
|
|
53
|
+
CARRO: "CAR",
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** The longest courier name kept: a longer one is truncated, never refused. */
|
|
57
|
+
export const IFOOD_COURIER_NAME_MAX = 120;
|
|
58
|
+
/** The longest photo URL kept: a longer one is dropped (a truncated URL is a broken one). */
|
|
59
|
+
const IFOOD_COURIER_PHOTO_URL_MAX = 2048;
|
|
60
|
+
|
|
61
|
+
/** An https URL of bounded length, or null: a photo the host renders is never another scheme. */
|
|
62
|
+
function httpsUrl(value: string | null): string | null {
|
|
63
|
+
if (!value || value.length > IFOOD_COURIER_PHOTO_URL_MAX) return null;
|
|
64
|
+
try {
|
|
65
|
+
return new URL(value).protocol === "https:" ? value : null;
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The event's `metadata`: an object, or a JSON string of one. */
|
|
72
|
+
function metadataOf(payload: unknown): unknown {
|
|
73
|
+
const raw = pick(payload, "metadata");
|
|
74
|
+
if (typeof raw !== "string") return raw;
|
|
75
|
+
try {
|
|
76
|
+
return JSON.parse(raw) as unknown;
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The courier an ADR names: `workerName`, `workerPhotoUrl`, `workerVehicleType`. Null when it names nothing. */
|
|
83
|
+
function readCourier(payload: unknown): MarketplaceCourier | null {
|
|
84
|
+
const metadata = metadataOf(payload);
|
|
85
|
+
const name = firstString(metadata, [["workerName"]])?.slice(0, IFOOD_COURIER_NAME_MAX) ?? null;
|
|
86
|
+
const photoUrl = httpsUrl(firstString(metadata, [["workerPhotoUrl"]]));
|
|
87
|
+
const stated = firstString(metadata, [["workerVehicleType"]])?.toUpperCase() ?? null;
|
|
88
|
+
const vehicle = stated === null ? null : (VEHICLE_OF[stated] ?? "OTHER");
|
|
89
|
+
return name === null && photoUrl === null && vehicle === null ? null : { name, photoUrl, vehicle };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The courier step an iFood event names, or null. */
|
|
93
|
+
export function readIfoodCourierEvent(payload: unknown, eventType: string): NormalizedCourierEvent | null {
|
|
94
|
+
const step = COURIER_STEP_OF[eventType.toUpperCase()];
|
|
95
|
+
if (!step) return null;
|
|
96
|
+
return {
|
|
97
|
+
step,
|
|
98
|
+
at: firstDate(payload, [["createdAt"]]),
|
|
99
|
+
courier: step === "ASSIGNED" ? readCourier(payload) : null,
|
|
100
|
+
returning: step === "RETURNING_TO_ORIGIN" ? "RETURNING" : step === "RETURNED_TO_ORIGIN" ? "RETURNED" : null,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const orderUrl = (ref: OutboundOrderRef, action: string): string =>
|
|
105
|
+
`${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(ref.externalOrderId)}/${action}`;
|
|
106
|
+
|
|
107
|
+
/** One authenticated call; a 401 forgets the token so the retry fetches another. */
|
|
108
|
+
async function call(
|
|
109
|
+
ctx: AdapterCallContext,
|
|
110
|
+
request: { method: "GET" | "POST"; url: string; body?: unknown },
|
|
111
|
+
): Promise<{ status: number; body: string } | { kind: "refused"; status: number; message: string; own?: true } | { kind: "retry"; reason: string }> {
|
|
112
|
+
const auth = await bearer(ctx);
|
|
113
|
+
if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "no token" } : auth;
|
|
114
|
+
const response = await ctx.http({
|
|
115
|
+
method: request.method,
|
|
116
|
+
url: request.url,
|
|
117
|
+
headers: {
|
|
118
|
+
Authorization: `Bearer ${auth.token}`,
|
|
119
|
+
...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
120
|
+
},
|
|
121
|
+
...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
|
|
122
|
+
});
|
|
123
|
+
if (response.status !== 401) return response;
|
|
124
|
+
ctx.tokens.delete(ifoodTokenKey(ctx));
|
|
125
|
+
return { kind: "retry", reason: "iFood refused the token" };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function parsed(body: string): unknown {
|
|
129
|
+
try {
|
|
130
|
+
return JSON.parse(body) as unknown;
|
|
131
|
+
} catch {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* `POST /order/v1.0/orders/{id}/validatePickupCode {"code"}`, answering
|
|
138
|
+
* `{"valid": true|false}` (confirmed). A 2xx without a boolean `valid` is no
|
|
139
|
+
* verdict: our own refusal, never read as INVALID.
|
|
140
|
+
*/
|
|
141
|
+
async function validatePickupCode(
|
|
142
|
+
ctx: AdapterCallContext,
|
|
143
|
+
order: OutboundOrderRef,
|
|
144
|
+
input: { code: string },
|
|
145
|
+
): Promise<PickupCodeCallResult> {
|
|
146
|
+
try {
|
|
147
|
+
const response = await call(ctx, { method: "POST", url: orderUrl(order, "validatePickupCode"), body: { code: input.code } });
|
|
148
|
+
if ("kind" in response) return response;
|
|
149
|
+
const read = outboundResultOf(response);
|
|
150
|
+
if (read.kind !== "accepted") return read;
|
|
151
|
+
const valid = pick(parsed(response.body), "valid");
|
|
152
|
+
return typeof valid === "boolean"
|
|
153
|
+
? { kind: "answered", valid }
|
|
154
|
+
: { kind: "refused", status: response.status, message: "iFood answered without a verdict", own: true };
|
|
155
|
+
} catch (error) {
|
|
156
|
+
return retryOf(error);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** A call that never got an answer is a retry. */
|
|
161
|
+
function retryOf(error: unknown): { kind: "retry"; reason: string } {
|
|
162
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function numberAt(source: unknown, key: string): number | null {
|
|
166
|
+
const value = pick(source, key);
|
|
167
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** `base` plus a number of seconds, or null when either is missing. */
|
|
171
|
+
function plusSeconds(base: Date, seconds: number | null): Date | null {
|
|
172
|
+
return seconds === null ? null : new Date(base.getTime() + seconds * 1000);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The tracking body. Confirmed: latitude, longitude, `expectedDelivery`,
|
|
177
|
+
* `trackDate`, and seconds to the pickup and to the delivery. ESTIMATED: the
|
|
178
|
+
* names of the two second counts (`pickupEtaStart`, `deliveryEtaEnd`, or
|
|
179
|
+
* `pickupEta`, `deliveryEta`), counted from `trackDate`.
|
|
180
|
+
*/
|
|
181
|
+
function readTracking(body: unknown, now: Date): MarketplaceCourierTracking {
|
|
182
|
+
const trackedAt = firstDate(body, [["trackDate"]]);
|
|
183
|
+
const base = trackedAt ?? now;
|
|
184
|
+
const pickupSeconds = numberAt(body, "pickupEtaStart") ?? numberAt(body, "pickupEta");
|
|
185
|
+
const deliverySeconds = numberAt(body, "deliveryEtaEnd") ?? numberAt(body, "deliveryEta");
|
|
186
|
+
return {
|
|
187
|
+
pickupEtaAt: plusSeconds(base, pickupSeconds),
|
|
188
|
+
deliveryEtaAt: firstDate(body, [["expectedDelivery"]]) ?? plusSeconds(base, deliverySeconds),
|
|
189
|
+
latitude: numberAt(body, "latitude"),
|
|
190
|
+
longitude: numberAt(body, "longitude"),
|
|
191
|
+
trackedAt,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** `GET /order/v1.0/orders/{id}/tracking` (confirmed): 404 before ASSIGN_DRIVER is "not yet". */
|
|
196
|
+
async function tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<CourierTrackingCallResult> {
|
|
197
|
+
try {
|
|
198
|
+
const response = await call(ctx, { method: "GET", url: orderUrl(order, "tracking") });
|
|
199
|
+
if ("kind" in response) return response;
|
|
200
|
+
if (response.status === 404) return { kind: "notYet" };
|
|
201
|
+
const read = outboundResultOf(response);
|
|
202
|
+
if (read.kind !== "accepted") return read;
|
|
203
|
+
return { kind: "tracking", tracking: readTracking(parsed(response.body), ctx.now) };
|
|
204
|
+
} catch (error) {
|
|
205
|
+
return retryOf(error);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** iFood's courier calls, for the adapter's `courier`. */
|
|
210
|
+
export const IFOOD_COURIER: MarketplaceCourierApi = { validatePickupCode, tracking };
|
package/src/ifood/index.ts
CHANGED
|
@@ -2,6 +2,8 @@ import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
|
|
|
2
2
|
import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
|
|
3
3
|
import { IFOOD_CATALOGUE } from "./catalogue";
|
|
4
4
|
import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
|
|
5
|
+
import { IFOOD_COURIER } from "./courier";
|
|
6
|
+
import { IFOOD_LINKING } from "./linking";
|
|
5
7
|
import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
|
|
6
8
|
import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
|
|
7
9
|
import { IFOOD_AVAILABILITY } from "./pause";
|
|
@@ -79,6 +81,10 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
79
81
|
informStatus: ifoodInformStatus,
|
|
80
82
|
// The Merchant API's interruptions: an id and an end per closure (FUT-4851).
|
|
81
83
|
availability: IFOOD_AVAILABILITY,
|
|
84
|
+
// The distributed-app authorization: a store links the software's own app (FUT-5613).
|
|
85
|
+
linking: IFOOD_LINKING,
|
|
86
|
+
// iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).
|
|
87
|
+
courier: IFOOD_COURIER,
|
|
82
88
|
// No per-order deep link is known, so the portal, where a live order is
|
|
83
89
|
// on the first screen.
|
|
84
90
|
appLink: () => IFOOD_PORTAL_URL,
|
|
@@ -89,5 +95,7 @@ export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
|
|
|
89
95
|
export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
|
|
90
96
|
export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
|
|
91
97
|
export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
|
|
98
|
+
export { IFOOD_LINKING } from "./linking";
|
|
99
|
+
export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
|
|
92
100
|
export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
|
|
93
101
|
export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
|