@12-apps/marketplace 1.11.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 +90 -1
- package/README.md +37 -1
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CD0SfdVS.d.ts → adapter-nUyZpLzz.d.ts} +325 -173
- package/dist/{chunk-YWMEIMO3.js → chunk-45ZVN5XI.js} +114 -24
- package/dist/chunk-45ZVN5XI.js.map +1 -0
- package/dist/{chunk-DCWOQ5PN.js → chunk-L6FG6T4S.js} +2 -2
- package/dist/{chunk-TVZU4HNT.js → chunk-LACBT6NC.js} +1 -1
- package/dist/{chunk-TVZU4HNT.js.map → chunk-LACBT6NC.js.map} +1 -1
- package/dist/{chunk-OS4TSIFU.js → chunk-MIPNQ7X5.js} +2 -2
- package/dist/{client-11sncog4.d.ts → client-Ctas7WCS.d.ts} +1 -1
- package/dist/{engine-C_3RK8wC.d.ts → engine-CIy9P7Cq.d.ts} +34 -5
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +7 -2
- package/dist/ifood/index.js +184 -30
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +162 -65
- 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/server.d.ts +2 -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 +2 -2
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/src/core/adapter.ts +6 -0
- package/src/core/courier-port.ts +100 -0
- package/src/core/courier.ts +153 -0
- package/src/core/engine.ts +4 -1
- package/src/core/lifecycle.ts +27 -4
- 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 +23 -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 +4 -0
- package/src/ifood/normalize.ts +7 -0
- package/src/index.ts +16 -0
- package/src/keeta/normalize.ts +21 -6
- package/dist/chunk-YWMEIMO3.js.map +0 -1
- /package/dist/{chunk-DCWOQ5PN.js.map → chunk-L6FG6T4S.js.map} +0 -0
- /package/dist/{chunk-OS4TSIFU.js.map → chunk-MIPNQ7X5.js.map} +0 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { OutboundOrderRef } from "./adapter";
|
|
2
|
+
import type { CourierTrackingResult, MarketplaceCourierAnswer, MarketplaceCourierEngine } from "./courier-port";
|
|
3
|
+
import { deferInboxEvent, settleInboxEvent } from "./inbox";
|
|
4
|
+
import type { IngestSettings } from "./ingest";
|
|
5
|
+
import { readOutboundConnection } from "./integration";
|
|
6
|
+
import { followLifecycle } from "./lifecycle";
|
|
7
|
+
import { validatePickupCode } from "./pickup-code";
|
|
8
|
+
import type { DeliveryOutcome } from "./pipeline";
|
|
9
|
+
import type { EngineContext } from "./ports";
|
|
10
|
+
import type { MarketplaceDeliveredBy, MarketplaceCourierStep, NormalizedEvent } from "./types";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The marketplace's own courier (FUT-5665), the engine's half: courier events
|
|
14
|
+
* reach the host's `onCourier`, and the host's job reads the tracking.
|
|
15
|
+
*
|
|
16
|
+
* A courier event moves nothing: it is a fact the host stores (who is coming,
|
|
17
|
+
* when they arrived, the bag coming back). The one that also moves the order,
|
|
18
|
+
* `COLLECTED`, names the lifecycle too and goes through `followLifecycle`
|
|
19
|
+
* like a `DISPATCHED`, after the host stored its facts.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
interface CourierAcceptance {
|
|
23
|
+
orderId: string;
|
|
24
|
+
status: string;
|
|
25
|
+
deliveredBy: string | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What the courier half made of an event, before the inbox row is settled. */
|
|
29
|
+
type CourierStepOutcome =
|
|
30
|
+
| { kind: "deferred" }
|
|
31
|
+
| { kind: "stopped"; reason: string }
|
|
32
|
+
| { kind: "recorded"; orderId: string; step: MarketplaceCourierStep };
|
|
33
|
+
|
|
34
|
+
function deliveredByOf(value: string | null): MarketplaceDeliveredBy | null {
|
|
35
|
+
return value === "MERCHANT" || value === "MARKETPLACE" ? value : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function reasonOf(answer: MarketplaceCourierAnswer, step: MarketplaceCourierStep): string {
|
|
39
|
+
if (answer === "unchanged") return `nothing to record for ${step}`;
|
|
40
|
+
return answer === "recorded" ? "" : answer.reason;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Hand the courier's facts to the host, or null when this host or this event has none. */
|
|
44
|
+
async function followCourier(ctx: EngineContext, clientId: string, event: NormalizedEvent): Promise<CourierStepOutcome | null> {
|
|
45
|
+
const hook = ctx.ports.order.onCourier;
|
|
46
|
+
const courier = event.courier;
|
|
47
|
+
if (!hook || !courier || !event.externalOrderId) return null;
|
|
48
|
+
const db = await ctx.ports.db();
|
|
49
|
+
const held = (await db.marketplaceAcceptance.findFirst({
|
|
50
|
+
where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
|
|
51
|
+
select: { orderId: true, status: true, deliveredBy: true },
|
|
52
|
+
})) as CourierAcceptance | null;
|
|
53
|
+
if (!held) return { kind: "deferred" };
|
|
54
|
+
if (held.status !== "ACCEPTED") return { kind: "stopped", reason: `the order is ${held.status}, not ACCEPTED` };
|
|
55
|
+
const facts = { deliveredBy: deliveredByOf(held.deliveredBy), at: courier.at ?? ctx.ports.clock.now() };
|
|
56
|
+
const answer = await hook.call(ctx.ports.order, clientId, held.orderId, courier, facts);
|
|
57
|
+
if (answer === "recorded") return { kind: "recorded", orderId: held.orderId, step: courier.step };
|
|
58
|
+
return { kind: "stopped", reason: reasonOf(answer, courier.step) };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Settle the inbox row for a courier event that named no lifecycle the host moved on. */
|
|
62
|
+
async function settleCourier(
|
|
63
|
+
ctx: EngineContext,
|
|
64
|
+
inboxId: string,
|
|
65
|
+
clientId: string,
|
|
66
|
+
outcome: CourierStepOutcome,
|
|
67
|
+
): Promise<DeliveryOutcome> {
|
|
68
|
+
if (outcome.kind === "recorded") {
|
|
69
|
+
await settleInboxEvent(ctx, inboxId, "PROCESSED");
|
|
70
|
+
ctx.ports.publishChanged(clientId);
|
|
71
|
+
return { kind: "courier", orderId: outcome.orderId, step: outcome.step };
|
|
72
|
+
}
|
|
73
|
+
if (outcome.kind === "deferred") {
|
|
74
|
+
const reason = "courier event before its order";
|
|
75
|
+
await deferInboxEvent(ctx, inboxId, reason);
|
|
76
|
+
return { kind: "ignored", reason };
|
|
77
|
+
}
|
|
78
|
+
await settleInboxEvent(ctx, inboxId, "IGNORED", outcome.reason);
|
|
79
|
+
return { kind: "ignored", reason: outcome.reason };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The courier's facts first, then the lifecycle the event names: null when
|
|
84
|
+
* neither applies (the caller then does what it did before). A lifecycle that
|
|
85
|
+
* moved the order answers for the row; one that moved nothing (already past
|
|
86
|
+
* it, an echo) leaves the row to the courier's facts when they were recorded.
|
|
87
|
+
*/
|
|
88
|
+
export async function followCourierAndLifecycle(
|
|
89
|
+
ctx: EngineContext,
|
|
90
|
+
inboxId: string,
|
|
91
|
+
clientId: string,
|
|
92
|
+
event: NormalizedEvent,
|
|
93
|
+
settings: IngestSettings,
|
|
94
|
+
): Promise<DeliveryOutcome | null> {
|
|
95
|
+
const courier = await followCourier(ctx, clientId, event);
|
|
96
|
+
const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
|
|
97
|
+
const recorded = courier?.kind === "recorded";
|
|
98
|
+
if (followed && !(recorded && followed.kind === "ignored")) return followed;
|
|
99
|
+
return courier ? settleCourier(ctx, inboxId, clientId, courier) : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface TrackedAcceptance {
|
|
103
|
+
orderId: string;
|
|
104
|
+
provider: string;
|
|
105
|
+
externalOrderId: string;
|
|
106
|
+
externalDisplayId: string | null;
|
|
107
|
+
deliveredBy: string | null;
|
|
108
|
+
createdAt: Date;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Read where the marketplace's courier is (FUT-5665). Calls the marketplace at
|
|
113
|
+
* once, so the host runs it in a job, never on a tap or a screen load, and at
|
|
114
|
+
* the marketplace's own rate (iFood: at most once per 30 s). `notYet` before a
|
|
115
|
+
* courier is assigned; `unsupported` with no call for an order the engine does
|
|
116
|
+
* not hold, a marketplace with no tracking, or a bag the store carries itself.
|
|
117
|
+
*/
|
|
118
|
+
async function readCourierTracking(
|
|
119
|
+
ctx: EngineContext,
|
|
120
|
+
input: { clientId: string; orderId: string },
|
|
121
|
+
): Promise<CourierTrackingResult> {
|
|
122
|
+
const db = await ctx.ports.db();
|
|
123
|
+
const row = (await db.marketplaceAcceptance.findFirst({
|
|
124
|
+
where: { clientId: input.clientId, orderId: input.orderId },
|
|
125
|
+
select: { orderId: true, provider: true, externalOrderId: true, externalDisplayId: true, deliveredBy: true, createdAt: true },
|
|
126
|
+
})) as TrackedAcceptance | null;
|
|
127
|
+
if (!row) return { kind: "unsupported", reason: "no marketplace order with this id" };
|
|
128
|
+
const api = ctx.registry.get(row.provider)?.courier;
|
|
129
|
+
if (!api) return { kind: "unsupported", reason: `${row.provider} has no courier tracking` };
|
|
130
|
+
if (row.deliveredBy !== "MARKETPLACE") return { kind: "unsupported", reason: "the order is not carried by the marketplace's courier" };
|
|
131
|
+
let connection;
|
|
132
|
+
try {
|
|
133
|
+
connection = await readOutboundConnection(ctx, input.clientId, row.provider);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
return { kind: "refused", status: 0, message: `credentials do not open: ${error instanceof Error ? error.message : String(error)}`, own: true };
|
|
136
|
+
}
|
|
137
|
+
if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
|
|
138
|
+
const ref: OutboundOrderRef = {
|
|
139
|
+
externalOrderId: row.externalOrderId,
|
|
140
|
+
externalDisplayId: row.externalDisplayId,
|
|
141
|
+
hostOrderCode: row.orderId,
|
|
142
|
+
placedAt: row.createdAt,
|
|
143
|
+
};
|
|
144
|
+
return api.tracking({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, ref);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The engine's courier calls, bound to its context. */
|
|
148
|
+
export function courierEngine(ctx: EngineContext): MarketplaceCourierEngine {
|
|
149
|
+
return {
|
|
150
|
+
validatePickupCode: (input) => validatePickupCode(ctx, input),
|
|
151
|
+
courierTracking: (input) => readCourierTracking(ctx, input),
|
|
152
|
+
};
|
|
153
|
+
}
|
package/src/core/engine.ts
CHANGED
|
@@ -35,6 +35,8 @@ import type { CatalogueMenuOptions } from "./catalogue-port";
|
|
|
35
35
|
import { readMarketplaceCatalogue } from "./catalogue-read";
|
|
36
36
|
import type { CatalogueReadResult } from "./catalogue-read-port";
|
|
37
37
|
import type { CataloguePublicationView } from "./catalogue-store";
|
|
38
|
+
import { courierEngine } from "./courier";
|
|
39
|
+
import type { MarketplaceCourierEngine } from "./courier-port";
|
|
38
40
|
import {
|
|
39
41
|
runFetchOrder,
|
|
40
42
|
type FetchOrderJobPayload,
|
|
@@ -97,7 +99,7 @@ import { readOrderStates, type MarketplaceOrderState } from "./state";
|
|
|
97
99
|
import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
98
100
|
|
|
99
101
|
/** Everything the mounted engine can do, with the ports and adapters bound in. */
|
|
100
|
-
export interface MarketplaceEngine {
|
|
102
|
+
export interface MarketplaceEngine extends MarketplaceCourierEngine {
|
|
101
103
|
/** Every registered marketplace, in registration order. */
|
|
102
104
|
providers(): readonly MarketplaceProvider[];
|
|
103
105
|
/** Whether a provider id (a URL segment, a body field) names a registered adapter. */
|
|
@@ -375,6 +377,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
|
|
|
375
377
|
runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
|
|
376
378
|
runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
|
|
377
379
|
informStatus: (input) => informStatus(ctx, input),
|
|
380
|
+
...courierEngine(ctx),
|
|
378
381
|
|
|
379
382
|
// Null too when the host bound no catalogue port: nothing could be published.
|
|
380
383
|
catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
|
package/src/core/lifecycle.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { deferInboxEvent, settleInboxEvent } from "./inbox";
|
|
|
2
2
|
import type { IngestSettings } from "./ingest";
|
|
3
3
|
import type { DeliveryOutcome } from "./pipeline";
|
|
4
4
|
import type { EngineContext } from "./ports";
|
|
5
|
-
import { readStatusRows, noteMarketplaceStep, statusTable } from "./status-store";
|
|
5
|
+
import { readStatusRows, noteMarketplaceStep, statusTable, type StatusRowStep } from "./status-store";
|
|
6
6
|
import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } from "./types";
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -20,7 +20,7 @@ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } fr
|
|
|
20
20
|
* 3. a cancellation request standing (PENDING or REQUESTED) is the store's
|
|
21
21
|
* last word and nothing here contradicts it;
|
|
22
22
|
* 4. an event that answers a step WE informed (a STORE row for DISPATCHED, or
|
|
23
|
-
* for HANDED_OVER when the event is CONCLUDED) is an echo: the failure case
|
|
23
|
+
* for HANDED_OVER when the event is COLLECTED or CONCLUDED) is an echo: the failure case
|
|
24
24
|
* of forward-only alone is the store's undo, where the echo would
|
|
25
25
|
* dispatch a card again with no courier.
|
|
26
26
|
*
|
|
@@ -36,9 +36,23 @@ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } fr
|
|
|
36
36
|
/** The step of the table an event's echo is looked for under. */
|
|
37
37
|
const ECHO_OF: Record<MarketplaceLifecycle, "DISPATCHED" | "HANDED_OVER"> = {
|
|
38
38
|
DISPATCHED: "DISPATCHED",
|
|
39
|
+
// The courier holding the bag answers the store's hand-over (FUT-5665).
|
|
40
|
+
COLLECTED: "HANDED_OVER",
|
|
39
41
|
CONCLUDED: "HANDED_OVER",
|
|
40
42
|
};
|
|
41
43
|
|
|
44
|
+
/**
|
|
45
|
+
* The step the marketplace's word is NOTED under. `COLLECTED` is the
|
|
46
|
+
* hand-over seen from the marketplace's side, so it is noted as HANDED_OVER:
|
|
47
|
+
* the table's vocabulary (its CHECK) is unchanged, and our own job never
|
|
48
|
+
* informs a hand-over the marketplace already announced.
|
|
49
|
+
*/
|
|
50
|
+
const NOTED_AS: Record<MarketplaceLifecycle, StatusRowStep> = {
|
|
51
|
+
DISPATCHED: "DISPATCHED",
|
|
52
|
+
COLLECTED: "HANDED_OVER",
|
|
53
|
+
CONCLUDED: "CONCLUDED",
|
|
54
|
+
};
|
|
55
|
+
|
|
42
56
|
interface HeldAcceptance {
|
|
43
57
|
orderId: string;
|
|
44
58
|
status: string;
|
|
@@ -62,6 +76,15 @@ function refusal(held: HeldAcceptance): string | null {
|
|
|
62
76
|
return null;
|
|
63
77
|
}
|
|
64
78
|
|
|
79
|
+
/**
|
|
80
|
+
* A COLLECTED is the marketplace's courier taking the bag (FUT-5665): for a
|
|
81
|
+
* bag the store carries it moves nothing and is never noted, so it cannot
|
|
82
|
+
* stand in for the store's own HANDED_OVER (a merchant bag's "delivered").
|
|
83
|
+
*/
|
|
84
|
+
function notTheFleets(lifecycle: MarketplaceLifecycle, held: HeldAcceptance): string | null {
|
|
85
|
+
return lifecycle === "COLLECTED" && held.deliveredBy !== "MARKETPLACE" ? "COLLECTED of a bag the marketplace does not carry" : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
65
88
|
function deliveredByOf(held: HeldAcceptance): MarketplaceDeliveredBy | null {
|
|
66
89
|
return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
|
|
67
90
|
}
|
|
@@ -108,7 +131,7 @@ export async function followLifecycle(
|
|
|
108
131
|
await deferInboxEvent(ctx, inboxId, reason);
|
|
109
132
|
return { kind: "ignored", reason };
|
|
110
133
|
}
|
|
111
|
-
const stopped = refusal(held);
|
|
134
|
+
const stopped = refusal(held) ?? notTheFleets(lifecycle, held);
|
|
112
135
|
if (stopped) return ignored(ctx, inboxId, stopped);
|
|
113
136
|
|
|
114
137
|
const echo = ECHO_OF[lifecycle];
|
|
@@ -121,7 +144,7 @@ export async function followLifecycle(
|
|
|
121
144
|
// FAILED and logged): the marketplace's state and ours already agree, and a stricter ordering
|
|
122
145
|
// would put a write before the host's answer on every event.
|
|
123
146
|
const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
|
|
124
|
-
await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
|
|
147
|
+
await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: NOTED_AS[lifecycle] });
|
|
125
148
|
if (answer === "moved") {
|
|
126
149
|
await settleInboxEvent(ctx, inboxId, "PROCESSED");
|
|
127
150
|
ctx.ports.publishChanged(clientId);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { StatusStep } from "./adapter";
|
|
1
|
+
import type { MarketplaceAdapter, StatusStep } from "./adapter";
|
|
2
2
|
import type { EngineContext } from "./ports";
|
|
3
3
|
import type { MarketplaceProvider } from "./types";
|
|
4
4
|
|
|
@@ -16,10 +16,11 @@ import type { MarketplaceProvider } from "./types";
|
|
|
16
16
|
export const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
|
-
* What goes out: the store's aceite, the store's cancellation request,
|
|
20
|
-
* step of the order the store reached (`status`, FUT-4653)
|
|
19
|
+
* What goes out: the store's aceite, the store's cancellation request, a
|
|
20
|
+
* step of the order the store reached (`status`, FUT-4653), or the pickup code
|
|
21
|
+
* the store checked at the hand-over (`validatePickupCode`, FUT-5665).
|
|
21
22
|
*/
|
|
22
|
-
export type OutboundAction = "confirm" | "requestCancellation" | "status";
|
|
23
|
+
export type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode";
|
|
23
24
|
|
|
24
25
|
/** The outbound job's payload. Identifiers only. */
|
|
25
26
|
export interface OutboundJobPayload {
|
|
@@ -33,6 +34,12 @@ export interface OutboundJobPayload {
|
|
|
33
34
|
* belongs to: the owner of its SENDING claim. Absent on every other action.
|
|
34
35
|
*/
|
|
35
36
|
claimKey?: string;
|
|
37
|
+
/**
|
|
38
|
+
* OPTIONAL. The pickup code a `validatePickupCode` call sends; absent on every
|
|
39
|
+
* other action. The one non-identifier in the payload: a short-lived code the
|
|
40
|
+
* job needs to send, which no log line prints.
|
|
41
|
+
*/
|
|
42
|
+
code?: string;
|
|
36
43
|
}
|
|
37
44
|
|
|
38
45
|
/** The dedupe key: at most one queued call per (order, action). */
|
|
@@ -45,6 +52,18 @@ export function statusDedupeKey(step: StatusStep, orderId: string, at: Date): st
|
|
|
45
52
|
return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
|
|
46
53
|
}
|
|
47
54
|
|
|
55
|
+
/** Whether the adapter's marketplace can take this call at all. */
|
|
56
|
+
function ableTo(adapter: MarketplaceAdapter, payload: OutboundJobPayload): boolean {
|
|
57
|
+
switch (payload.action) {
|
|
58
|
+
case "status":
|
|
59
|
+
return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
|
|
60
|
+
case "confirm":
|
|
61
|
+
return adapter.capabilities.apiConfirm;
|
|
62
|
+
default:
|
|
63
|
+
return adapter.capabilities.apiCancel;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
48
67
|
/**
|
|
49
68
|
* Queue one outbound call, when the marketplace's API can take it at all.
|
|
50
69
|
*
|
|
@@ -65,13 +84,7 @@ export async function enqueueOutbound(
|
|
|
65
84
|
): Promise<boolean> {
|
|
66
85
|
const adapter = ctx.registry.get(provider);
|
|
67
86
|
if (!adapter) return false;
|
|
68
|
-
|
|
69
|
-
payload.action === "status"
|
|
70
|
-
? Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step))
|
|
71
|
-
: payload.action === "confirm"
|
|
72
|
-
? adapter.capabilities.apiConfirm
|
|
73
|
-
: adapter.capabilities.apiCancel;
|
|
74
|
-
if (!able) return false;
|
|
87
|
+
if (!ableTo(adapter, payload)) return false;
|
|
75
88
|
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
|
|
76
89
|
if (!outcome.enqueued) {
|
|
77
90
|
ctx.ports.logger.warn(
|
package/src/core/outbound.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from "./cancellation-outcome";
|
|
10
10
|
import { readOutboundConnection, type OutboundConnection } from "./integration";
|
|
11
11
|
import type { OutboundJobPayload } from "./outbound-queue";
|
|
12
|
+
import { runPickupCode, tellPickupCode } from "./pickup-code";
|
|
12
13
|
import { failStatusRow, runStatus } from "./status-job";
|
|
13
14
|
import { failAsTimeout } from "./outbound-sweep";
|
|
14
15
|
import type { CancellationFailureReason, EngineContext } from "./ports";
|
|
@@ -334,9 +335,10 @@ async function runCancellation(
|
|
|
334
335
|
*/
|
|
335
336
|
async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
|
|
336
337
|
const reason = error instanceof Error ? error.message : String(error);
|
|
337
|
-
if (payload.action === "status") {
|
|
338
|
-
await failStatusRow(ctx, payload);
|
|
339
|
-
ctx
|
|
338
|
+
if (payload.action === "status" || payload.action === "validatePickupCode") {
|
|
339
|
+
if (payload.action === "status") await failStatusRow(ctx, payload);
|
|
340
|
+
else await tellPickupCode(ctx, payload, "UNVERIFIED");
|
|
341
|
+
ctx.ports.logger.error(`marketplace.outbound: ${payload.action}${payload.step ? ` ${payload.step}` : ""} for order ${payload.orderId} failed: ${reason}`);
|
|
340
342
|
return { kind: "failed", action: payload.action, reason };
|
|
341
343
|
}
|
|
342
344
|
const db = await ctx.ports.db();
|
|
@@ -366,9 +368,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
|
|
|
366
368
|
if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
|
|
367
369
|
const adapter = ctx.registry.get(row.provider);
|
|
368
370
|
if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
371
|
+
const deps = { attempt, ref: refOf(row), retryError: (m: string) => new OutboundRetryError(m) };
|
|
372
|
+
if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
|
|
373
|
+
if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
|
|
372
374
|
return payload.action === "confirm"
|
|
373
375
|
? runConfirm(ctx, payload, row, adapter, attempt)
|
|
374
376
|
: runCancellation(ctx, payload, row, adapter, attempt);
|
|
@@ -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,6 +1,7 @@
|
|
|
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";
|
|
5
6
|
import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
|
|
6
7
|
import type {
|
|
@@ -11,7 +12,7 @@ import type {
|
|
|
11
12
|
MarketplaceRefusal,
|
|
12
13
|
ResolvedOrderLine,
|
|
13
14
|
} from "./order-types";
|
|
14
|
-
import type { NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
15
|
+
import type { NormalizedCourierEvent, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
15
16
|
|
|
16
17
|
export type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
|
|
17
18
|
export type {
|
|
@@ -222,6 +223,27 @@ export interface MarketplaceOrderPort {
|
|
|
222
223
|
* Absent: the engine cannot tell, and sends nothing.
|
|
223
224
|
*/
|
|
224
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>;
|
|
225
247
|
/** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
|
|
226
248
|
summarize(
|
|
227
249
|
clientId: string,
|
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: "" });
|