@12-apps/marketplace 1.2.0 → 1.3.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 +29 -4
- package/README.md +92 -3
- package/dist/99food/index.d.ts +48 -2
- package/dist/99food/index.js +84 -1
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-_iuSxvVD.d.ts → adapter-0l_EmuJA.d.ts} +172 -2
- package/dist/{chunk-CRYFYDQ2.js → chunk-AYYBRQJV.js} +28 -4
- package/dist/chunk-AYYBRQJV.js.map +1 -0
- package/dist/chunk-M2V4RFMA.js +23 -0
- package/dist/chunk-M2V4RFMA.js.map +1 -0
- package/dist/{chunk-24RQZPSV.js → chunk-RVBTARIY.js} +1 -1
- package/dist/chunk-RVBTARIY.js.map +1 -0
- package/dist/{chunk-D2X7TOR6.js → chunk-XUAFXNOH.js} +449 -85
- package/dist/chunk-XUAFXNOH.js.map +1 -0
- package/dist/{engine-D-a4mttc.d.ts → engine-CZsP8KWd.d.ts} +222 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +10 -2
- package/dist/ifood/index.js +246 -69
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +30 -4
- package/dist/index.js +148 -9
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +3 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +7 -1
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +12 -8
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +92 -1
- package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
- package/src/99food/catalogue.ts +117 -0
- package/src/99food/index.ts +4 -0
- package/src/99food/outbound.ts +3 -3
- package/src/core/adapter.ts +10 -1
- package/src/core/catalogue-category.ts +119 -0
- package/src/core/catalogue-ids.ts +23 -0
- package/src/core/catalogue-job.ts +332 -0
- package/src/core/catalogue-port.ts +173 -0
- package/src/core/catalogue-store.ts +172 -0
- package/src/core/catalogue-sweep.ts +43 -0
- package/src/core/catalogue.ts +226 -0
- package/src/core/engine.ts +46 -0
- package/src/core/outbound-sweep.ts +7 -2
- package/src/core/ports.ts +36 -0
- package/src/ifood/catalogue.ts +273 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/outbound.ts +9 -6
- package/src/index.ts +40 -0
- package/src/rappi/index.ts +6 -0
- package/src/server/jobs.ts +39 -9
- package/dist/chunk-24RQZPSV.js.map +0 -1
- package/dist/chunk-CRYFYDQ2.js.map +0 -1
- package/dist/chunk-D2X7TOR6.js.map +0 -1
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type { AdapterCallContext, OutboundResult } from "./adapter";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The catalogue half of the adapter port (FUT-4768): a store turns one of its
|
|
5
|
+
* products ON or OFF per connected marketplace, with an optional price for
|
|
6
|
+
* that marketplace, and the engine keeps the marketplace's catalogue in step.
|
|
7
|
+
*
|
|
8
|
+
* Marketplaces differ in exactly one way that shapes the engine: who moves the
|
|
9
|
+
* menu.
|
|
10
|
+
*
|
|
11
|
+
* - **push** — the store's software writes each item to the marketplace's API
|
|
12
|
+
* (iFood's Catalog API v2.0). The adapter publishes and withdraws ONE item.
|
|
13
|
+
* - **pull** — the marketplace reads the menu from the store's software (Open
|
|
14
|
+
* Delivery's `GET /v1/merchant`, which 99Food implements). The adapter turns
|
|
15
|
+
* the published items into the marketplace's menu document, which the HOST
|
|
16
|
+
* serves, and tells the marketplace the menu changed.
|
|
17
|
+
*
|
|
18
|
+
* A marketplace whose adapter states no `catalogue` cannot be published to,
|
|
19
|
+
* and the host says so (`engine.catalogueMode(provider)` is null). Everything
|
|
20
|
+
* else — the publication record and its states, the job, its retries, the
|
|
21
|
+
* sweep, the price rule — is the engine's and does not change with the
|
|
22
|
+
* marketplace.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** One product as it goes out to a marketplace. The host maps its product into this shape. */
|
|
26
|
+
export interface CatalogueItem {
|
|
27
|
+
name: string;
|
|
28
|
+
description: string | null;
|
|
29
|
+
/**
|
|
30
|
+
* An absolute https URL of the product's photo, or null. It must CHANGE when
|
|
31
|
+
* the photo changes (a versioned URL: a content hash or an upload id in it):
|
|
32
|
+
* a marketplace that holds an uploaded copy reuses it while the URL is the
|
|
33
|
+
* same, so new bytes at an old URL are never sent.
|
|
34
|
+
*/
|
|
35
|
+
imageUrl: string | null;
|
|
36
|
+
/** The name of the host category the product sits in; the adapter finds or creates it. */
|
|
37
|
+
categoryName: string;
|
|
38
|
+
/** The store's own price, in the smallest currency unit. */
|
|
39
|
+
priceCents: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* What the adapter is handed to publish: the host's item with `priceCents`
|
|
44
|
+
* already the price for THIS marketplace (the connection's own price when the
|
|
45
|
+
* store set one, else the store's), and the engine's stable reference.
|
|
46
|
+
*/
|
|
47
|
+
export interface CatalogueItemOut extends CatalogueItem {
|
|
48
|
+
/**
|
|
49
|
+
* The engine's stable id for this (connection, product) publication. The
|
|
50
|
+
* same across retries and re-publishes, so an adapter that must invent the
|
|
51
|
+
* marketplace's id (iFood wants a UUID it does not issue) derives it from
|
|
52
|
+
* this and a lost answer never creates a second item.
|
|
53
|
+
*/
|
|
54
|
+
ref: string;
|
|
55
|
+
/** The host's product id: the item's external code on the marketplace. */
|
|
56
|
+
productId: string;
|
|
57
|
+
/** The marketplace's id from the last publish, or null before the first. */
|
|
58
|
+
externalId: string | null;
|
|
59
|
+
/**
|
|
60
|
+
* The photo this marketplace already holds for the item, from an earlier
|
|
61
|
+
* publish: the adapter's own reference (iFood's `imagePath`) and the
|
|
62
|
+
* `imageUrl` it was made from. Reuse it while `sourceUrl` is still the
|
|
63
|
+
* item's `imageUrl` rather than uploading again; null when none is held.
|
|
64
|
+
*/
|
|
65
|
+
storedImage: CatalogueStoredImage | null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A photo a marketplace holds: the adapter's reference to it, and the URL it was made from. */
|
|
69
|
+
export interface CatalogueStoredImage {
|
|
70
|
+
ref: string;
|
|
71
|
+
sourceUrl: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Something a publish that SUCCEEDED could not do, for the host to say:
|
|
76
|
+
* the photo was too large for the marketplace, or it refused the photo.
|
|
77
|
+
*/
|
|
78
|
+
export type CatalogueWarningCode = "IMAGE_TOO_LARGE" | "IMAGE_REFUSED";
|
|
79
|
+
|
|
80
|
+
/** What the adapter is handed to withdraw. */
|
|
81
|
+
export type CatalogueItemRef = Pick<CatalogueItemOut, "ref" | "productId" | "externalId">;
|
|
82
|
+
|
|
83
|
+
/** An image's bytes, for a marketplace that takes an upload rather than a URL. */
|
|
84
|
+
export interface CatalogueImage {
|
|
85
|
+
contentType: string;
|
|
86
|
+
/** The file, base64-encoded, no data-URL prefix. */
|
|
87
|
+
base64: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** An outbound call's answer when it is not a success: refused (final) or retry. */
|
|
91
|
+
export type CatalogueFailure = Exclude<OutboundResult, { kind: "accepted" }>;
|
|
92
|
+
|
|
93
|
+
/** What one catalogue call is handed: the outbound context plus the store's merchant id and the image loader. */
|
|
94
|
+
export interface CatalogueCallContext extends AdapterCallContext {
|
|
95
|
+
/** The connection's merchant id on the marketplace. */
|
|
96
|
+
externalMerchantId: string;
|
|
97
|
+
/** The host's image loader: the bytes behind an item's `imageUrl`, or null when it cannot load them. */
|
|
98
|
+
loadImage(url: string): Promise<CatalogueImage | null>;
|
|
99
|
+
/**
|
|
100
|
+
* The marketplace's id for the host category `name`: the one the engine
|
|
101
|
+
* stored for this connection, else `resolve()` (the adapter's find-or-create)
|
|
102
|
+
* run by ONE publish at a time and stored. A second publish into a category
|
|
103
|
+
* being created is answered `retry`, so a new category is created once.
|
|
104
|
+
*/
|
|
105
|
+
category(name: string, resolve: () => Promise<{ id: string } | CatalogueFailure>): Promise<{ id: string } | CatalogueFailure>;
|
|
106
|
+
/**
|
|
107
|
+
* Forget the id stored for the host category `name` (the marketplace no
|
|
108
|
+
* longer has it: the store deleted it on the marketplace's portal), so the
|
|
109
|
+
* next `category` finds or creates it again.
|
|
110
|
+
*/
|
|
111
|
+
forgetCategory(name: string): Promise<void>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A publish's answer: the marketplace's id for the item, or the refusal and retry shapes of every outbound call. */
|
|
115
|
+
export type CataloguePublishResult =
|
|
116
|
+
| {
|
|
117
|
+
kind: "published";
|
|
118
|
+
externalId: string;
|
|
119
|
+
/**
|
|
120
|
+
* OPTIONAL. The SKU this marketplace's orders will carry for the item,
|
|
121
|
+
* when it is not the host's product id (the item's external code). The
|
|
122
|
+
* engine maps it to the product, so its orders arrive mapped.
|
|
123
|
+
*/
|
|
124
|
+
sku?: string;
|
|
125
|
+
/**
|
|
126
|
+
* OPTIONAL. The photo the marketplace now holds (stored for the next
|
|
127
|
+
* publish to reuse), null when it holds none; absent leaves the stored one.
|
|
128
|
+
*/
|
|
129
|
+
image?: CatalogueStoredImage | null;
|
|
130
|
+
/** OPTIONAL. What the publish could not do although it succeeded. */
|
|
131
|
+
warning?: CatalogueWarningCode;
|
|
132
|
+
}
|
|
133
|
+
| CatalogueFailure;
|
|
134
|
+
|
|
135
|
+
/** A marketplace the store's software writes to. */
|
|
136
|
+
export interface PushCatalogue {
|
|
137
|
+
readonly mode: "push";
|
|
138
|
+
/** Create or replace ONE item in the marketplace's catalogue, available for sale. Idempotent by `item.ref`. */
|
|
139
|
+
publishItem(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult>;
|
|
140
|
+
/** Take ONE item out of the marketplace's catalogue. An item already absent is `accepted`. */
|
|
141
|
+
withdrawItem(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** One published item, as a pull marketplace's menu document lists it. */
|
|
145
|
+
export type CatalogueMenuEntry = CatalogueItemOut;
|
|
146
|
+
|
|
147
|
+
/** What the host states about the menu a pull marketplace reads: its words and money, never the engine's. */
|
|
148
|
+
export interface CatalogueMenuOptions {
|
|
149
|
+
/** The menu's display name, in the store's language. */
|
|
150
|
+
menuName: string;
|
|
151
|
+
/** ISO 4217 code of the prices. */
|
|
152
|
+
currency: string;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A marketplace that reads the menu from the store's software. */
|
|
156
|
+
export interface PullCatalogue {
|
|
157
|
+
readonly mode: "pull";
|
|
158
|
+
/**
|
|
159
|
+
* The menu part of the document the marketplace pulls, built from every item
|
|
160
|
+
* published to this connection. Pure and offline: the host serves it, merged
|
|
161
|
+
* into whatever else that document carries (the store's own details).
|
|
162
|
+
*/
|
|
163
|
+
menuDocument(input: {
|
|
164
|
+
externalMerchantId: string;
|
|
165
|
+
entries: readonly CatalogueMenuEntry[];
|
|
166
|
+
options: CatalogueMenuOptions;
|
|
167
|
+
}): unknown;
|
|
168
|
+
/** Tell the marketplace the menu changed, so it pulls it again. */
|
|
169
|
+
notifyMenuChanged(ctx: CatalogueCallContext): Promise<OutboundResult>;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The catalogue capability an adapter states, or leaves out. */
|
|
173
|
+
export type MarketplaceCatalogue = PushCatalogue | PullCatalogue;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { forgetCategory, resolveCategory, type CategoryRunState } from "./catalogue-category";
|
|
2
|
+
import type { CatalogueCallContext, CatalogueWarningCode } from "./catalogue-port";
|
|
3
|
+
import { connectionMerchantId, readOutboundConnection } from "./integration";
|
|
4
|
+
import type { EngineContext, MarketplaceDb } from "./ports";
|
|
5
|
+
import type { MarketplaceProvider } from "./types";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The catalogue publication's rows and the reads every catalogue path shares
|
|
9
|
+
* (FUT-4768). The table is `marketplace_catalogue_publications`; its states
|
|
10
|
+
* are the mechanism's vocabulary, never a language.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Where one product stands in one marketplace's catalogue. */
|
|
14
|
+
export type CatalogueStatus = "PUBLISHING" | "PUBLISHED" | "WITHDRAWING" | "WITHDRAWN" | "FAILED";
|
|
15
|
+
|
|
16
|
+
/** Which action a FAILED row failed at. */
|
|
17
|
+
export type CatalogueFailedAction = "PUBLISH" | "WITHDRAW";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Why a row FAILED, as a code the host turns into its own words. Vocabulary,
|
|
21
|
+
* not copy: the engine writes no sentence a person reads.
|
|
22
|
+
*
|
|
23
|
+
* - `REFUSED` — the marketplace said no; its own words are in `failureReason`.
|
|
24
|
+
* - `UNAVAILABLE` — no usable answer on any attempt (5xx, 429, timeouts).
|
|
25
|
+
* - `TIMEOUT` — still on its way a day later (the sweep gave up).
|
|
26
|
+
* - `NOT_CONNECTED` — no live connection with a merchant id (archived, removed).
|
|
27
|
+
* - `CREDENTIALS` — no credentials on file, or they would not open.
|
|
28
|
+
* - `PRODUCT_GONE` — the host's catalogue no longer has the product.
|
|
29
|
+
* - `UNSUPPORTED` — the marketplace has no catalogue capability any more.
|
|
30
|
+
* - `INTERNAL` — the engine or the adapter threw (logged, never shown).
|
|
31
|
+
*/
|
|
32
|
+
export type CatalogueFailureCode =
|
|
33
|
+
| "REFUSED"
|
|
34
|
+
| "UNAVAILABLE"
|
|
35
|
+
| "TIMEOUT"
|
|
36
|
+
| "NOT_CONNECTED"
|
|
37
|
+
| "CREDENTIALS"
|
|
38
|
+
| "PRODUCT_GONE"
|
|
39
|
+
| "UNSUPPORTED"
|
|
40
|
+
| "INTERNAL";
|
|
41
|
+
|
|
42
|
+
/** One publication as a host reads it. */
|
|
43
|
+
export interface CataloguePublicationView {
|
|
44
|
+
provider: MarketplaceProvider;
|
|
45
|
+
productId: string;
|
|
46
|
+
status: CatalogueStatus;
|
|
47
|
+
/** The store's price for this marketplace; null is "the store's own price". */
|
|
48
|
+
priceCents: number | null;
|
|
49
|
+
/** The price the last successful publish sent. */
|
|
50
|
+
sentPriceCents: number | null;
|
|
51
|
+
/** The marketplace's id for the item, from the last successful publish. */
|
|
52
|
+
externalId: string | null;
|
|
53
|
+
/** What the last successful publish could not do (the photo); null when it did everything. */
|
|
54
|
+
warningCode: CatalogueWarningCode | null;
|
|
55
|
+
failedAction: CatalogueFailedAction | null;
|
|
56
|
+
/** Why it FAILED; null unless FAILED. The host's copy is keyed by it. */
|
|
57
|
+
failureCode: CatalogueFailureCode | null;
|
|
58
|
+
/**
|
|
59
|
+
* The marketplace's OWN words for a `REFUSED` (its answer's body, truncated);
|
|
60
|
+
* null for every other code. Never an engine or internal message.
|
|
61
|
+
*/
|
|
62
|
+
failureReason: string | null;
|
|
63
|
+
requestedAt: Date;
|
|
64
|
+
publishedAt: Date | null;
|
|
65
|
+
withdrawnAt: Date | null;
|
|
66
|
+
failedAt: Date | null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A publication row, with the engine's own columns. */
|
|
70
|
+
export interface CatalogueRow extends CataloguePublicationView {
|
|
71
|
+
id: string;
|
|
72
|
+
clientId: string;
|
|
73
|
+
imageRef: string | null;
|
|
74
|
+
imageSourceUrl: string | null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export const CATALOGUE_ROW_SELECT = {
|
|
78
|
+
id: true,
|
|
79
|
+
clientId: true,
|
|
80
|
+
provider: true,
|
|
81
|
+
productId: true,
|
|
82
|
+
status: true,
|
|
83
|
+
priceCents: true,
|
|
84
|
+
sentPriceCents: true,
|
|
85
|
+
externalId: true,
|
|
86
|
+
imageRef: true,
|
|
87
|
+
imageSourceUrl: true,
|
|
88
|
+
warningCode: true,
|
|
89
|
+
failedAction: true,
|
|
90
|
+
failureCode: true,
|
|
91
|
+
failureReason: true,
|
|
92
|
+
requestedAt: true,
|
|
93
|
+
publishedAt: true,
|
|
94
|
+
withdrawnAt: true,
|
|
95
|
+
failedAt: true,
|
|
96
|
+
} as const;
|
|
97
|
+
|
|
98
|
+
/** The delegate, or null on a host that has not composed the catalogue model. */
|
|
99
|
+
export type CatalogueTable = NonNullable<MarketplaceDb["marketplaceCataloguePublication"]>;
|
|
100
|
+
|
|
101
|
+
export async function catalogueTable(ctx: EngineContext): Promise<CatalogueTable | null> {
|
|
102
|
+
return (await ctx.ports.db()).marketplaceCataloguePublication ?? null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A row without the engine's own columns. */
|
|
106
|
+
export function viewOf(row: CatalogueRow): CataloguePublicationView {
|
|
107
|
+
return {
|
|
108
|
+
provider: row.provider,
|
|
109
|
+
productId: row.productId,
|
|
110
|
+
status: row.status,
|
|
111
|
+
priceCents: row.priceCents,
|
|
112
|
+
sentPriceCents: row.sentPriceCents,
|
|
113
|
+
externalId: row.externalId,
|
|
114
|
+
warningCode: row.warningCode,
|
|
115
|
+
failedAction: row.failedAction,
|
|
116
|
+
failureCode: row.failureCode,
|
|
117
|
+
failureReason: row.failureReason,
|
|
118
|
+
requestedAt: row.requestedAt,
|
|
119
|
+
publishedAt: row.publishedAt,
|
|
120
|
+
withdrawnAt: row.withdrawnAt,
|
|
121
|
+
failedAt: row.failedAt,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The failure columns cleared, for every write that leaves FAILED. */
|
|
126
|
+
export const NO_FAILURE = { failedAction: null, failureCode: null, failureReason: null, failedAt: null } as const;
|
|
127
|
+
|
|
128
|
+
/** The longest failure reason a row keeps: the column is read by a person in a list. */
|
|
129
|
+
const REASON_LIMIT = 300;
|
|
130
|
+
|
|
131
|
+
export function truncateReason(reason: string): string {
|
|
132
|
+
return reason.length > REASON_LIMIT ? reason.slice(0, REASON_LIMIT) : reason;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Why a connection cannot carry a catalogue call. */
|
|
136
|
+
interface ConnectionProblem {
|
|
137
|
+
problem: "NOT_CONNECTED" | "CREDENTIALS";
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Everything one catalogue call needs from the store's connection, or why it
|
|
142
|
+
* cannot be used: NOT_CONNECTED (none, archived, no merchant id) or
|
|
143
|
+
* CREDENTIALS (none on file, or they will not open).
|
|
144
|
+
*/
|
|
145
|
+
export async function catalogueConnection(
|
|
146
|
+
ctx: EngineContext,
|
|
147
|
+
clientId: string,
|
|
148
|
+
provider: MarketplaceProvider,
|
|
149
|
+
categoryState?: CategoryRunState,
|
|
150
|
+
): Promise<Omit<CatalogueCallContext, "now"> | ConnectionProblem> {
|
|
151
|
+
const merchantId = await connectionMerchantId(ctx, clientId, provider);
|
|
152
|
+
if (merchantId === null) return { problem: "NOT_CONNECTED" };
|
|
153
|
+
try {
|
|
154
|
+
const connection = await readOutboundConnection(ctx, clientId, provider);
|
|
155
|
+
if (!connection) return { problem: "CREDENTIALS" };
|
|
156
|
+
const catalogue = ctx.ports.catalogue;
|
|
157
|
+
return {
|
|
158
|
+
...connection,
|
|
159
|
+
http: ctx.ports.http,
|
|
160
|
+
tokens: ctx.tokens,
|
|
161
|
+
externalMerchantId: merchantId,
|
|
162
|
+
loadImage: (url) => (catalogue ? catalogue.image(url) : Promise.resolve(null)),
|
|
163
|
+
category: (name, resolve) => resolveCategory(ctx, { clientId, provider }, name, resolve, categoryState),
|
|
164
|
+
forgetCategory: (name) => forgetCategory(ctx, { clientId, provider }, name),
|
|
165
|
+
};
|
|
166
|
+
} catch (error) {
|
|
167
|
+
ctx.ports.logger.error(
|
|
168
|
+
`marketplace.catalogue: ${provider} credentials of ${clientId} do not open: ${error instanceof Error ? error.message : String(error)}`,
|
|
169
|
+
);
|
|
170
|
+
return { problem: "CREDENTIALS" };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { catalogueDedupeKey, enqueueCatalogue, type CatalogueJobPayload } from "./catalogue-job";
|
|
2
|
+
import { CATALOGUE_ROW_SELECT, catalogueTable, type CatalogueRow } from "./catalogue-store";
|
|
3
|
+
import type { EngineContext } from "./ports";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The outbound sweep's catalogue half (FUT-4768): nothing the store switched
|
|
7
|
+
* on or off is lost, and nothing waits forever on "sending".
|
|
8
|
+
*
|
|
9
|
+
* A row still owed (PUBLISHING or WITHDRAWING) older than the catalogue job's
|
|
10
|
+
* own retry span is re-queued under a key of its own per pass; one older than
|
|
11
|
+
* the give-up is FAILED, with the action it failed at, so the host shows the
|
|
12
|
+
* reason and "try again" instead of a switch stuck on its way.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Longer than the catalogue job's three attempts with their backoff. */
|
|
16
|
+
export const CATALOGUE_STALE_MS = 10 * 60_000;
|
|
17
|
+
|
|
18
|
+
/** Past this, the marketplace is not going to answer this ask. */
|
|
19
|
+
export const CATALOGUE_GIVE_UP_MS = 24 * 60 * 60_000;
|
|
20
|
+
|
|
21
|
+
/** One pass. Returns how many runs it re-queued. */
|
|
22
|
+
export async function sweepCatalogue(ctx: EngineContext, now: Date): Promise<number> {
|
|
23
|
+
const table = await catalogueTable(ctx);
|
|
24
|
+
if (!table) return 0;
|
|
25
|
+
const stale = new Date(now.getTime() - CATALOGUE_STALE_MS);
|
|
26
|
+
const giveUp = new Date(now.getTime() - CATALOGUE_GIVE_UP_MS);
|
|
27
|
+
for (const [status, failedAction] of [["PUBLISHING", "PUBLISH"], ["WITHDRAWING", "WITHDRAW"]] as const) {
|
|
28
|
+
await table.updateMany({
|
|
29
|
+
where: { status, requestedAt: { lt: giveUp } },
|
|
30
|
+
data: { status: "FAILED", failedAction, failureCode: "TIMEOUT", failureReason: null, failedAt: now },
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
const rows = (await table.findMany({
|
|
34
|
+
where: { status: { in: ["PUBLISHING", "WITHDRAWING"] }, requestedAt: { lt: stale, gte: giveUp } },
|
|
35
|
+
select: CATALOGUE_ROW_SELECT,
|
|
36
|
+
})) as CatalogueRow[];
|
|
37
|
+
for (const row of rows) {
|
|
38
|
+
const action = row.status === "PUBLISHING" ? "publish" : "withdraw";
|
|
39
|
+
const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action };
|
|
40
|
+
await enqueueCatalogue(ctx, payload, `${catalogueDedupeKey(payload, row.requestedAt)}:sweep:${now.getTime()}`);
|
|
41
|
+
}
|
|
42
|
+
return rows.length;
|
|
43
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { catalogueDedupeKey, enqueueCatalogue, type CatalogueJobPayload } from "./catalogue-job";
|
|
2
|
+
import type { CatalogueMenuEntry, CatalogueMenuOptions } from "./catalogue-port";
|
|
3
|
+
import {
|
|
4
|
+
CATALOGUE_ROW_SELECT,
|
|
5
|
+
NO_FAILURE,
|
|
6
|
+
catalogueConnection,
|
|
7
|
+
catalogueTable,
|
|
8
|
+
viewOf,
|
|
9
|
+
type CataloguePublicationView,
|
|
10
|
+
type CatalogueRow,
|
|
11
|
+
type CatalogueTable,
|
|
12
|
+
} from "./catalogue-store";
|
|
13
|
+
import { connectionMerchantId } from "./integration";
|
|
14
|
+
import type { EngineContext } from "./ports";
|
|
15
|
+
import type { MarketplaceProvider } from "./types";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Catalogue publishing, as a host calls it (FUT-4768): from a product's page,
|
|
19
|
+
* the store turns the product ON (`publish`) or OFF (`withdraw`) per connected
|
|
20
|
+
* marketplace, with an optional price for that marketplace, and reads where
|
|
21
|
+
* each stands (`catalogueState`, one read for a whole page).
|
|
22
|
+
*
|
|
23
|
+
* Nothing here calls a marketplace: a publish or withdraw stamps the row and
|
|
24
|
+
* queues `marketplace.catalogue`, whose job makes the call. The host's product
|
|
25
|
+
* is read through its `catalogue` port, never from a host table, and only the
|
|
26
|
+
* job reads it for sending, so what goes out is the product as it is then.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** Why a catalogue call was refused before anything was stamped. Vocabulary, not copy. */
|
|
30
|
+
export type CatalogueRefusalCode =
|
|
31
|
+
/** The marketplace has no catalogue capability, or the host bound no catalogue port or table. */
|
|
32
|
+
| "UNSUPPORTED"
|
|
33
|
+
/** No live connection with credentials and a merchant id. */
|
|
34
|
+
| "NOT_CONNECTED"
|
|
35
|
+
/** The host's catalogue does not have this product. */
|
|
36
|
+
| "UNKNOWN_PRODUCT"
|
|
37
|
+
/** The price for the marketplace is not a positive integer of the smallest unit. */
|
|
38
|
+
| "INVALID_PRICE";
|
|
39
|
+
|
|
40
|
+
/** What `publish` and `withdraw` answer. */
|
|
41
|
+
export type CatalogueActionResult =
|
|
42
|
+
/** Stamped and queued (or already on its way: a double tap is this, with nothing new queued). */
|
|
43
|
+
| { kind: "queued"; publication: CataloguePublicationView }
|
|
44
|
+
/** Nothing to do: the product is not in that marketplace's catalogue, or was never there. */
|
|
45
|
+
| { kind: "unchanged"; publication: CataloguePublicationView | null }
|
|
46
|
+
| { kind: "refused"; code: CatalogueRefusalCode };
|
|
47
|
+
|
|
48
|
+
/** What a pull marketplace's menu document read answers. */
|
|
49
|
+
export type CatalogueDocumentResult =
|
|
50
|
+
| { kind: "document"; document: unknown }
|
|
51
|
+
| { kind: "refused"; code: Exclude<CatalogueRefusalCode, "UNKNOWN_PRODUCT" | "INVALID_PRICE"> };
|
|
52
|
+
|
|
53
|
+
/** One product on one marketplace. */
|
|
54
|
+
export interface CatalogueTarget {
|
|
55
|
+
clientId: string;
|
|
56
|
+
provider: MarketplaceProvider;
|
|
57
|
+
productId: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A publish: the target, and the price for this marketplace — absent keeps the stored one, null is the store's. */
|
|
61
|
+
export interface CataloguePublishInput extends CatalogueTarget {
|
|
62
|
+
priceCents?: number | null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const refused = (code: CatalogueRefusalCode): CatalogueActionResult => ({ kind: "refused", code });
|
|
66
|
+
|
|
67
|
+
/** The table, or why the catalogue cannot be used at all for this marketplace. */
|
|
68
|
+
async function usableTable(ctx: EngineContext, provider: string): Promise<CatalogueTable | null> {
|
|
69
|
+
if (!ctx.ports.catalogue || !ctx.registry.get(provider)?.catalogue) return null;
|
|
70
|
+
return catalogueTable(ctx);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function findRow(table: CatalogueTable, target: CatalogueTarget): Promise<CatalogueRow | null> {
|
|
74
|
+
return (await table.findFirst({
|
|
75
|
+
where: { clientId: target.clientId, provider: target.provider, productId: target.productId },
|
|
76
|
+
select: CATALOGUE_ROW_SELECT,
|
|
77
|
+
})) as CatalogueRow | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function queue(ctx: EngineContext, row: CatalogueRow, action: CatalogueJobPayload["action"]): Promise<CatalogueActionResult> {
|
|
81
|
+
const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action };
|
|
82
|
+
await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, row.requestedAt));
|
|
83
|
+
ctx.ports.publishChanged(row.clientId);
|
|
84
|
+
return { kind: "queued", publication: viewOf(row) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const validPrice = (price: number | null | undefined): boolean =>
|
|
88
|
+
price === undefined || price === null || (Number.isInteger(price) && price > 0);
|
|
89
|
+
|
|
90
|
+
/** Why a publish cannot be asked, or null. */
|
|
91
|
+
async function publishRefusal(ctx: EngineContext, input: CataloguePublishInput): Promise<CatalogueRefusalCode | null> {
|
|
92
|
+
if (!validPrice(input.priceCents)) return "INVALID_PRICE";
|
|
93
|
+
if ("problem" in (await catalogueConnection(ctx, input.clientId, input.provider))) return "NOT_CONNECTED";
|
|
94
|
+
const items = await ctx.ports.catalogue?.items(input.clientId, [input.productId]);
|
|
95
|
+
return items?.has(input.productId) ? null : "UNKNOWN_PRODUCT";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Put the product in the marketplace's catalogue, or send it again (a new
|
|
100
|
+
* price, a retry after FAILED). A double tap while it is on its way keeps the
|
|
101
|
+
* same ask and queues nothing new.
|
|
102
|
+
*/
|
|
103
|
+
export async function publishToCatalogue(ctx: EngineContext, input: CataloguePublishInput): Promise<CatalogueActionResult> {
|
|
104
|
+
const table = await usableTable(ctx, input.provider);
|
|
105
|
+
if (!table) return refused("UNSUPPORTED");
|
|
106
|
+
const refusal = await publishRefusal(ctx, input);
|
|
107
|
+
if (refusal) return refused(refusal);
|
|
108
|
+
const existing = await findRow(table, input);
|
|
109
|
+
const now = ctx.ports.clock.now();
|
|
110
|
+
const price = input.priceCents === undefined ? {} : { priceCents: input.priceCents };
|
|
111
|
+
// A double tap keeps the ask on its way; a NEW price is a new ask, so the
|
|
112
|
+
// run already queued (which reads the row's price at its own instant) misses
|
|
113
|
+
// its stamp and the new run sends the new price.
|
|
114
|
+
const samePrice = input.priceCents === undefined || input.priceCents === existing?.priceCents;
|
|
115
|
+
const asked = existing?.status === "PUBLISHING" && samePrice ? {} : { requestedAt: now };
|
|
116
|
+
const row = (await table.upsert({
|
|
117
|
+
where: { clientId_provider_productId: { clientId: input.clientId, provider: input.provider, productId: input.productId } },
|
|
118
|
+
create: { clientId: input.clientId, provider: input.provider, productId: input.productId, status: "PUBLISHING", requestedAt: now, ...price },
|
|
119
|
+
update: { status: "PUBLISHING", ...NO_FAILURE, ...asked, ...price },
|
|
120
|
+
select: CATALOGUE_ROW_SELECT,
|
|
121
|
+
})) as CatalogueRow;
|
|
122
|
+
return queue(ctx, row, "publish");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Take the product out of the marketplace's catalogue. A product never
|
|
127
|
+
* switched on (no row, or WITHDRAWN) is `unchanged`; a double tap while it is
|
|
128
|
+
* on its way out queues nothing new; a withdraw while a publish is on its way
|
|
129
|
+
* wins (the job re-withdraws a publish that lands after it).
|
|
130
|
+
*
|
|
131
|
+
* A withdraw is SENT even after a publish that FAILED: a call whose answer was
|
|
132
|
+
* lost may have put the item there, and a marketplace answers a withdraw of
|
|
133
|
+
* an item it does not have as done. Only a store with no live connection any
|
|
134
|
+
* more (archived, removed) ends WITHDRAWN at once: there is nobody to tell.
|
|
135
|
+
*/
|
|
136
|
+
export async function withdrawFromCatalogue(ctx: EngineContext, target: CatalogueTarget): Promise<CatalogueActionResult> {
|
|
137
|
+
const table = await usableTable(ctx, target.provider);
|
|
138
|
+
if (!table) return refused("UNSUPPORTED");
|
|
139
|
+
const existing = await findRow(table, target);
|
|
140
|
+
if (!existing || existing.status === "WITHDRAWN") return { kind: "unchanged", publication: existing && viewOf(existing) };
|
|
141
|
+
if (existing.status === "WITHDRAWING") return queue(ctx, existing, "withdraw");
|
|
142
|
+
const now = ctx.ports.clock.now();
|
|
143
|
+
// No live connection (archived, removed): nothing to tell, so it is out here and now.
|
|
144
|
+
const local = (await connectionMerchantId(ctx, target.clientId, target.provider)) === null;
|
|
145
|
+
const data = local
|
|
146
|
+
? { status: "WITHDRAWN", withdrawnAt: now, requestedAt: now, ...NO_FAILURE }
|
|
147
|
+
: { status: "WITHDRAWING", requestedAt: now, ...NO_FAILURE };
|
|
148
|
+
const moved = await table.updateMany({ where: { id: existing.id, status: existing.status }, data });
|
|
149
|
+
// Lost a race with another write: answer what the row now says.
|
|
150
|
+
const row = (await findRow(table, target)) ?? existing;
|
|
151
|
+
if (moved.count === 0 || local) {
|
|
152
|
+
ctx.ports.publishChanged(target.clientId);
|
|
153
|
+
return { kind: "unchanged", publication: viewOf(row) };
|
|
154
|
+
}
|
|
155
|
+
return queue(ctx, row, "withdraw");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Where these products stand on these marketplaces, in ONE read: a product's
|
|
160
|
+
* page asks for one product on every connected marketplace; a list asks for
|
|
161
|
+
* many. Rows only for what was ever switched on.
|
|
162
|
+
*/
|
|
163
|
+
export async function readCatalogueState(
|
|
164
|
+
ctx: EngineContext,
|
|
165
|
+
input: { clientId: string; productIds: readonly string[]; providers?: readonly string[] },
|
|
166
|
+
): Promise<CataloguePublicationView[]> {
|
|
167
|
+
const table = await catalogueTable(ctx);
|
|
168
|
+
if (!table || input.productIds.length === 0) return [];
|
|
169
|
+
const rows = (await table.findMany({
|
|
170
|
+
where: {
|
|
171
|
+
clientId: input.clientId,
|
|
172
|
+
productId: { in: [...input.productIds] },
|
|
173
|
+
...(input.providers ? { provider: { in: [...input.providers] } } : {}),
|
|
174
|
+
},
|
|
175
|
+
select: CATALOGUE_ROW_SELECT,
|
|
176
|
+
})) as CatalogueRow[];
|
|
177
|
+
return rows.map(viewOf);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Every product a pull marketplace's menu lists: switched on, on its way, or
|
|
182
|
+
* already published once and since FAILED to be published again (it stays,
|
|
183
|
+
* at the price last sent, until it is withdrawn).
|
|
184
|
+
*/
|
|
185
|
+
const IN_MENU = ["PUBLISHING", "PUBLISHED", "FAILED"];
|
|
186
|
+
|
|
187
|
+
/** Whether a row belongs in the served menu, and at which price. */
|
|
188
|
+
function menuPrice(row: CatalogueRow, storePrice: number): number | null {
|
|
189
|
+
if (row.status !== "FAILED") return row.priceCents ?? storePrice;
|
|
190
|
+
// Published, and not withdrawn since: a withdraw → re-publish that FAILED is
|
|
191
|
+
// not on the marketplace's menu, so it is not listed at an old price.
|
|
192
|
+
const live = row.publishedAt !== null && (row.withdrawnAt === null || row.withdrawnAt < row.publishedAt);
|
|
193
|
+
const republishFailed = row.failedAction === "PUBLISH" && live;
|
|
194
|
+
return republishFailed ? (row.sentPriceCents ?? row.priceCents ?? storePrice) : null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The menu part of the document a pull marketplace reads, for the host to
|
|
199
|
+
* serve (merged into the rest of that document, which is the host's). Built
|
|
200
|
+
* from every product switched on for the connection, read through the host's
|
|
201
|
+
* catalogue port; a product that no longer exists is left out.
|
|
202
|
+
*/
|
|
203
|
+
export async function readCatalogueDocument(
|
|
204
|
+
ctx: EngineContext,
|
|
205
|
+
input: { clientId: string; provider: MarketplaceProvider; options: CatalogueMenuOptions },
|
|
206
|
+
): Promise<CatalogueDocumentResult> {
|
|
207
|
+
const catalogue = ctx.registry.get(input.provider)?.catalogue;
|
|
208
|
+
const table = await usableTable(ctx, input.provider);
|
|
209
|
+
if (!table || catalogue?.mode !== "pull") return { kind: "refused", code: "UNSUPPORTED" };
|
|
210
|
+
const connection = await catalogueConnection(ctx, input.clientId, input.provider);
|
|
211
|
+
if ("problem" in connection) return { kind: "refused", code: "NOT_CONNECTED" };
|
|
212
|
+
const rows = (await table.findMany({
|
|
213
|
+
where: { clientId: input.clientId, provider: input.provider, status: { in: IN_MENU } },
|
|
214
|
+
select: CATALOGUE_ROW_SELECT,
|
|
215
|
+
orderBy: { createdAt: "asc" },
|
|
216
|
+
})) as CatalogueRow[];
|
|
217
|
+
const items = (await ctx.ports.catalogue?.items(input.clientId, rows.map((row) => row.productId))) ?? new Map();
|
|
218
|
+
const entries: CatalogueMenuEntry[] = rows.flatMap((row) => {
|
|
219
|
+
const item = items.get(row.productId);
|
|
220
|
+
const priceCents = item ? menuPrice(row, item.priceCents) : null;
|
|
221
|
+
if (!item || priceCents === null) return [];
|
|
222
|
+
return [{ ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage: null }];
|
|
223
|
+
});
|
|
224
|
+
const document = catalogue.menuDocument({ externalMerchantId: connection.externalMerchantId, entries, options: input.options });
|
|
225
|
+
return { kind: "document", document };
|
|
226
|
+
}
|
package/src/core/engine.ts
CHANGED
|
@@ -20,6 +20,19 @@ import {
|
|
|
20
20
|
type DecisionInput,
|
|
21
21
|
type DecisionResult,
|
|
22
22
|
} from "./decisions";
|
|
23
|
+
import {
|
|
24
|
+
publishToCatalogue,
|
|
25
|
+
readCatalogueDocument,
|
|
26
|
+
readCatalogueState,
|
|
27
|
+
withdrawFromCatalogue,
|
|
28
|
+
type CatalogueActionResult,
|
|
29
|
+
type CatalogueDocumentResult,
|
|
30
|
+
type CataloguePublishInput,
|
|
31
|
+
type CatalogueTarget,
|
|
32
|
+
} from "./catalogue";
|
|
33
|
+
import { runCatalogue, type CatalogueJobPayload, type CatalogueOutcome } from "./catalogue-job";
|
|
34
|
+
import type { CatalogueMenuOptions } from "./catalogue-port";
|
|
35
|
+
import type { CataloguePublicationView } from "./catalogue-store";
|
|
23
36
|
import {
|
|
24
37
|
runFetchOrder,
|
|
25
38
|
type FetchOrderJobPayload,
|
|
@@ -170,6 +183,31 @@ export interface MarketplaceEngine {
|
|
|
170
183
|
runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;
|
|
171
184
|
/** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */
|
|
172
185
|
runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* How this marketplace's catalogue is published (`push`, `pull`), or null
|
|
189
|
+
* when it cannot be: the adapter states no catalogue, or the host bound no
|
|
190
|
+
* catalogue port (FUT-4768).
|
|
191
|
+
*/
|
|
192
|
+
catalogueMode(provider: string): "push" | "pull" | null;
|
|
193
|
+
/** Put a product in a marketplace's catalogue (or send it again), with an optional price for it. Queued. */
|
|
194
|
+
publish(input: CataloguePublishInput): Promise<CatalogueActionResult>;
|
|
195
|
+
/** Take a product out of a marketplace's catalogue. Queued. */
|
|
196
|
+
withdraw(input: CatalogueTarget): Promise<CatalogueActionResult>;
|
|
197
|
+
/** Where these products stand on these marketplaces, in one read. */
|
|
198
|
+
catalogueState(input: {
|
|
199
|
+
clientId: string;
|
|
200
|
+
productIds: readonly string[];
|
|
201
|
+
providers?: readonly string[];
|
|
202
|
+
}): Promise<CataloguePublicationView[]>;
|
|
203
|
+
/** The menu part of the document a PULL marketplace reads, for the host to serve. */
|
|
204
|
+
catalogueDocument(input: {
|
|
205
|
+
clientId: string;
|
|
206
|
+
provider: MarketplaceProvider;
|
|
207
|
+
options: CatalogueMenuOptions;
|
|
208
|
+
}): Promise<CatalogueDocumentResult>;
|
|
209
|
+
/** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
|
|
210
|
+
runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
|
|
173
211
|
}
|
|
174
212
|
|
|
175
213
|
/**
|
|
@@ -233,5 +271,13 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
|
|
|
233
271
|
sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),
|
|
234
272
|
runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
|
|
235
273
|
runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
|
|
274
|
+
|
|
275
|
+
// Null too when the host bound no catalogue port: nothing could be published.
|
|
276
|
+
catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
|
|
277
|
+
publish: (input) => publishToCatalogue(ctx, input),
|
|
278
|
+
withdraw: (input) => withdrawFromCatalogue(ctx, input),
|
|
279
|
+
catalogueState: (input) => readCatalogueState(ctx, input),
|
|
280
|
+
catalogueDocument: (input) => readCatalogueDocument(ctx, input),
|
|
281
|
+
runCatalogue: (payload, attempt) => runCatalogue(ctx, payload, attempt),
|
|
236
282
|
};
|
|
237
283
|
}
|