@12-apps/marketplace 1.17.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.
- package/ADOPTING.md +70 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CxzF-qGx.d.ts → adapter-ZpAWKoCk.d.ts} +116 -2
- package/dist/{chunk-7IYUO2KC.js → chunk-3B5EULS6.js} +2 -2
- package/dist/{chunk-EABVLQKK.js → chunk-BLHZ3MRB.js} +2 -2
- package/dist/{chunk-UZO2NILN.js → chunk-MDEIRGNL.js} +1067 -877
- package/dist/chunk-MDEIRGNL.js.map +1 -0
- package/dist/{chunk-KKFMDV5K.js → chunk-Q5RMVNU5.js} +1 -1
- package/dist/{chunk-KKFMDV5K.js.map → chunk-Q5RMVNU5.js.map} +1 -1
- package/dist/{chunk-CF5BSXE5.js → chunk-ZT6TZTLD.js} +1 -1
- package/dist/chunk-ZT6TZTLD.js.map +1 -0
- package/dist/{client-C-4QvVq3.d.ts → client-DpEq0yXb.d.ts} +1 -1
- package/dist/{engine-Y6Rpf5p7.d.ts → engine-DRRhAjZK.d.ts} +171 -143
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +7 -2
- package/dist/ifood/index.js +138 -100
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +76 -5
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- 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/index.d.ts +2 -2
- package/dist/server/index.js +3 -3
- package/package.json +1 -1
- package/prisma/marketplace.prisma +1 -1
- package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
- package/src/core/adapter.ts +2 -1
- package/src/core/delivery-code.ts +119 -0
- package/src/core/engine.ts +10 -2
- package/src/core/logistics.ts +388 -0
- package/src/core/outbound-queue.ts +6 -1
- package/src/core/outbound-sweep.ts +10 -5
- package/src/core/outbound.ts +4 -5
- package/src/core/pipeline.ts +6 -1
- package/src/core/ports.ts +5 -2
- package/src/core/status-job.ts +3 -0
- package/src/core/status-store.ts +2 -1
- package/src/core/types.ts +2 -0
- package/src/ifood/index.ts +3 -0
- package/src/ifood/logistics.ts +38 -0
- package/src/ifood/normalize.ts +11 -1
- package/src/index.ts +10 -0
- package/dist/chunk-CF5BSXE5.js.map +0 -1
- package/dist/chunk-UZO2NILN.js.map +0 -1
- /package/dist/{chunk-7IYUO2KC.js.map → chunk-3B5EULS6.js.map} +0 -0
- /package/dist/{chunk-EABVLQKK.js.map → chunk-BLHZ3MRB.js.map} +0 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import type { AdapterCallContext, MarketplaceAdapter, MarketplaceCredentials, OutboundOrderRef, OutboundResult } from "./adapter";
|
|
2
|
+
import type { OutboundConnection } from "./integration";
|
|
3
|
+
import { readOutboundConnection } from "./integration";
|
|
4
|
+
import { MARKETPLACE_OUTBOUND_JOB, type OutboundJobPayload } from "./outbound-queue";
|
|
5
|
+
import type { MarketplaceAppCredentialsPort } from "./linking-port";
|
|
6
|
+
import type { EngineContext } from "./ports";
|
|
7
|
+
import { insertStatusRow, readStatusRows, settleStatusRow, statusTable, type StatusRow, type StatusRowStep } from "./status-store";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The store's OWN courier carrying a marketplace order, reported to the
|
|
11
|
+
* marketplace (FUT-5988, FUT-6166): iFood's Logistics module, so the buyer
|
|
12
|
+
* follows the delivery in the marketplace's app.
|
|
13
|
+
*
|
|
14
|
+
* The host says the courier reached a step (`informLogistics`, one enqueue);
|
|
15
|
+
* the `marketplace.outbound` job, action `logistics`, sends every step still
|
|
16
|
+
* owed up to it, in the marketplace's one order, each under its own claim row
|
|
17
|
+
* in the status table (`LOGISTICS_<STEP>`, unique per order and step, so a
|
|
18
|
+
* step is never sent twice). Only for an ACCEPTED order the store carries
|
|
19
|
+
* itself (`deliveredBy: MERCHANT`), only when the adapter has a Logistics
|
|
20
|
+
* half and the host configured the Logistics app's credentials
|
|
21
|
+
* (`logisticsCredentials`, the software's own app, never the store's PDV
|
|
22
|
+
* credentials). The courier's name and phone are read from the host at send
|
|
23
|
+
* time (`order.logisticsDriver`), never carried in the job's payload.
|
|
24
|
+
*
|
|
25
|
+
* A step that fails (a final refusal, or the last attempt) is FAILED and the
|
|
26
|
+
* chain stops there: the marketplace refuses a later step out of order. A
|
|
27
|
+
* failure never touches the order.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** The steps, in the one order a marketplace takes them. */
|
|
31
|
+
export const LOGISTICS_STEPS = ["ASSIGNED", "GOING_TO_ORIGIN", "ARRIVED_AT_ORIGIN", "DISPATCHED", "ARRIVED_AT_DESTINATION"] as const;
|
|
32
|
+
|
|
33
|
+
export type LogisticsStep = (typeof LOGISTICS_STEPS)[number];
|
|
34
|
+
|
|
35
|
+
/** How the courier travels, as the marketplace is told. */
|
|
36
|
+
export type LogisticsVehicle = "MOTORCYCLE" | "CAR" | "BICYCLE" | "ON_FOOT" | "SCOOTER";
|
|
37
|
+
|
|
38
|
+
/** Who carries the order, read from the host when ASSIGNED is sent. */
|
|
39
|
+
export interface LogisticsDriver {
|
|
40
|
+
name: string;
|
|
41
|
+
phone: string;
|
|
42
|
+
vehicle: LogisticsVehicle;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** An adapter's Logistics half: the wire calls, nothing else. */
|
|
46
|
+
export interface MarketplaceLogistics {
|
|
47
|
+
assignDriver(ctx: AdapterCallContext, order: OutboundOrderRef, driver: LogisticsDriver): Promise<OutboundResult | { kind: "invalid"; reason: string }>;
|
|
48
|
+
step(ctx: AdapterCallContext, order: OutboundOrderRef, step: Exclude<LogisticsStep, "ASSIGNED">): Promise<OutboundResult>;
|
|
49
|
+
/** OPTIONAL (FUT-6167). The customer's delivery code, typed by the courier at the door. */
|
|
50
|
+
verifyDeliveryCode?(ctx: AdapterCallContext, order: OutboundOrderRef, code: string): Promise<DeliveryCodeAnswer>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* What the marketplace said of the customer's delivery code (FUT-6167).
|
|
55
|
+
* UNAVAILABLE is never a refusal of the close: the host closes and records it.
|
|
56
|
+
*/
|
|
57
|
+
export type DeliveryCodeAnswer =
|
|
58
|
+
| { kind: "VERIFIED" }
|
|
59
|
+
/** Wrong, or not a code at all: the courier may type it again. */
|
|
60
|
+
| { kind: "WRONG_CODE" }
|
|
61
|
+
/** The marketplace never asked this order for a code. */
|
|
62
|
+
| { kind: "NOT_REQUESTED" }
|
|
63
|
+
| { kind: "UNAVAILABLE"; reason: string };
|
|
64
|
+
|
|
65
|
+
/** The adapter's Logistics half (`MarketplaceAdapter` extends it). */
|
|
66
|
+
export interface LogisticsAdapter {
|
|
67
|
+
/** OPTIONAL (FUT-6166). The store's own courier reported to the marketplace. */
|
|
68
|
+
readonly logistics?: MarketplaceLogistics;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The order port's Logistics half (`MarketplaceOrderPort` extends it). */
|
|
72
|
+
export interface LogisticsOrderPort {
|
|
73
|
+
/**
|
|
74
|
+
* OPTIONAL (FUT-6166). The store's courier carrying the order, read before a
|
|
75
|
+
* Logistics run claims anything while ASSIGNED is still owed, or null when none
|
|
76
|
+
* is. Null or absent: the run is skipped and claims nothing. Answer null after
|
|
77
|
+
* the host's undo of a dispatch (ADOPTING §16).
|
|
78
|
+
*/
|
|
79
|
+
logisticsDriver?(clientId: string, orderId: string): Promise<LogisticsDriver | null>;
|
|
80
|
+
/**
|
|
81
|
+
* OPTIONAL (FUT-6167). The marketplace asked the customer's delivery code for
|
|
82
|
+
* an ACCEPTED order: store it, so the courier's close asks for the code.
|
|
83
|
+
* Idempotent: a redelivery calls it again. Absent: the event is ignored.
|
|
84
|
+
*/
|
|
85
|
+
onDeliveryCodeRequested?(clientId: string, orderId: string): Promise<void>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The host's Logistics ports (`MarketplacePorts` extends it). */
|
|
89
|
+
export interface LogisticsPorts {
|
|
90
|
+
/**
|
|
91
|
+
* OPTIONAL (FUT-6166). The software's Logistics app on this marketplace (a
|
|
92
|
+
* separate app from the one that links stores), or null. Absent or null: no
|
|
93
|
+
* Logistics step is ever sent.
|
|
94
|
+
*/
|
|
95
|
+
logisticsCredentials?: MarketplaceAppCredentialsPort;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What the host says when its courier reaches a step. */
|
|
99
|
+
export interface InformLogisticsInput {
|
|
100
|
+
clientId: string;
|
|
101
|
+
orderId: string;
|
|
102
|
+
step: LogisticsStep;
|
|
103
|
+
/** The move's instant: it keys the job and owns the claims it makes. */
|
|
104
|
+
at: Date;
|
|
105
|
+
/**
|
|
106
|
+
* Hold the job this long (the host's undo window): a move undone inside it
|
|
107
|
+
* leaves the order with no courier, and the job then sends nothing.
|
|
108
|
+
*/
|
|
109
|
+
delayMs?: number;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The status-table step a Logistics claim is stored under. */
|
|
113
|
+
export const LOGISTICS_ROW_PREFIX = "LOGISTICS_";
|
|
114
|
+
|
|
115
|
+
const rowStep = (step: LogisticsStep): StatusRowStep => `${LOGISTICS_ROW_PREFIX}${step}` as StatusRowStep;
|
|
116
|
+
|
|
117
|
+
/** The dedupe key of one move. */
|
|
118
|
+
function logisticsDedupeKey(step: LogisticsStep, orderId: string, at: Date): string {
|
|
119
|
+
return `${MARKETPLACE_OUTBOUND_JOB}:logistics:${step}:${orderId}:${at.getTime()}`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One enqueue, never a statement, never thrown (as `informStatus`). */
|
|
123
|
+
async function informLogistics(ctx: EngineContext, input: InformLogisticsInput): Promise<boolean> {
|
|
124
|
+
const payload: OutboundJobPayload = {
|
|
125
|
+
clientId: input.clientId,
|
|
126
|
+
orderId: input.orderId,
|
|
127
|
+
action: "logistics",
|
|
128
|
+
logisticsStep: input.step,
|
|
129
|
+
// The step is in the key: two moves at one instant never share a claim.
|
|
130
|
+
claimKey: `${input.step}:${input.at.getTime()}`,
|
|
131
|
+
};
|
|
132
|
+
try {
|
|
133
|
+
const options = {
|
|
134
|
+
dedupeKey: logisticsDedupeKey(input.step, input.orderId, input.at),
|
|
135
|
+
...(input.delayMs === undefined ? {} : { delayMs: input.delayMs }),
|
|
136
|
+
};
|
|
137
|
+
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, options);
|
|
138
|
+
if (!outcome.enqueued) ctx.ports.logger.warn(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued`);
|
|
139
|
+
return outcome.enqueued;
|
|
140
|
+
} catch (error) {
|
|
141
|
+
ctx.ports.logger.warn(
|
|
142
|
+
`${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued: ` +
|
|
143
|
+
(error instanceof Error ? error.message : String(error)),
|
|
144
|
+
);
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The engine's Logistics half (`MarketplaceEngine` extends it). */
|
|
150
|
+
export interface MarketplaceLogisticsEngine {
|
|
151
|
+
/**
|
|
152
|
+
* The store's own courier reached a step (FUT-6166): ONE enqueue of the
|
|
153
|
+
* `marketplace.outbound` job, action `logistics`, which sends every step
|
|
154
|
+
* still owed up to it. Never throws. True when the queue took it.
|
|
155
|
+
*/
|
|
156
|
+
informLogistics(input: InformLogisticsInput): Promise<boolean>;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function logisticsEngine(ctx: EngineContext): MarketplaceLogisticsEngine {
|
|
160
|
+
return { informLogistics: (input) => informLogistics(ctx, input) };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** What the job reads of the acceptance row. */
|
|
164
|
+
interface LogisticsJobRow {
|
|
165
|
+
confirmedAt?: Date | null;
|
|
166
|
+
confirmFailedAt?: Date | null;
|
|
167
|
+
orderId: string;
|
|
168
|
+
provider: string;
|
|
169
|
+
status: string;
|
|
170
|
+
cancellationStatus: string | null;
|
|
171
|
+
deliveredBy: string | null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
type LogisticsJobOutcome =
|
|
175
|
+
| { kind: "skipped"; reason: string }
|
|
176
|
+
| { kind: "done"; action: "logistics" }
|
|
177
|
+
| { kind: "failed"; action: "logistics"; reason: string };
|
|
178
|
+
|
|
179
|
+
interface LogisticsJobDeps {
|
|
180
|
+
attempt: { attempt: number; maxAttempts: number };
|
|
181
|
+
ref: OutboundOrderRef;
|
|
182
|
+
retryError: (message: string) => Error;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const skipped = (reason: string): LogisticsJobOutcome => ({ kind: "skipped", reason });
|
|
186
|
+
|
|
187
|
+
/** Why the order is not one to report, or null. */
|
|
188
|
+
function orderSkip(row: LogisticsJobRow, adapter: MarketplaceAdapter): string | null {
|
|
189
|
+
if (!adapter.logistics) return "the marketplace has no Logistics half";
|
|
190
|
+
if (row.deliveredBy !== "MERCHANT") return "the store does not carry this order";
|
|
191
|
+
if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
|
|
192
|
+
const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
|
|
193
|
+
return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* As the status job (FUT-5673): a marketplace that wants its steps after the
|
|
198
|
+
* store's confirm gets none before it. Still owed: retried while attempts are
|
|
199
|
+
* left; failed or the last attempt: skipped.
|
|
200
|
+
*/
|
|
201
|
+
function confirmSkip(row: LogisticsJobRow, adapter: MarketplaceAdapter, deps: LogisticsJobDeps): string | null {
|
|
202
|
+
if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
|
|
203
|
+
if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
|
|
204
|
+
if (deps.attempt.attempt < deps.attempt.maxAttempts) throw deps.retryError(`logistics for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
|
|
205
|
+
return "the store's confirm has not reached the marketplace";
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The Logistics app's credentials, or null when the host configured none. */
|
|
209
|
+
async function logisticsAppOf(ctx: EngineContext, provider: string, environment: "SANDBOX" | "PRODUCTION"): Promise<MarketplaceCredentials | null> {
|
|
210
|
+
const port = ctx.ports.logisticsCredentials;
|
|
211
|
+
if (!port) return null;
|
|
212
|
+
const credentials = await port(provider, environment);
|
|
213
|
+
return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** The store's connection environment, or why there is none. */
|
|
217
|
+
async function environmentOf(
|
|
218
|
+
ctx: EngineContext,
|
|
219
|
+
clientId: string,
|
|
220
|
+
provider: string,
|
|
221
|
+
): Promise<{ environment: OutboundConnection["environment"] } | { missing: string }> {
|
|
222
|
+
try {
|
|
223
|
+
const connection = await readOutboundConnection(ctx, clientId, provider);
|
|
224
|
+
return connection ? { environment: connection.environment } : { missing: "no credentials on file" };
|
|
225
|
+
} catch (error) {
|
|
226
|
+
return { missing: `credentials do not open: ${error instanceof Error ? error.message : String(error)}` };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** The steps up to `target`, in order. */
|
|
231
|
+
function chainTo(target: LogisticsStep): LogisticsStep[] {
|
|
232
|
+
return LOGISTICS_STEPS.slice(0, LOGISTICS_STEPS.indexOf(target) + 1);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
interface ChainRun {
|
|
236
|
+
ctx: EngineContext;
|
|
237
|
+
table: NonNullable<ReturnType<typeof statusTable>>;
|
|
238
|
+
payload: OutboundJobPayload;
|
|
239
|
+
row: LogisticsJobRow;
|
|
240
|
+
call: AdapterCallContext;
|
|
241
|
+
logistics: MarketplaceLogistics;
|
|
242
|
+
/** The courier, read before any claim; null once ASSIGNED was SENT (no later step needs him). */
|
|
243
|
+
driver: LogisticsDriver | null;
|
|
244
|
+
key: string;
|
|
245
|
+
deps: LogisticsJobDeps;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Wait for another run's claim: retried while attempts are left. On the last
|
|
250
|
+
* attempt this run's own target is left owed (SENDING under its key), so the
|
|
251
|
+
* outbound sweep re-queues it once the other run is done, and no move is lost.
|
|
252
|
+
*/
|
|
253
|
+
async function waitOrSkip(run: ChainRun, target: LogisticsStep, reason: string): Promise<LogisticsJobOutcome> {
|
|
254
|
+
if (run.deps.attempt.attempt < run.deps.attempt.maxAttempts) throw run.deps.retryError(`logistics for order ${run.row.orderId}: ${reason}`);
|
|
255
|
+
await claimStep(run, target, undefined);
|
|
256
|
+
return skipped(reason);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Send one step under a claim this run holds. */
|
|
260
|
+
async function send(run: ChainRun, step: LogisticsStep): Promise<OutboundResult | { kind: "invalid"; reason: string }> {
|
|
261
|
+
if (step !== "ASSIGNED") return run.logistics.step(run.call, run.deps.ref, step);
|
|
262
|
+
if (!run.driver) return { kind: "invalid", reason: "the host names no courier for this order" };
|
|
263
|
+
return run.logistics.assignDriver(run.call, run.deps.ref, run.driver);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Stamp a step's answer: SENT, a thrown retry, or FAILED (which stops the chain). */
|
|
267
|
+
async function settle(run: ChainRun, step: LogisticsStep, result: OutboundResult | { kind: "invalid"; reason: string }): Promise<string | null> {
|
|
268
|
+
const where = { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key };
|
|
269
|
+
if (result.kind === "accepted") {
|
|
270
|
+
await settleStatusRow(run.table, where, "SENT");
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
|
|
274
|
+
if (result.kind === "retry" && run.deps.attempt.attempt < run.deps.attempt.maxAttempts) {
|
|
275
|
+
throw run.deps.retryError(`logistics ${step} for order ${run.row.orderId}: ${reason}`);
|
|
276
|
+
}
|
|
277
|
+
await settleStatusRow(run.table, where, "FAILED");
|
|
278
|
+
run.ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${step} for order ${run.row.orderId} failed: ${reason}`);
|
|
279
|
+
return reason;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Claim one step, or say why this run does not send it ("sent": it already went). */
|
|
283
|
+
async function claimStep(run: ChainRun, step: LogisticsStep, found: StatusRow | undefined): Promise<"mine" | "sent" | { stop: string } | { wait: string }> {
|
|
284
|
+
if (found?.state === "SENT") return "sent";
|
|
285
|
+
if (found?.state === "FAILED") return { stop: `${step} failed earlier` };
|
|
286
|
+
if (found?.state === "SENDING") return found.claimKey === run.key ? "mine" : { wait: `${step} is being sent by another run` };
|
|
287
|
+
const claimed = await insertStatusRow(run.table, {
|
|
288
|
+
clientId: run.payload.clientId,
|
|
289
|
+
orderId: run.row.orderId,
|
|
290
|
+
provider: run.row.provider,
|
|
291
|
+
step: rowStep(step),
|
|
292
|
+
source: "STORE",
|
|
293
|
+
state: "SENDING",
|
|
294
|
+
claimKey: run.key,
|
|
295
|
+
});
|
|
296
|
+
return claimed ? "mine" : { wait: `another run holds the claim on ${step}` };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** The Logistics app's call context for this order, or why nothing is sent. */
|
|
300
|
+
export async function logisticsCallContext(ctx: EngineContext, clientId: string, provider: string): Promise<AdapterCallContext | string> {
|
|
301
|
+
const connection = await environmentOf(ctx, clientId, provider);
|
|
302
|
+
if ("missing" in connection) return connection.missing;
|
|
303
|
+
const app = await logisticsAppOf(ctx, provider, connection.environment);
|
|
304
|
+
if (!app) return "no Logistics app credentials are configured";
|
|
305
|
+
return { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), environment: connection.environment, credentials: app };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** An earlier step FAILED: fail what this run still holds of the chain, so the sweep stops re-queuing it. */
|
|
309
|
+
async function stopChain(run: ChainRun, chain: readonly LogisticsStep[], reason: string): Promise<LogisticsJobOutcome> {
|
|
310
|
+
for (const step of chain) await settleStatusRow(run.table, { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key }, "FAILED");
|
|
311
|
+
return { kind: "failed", action: "logistics", reason };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* The courier, read before any claim while ASSIGNED is still owed: once it went,
|
|
316
|
+
* the later steps need nobody (a host may clear the courier on a later move).
|
|
317
|
+
* "none": the order has no courier now, a dispatch undone in the host's window.
|
|
318
|
+
*/
|
|
319
|
+
async function courierWhileOwed(
|
|
320
|
+
ctx: EngineContext,
|
|
321
|
+
table: ChainRun["table"],
|
|
322
|
+
payload: OutboundJobPayload,
|
|
323
|
+
orderId: string,
|
|
324
|
+
): Promise<LogisticsDriver | null | "none"> {
|
|
325
|
+
const [assigned] = await readStatusRows(table, orderId, [rowStep("ASSIGNED")]);
|
|
326
|
+
if (assigned?.state === "SENT") return null;
|
|
327
|
+
return (await ctx.ports.order.logisticsDriver?.call(ctx.ports.order, payload.clientId, orderId)) ?? "none";
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** No courier now: skipped, never failed, and this run lets go of its claims so a later dispatch sends. */
|
|
331
|
+
async function releaseHeld(ctx: EngineContext, table: ChainRun["table"], orderId: string, chain: readonly LogisticsStep[], key: string): Promise<LogisticsJobOutcome> {
|
|
332
|
+
await table.deleteMany?.({ where: { orderId, step: { in: chain.map(rowStep) }, state: "SENDING", claimKey: key } });
|
|
333
|
+
ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics for order ${orderId} not sent: the host names no courier for it now`);
|
|
334
|
+
return skipped("the host names no courier for this order");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Claim and send each step of the chain in order; stops at the first failure or wait. */
|
|
338
|
+
async function runChain(run: ChainRun, chain: readonly LogisticsStep[]): Promise<LogisticsJobOutcome> {
|
|
339
|
+
const rows = await readStatusRows(run.table, run.row.orderId, chain.map(rowStep));
|
|
340
|
+
for (const step of chain) {
|
|
341
|
+
const claim = await claimStep(run, step, rows.find((found) => found.step === rowStep(step)));
|
|
342
|
+
if (claim === "sent") continue;
|
|
343
|
+
if (typeof claim === "object") return "wait" in claim ? waitOrSkip(run, chain.at(-1)!, claim.wait) : stopChain(run, chain, claim.stop);
|
|
344
|
+
const failed = await settle(run, step, await send(run, step));
|
|
345
|
+
if (failed) return stopChain(run, chain, failed);
|
|
346
|
+
}
|
|
347
|
+
return { kind: "done", action: "logistics" };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Run one `logistics` job. `row` is the acceptance the outbound job already read. */
|
|
351
|
+
export async function runLogistics(
|
|
352
|
+
ctx: EngineContext,
|
|
353
|
+
payload: OutboundJobPayload,
|
|
354
|
+
row: LogisticsJobRow,
|
|
355
|
+
adapter: MarketplaceAdapter,
|
|
356
|
+
deps: LogisticsJobDeps,
|
|
357
|
+
): Promise<LogisticsJobOutcome> {
|
|
358
|
+
const target = payload.logisticsStep;
|
|
359
|
+
if (!target || !LOGISTICS_STEPS.includes(target)) return skipped("a logistics call names no step");
|
|
360
|
+
const stopped = orderSkip(row, adapter) ?? confirmSkip(row, adapter, deps);
|
|
361
|
+
if (stopped) return skipped(stopped);
|
|
362
|
+
const table = statusTable(await ctx.ports.db());
|
|
363
|
+
if (!table) return skipped("the host has not composed the status model");
|
|
364
|
+
const call = await logisticsCallContext(ctx, payload.clientId, row.provider);
|
|
365
|
+
if (typeof call === "string") {
|
|
366
|
+
ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${target} for order ${row.orderId} not sent: ${call}`);
|
|
367
|
+
return skipped(call);
|
|
368
|
+
}
|
|
369
|
+
const chain = chainTo(target);
|
|
370
|
+
const key = payload.claimKey ?? "";
|
|
371
|
+
const driver = await courierWhileOwed(ctx, table, payload, row.orderId);
|
|
372
|
+
if (driver === "none") return releaseHeld(ctx, table, row.orderId, chain, key);
|
|
373
|
+
return runChain({ ctx, table, payload, row, call, logistics: adapter.logistics!, driver, key, deps }, chain);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* The last attempt died on a throw: every SENDING claim of this run is FAILED,
|
|
378
|
+
* so nothing stays owed, and the failure is logged.
|
|
379
|
+
*/
|
|
380
|
+
export async function failLogisticsJob(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<LogisticsJobOutcome> {
|
|
381
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
382
|
+
const table = statusTable(await ctx.ports.db());
|
|
383
|
+
for (const step of table && payload.logisticsStep ? chainTo(payload.logisticsStep) : []) {
|
|
384
|
+
await settleStatusRow(table!, { orderId: payload.orderId, step: rowStep(step), claimKey: payload.claimKey ?? "" }, "FAILED");
|
|
385
|
+
}
|
|
386
|
+
ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${payload.logisticsStep ?? ""} for order ${payload.orderId} failed: ${reason}`);
|
|
387
|
+
return { kind: "failed", action: "logistics", reason };
|
|
388
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { MarketplaceAdapter, StatusStep } from "./adapter";
|
|
2
|
+
import type { LogisticsStep } from "./logistics";
|
|
2
3
|
import type { EngineContext } from "./ports";
|
|
3
4
|
import type { MarketplaceProvider } from "./types";
|
|
4
5
|
|
|
@@ -20,7 +21,7 @@ export const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
|
|
|
20
21
|
* step of the order the store reached (`status`, FUT-4653), or the pickup code
|
|
21
22
|
* the store checked at the hand-over (`validatePickupCode`, FUT-5665).
|
|
22
23
|
*/
|
|
23
|
-
export type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode";
|
|
24
|
+
export type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode" | "logistics";
|
|
24
25
|
|
|
25
26
|
/** The outbound job's payload. Identifiers only. */
|
|
26
27
|
export interface OutboundJobPayload {
|
|
@@ -40,6 +41,8 @@ export interface OutboundJobPayload {
|
|
|
40
41
|
* job needs to send, which no log line prints.
|
|
41
42
|
*/
|
|
42
43
|
code?: string;
|
|
44
|
+
/** OPTIONAL (FUT-6166). The step a `logistics` call sends up to; absent on every other action. */
|
|
45
|
+
logisticsStep?: LogisticsStep;
|
|
43
46
|
}
|
|
44
47
|
|
|
45
48
|
/** The dedupe key: at most one queued call per (order, action). */
|
|
@@ -57,6 +60,8 @@ function ableTo(adapter: MarketplaceAdapter, payload: OutboundJobPayload): boole
|
|
|
57
60
|
switch (payload.action) {
|
|
58
61
|
case "status":
|
|
59
62
|
return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
|
|
63
|
+
case "logistics":
|
|
64
|
+
return Boolean(adapter.logistics);
|
|
60
65
|
case "confirm":
|
|
61
66
|
return adapter.capabilities.apiConfirm;
|
|
62
67
|
default:
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { NO_STANDING_REQUEST } from "./cancellation";
|
|
2
|
+
import { LOGISTICS_ROW_PREFIX, type LogisticsStep } from "./logistics";
|
|
2
3
|
import { sweepCatalogue } from "./catalogue-sweep";
|
|
3
4
|
import { sweepDisputes } from "./dispute-job";
|
|
4
5
|
import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
|
|
@@ -86,14 +87,16 @@ function sweepDedupeKey(action: OutboundAction, orderId: string, now: Date, step
|
|
|
86
87
|
async function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: OutboundAction, now: Date): Promise<number> {
|
|
87
88
|
let queued = 0;
|
|
88
89
|
for (const row of rows) {
|
|
90
|
+
// A Logistics claim (FUT-6166) is the `logistics` job's, sent up to its own step.
|
|
91
|
+
const logistics = row.step?.startsWith(LOGISTICS_ROW_PREFIX) === true;
|
|
89
92
|
const payload = {
|
|
90
93
|
clientId: row.clientId,
|
|
91
94
|
orderId: row.orderId,
|
|
92
|
-
action,
|
|
93
|
-
...(row.step ? { step: row.step as StatusStep } : {}),
|
|
95
|
+
action: logistics ? ("logistics" as const) : action,
|
|
96
|
+
...(logistics ? { logisticsStep: row.step!.slice(LOGISTICS_ROW_PREFIX.length) as LogisticsStep } : row.step ? { step: row.step as StatusStep } : {}),
|
|
94
97
|
...(row.claimKey === undefined ? {} : { claimKey: row.claimKey }),
|
|
95
98
|
};
|
|
96
|
-
if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now, row.step))) queued += 1;
|
|
99
|
+
if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(payload.action, row.orderId, now, row.step))) queued += 1;
|
|
97
100
|
}
|
|
98
101
|
return queued;
|
|
99
102
|
}
|
|
@@ -168,10 +171,12 @@ async function sweepStatus(ctx: EngineContext, now: Date): Promise<{ requeued: n
|
|
|
168
171
|
})) as OwedRow[];
|
|
169
172
|
// The stale claim is TAKEN OVER under a fresh key, predicated on the old one, before the job
|
|
170
173
|
// is queued under the new: a job still alive under the old key can then settle or fail
|
|
171
|
-
// nothing, and a second sweep pass finds nothing to take.
|
|
174
|
+
// nothing, and a second sweep pass finds nothing to take. The key names the row's step: two
|
|
175
|
+
// rows of one order taken over in one pass must not share a claim (a logistics chain owns
|
|
176
|
+
// every SENDING row under its own key, so a shared one would send the overlap twice).
|
|
172
177
|
const claimed: OwedRow[] = [];
|
|
173
178
|
for (const row of owed) {
|
|
174
|
-
const fresh = `sweep:${now.getTime()}`;
|
|
179
|
+
const fresh = `sweep:${now.getTime()}:${row.step}`;
|
|
175
180
|
const taken = await table.updateMany({
|
|
176
181
|
where: { orderId: row.orderId, step: row.step, state: "SENDING", claimKey: row.claimKey, updatedAt: { lt: stale } },
|
|
177
182
|
data: { claimKey: fresh },
|
package/src/core/outbound.ts
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
import { readOutboundConnection, type OutboundConnection } from "./integration";
|
|
11
11
|
import type { OutboundJobPayload } from "./outbound-queue";
|
|
12
12
|
import { runPickupCode, tellPickupCode } from "./pickup-code";
|
|
13
|
-
import { failStatusRow, runStatus } from "./status-job";
|
|
13
|
+
import { failLogisticsJob, failStatusRow, runLogistics, runStatus } from "./status-job";
|
|
14
14
|
import { failAsTimeout } from "./outbound-sweep";
|
|
15
15
|
import type { CancellationFailureReason, EngineContext } from "./ports";
|
|
16
16
|
import { resolveReason } from "./registry";
|
|
@@ -374,10 +374,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
|
|
|
374
374
|
if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
|
|
375
375
|
const deps = { attempt, ref: refOf(row), retryError: (m: string) => new OutboundRetryError(m) };
|
|
376
376
|
if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
|
|
377
|
+
if (payload.action === "logistics") return runLogistics(ctx, payload, row, adapter, deps);
|
|
377
378
|
if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
|
|
378
|
-
return payload.action === "confirm"
|
|
379
|
-
? runConfirm(ctx, payload, row, adapter, attempt)
|
|
380
|
-
: runCancellation(ctx, payload, row, adapter, attempt);
|
|
379
|
+
return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
|
|
381
380
|
}
|
|
382
381
|
|
|
383
382
|
/**
|
|
@@ -395,6 +394,6 @@ export async function runOutbound(
|
|
|
395
394
|
return await runOnce(ctx, payload, attempt);
|
|
396
395
|
} catch (error) {
|
|
397
396
|
if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;
|
|
398
|
-
return stampLastAttemptFailure(ctx, payload, error);
|
|
397
|
+
return payload.action === "logistics" ? failLogisticsJob(ctx, payload, error) : stampLastAttemptFailure(ctx, payload, error);
|
|
399
398
|
}
|
|
400
399
|
}
|
package/src/core/pipeline.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { applyDeliveryCodeRequest } from "./delivery-code";
|
|
1
2
|
import { cancelAcceptance } from "./acceptance";
|
|
2
3
|
import { failCancellationRequest } from "./cancellation";
|
|
3
4
|
import { awaitOrderBody, merchantMismatch, requeueOwedFetch } from "./fetch-order";
|
|
@@ -46,6 +47,8 @@ export type DeliveryOutcome =
|
|
|
46
47
|
| { kind: "ingested"; orderId: string; unmappedSkus: string[] }
|
|
47
48
|
/** A lifecycle event moved the order forward, through the host's `onLifecycle` (FUT-4653). */
|
|
48
49
|
| { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
|
|
50
|
+
/** The marketplace asked the customer's delivery code; the host stored it (FUT-6167). */
|
|
51
|
+
| { kind: "deliveryCodeRequested"; orderId: string }
|
|
49
52
|
/** A courier event's facts were stored by the host's `onCourier` (FUT-5665). */
|
|
50
53
|
| { kind: "courier"; orderId: string; step: MarketplaceCourierStep }
|
|
51
54
|
/**
|
|
@@ -208,7 +211,9 @@ async function followMarketplace(
|
|
|
208
211
|
const disputed = await applyDisputeEvent(ctx, inboxId, clientId, event);
|
|
209
212
|
if (disputed) return disputed;
|
|
210
213
|
const confirmed = await applyMarketplaceConfirmation(ctx, inboxId, clientId, event);
|
|
211
|
-
|
|
214
|
+
if (confirmed) return confirmed;
|
|
215
|
+
const codeRequested = await applyDeliveryCodeRequest(ctx, inboxId, clientId, event);
|
|
216
|
+
return codeRequested ?? followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
|
|
212
217
|
}
|
|
213
218
|
|
|
214
219
|
/** An event with no order body is understood and ignored; one that carries an order is ingested. */
|
package/src/core/ports.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { MarketplaceCourierAnswer, MarketplaceCourierFacts, PickupCodeValid
|
|
|
5
5
|
import type { MarketplaceDisputeChange, MarketplaceDisputeDelegate } from "./dispute-port";
|
|
6
6
|
import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
|
|
7
7
|
import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
|
|
8
|
+
import type { LogisticsOrderPort, LogisticsPorts } from "./logistics";
|
|
8
9
|
import type {
|
|
9
10
|
CancellationFailureReason,
|
|
10
11
|
MarketplaceAdmission,
|
|
@@ -114,6 +115,8 @@ export interface MarketplaceDb {
|
|
|
114
115
|
findMany(args: unknown): Promise<unknown[]>;
|
|
115
116
|
create(args: unknown): Promise<unknown>;
|
|
116
117
|
updateMany(args: unknown): Promise<{ count: number }>;
|
|
118
|
+
/** OPTIONAL (FUT-6166): a Logistics run lets go of its claims when the order has no courier now. */
|
|
119
|
+
deleteMany?(args: unknown): Promise<{ count: number }>;
|
|
117
120
|
};
|
|
118
121
|
marketplaceLinkAttempt?: MarketplaceLinkAttemptDelegate; // OPTIONAL, as above; absent: no linking (FUT-5613).
|
|
119
122
|
/** OPTIONAL (FUT-6099): the buyer's disputes, migration `20261203190000_marketplace_disputes`. */
|
|
@@ -142,7 +145,7 @@ export interface MarketplaceAdmissionRequest {
|
|
|
142
145
|
* transition has already been claimed and committed when they are called, and
|
|
143
146
|
* a host that fails its half must not un-decide the acceptance.
|
|
144
147
|
*/
|
|
145
|
-
export interface MarketplaceOrderPort {
|
|
148
|
+
export interface MarketplaceOrderPort extends LogisticsOrderPort {
|
|
146
149
|
/**
|
|
147
150
|
* Judge a decision BEFORE its claim commits, inside the claim's
|
|
148
151
|
* transaction: the stock check (and the draw) of an accept, anything the
|
|
@@ -333,7 +336,7 @@ export interface MarketplaceCataloguePort {
|
|
|
333
336
|
}
|
|
334
337
|
|
|
335
338
|
/** Everything the host plugs in. */
|
|
336
|
-
export interface MarketplacePorts {
|
|
339
|
+
export interface MarketplacePorts extends LogisticsPorts {
|
|
337
340
|
db: () => Promise<MarketplaceDb>;
|
|
338
341
|
/**
|
|
339
342
|
* Run `fn` in ONE database transaction and hand it the transaction's client
|
package/src/core/status-job.ts
CHANGED
|
@@ -5,6 +5,9 @@ import type { EngineContext, MarketplaceDb } from "./ports";
|
|
|
5
5
|
import { insertStatusRow, readStatusRows, settleStatusRow, statusTable, type StatusRow } from "./status-store";
|
|
6
6
|
import type { MarketplaceDeliveredBy } from "./types";
|
|
7
7
|
|
|
8
|
+
// The Logistics job (FUT-6166) is dispatched beside this one by the outbound job.
|
|
9
|
+
export { failLogisticsJob, runLogistics } from "./logistics";
|
|
10
|
+
|
|
8
11
|
/**
|
|
9
12
|
* The status job's body (FUT-4653), `marketplace.outbound` with action
|
|
10
13
|
* `status`: tell the marketplace the order reached a step.
|
package/src/core/status-store.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { StatusStep } from "./adapter";
|
|
2
|
+
import type { LogisticsStep } from "./logistics";
|
|
2
3
|
import type { EngineContext, MarketplaceDb } from "./ports";
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -10,7 +11,7 @@ import type { EngineContext, MarketplaceDb } from "./ports";
|
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
13
|
/** A step as the table holds it: the three the store informs, and the one only a marketplace announces. */
|
|
13
|
-
export type StatusRowStep = StatusStep | "CONCLUDED"
|
|
14
|
+
export type StatusRowStep = StatusStep | "CONCLUDED" | `LOGISTICS_${LogisticsStep}`;
|
|
14
15
|
|
|
15
16
|
/** Where a row stands. */
|
|
16
17
|
export type StatusRowState = "SENDING" | "SENT" | "FAILED" | "NOTED";
|
package/src/core/types.ts
CHANGED
|
@@ -350,6 +350,8 @@ export interface NormalizedEvent {
|
|
|
350
350
|
* host's admit, with no confirm sent back. Carries no order body.
|
|
351
351
|
*/
|
|
352
352
|
marketplaceConfirmed?: boolean;
|
|
353
|
+
/** The marketplace asked the customer's delivery code for the order (FUT-6167). */
|
|
354
|
+
deliveryCodeRequested?: boolean;
|
|
353
355
|
/**
|
|
354
356
|
* OPTIONAL (FUT-6099). A dispute the marketplace opened or closed on this
|
|
355
357
|
* order (iFood's HSD / HSS). Carries no order body, and never moves the
|
package/src/ifood/index.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { IFOOD_CATALOGUE } from "./catalogue";
|
|
|
4
4
|
import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
|
|
5
5
|
import { IFOOD_COURIER } from "./courier";
|
|
6
6
|
import { IFOOD_DISPUTES } from "./disputes";
|
|
7
|
+
import { IFOOD_LOGISTICS } from "./logistics";
|
|
7
8
|
import { ifoodFetchOrder } from "./fetch-order";
|
|
8
9
|
import { IFOOD_APP_LINKING } from "./app-linking";
|
|
9
10
|
import { IFOOD_LINKING } from "./linking";
|
|
@@ -121,6 +122,7 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
121
122
|
courier: IFOOD_COURIER,
|
|
122
123
|
// The buyer's disputes: accept, reject with iFood's reason, or one of its alternatives (FUT-6099).
|
|
123
124
|
disputes: IFOOD_DISPUTES,
|
|
125
|
+
logistics: IFOOD_LOGISTICS,
|
|
124
126
|
// No per-order deep link is known, so the portal, where a live order is
|
|
125
127
|
// on the first screen.
|
|
126
128
|
appLink: () => IFOOD_PORTAL_URL,
|
|
@@ -138,6 +140,7 @@ export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
|
|
|
138
140
|
export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
|
|
139
141
|
export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
|
|
140
142
|
export {
|
|
143
|
+
IFOOD_LOGISTICS,
|
|
141
144
|
IFOOD_LOGISTICS_STEPS,
|
|
142
145
|
IFOOD_LOGISTICS_VEHICLES,
|
|
143
146
|
ifoodLogisticsAssignDriver,
|
package/src/ifood/logistics.ts
CHANGED
|
@@ -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
|
+
}
|