@12-apps/marketplace 1.12.0 → 1.14.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 +184 -0
- package/README.md +39 -4
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-nUyZpLzz.d.ts → adapter-szxo9ohc.d.ts} +84 -3
- package/dist/{chunk-L6FG6T4S.js → chunk-BNWRIR5J.js} +2 -2
- package/dist/{chunk-LACBT6NC.js → chunk-BTKVZAJI.js} +1 -1
- package/dist/chunk-BTKVZAJI.js.map +1 -0
- package/dist/{chunk-45ZVN5XI.js → chunk-MDXSVE7Q.js} +707 -255
- package/dist/chunk-MDXSVE7Q.js.map +1 -0
- package/dist/{chunk-MIPNQ7X5.js → chunk-R3BUW5PX.js} +53 -6
- package/dist/chunk-R3BUW5PX.js.map +1 -0
- package/dist/{client-Ctas7WCS.d.ts → client-CaZiG7Lw.d.ts} +1 -1
- package/dist/{engine-CIy9P7Cq.d.ts → engine-CgKBbk9J.d.ts} +127 -3
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +26 -3
- package/dist/ifood/index.js +301 -140
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +29 -5
- package/dist/index.js +54 -6
- 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 +4 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/index.d.ts +14 -5
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +17 -3
- package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
- package/src/core/acceptance.ts +12 -6
- package/src/core/acknowledge.ts +189 -0
- package/src/core/adapter.ts +76 -2
- package/src/core/cancellation.ts +10 -6
- package/src/core/conformity.ts +63 -0
- package/src/core/connection-stamp.ts +61 -0
- package/src/core/engine.ts +3 -2
- package/src/core/fetch-order.ts +54 -12
- package/src/core/ingest.ts +6 -0
- package/src/core/integration.ts +19 -4
- package/src/core/link-store.ts +2 -4
- package/src/core/marketplace-confirmed.ts +229 -0
- package/src/core/order-reasons.ts +119 -0
- package/src/core/outbound.ts +5 -1
- package/src/core/pipeline.ts +27 -1
- package/src/core/ports.ts +2 -0
- package/src/core/registry.ts +28 -2
- package/src/core/state.ts +10 -0
- package/src/core/status-job.ts +86 -3
- package/src/core/types.ts +6 -0
- package/src/ifood/fetch-order.ts +103 -0
- package/src/ifood/index.ts +31 -4
- package/src/ifood/normalize.ts +39 -3
- package/src/ifood/outbound.ts +131 -27
- package/src/index.ts +18 -0
- package/src/server/jobs.ts +57 -4
- package/src/server/webhook.ts +27 -4
- package/dist/chunk-45ZVN5XI.js.map +0 -1
- package/dist/chunk-LACBT6NC.js.map +0 -1
- package/dist/chunk-MIPNQ7X5.js.map +0 -1
- /package/dist/{chunk-L6FG6T4S.js.map → chunk-BNWRIR5J.js.map} +0 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { CancellationReason, OrderCancellationReason } from "./adapter";
|
|
2
|
+
import { readOutboundConnection } from "./integration";
|
|
3
|
+
import type { EngineContext, MarketplaceDb } from "./ports";
|
|
4
|
+
import { reasonsForOrder, storedReasons } from "./registry";
|
|
5
|
+
import type { MarketplaceProvider } from "./types";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* An order's own cancellation reasons (FUT-5984, iFood's
|
|
9
|
+
* `GET /order/v1.0/orders/{id}/cancellationReasons`): read once, in the
|
|
10
|
+
* `marketplace.cancellation-reasons` job queued after the ingest's commit, and
|
|
11
|
+
* kept on the acceptance row (`cancellation_reasons`) for the order's life.
|
|
12
|
+
* The adapter's static list is the fallback while, or when, that read did not
|
|
13
|
+
* land: a refusal is never held on the marketplace.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** The wire name, `<namespace>.<blueprint>`. */
|
|
17
|
+
export const MARKETPLACE_CANCELLATION_REASONS_JOB = "marketplace.cancellation-reasons";
|
|
18
|
+
|
|
19
|
+
/** The job's payload: identifiers only. */
|
|
20
|
+
export interface CancellationReasonsJobPayload {
|
|
21
|
+
clientId: string;
|
|
22
|
+
orderId: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What one run did. */
|
|
26
|
+
export type CancellationReasonsOutcome =
|
|
27
|
+
| { kind: "skipped"; reason: string }
|
|
28
|
+
| { kind: "done"; count: number }
|
|
29
|
+
| { kind: "failed"; reason: string };
|
|
30
|
+
|
|
31
|
+
/** Thrown so the queue retries. */
|
|
32
|
+
export class CancellationReasonsRetryError extends Error {
|
|
33
|
+
constructor(message: string) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "CancellationReasonsRetryError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Queue the read of a new order's reasons, when its marketplace lists them per order. Never throws. */
|
|
40
|
+
export async function enqueueOrderReasons(
|
|
41
|
+
ctx: EngineContext,
|
|
42
|
+
input: { clientId: string; orderId: string; provider: MarketplaceProvider },
|
|
43
|
+
): Promise<void> {
|
|
44
|
+
if (!ctx.registry.get(input.provider)?.orderCancellationReasons) return;
|
|
45
|
+
const payload: CancellationReasonsJobPayload = { clientId: input.clientId, orderId: input.orderId };
|
|
46
|
+
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CANCELLATION_REASONS_JOB, payload, {
|
|
47
|
+
dedupeKey: `${MARKETPLACE_CANCELLATION_REASONS_JOB}:${input.orderId}`,
|
|
48
|
+
});
|
|
49
|
+
if (!outcome.enqueued) {
|
|
50
|
+
ctx.ports.logger.warn(
|
|
51
|
+
`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${input.orderId} was not queued; its reasons stay the static list` +
|
|
52
|
+
(outcome.reason ? ` (${outcome.reason})` : ""),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface ReasonsRow {
|
|
58
|
+
orderId: string;
|
|
59
|
+
provider: string;
|
|
60
|
+
externalOrderId: string;
|
|
61
|
+
cancellationReasons: unknown;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Keep a read list on the order; an empty one is not kept, so the static list stays (FUT-5984). */
|
|
65
|
+
async function keep(
|
|
66
|
+
ctx: EngineContext,
|
|
67
|
+
db: MarketplaceDb,
|
|
68
|
+
clientId: string,
|
|
69
|
+
orderId: string,
|
|
70
|
+
reasons: readonly OrderCancellationReason[],
|
|
71
|
+
): Promise<CancellationReasonsOutcome> {
|
|
72
|
+
if (reasons.length === 0) {
|
|
73
|
+
ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${orderId} got an empty list; it keeps the static reasons`);
|
|
74
|
+
return { kind: "skipped", reason: "the marketplace listed no reason" };
|
|
75
|
+
}
|
|
76
|
+
await db.marketplaceAcceptance.updateMany({ where: { orderId }, data: { cancellationReasons: reasons } });
|
|
77
|
+
ctx.ports.publishChanged(clientId);
|
|
78
|
+
return { kind: "done", count: reasons.length };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Run one read. Throws {@link CancellationReasonsRetryError} for a retryable answer before the last attempt. */
|
|
82
|
+
export async function runCancellationReasons(
|
|
83
|
+
ctx: EngineContext,
|
|
84
|
+
payload: CancellationReasonsJobPayload,
|
|
85
|
+
attempt: { attempt: number; maxAttempts: number },
|
|
86
|
+
): Promise<CancellationReasonsOutcome> {
|
|
87
|
+
const db = await ctx.ports.db();
|
|
88
|
+
const row = (await db.marketplaceAcceptance.findFirst({
|
|
89
|
+
where: { orderId: payload.orderId, clientId: payload.clientId },
|
|
90
|
+
select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true },
|
|
91
|
+
})) as ReasonsRow | null;
|
|
92
|
+
if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
|
|
93
|
+
if (storedReasons(row.cancellationReasons) !== null) return { kind: "skipped", reason: "the order's reasons are already kept" };
|
|
94
|
+
const read = ctx.registry.get(row.provider)?.orderCancellationReasons;
|
|
95
|
+
if (!read) return { kind: "skipped", reason: `${row.provider} lists no reasons per order` };
|
|
96
|
+
const connection = await readOutboundConnection(ctx, payload.clientId, row.provider).catch(() => null);
|
|
97
|
+
if (!connection) return { kind: "skipped", reason: "no credentials on file" };
|
|
98
|
+
|
|
99
|
+
const result = await read({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, row);
|
|
100
|
+
if (result.kind === "reasons") return keep(ctx, db, payload.clientId, row.orderId, result.reasons);
|
|
101
|
+
const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
|
|
102
|
+
if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
|
|
103
|
+
throw new CancellationReasonsRetryError(`reasons of order ${row.orderId}: ${reason}`);
|
|
104
|
+
}
|
|
105
|
+
// The static list stays this order's reasons: a refusal never waits on the marketplace.
|
|
106
|
+
ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${row.orderId} keeps the static reasons: ${reason}`);
|
|
107
|
+
return { kind: "failed", reason };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** One order's reasons, for the refusal dialog: its own, else the static list. Empty for an unknown order. */
|
|
111
|
+
export async function readOrderReasons(ctx: EngineContext, clientId: string, orderId: string): Promise<readonly CancellationReason[]> {
|
|
112
|
+
const db = await ctx.ports.db();
|
|
113
|
+
const row = (await db.marketplaceAcceptance.findFirst({
|
|
114
|
+
where: { orderId, clientId },
|
|
115
|
+
select: { provider: true, cancellationReasons: true },
|
|
116
|
+
})) as { provider: string; cancellationReasons: unknown } | null;
|
|
117
|
+
const adapter = row ? ctx.registry.get(row.provider) : null;
|
|
118
|
+
return adapter ? reasonsForOrder(adapter, row?.cancellationReasons) : [];
|
|
119
|
+
}
|
package/src/core/outbound.ts
CHANGED
|
@@ -70,6 +70,7 @@ interface OutboundRow {
|
|
|
70
70
|
cancellationOffendingSkus: unknown;
|
|
71
71
|
cancellationRequestedAt: Date | null;
|
|
72
72
|
preparationMinutes: number | null;
|
|
73
|
+
cancellationReasons: unknown;
|
|
73
74
|
createdAt: Date;
|
|
74
75
|
}
|
|
75
76
|
|
|
@@ -87,6 +88,7 @@ const ROW_SELECT = {
|
|
|
87
88
|
cancellationOffendingSkus: true,
|
|
88
89
|
cancellationRequestedAt: true,
|
|
89
90
|
preparationMinutes: true,
|
|
91
|
+
cancellationReasons: true,
|
|
90
92
|
createdAt: true,
|
|
91
93
|
} as const;
|
|
92
94
|
|
|
@@ -303,7 +305,9 @@ async function runCancellation(
|
|
|
303
305
|
await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
|
|
304
306
|
return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
|
|
305
307
|
}
|
|
306
|
-
|
|
308
|
+
// The order's own list, else the static list the code was validated against when the order's
|
|
309
|
+
// was not read yet (FUT-5984): a list stored in between never turns a valid request into ours.
|
|
310
|
+
const reason = resolveReason(adapter, row.cancellationReasonCode, row.cancellationReasons) ?? resolveReason(adapter, row.cancellationReasonCode);
|
|
307
311
|
const connection = await connectionFor(ctx, payload.clientId, row.provider);
|
|
308
312
|
let result: OutboundResult;
|
|
309
313
|
// A stored reason that is not the marketplace's own was never sent: our side (UNREACHABLE).
|
package/src/core/pipeline.ts
CHANGED
|
@@ -14,6 +14,8 @@ import type {
|
|
|
14
14
|
NormalizedMarketplaceOrder,
|
|
15
15
|
} from "./types";
|
|
16
16
|
import { followCourierAndLifecycle } from "./courier";
|
|
17
|
+
import { enqueueAcknowledge } from "./acknowledge";
|
|
18
|
+
import { applyMarketplaceConfirmation } from "./marketplace-confirmed";
|
|
17
19
|
|
|
18
20
|
/**
|
|
19
21
|
* One delivery, start to finish: normalize → inbox → ingest.
|
|
@@ -45,6 +47,12 @@ export type DeliveryOutcome =
|
|
|
45
47
|
| { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
|
|
46
48
|
/** A courier event's facts were stored by the host's `onCourier` (FUT-5665). */
|
|
47
49
|
| { kind: "courier"; orderId: string; step: MarketplaceCourierStep }
|
|
50
|
+
/**
|
|
51
|
+
* The store accepted it in the marketplace's own app (FUT-5653): `accepted`
|
|
52
|
+
* when the host admitted it here too, else it waits AWAITING for a person
|
|
53
|
+
* (with the host's `refusal`, when it refused), never expired.
|
|
54
|
+
*/
|
|
55
|
+
| { kind: "confirmedByMarketplace"; orderId: string; accepted: boolean; refusal?: { code: string; message: string } }
|
|
48
56
|
| { kind: "cancelled" }
|
|
49
57
|
| { kind: "cancellationFailed" }
|
|
50
58
|
/** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
|
|
@@ -80,6 +88,8 @@ export async function processDelivery(
|
|
|
80
88
|
const { clientId, event, settings } = input;
|
|
81
89
|
const record = await recordInboxEvent(ctx, { clientId, event, payload: input.payload });
|
|
82
90
|
if (!record.fresh) return { kind: "duplicate" };
|
|
91
|
+
// The marketplace hears it was recorded, from a job after this commit (FUT-5984); a queue call only.
|
|
92
|
+
await enqueueAcknowledge(ctx, { clientId, provider: event.provider, inboxId: record.id });
|
|
83
93
|
|
|
84
94
|
if (!clientId || !settings) {
|
|
85
95
|
// Stored, not dropped, and the two reasons are kept apart because only one
|
|
@@ -175,11 +185,27 @@ async function applyEvent(
|
|
|
175
185
|
// lifecycle event (dispatched, collected, concluded) of an order we hold:
|
|
176
186
|
// with the connection's switch ON and a host that binds the hook, the order
|
|
177
187
|
// follows. Anything else falls through to "understood, nothing to do", as before.
|
|
178
|
-
const followed = await
|
|
188
|
+
const followed = await followMarketplace(ctx, inboxId, clientId, event, settings);
|
|
179
189
|
if (followed) return followed;
|
|
180
190
|
return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
|
|
181
191
|
}
|
|
182
192
|
|
|
193
|
+
/**
|
|
194
|
+
* What the marketplace says about an order it already gave us: the store
|
|
195
|
+
* accepted it in the marketplace's app (FUT-5653), or a courier or lifecycle
|
|
196
|
+
* step. Null for anything else.
|
|
197
|
+
*/
|
|
198
|
+
async function followMarketplace(
|
|
199
|
+
ctx: EngineContext,
|
|
200
|
+
inboxId: string,
|
|
201
|
+
clientId: string,
|
|
202
|
+
event: NormalizedEvent,
|
|
203
|
+
settings: IngestSettings,
|
|
204
|
+
): Promise<DeliveryOutcome | null> {
|
|
205
|
+
const confirmed = await applyMarketplaceConfirmation(ctx, inboxId, clientId, event);
|
|
206
|
+
return confirmed ?? followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
|
|
207
|
+
}
|
|
208
|
+
|
|
183
209
|
/** An event with no order body is understood and ignored; one that carries an order is ingested. */
|
|
184
210
|
async function ingestOrIgnore(
|
|
185
211
|
ctx: EngineContext,
|
package/src/core/ports.ts
CHANGED
|
@@ -67,6 +67,8 @@ export interface MarketplaceDb {
|
|
|
67
67
|
findMany(args: unknown): Promise<unknown[]>;
|
|
68
68
|
create(args: unknown): Promise<unknown>;
|
|
69
69
|
update(args: unknown): Promise<unknown>;
|
|
70
|
+
/** The acknowledgment's stamp (FUT-5984). */
|
|
71
|
+
updateMany(args: unknown): Promise<{ count: number }>;
|
|
70
72
|
};
|
|
71
73
|
marketplaceAcceptance: {
|
|
72
74
|
findFirst(args: unknown): Promise<unknown>;
|
package/src/core/registry.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CancellationReason, MarketplaceAdapter } from "./adapter";
|
|
1
|
+
import type { CancellationReason, MarketplaceAdapter, OrderCancellationReason } from "./adapter";
|
|
2
2
|
import { PROVIDER_ID_PATTERN, type MarketplaceProvider } from "./types";
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -75,6 +75,30 @@ export function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]):
|
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
/** The stored list, read defensively: anything that is not a list of codes is "not read". */
|
|
79
|
+
export function storedReasons(value: unknown): OrderCancellationReason[] | null {
|
|
80
|
+
// An empty list is "not read": every refusal would be refused, so the static list applies.
|
|
81
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
82
|
+
return value.flatMap((entry: unknown) => {
|
|
83
|
+
const { code, description } = (entry ?? {}) as { code?: unknown; description?: unknown };
|
|
84
|
+
return typeof code === "string" ? [{ code, description: typeof description === "string" ? description : code }] : [];
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The reasons an order may be refused or cancelled with: its own list when it
|
|
90
|
+
* was read (each labelled by the adapter's pack when the pack names the code,
|
|
91
|
+
* else by the marketplace's own words), else the adapter's static list.
|
|
92
|
+
*/
|
|
93
|
+
export function reasonsForOrder(adapter: MarketplaceAdapter, stored: unknown): readonly CancellationReason[] {
|
|
94
|
+
const own = storedReasons(stored);
|
|
95
|
+
if (own === null) return adapter.cancellationReasons();
|
|
96
|
+
const known = new Map(adapter.cancellationReasons().map((reason) => [reason.code, reason]));
|
|
97
|
+
return own.map(
|
|
98
|
+
(reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false },
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
78
102
|
/**
|
|
79
103
|
* The reason a refusal carries: the one named by `code`, or — when the store
|
|
80
104
|
* named none — the adapter's first. `null` when the code is not one of the
|
|
@@ -83,8 +107,10 @@ export function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]):
|
|
|
83
107
|
export function resolveReason(
|
|
84
108
|
adapter: MarketplaceAdapter,
|
|
85
109
|
code: string | null | undefined,
|
|
110
|
+
/** The order's own list (`cancellation_reasons`, FUT-5984); absent or unread: the static one. */
|
|
111
|
+
stored?: unknown,
|
|
86
112
|
): CancellationReason | null {
|
|
87
|
-
const reasons = adapter
|
|
113
|
+
const reasons = reasonsForOrder(adapter, stored);
|
|
88
114
|
if (code === null || code === undefined) return reasons[0] ?? null;
|
|
89
115
|
return reasons.find((reason) => reason.code === code) ?? null;
|
|
90
116
|
}
|
package/src/core/state.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
|
|
2
|
+
import type { CancellationReason } from "./adapter";
|
|
2
3
|
import type { CancellationFailureReason, EngineContext } from "./ports";
|
|
4
|
+
import { reasonsForOrder, storedReasons } from "./registry";
|
|
3
5
|
import type { MarketplaceProvider } from "./types";
|
|
4
6
|
|
|
5
7
|
/**
|
|
@@ -21,6 +23,11 @@ export interface MarketplaceOrderState {
|
|
|
21
23
|
cancellationFailure: CancellationFailureReason | null;
|
|
22
24
|
/** The adapter's app link, or null when no adapter is registered for it. */
|
|
23
25
|
appUrl: string | null;
|
|
26
|
+
/**
|
|
27
|
+
* This order's own reasons, read from the marketplace (FUT-5984); null while
|
|
28
|
+
* or when they were not read: the adapter's static `reasons(provider)` then.
|
|
29
|
+
*/
|
|
30
|
+
cancellationReasons: readonly CancellationReason[] | null;
|
|
24
31
|
}
|
|
25
32
|
|
|
26
33
|
interface StateRow {
|
|
@@ -34,6 +41,7 @@ interface StateRow {
|
|
|
34
41
|
cancellationStatus: string | null;
|
|
35
42
|
cancellationReasonCode: string | null;
|
|
36
43
|
cancellationFailureReason: string | null;
|
|
44
|
+
cancellationReasons: unknown;
|
|
37
45
|
}
|
|
38
46
|
|
|
39
47
|
/** The state of each of these orders that is a marketplace order, keyed by id. */
|
|
@@ -57,6 +65,7 @@ export async function readOrderStates(
|
|
|
57
65
|
cancellationStatus: true,
|
|
58
66
|
cancellationReasonCode: true,
|
|
59
67
|
cancellationFailureReason: true,
|
|
68
|
+
cancellationReasons: true,
|
|
60
69
|
},
|
|
61
70
|
})) as StateRow[];
|
|
62
71
|
return new Map(
|
|
@@ -74,6 +83,7 @@ export async function readOrderStates(
|
|
|
74
83
|
cancellationReasonCode: row.cancellationReasonCode,
|
|
75
84
|
cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,
|
|
76
85
|
appUrl: adapter ? adapter.appLink(row) : null,
|
|
86
|
+
cancellationReasons: adapter && storedReasons(row.cancellationReasons) !== null ? reasonsForOrder(adapter, row.cancellationReasons) : null,
|
|
77
87
|
};
|
|
78
88
|
return [row.orderId, state];
|
|
79
89
|
}),
|
package/src/core/status-job.ts
CHANGED
|
@@ -11,7 +11,11 @@ import type { MarketplaceDeliveredBy } from "./types";
|
|
|
11
11
|
*
|
|
12
12
|
* In order, stopping at the first rule that fails, with no row and no call:
|
|
13
13
|
*
|
|
14
|
-
* 1. the acceptance is ACCEPTED and no cancellation request stands
|
|
14
|
+
* 1. the acceptance is ACCEPTED and no cancellation request stands, and the
|
|
15
|
+
* marketplace took the store's confirm (`confirmedAt`, FUT-5673), for a
|
|
16
|
+
* marketplace that states `statusAfterConfirm` (iFood): while the confirm
|
|
17
|
+
* is still owed the job is retried, and once it failed (`confirmFailedAt`)
|
|
18
|
+
* or on the last attempt it is skipped; any other marketplace never waits;
|
|
15
19
|
* 2. the adapter states the step and takes it for this kind of order;
|
|
16
20
|
* 3. the host says the order still holds the step (a dispatch undone inside
|
|
17
21
|
* the board's undo window sends nothing);
|
|
@@ -19,7 +23,12 @@ import type { MarketplaceDeliveredBy } from "./types";
|
|
|
19
23
|
* the order (a step it announced itself is in the same table);
|
|
20
24
|
* 5. claim: insert the row (STORE, SENDING), unique on (order, step); a lost
|
|
21
25
|
* claim stops the run;
|
|
22
|
-
* 6.
|
|
26
|
+
* 6. a step the adapter says must follow another for this order
|
|
27
|
+
* (`statusPrerequisite`: iFood's dispatch of a merchant bag follows its
|
|
28
|
+
* `readyToPickup`, FUT-5984) sends that one first, under its own row,
|
|
29
|
+
* unless it is already SENT or FAILED; one still SENDING under another run
|
|
30
|
+
* makes this one wait (retried);
|
|
31
|
+
* 7. call the adapter: 2xx SENT; a final 4xx FAILED, logged at error, never
|
|
23
32
|
* retried; 408/425/429/5xx/timeout retried, the last attempt FAILED. A run
|
|
24
33
|
* on a SENDING row it owns (a retry, or the sweep's re-queue) calls again.
|
|
25
34
|
*
|
|
@@ -34,6 +43,8 @@ interface StatusJobRow {
|
|
|
34
43
|
status: string;
|
|
35
44
|
cancellationStatus: string | null;
|
|
36
45
|
deliveredBy: string | null;
|
|
46
|
+
confirmedAt?: Date | null;
|
|
47
|
+
confirmFailedAt?: Date | null;
|
|
37
48
|
}
|
|
38
49
|
|
|
39
50
|
/** What one run did, in the outbound job's own shape. */
|
|
@@ -61,6 +72,20 @@ function acceptanceSkip(row: StatusJobRow): string | null {
|
|
|
61
72
|
return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
|
|
62
73
|
}
|
|
63
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Rule 1's second half (FUT-5673): why the confirm stops the job, or null once
|
|
77
|
+
* the marketplace took it. Still owed and attempts left: retried.
|
|
78
|
+
*/
|
|
79
|
+
function confirmSkip(row: StatusJobRow, adapter: MarketplaceAdapter, deps: StatusJobDeps): string | null {
|
|
80
|
+
// Only a marketplace that states it (iFood, FUT-5673): every other one tells its steps as before.
|
|
81
|
+
if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
|
|
82
|
+
if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
|
|
83
|
+
if (deps.attempt.attempt < deps.attempt.maxAttempts) {
|
|
84
|
+
throw deps.retryError(`status for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
|
|
85
|
+
}
|
|
86
|
+
return "the store's confirm has not reached the marketplace";
|
|
87
|
+
}
|
|
88
|
+
|
|
64
89
|
/** Why rules 2 and 3 stop the job, or null. Rule 3 asks the host, so it comes last. */
|
|
65
90
|
async function adapterAndHostSkip(
|
|
66
91
|
ctx: EngineContext,
|
|
@@ -177,7 +202,7 @@ export async function runStatus(
|
|
|
177
202
|
): Promise<StatusJobOutcome> {
|
|
178
203
|
const step = payload.step;
|
|
179
204
|
if (!step) return skipped("a status call names no step");
|
|
180
|
-
const stopped = acceptanceSkip(row) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
|
|
205
|
+
const stopped = acceptanceSkip(row) ?? confirmSkip(row, adapter, deps) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
|
|
181
206
|
if (stopped) return skipped(stopped);
|
|
182
207
|
const db = await ctx.ports.db();
|
|
183
208
|
const table = statusTable(db);
|
|
@@ -194,10 +219,68 @@ export async function runStatus(
|
|
|
194
219
|
const key = payload.claimKey ?? "";
|
|
195
220
|
const unclaimed = await claim(table, payload, row, step, key);
|
|
196
221
|
if (unclaimed) return skipped(unclaimed);
|
|
222
|
+
const before = await sendPrerequisite(ctx, { table, payload, row, step, key, connection, adapter }, deps);
|
|
223
|
+
if (before) return before;
|
|
197
224
|
const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
|
|
198
225
|
return settle(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
|
|
199
226
|
}
|
|
200
227
|
|
|
228
|
+
/** What rule 6 needs: the claimed step's run, and the connection it calls with. */
|
|
229
|
+
interface PrerequisiteRun {
|
|
230
|
+
table: NonNullable<MarketplaceDb["marketplaceStatusUpdate"]>;
|
|
231
|
+
payload: OutboundJobPayload;
|
|
232
|
+
row: StatusJobRow;
|
|
233
|
+
step: StatusStep;
|
|
234
|
+
key: string;
|
|
235
|
+
connection: OutboundConnection;
|
|
236
|
+
adapter: MarketplaceAdapter;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Whether a prerequisite row lets this run go on: `proceed` (it stands SENT or
|
|
241
|
+
* FAILED), `send` (absent, or this run's own claim), or a wait. A wait is
|
|
242
|
+
* retried; on the last attempt it ends skipped, never sent out of order.
|
|
243
|
+
*/
|
|
244
|
+
function prerequisiteState(
|
|
245
|
+
found: StatusRow | undefined,
|
|
246
|
+
key: string,
|
|
247
|
+
run: PrerequisiteRun,
|
|
248
|
+
first: StatusStep,
|
|
249
|
+
deps: StatusJobDeps,
|
|
250
|
+
): "proceed" | "send" | StatusJobOutcome {
|
|
251
|
+
if (!found || ownsClaim(found, key)) return "send";
|
|
252
|
+
if (found.state !== "SENDING") return "proceed";
|
|
253
|
+
if (deps.attempt.attempt < deps.attempt.maxAttempts) {
|
|
254
|
+
throw deps.retryError(`status ${run.step} for order ${run.row.orderId}: waiting for ${first}, held by another run`);
|
|
255
|
+
}
|
|
256
|
+
return skipped(`${first} is still being sent by another run`);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Rule 6: the step this one must follow, sent first under its own row and key
|
|
261
|
+
* (`<key>:<step>`, so this run's retry owns it), or null when there is none or
|
|
262
|
+
* it already stands. A prerequisite refused is FAILED and logged; the step
|
|
263
|
+
* itself still goes.
|
|
264
|
+
*/
|
|
265
|
+
async function sendPrerequisite(ctx: EngineContext, run: PrerequisiteRun, deps: StatusJobDeps): Promise<StatusJobOutcome | null> {
|
|
266
|
+
const first = run.adapter.statusPrerequisite?.({ step: run.step, deliveredBy: deliveredByOf(run.row) }) ?? null;
|
|
267
|
+
if (first === null) return null;
|
|
268
|
+
const key = `${run.key}:${first}`;
|
|
269
|
+
const [found] = await readStatusRows(run.table, run.row.orderId, [first]);
|
|
270
|
+
const state = prerequisiteState(found, key, run, first, deps);
|
|
271
|
+
if (state === "proceed") return null;
|
|
272
|
+
if (typeof state !== "string") return state;
|
|
273
|
+
if (!found) {
|
|
274
|
+
const row = { clientId: run.payload.clientId, orderId: run.row.orderId, provider: run.row.provider };
|
|
275
|
+
const claimed = await insertStatusRow(run.table, { ...row, step: first, source: "STORE", state: "SENDING", claimKey: key });
|
|
276
|
+
if (!claimed) return sendPrerequisite(ctx, run, deps);
|
|
277
|
+
}
|
|
278
|
+
const result = await callAdapter(ctx, run.connection, run.adapter, run.row, first, deps.ref);
|
|
279
|
+
const outcome = await settle(ctx, await ctx.ports.db(), { orderId: run.row.orderId, step: first, claimKey: key }, result, deps);
|
|
280
|
+
return outcome.kind === "skipped" ? outcome : null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
|
|
201
284
|
/** The last attempt died without an answer: FAILED, never left SENDING. Best-effort. */
|
|
202
285
|
export async function failStatusRow(ctx: EngineContext, payload: OutboundJobPayload): Promise<void> {
|
|
203
286
|
const table = statusTable(await ctx.ports.db());
|
package/src/core/types.ts
CHANGED
|
@@ -233,4 +233,10 @@ export interface NormalizedEvent {
|
|
|
233
233
|
* names no courier step.
|
|
234
234
|
*/
|
|
235
235
|
courier?: NormalizedCourierEvent | null;
|
|
236
|
+
/**
|
|
237
|
+
* OPTIONAL (FUT-5653). The store accepted the order in the marketplace's own
|
|
238
|
+
* app (iFood's `CFM`): an order still AWAITING here is accepted through the
|
|
239
|
+
* host's admit, with no confirm sent back. Carries no order body.
|
|
240
|
+
*/
|
|
241
|
+
marketplaceConfirmed?: boolean;
|
|
236
242
|
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import {
|
|
2
|
+
outboundResultOf,
|
|
3
|
+
type AdapterCallContext,
|
|
4
|
+
type FetchOrderResult,
|
|
5
|
+
type MarketplaceHttpResponse,
|
|
6
|
+
} from "../core/adapter";
|
|
7
|
+
import { firstString } from "../core/payload-read";
|
|
8
|
+
import { readIfoodOrder } from "./normalize";
|
|
9
|
+
import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The iFood adapter's order read (FUT-5800): `GET /order/v1.0/orders/{id}`.
|
|
13
|
+
*
|
|
14
|
+
* iFood's events carry only the order id, so a PLACED with no items is marked
|
|
15
|
+
* `orderToFetch` (`./normalize.ts`) and the engine's `marketplace.fetch-order`
|
|
16
|
+
* job calls this, after the webhook's row is committed, never inside the
|
|
17
|
+
* request. The order iFood serves has the fields the event's `order` would
|
|
18
|
+
* have carried, so it is normalized by the same reader: a fetched order and a
|
|
19
|
+
* carried one land identically.
|
|
20
|
+
*
|
|
21
|
+
* How an answer is read:
|
|
22
|
+
* - 2xx with an order: the order, with the merchant its `merchant.id` names
|
|
23
|
+
* (the engine refuses one naming another merchant than the connection's).
|
|
24
|
+
* - 2xx that is not JSON: retried. 2xx naming another order, or no items: refused.
|
|
25
|
+
* - 401: the cached token is forgotten and a new one asked for, ONCE, in the
|
|
26
|
+
* same call. A second 401 is our credentials refused (`own`), as is a 403
|
|
27
|
+
* (the merchant has not authorized this app) and a token grant iFood refuses.
|
|
28
|
+
* - 404: retried. ESTIMATED: an order read right after its PLACED may not be
|
|
29
|
+
* served yet; the job's attempt bound ends it.
|
|
30
|
+
* - Everything else: the engine's one rule (`outboundResultOf`).
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const orderResourceUrl = (externalOrderId: string): string =>
|
|
34
|
+
`${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`;
|
|
35
|
+
|
|
36
|
+
/** One authenticated GET, or the token's refusal or retry in its place. */
|
|
37
|
+
async function getOrder(
|
|
38
|
+
ctx: AdapterCallContext,
|
|
39
|
+
externalOrderId: string,
|
|
40
|
+
): Promise<{ response: MarketplaceHttpResponse } | Exclude<FetchOrderResult, { kind: "order" }>> {
|
|
41
|
+
const auth = await bearer(ctx);
|
|
42
|
+
if (!("token" in auth)) {
|
|
43
|
+
return auth.kind === "accepted" ? { kind: "retry", reason: "iFood answered the token grant without a token" } : auth;
|
|
44
|
+
}
|
|
45
|
+
const response = await ctx.http({
|
|
46
|
+
method: "GET",
|
|
47
|
+
url: orderResourceUrl(externalOrderId),
|
|
48
|
+
headers: { Authorization: `Bearer ${auth.token}`, Accept: "application/json" },
|
|
49
|
+
});
|
|
50
|
+
return { response };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The order in a 2xx answer, or why it is not one. */
|
|
54
|
+
function orderOf(body: string, externalOrderId: string, missingStreetNumber: string): FetchOrderResult {
|
|
55
|
+
let parsed: unknown;
|
|
56
|
+
try {
|
|
57
|
+
parsed = JSON.parse(body) as unknown;
|
|
58
|
+
} catch {
|
|
59
|
+
return { kind: "retry", reason: "iFood answered the order read with a body that is not JSON" };
|
|
60
|
+
}
|
|
61
|
+
const named = firstString(parsed, [["id"]]);
|
|
62
|
+
if (named !== null && named !== externalOrderId) {
|
|
63
|
+
return { kind: "refused", status: 200, message: `iFood answered order ${named} for ${externalOrderId}` };
|
|
64
|
+
}
|
|
65
|
+
const order = readIfoodOrder(parsed, externalOrderId, missingStreetNumber);
|
|
66
|
+
if (!order) return { kind: "refused", status: 200, message: "iFood answered an order with no items" };
|
|
67
|
+
return { kind: "order", order: { ...order, externalMerchantId: firstString(parsed, [["merchant", "id"]]) } };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What a non-2xx answer means for the fetch. */
|
|
71
|
+
function failureOf(response: MarketplaceHttpResponse): Exclude<FetchOrderResult, { kind: "order" }> {
|
|
72
|
+
const message = response.body.slice(0, 300);
|
|
73
|
+
if (response.status === 401 || response.status === 403) {
|
|
74
|
+
return { kind: "refused", status: response.status, message, own: true };
|
|
75
|
+
}
|
|
76
|
+
if (response.status === 404) return { kind: "retry", reason: `status 404: ${message}` };
|
|
77
|
+
const result = outboundResultOf(response);
|
|
78
|
+
return result.kind === "accepted" ? { kind: "retry", reason: `status ${response.status}` } : result;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Fetch one order iFood's event only named. Never throws: no answer is a retry. */
|
|
82
|
+
export async function ifoodFetchOrder(
|
|
83
|
+
ctx: AdapterCallContext,
|
|
84
|
+
ref: { externalOrderId: string },
|
|
85
|
+
options: { missingStreetNumber: string },
|
|
86
|
+
): Promise<FetchOrderResult> {
|
|
87
|
+
try {
|
|
88
|
+
let answer = await getOrder(ctx, ref.externalOrderId);
|
|
89
|
+
if ("response" in answer && answer.response.status === 401) {
|
|
90
|
+
// A token that went stale under us: forget it and try once with a new one.
|
|
91
|
+
ctx.tokens.delete(ifoodTokenKey(ctx));
|
|
92
|
+
answer = await getOrder(ctx, ref.externalOrderId);
|
|
93
|
+
}
|
|
94
|
+
if (!("response" in answer)) return answer;
|
|
95
|
+
const { response } = answer;
|
|
96
|
+
if (response.status >= 200 && response.status < 300) {
|
|
97
|
+
return orderOf(response.body, ref.externalOrderId, options.missingStreetNumber);
|
|
98
|
+
}
|
|
99
|
+
return failureOf(response);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
102
|
+
}
|
|
103
|
+
}
|
package/src/ifood/index.ts
CHANGED
|
@@ -3,9 +3,19 @@ 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 { ifoodFetchOrder } from "./fetch-order";
|
|
6
7
|
import { IFOOD_LINKING } from "./linking";
|
|
7
|
-
import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
|
|
8
|
-
import {
|
|
8
|
+
import { normalizeIfoodEvent, readIfoodPresence, verifyIfoodSignature } from "./normalize";
|
|
9
|
+
import {
|
|
10
|
+
IFOOD_ACKNOWLEDGEMENT,
|
|
11
|
+
IFOOD_PORTAL_URL,
|
|
12
|
+
ifoodConfirm,
|
|
13
|
+
ifoodInformStatus,
|
|
14
|
+
ifoodOrderCancellationReasons,
|
|
15
|
+
ifoodRequestCancellation,
|
|
16
|
+
ifoodStatusPrerequisite,
|
|
17
|
+
ifoodStatusSupported,
|
|
18
|
+
} from "./outbound";
|
|
9
19
|
import { IFOOD_AVAILABILITY } from "./pause";
|
|
10
20
|
|
|
11
21
|
/**
|
|
@@ -38,7 +48,10 @@ export interface IfoodAdapterConfig {
|
|
|
38
48
|
copy: IfoodAdapterCopy;
|
|
39
49
|
}
|
|
40
50
|
|
|
41
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* Build the iFood adapter. Its static reasons are the fallback: each order's
|
|
53
|
+
* own are read from iFood in a job after its ingest (FUT-5984).
|
|
54
|
+
*/
|
|
42
55
|
export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {
|
|
43
56
|
const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({
|
|
44
57
|
code,
|
|
@@ -66,6 +79,12 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
66
79
|
// pickup, and dispatched for a merchant bag. Never "handed over": iFood's own
|
|
67
80
|
// CONCLUDED is that.
|
|
68
81
|
statusSteps: ["READY", "DISPATCHED"],
|
|
82
|
+
// "Retorne `202 Accepted` em até 5 segundos" (Events `webhook-overview`, FUT-5984).
|
|
83
|
+
webhookAnswerStatus: 202,
|
|
84
|
+
// CFM: the store accepted on iFood's own app (FUT-5653).
|
|
85
|
+
marketplaceConfirms: true,
|
|
86
|
+
// A step is told only once iFood took the confirm (FUT-5673).
|
|
87
|
+
statusAfterConfirm: true,
|
|
69
88
|
},
|
|
70
89
|
normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
|
|
71
90
|
readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
|
|
@@ -77,8 +96,15 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
77
96
|
catalogueReader: IFOOD_CATALOGUE_READER,
|
|
78
97
|
confirm: (ctx, order) => ifoodConfirm(ctx, order),
|
|
79
98
|
requestCancellation: ifoodRequestCancellation,
|
|
99
|
+
// iFood's events carry only the order id: a PLACED with no items is fetched (FUT-5800).
|
|
100
|
+
fetchOrder: (ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions),
|
|
80
101
|
statusSupported: ifoodStatusSupported,
|
|
81
102
|
informStatus: ifoodInformStatus,
|
|
103
|
+
statusPrerequisite: ifoodStatusPrerequisite,
|
|
104
|
+
// The presence heartbeat, the events' acknowledgment and each order's own reasons (FUT-5984).
|
|
105
|
+
presence: readIfoodPresence,
|
|
106
|
+
acknowledgement: IFOOD_ACKNOWLEDGEMENT,
|
|
107
|
+
orderCancellationReasons: ifoodOrderCancellationReasons,
|
|
82
108
|
// The Merchant API's interruptions: an id and an end per closure (FUT-4851).
|
|
83
109
|
availability: IFOOD_AVAILABILITY,
|
|
84
110
|
// The distributed-app authorization: a store links the software's own app (FUT-5613).
|
|
@@ -92,7 +118,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
92
118
|
}
|
|
93
119
|
|
|
94
120
|
export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
|
|
95
|
-
export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
|
|
121
|
+
export { normalizeIfoodEvent, readIfoodOrder, readIfoodPresence, verifyIfoodSignature } from "./normalize";
|
|
122
|
+
export { ifoodFetchOrder } from "./fetch-order";
|
|
96
123
|
export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
|
|
97
124
|
export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
|
|
98
125
|
export { IFOOD_LINKING } from "./linking";
|