@12-apps/marketplace 1.8.0 → 1.9.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/README.md +102 -8
- package/dist/99food/index.d.ts +30 -54
- package/dist/99food/index.js +60 -418
- package/dist/99food/index.js.map +1 -1
- package/dist/chunk-PYHNM47K.js +478 -0
- package/dist/chunk-PYHNM47K.js.map +1 -0
- package/dist/client-B4EQCRD_.d.ts +20 -0
- package/dist/keeta/en-US.d.ts +19 -0
- package/dist/keeta/en-US.js +23 -0
- package/dist/keeta/en-US.js.map +1 -0
- package/dist/keeta/index.d.ts +253 -0
- package/dist/keeta/index.js +388 -0
- package/dist/keeta/index.js.map +1 -0
- package/dist/keeta/pt-BR.d.ts +23 -0
- package/dist/keeta/pt-BR.js +23 -0
- package/dist/keeta/pt-BR.js.map +1 -0
- package/package.json +14 -2
- package/src/99food/catalogue.ts +19 -89
- package/src/99food/copy.ts +4 -19
- package/src/99food/index.ts +28 -33
- package/src/99food/normalize.ts +11 -253
- package/src/99food/outbound.ts +29 -270
- package/src/99food/pause.ts +7 -22
- package/src/index.ts +2 -1
- package/src/keeta/authorization.ts +226 -0
- package/src/keeta/copy.ts +27 -0
- package/src/keeta/en-US.ts +19 -0
- package/src/keeta/index.ts +162 -0
- package/src/keeta/merchant.ts +70 -0
- package/src/keeta/normalize.ts +131 -0
- package/src/keeta/outbound.ts +55 -0
- package/src/keeta/pt-BR.ts +23 -0
- package/src/keeta/signature.ts +85 -0
- package/src/open-delivery/client.ts +185 -0
- package/src/open-delivery/merchant.ts +126 -0
- package/src/open-delivery/normalize.ts +269 -0
- package/src/open-delivery/orders.ts +241 -0
- package/src/open-delivery/reasons.ts +26 -0
package/src/99food/outbound.ts
CHANGED
|
@@ -1,280 +1,39 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
outboundResultOf,
|
|
4
|
-
tokenGrantResultOf,
|
|
5
|
-
type AdapterCallContext,
|
|
6
|
-
type CancellationRequestInput,
|
|
7
|
-
type FetchOrderResult,
|
|
8
|
-
type MarketplaceHttpResponse,
|
|
9
|
-
type OutboundOrderRef,
|
|
10
|
-
type OutboundResult,
|
|
11
|
-
type StatusFacts,
|
|
12
|
-
} from "../core/adapter";
|
|
13
|
-
import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from "./normalize";
|
|
1
|
+
import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from "../open-delivery/client";
|
|
2
|
+
import { NINETY_NINE_FOOD_PROVIDER } from "./normalize";
|
|
14
3
|
|
|
15
4
|
/**
|
|
16
|
-
*
|
|
17
|
-
* grant, the order fetch, confirm
|
|
18
|
-
*
|
|
19
|
-
*
|
|
5
|
+
* 99Food's Open Delivery DIALECT: v1.7.1 as the standard writes it. The calls
|
|
6
|
+
* themselves (the grant, the order fetch, confirm, requestCancellation, the
|
|
7
|
+
* status steps) are `../open-delivery/`'s; this file only says where and how
|
|
8
|
+
* 99Food takes them.
|
|
9
|
+
*
|
|
10
|
+
* - Token: `POST /oauth/token`, form-encoded `client_id`, `client_secret`,
|
|
11
|
+
* `grant_type=client_credentials`.
|
|
12
|
+
* - Bodies: plain JSON; no request signature.
|
|
20
13
|
*
|
|
21
14
|
* The one thing the spec cannot pin is WHERE: Open Delivery standardizes the
|
|
22
15
|
* paths under each Ordering Application's own base URL, and 99Food gives its
|
|
23
16
|
* base URLs to a partner at onboarding. So the base URL per environment is
|
|
24
|
-
* the adapter's REQUIRED config, never a guessed default.
|
|
25
|
-
* 99Food: the HTTP client is the host's port, answered by a fake.
|
|
17
|
+
* the adapter's REQUIRED config, never a guessed default.
|
|
26
18
|
*/
|
|
27
19
|
|
|
28
20
|
/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */
|
|
29
|
-
export type NinetyNineFoodApiBaseUrls =
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
|
|
48
|
-
try {
|
|
49
|
-
const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };
|
|
50
|
-
if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
|
|
51
|
-
const expires =
|
|
52
|
-
typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
|
|
53
|
-
return { token: parsed.access_token, expiresInSeconds: expires };
|
|
54
|
-
} catch {
|
|
55
|
-
return null;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* A bearer token from the per-process cache, or a fresh `client_credentials`
|
|
61
|
-
* grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,
|
|
62
|
-
* `grant_type`). Keyed by environment and client id; memory only.
|
|
63
|
-
*/
|
|
64
|
-
export async function bearer(
|
|
65
|
-
ctx: AdapterCallContext,
|
|
66
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
67
|
-
): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
|
|
68
|
-
const cached = ctx.tokens.get(tokenKey(ctx));
|
|
69
|
-
if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
|
|
70
|
-
const response = await ctx.http({
|
|
71
|
-
method: "POST",
|
|
72
|
-
url: `${baseOf(ctx, bases)}/oauth/token`,
|
|
73
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
74
|
-
body: new URLSearchParams({
|
|
75
|
-
client_id: ctx.credentials.clientId,
|
|
76
|
-
client_secret: ctx.credentials.clientSecret,
|
|
77
|
-
grant_type: "client_credentials",
|
|
78
|
-
}).toString(),
|
|
79
|
-
});
|
|
80
|
-
if (response.status < 200 || response.status >= 300) {
|
|
81
|
-
const result = tokenGrantResultOf(response);
|
|
82
|
-
return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
|
|
83
|
-
}
|
|
84
|
-
const token = tokenOf(response.body);
|
|
85
|
-
if (!token) return { kind: "retry", reason: "99Food answered the token grant without a token" };
|
|
86
|
-
ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });
|
|
87
|
-
return { token: token.token };
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** One authenticated call to an order's resource, the raw answer or the result that ends it. */
|
|
91
|
-
async function callOrder(
|
|
92
|
-
ctx: AdapterCallContext,
|
|
93
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
94
|
-
request: { method: "GET" | "POST"; externalOrderId: string; action: string | null; body?: unknown },
|
|
95
|
-
): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: "accepted" }>> {
|
|
96
|
-
const auth = await bearer(ctx, bases);
|
|
97
|
-
if (!("token" in auth)) return auth;
|
|
98
|
-
const suffix = request.action === null ? "" : `/${request.action}`;
|
|
99
|
-
const response = await ctx.http({
|
|
100
|
-
method: request.method,
|
|
101
|
-
url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,
|
|
102
|
-
headers: {
|
|
103
|
-
Authorization: `Bearer ${auth.token}`,
|
|
104
|
-
...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
105
|
-
},
|
|
106
|
-
...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
|
|
107
|
-
});
|
|
108
|
-
// A 401 is a token that went stale under us: forget it, and the retry fetches another.
|
|
109
|
-
if (response.status !== 401) return response;
|
|
110
|
-
ctx.tokens.delete(tokenKey(ctx));
|
|
111
|
-
return { kind: "retry", reason: "99Food refused the token" };
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */
|
|
115
|
-
function alreadyCancelled(response: MarketplaceHttpResponse): boolean {
|
|
116
|
-
if (response.status !== 422) return false;
|
|
117
|
-
try {
|
|
118
|
-
return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === "CANCELLED";
|
|
119
|
-
} catch {
|
|
120
|
-
return false;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** {@link answered} for a fetch: a call that never got an answer is a retry. */
|
|
125
|
-
async function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {
|
|
126
|
-
try {
|
|
127
|
-
return await call();
|
|
128
|
-
} catch (error) {
|
|
129
|
-
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */
|
|
134
|
-
export function openDeliveryFetchOrder(
|
|
135
|
-
ctx: AdapterCallContext,
|
|
136
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
137
|
-
order: { externalOrderId: string },
|
|
138
|
-
options: { missingStreetNumber: string },
|
|
139
|
-
): Promise<FetchOrderResult> {
|
|
140
|
-
return fetched(async () => {
|
|
141
|
-
const response = await callOrder(ctx, bases, { method: "GET", externalOrderId: order.externalOrderId, action: null });
|
|
142
|
-
if ("kind" in response) return response;
|
|
143
|
-
const result = outboundResultOf(response);
|
|
144
|
-
if (result.kind !== "accepted") return result;
|
|
145
|
-
let body: unknown;
|
|
146
|
-
try {
|
|
147
|
-
body = JSON.parse(response.body);
|
|
148
|
-
} catch {
|
|
149
|
-
return { kind: "refused", status: response.status, message: "the order is not JSON" };
|
|
150
|
-
}
|
|
151
|
-
const normalized = normalizeOpenDeliveryOrder(body, options);
|
|
152
|
-
return normalized
|
|
153
|
-
? { kind: "order", order: normalized }
|
|
154
|
-
: { kind: "refused", status: response.status, message: "the order carries no id or no line" };
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:
|
|
160
|
-
* `orderExternalCode` (the host's own order id) and `createdAt`, plus the
|
|
161
|
-
* `preparationTime` in minutes when the store stated one. The spec describes
|
|
162
|
-
* `createdAt` with the ORDER's creation text (a copy of another schema's), so
|
|
163
|
-
* it is sent as the moment of the confirmation: ESTIMATED.
|
|
164
|
-
*
|
|
165
|
-
* Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`
|
|
166
|
-
* ("unable to process the contained instructions. (Check if the instruction
|
|
167
|
-
* has not been sent before.)"), and its body cannot tell a duplicate from a
|
|
168
|
-
* cancelled order. So a retried confirm whose first answer was lost reads
|
|
169
|
-
* "não confirmou" with the app link — a false alarm a person dismisses on
|
|
170
|
-
* 99Food — and a confirm 99Food truly refused is never stamped confirmed.
|
|
171
|
-
*/
|
|
172
|
-
export function openDeliveryConfirm(
|
|
173
|
-
ctx: AdapterCallContext,
|
|
174
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
175
|
-
order: OutboundOrderRef,
|
|
176
|
-
input: { preparationMinutes: number | null },
|
|
177
|
-
): Promise<OutboundResult> {
|
|
178
|
-
return answered(async () => {
|
|
179
|
-
const response = await callOrder(ctx, bases, {
|
|
180
|
-
method: "POST",
|
|
181
|
-
externalOrderId: order.externalOrderId,
|
|
182
|
-
action: "confirm",
|
|
183
|
-
body: {
|
|
184
|
-
orderExternalCode: order.hostOrderCode,
|
|
185
|
-
createdAt: ctx.now.toISOString(),
|
|
186
|
-
...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),
|
|
187
|
-
},
|
|
188
|
-
});
|
|
189
|
-
if ("kind" in response) return response;
|
|
190
|
-
return outboundResultOf(response);
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* `POST /v1/orders/{orderId}/requestCancellation` with the spec's
|
|
196
|
-
* `RequestCancelled`: `reason` (free text: the store's, else the label),
|
|
197
|
-
* `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means
|
|
198
|
-
* taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`
|
|
199
|
-
* event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is
|
|
200
|
-
* cancelled already, which is what the request wanted.
|
|
201
|
-
*
|
|
202
|
-
* `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,
|
|
203
|
-
* and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU
|
|
204
|
-
* map is keyed on. The field is optional.
|
|
205
|
-
*/
|
|
206
|
-
export function openDeliveryRequestCancellation(
|
|
207
|
-
ctx: AdapterCallContext,
|
|
208
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
209
|
-
order: OutboundOrderRef,
|
|
210
|
-
input: CancellationRequestInput,
|
|
211
|
-
): Promise<OutboundResult> {
|
|
212
|
-
return answered(async () => {
|
|
213
|
-
const response = await callOrder(ctx, bases, {
|
|
214
|
-
method: "POST",
|
|
215
|
-
externalOrderId: order.externalOrderId,
|
|
216
|
-
action: "requestCancellation",
|
|
217
|
-
body: { reason: input.text === "" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },
|
|
218
|
-
});
|
|
219
|
-
if ("kind" in response) return response;
|
|
220
|
-
if (alreadyCancelled(response)) return { kind: "accepted" };
|
|
221
|
-
const result = outboundResultOf(response);
|
|
222
|
-
// Open Delivery's 400 is a malformed request (a bad id or body: ours);
|
|
223
|
-
// its 422 is the business answer and stays a refusal.
|
|
224
|
-
return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* What 99Food is told per step (FUT-4653), from Open Delivery v1.7.1's
|
|
230
|
-
* `openapi.yaml` (https://abrasel-nacional.github.io/opendelivery/openapi.yaml,
|
|
231
|
-
* read 2026-11-25, paths at lines 1605-1890):
|
|
232
|
-
*
|
|
233
|
-
* - READY: `POST /v1/orders/{id}/readyForPickup`, "ready for pickup by the
|
|
234
|
-
* customer or delivery person"; 202. Every kind of order.
|
|
235
|
-
* - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`
|
|
236
|
-
* (`deliveryTrackingInfo` optional, sent empty), and "a DISPATCHED event is
|
|
237
|
-
* expected after this action". Only where the logistics is the merchant's.
|
|
238
|
-
* - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a
|
|
239
|
-
* take-out `POST /v1/orders/{id}/pickedUp`. Both optional in the spec. The
|
|
240
|
-
* marketplace's own fleet: none.
|
|
241
|
-
*
|
|
242
|
-
* The kind of order is `deliveredBy` (null: a take-out). That a take-out's
|
|
243
|
-
* order states no `deliveredBy` is how 99Food's order reads (ESTIMATED: an
|
|
244
|
-
* order that merely omits it reads as a take-out here).
|
|
245
|
-
*/
|
|
246
|
-
const STATUS_PATH: Readonly<Record<string, (facts: StatusFacts) => { action: string; body?: unknown } | null>> = {
|
|
247
|
-
READY: () => ({ action: "readyForPickup" }),
|
|
248
|
-
DISPATCHED: (facts) => (facts.deliveredBy === "MERCHANT" ? { action: "dispatch", body: {} } : null),
|
|
249
|
-
HANDED_OVER: (facts) =>
|
|
250
|
-
facts.deliveredBy === "MERCHANT"
|
|
251
|
-
? { action: "delivered", body: {} }
|
|
252
|
-
: facts.deliveredBy === null
|
|
253
|
-
? { action: "pickedUp", body: {} }
|
|
254
|
-
: null,
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
/** Whether 99Food takes this step for this kind of order: answered offline. */
|
|
258
|
-
export function openDeliveryStatusSupported(facts: StatusFacts): boolean {
|
|
259
|
-
return STATUS_PATH[facts.step]?.(facts) != null;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
/** Tell 99Food a step happened. `unsupported` when the spec has no call for it. */
|
|
263
|
-
export function openDeliveryInformStatus(
|
|
264
|
-
ctx: AdapterCallContext,
|
|
265
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
266
|
-
order: OutboundOrderRef,
|
|
267
|
-
facts: StatusFacts,
|
|
268
|
-
): Promise<OutboundResult | { kind: "unsupported" }> {
|
|
269
|
-
const path = STATUS_PATH[facts.step]?.(facts) ?? null;
|
|
270
|
-
if (path === null) return Promise.resolve({ kind: "unsupported" });
|
|
271
|
-
return answered(async () => {
|
|
272
|
-
const response = await callOrder(ctx, bases, {
|
|
273
|
-
method: "POST",
|
|
274
|
-
externalOrderId: order.externalOrderId,
|
|
275
|
-
action: path.action,
|
|
276
|
-
...(path.body === undefined ? {} : { body: path.body }),
|
|
277
|
-
});
|
|
278
|
-
return "kind" in response ? response : outboundResultOf(response);
|
|
279
|
-
});
|
|
21
|
+
export type NinetyNineFoodApiBaseUrls = OpenDeliveryApiBaseUrls;
|
|
22
|
+
|
|
23
|
+
/** 99Food's dialect, for the base URLs it was given. */
|
|
24
|
+
export function ninetyNineFoodDialect(bases: NinetyNineFoodApiBaseUrls): OpenDeliveryDialect {
|
|
25
|
+
return {
|
|
26
|
+
provider: NINETY_NINE_FOOD_PROVIDER,
|
|
27
|
+
name: "99Food",
|
|
28
|
+
bases,
|
|
29
|
+
tokenGrant: (ctx) => ({
|
|
30
|
+
contentType: "application/x-www-form-urlencoded",
|
|
31
|
+
body: new URLSearchParams({
|
|
32
|
+
client_id: ctx.credentials.clientId,
|
|
33
|
+
client_secret: ctx.credentials.clientSecret,
|
|
34
|
+
grant_type: "client_credentials",
|
|
35
|
+
}).toString(),
|
|
36
|
+
}),
|
|
37
|
+
serialize: (body) => JSON.stringify(body),
|
|
38
|
+
};
|
|
280
39
|
}
|
package/src/99food/pause.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { AdapterCallContext, OutboundResult } from "../core/adapter";
|
|
2
2
|
import type { MarketplaceAvailability } from "../core/pause-port";
|
|
3
|
-
import {
|
|
3
|
+
import { openDeliveryMerchantUpdate, openDeliverySwitchAvailability } from "../open-delivery/merchant";
|
|
4
|
+
import { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from "./outbound";
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the
|
|
@@ -28,29 +29,13 @@ export function openDeliverySetMerchantStatus(
|
|
|
28
29
|
bases: NinetyNineFoodApiBaseUrls,
|
|
29
30
|
status: "AVAILABLE" | "UNAVAILABLE",
|
|
30
31
|
): Promise<OutboundResult> {
|
|
31
|
-
return
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const response = await ctx.http({
|
|
35
|
-
method: "POST",
|
|
36
|
-
url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
|
|
37
|
-
headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
|
|
38
|
-
body: JSON.stringify({ merchantStatus: status }),
|
|
39
|
-
});
|
|
40
|
-
if (response.status !== 401) return outboundResultOf(response);
|
|
41
|
-
ctx.tokens.delete(tokenKey(ctx));
|
|
42
|
-
return { kind: "retry", reason: "99Food refused the token" };
|
|
32
|
+
return openDeliveryMerchantUpdate(ctx, ninetyNineFoodDialect(bases), {
|
|
33
|
+
path: "/v1/merchantUpdate",
|
|
34
|
+
body: { merchantStatus: status },
|
|
43
35
|
});
|
|
44
36
|
}
|
|
45
37
|
|
|
46
38
|
/** 99Food's availability capability: Open Delivery's merchant status, a switch. */
|
|
47
39
|
export function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {
|
|
48
|
-
return
|
|
49
|
-
kind: "switch",
|
|
50
|
-
pause: async (ctx, request) => {
|
|
51
|
-
const result = await openDeliverySetMerchantStatus(ctx, bases, "UNAVAILABLE");
|
|
52
|
-
return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
|
|
53
|
-
},
|
|
54
|
-
resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, "AVAILABLE"),
|
|
55
|
-
};
|
|
40
|
+
return openDeliverySwitchAvailability((ctx, _merchantId, status) => openDeliverySetMerchantStatus(ctx, bases, status));
|
|
56
41
|
}
|
package/src/index.ts
CHANGED
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* acceptance clock and its sweep, the SKU map, the integration settings and
|
|
14
14
|
* the outbound engine, and knows no marketplace by name. Each marketplace is
|
|
15
15
|
* an adapter at its own subpath (`@12-apps/marketplace/ifood`,
|
|
16
|
-
* `@12-apps/marketplace/99food`, `@12-apps/marketplace/
|
|
16
|
+
* `@12-apps/marketplace/99food`, `@12-apps/marketplace/keeta`,
|
|
17
|
+
* `@12-apps/marketplace/rappi`), registered at
|
|
17
18
|
* mount. The wiring manifests are at `./manifest` and `./manifest/server`.
|
|
18
19
|
*
|
|
19
20
|
* Everything the engine needs from its host is a required port with no
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { outboundResultOf, type AdapterCallContext } from "../core/adapter";
|
|
2
|
+
import { asString, firstString, pick } from "../core/payload-read";
|
|
3
|
+
import { isStop, openDeliveryCall, type OpenDeliveryDialect, type OpenDeliveryStop } from "../open-delivery/client";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
|
|
7
|
+
* "Autorização Self-serve do Merchant", read 2026-11-26 at
|
|
8
|
+
* https://api-docs.mykeeta.com/apis/opendelivery/merchant-self-serve-authorization).
|
|
9
|
+
* Not on the adapter port: connecting a store is the host's flow, and these
|
|
10
|
+
* are the calls it is built from.
|
|
11
|
+
*
|
|
12
|
+
* 1. {@link KeetaAuthorization.authorizationUrl}: `GET
|
|
13
|
+
* /oauth/authorization/url?clientId=&redirectUri=` (no token: a token
|
|
14
|
+
* needs at least one authorized store), the link the merchant opens.
|
|
15
|
+
* 2. The merchant authorizes; Keeta redirects to `redirectUri` with `authId`
|
|
16
|
+
* (and `state`, `appId`, `timestamp`), and POSTs the authorization webhook
|
|
17
|
+
* ({@link normalizeKeetaAuthorizationEvent}: `opType` 1 added, 2 revoked).
|
|
18
|
+
* 3. {@link KeetaAuthorization.authorizedShops}: `GET
|
|
19
|
+
* /oauth/authorized/{authId}/merchantInfo?pageNum=&pageSize=` lists the
|
|
20
|
+
* stores of that authorization (Keeta's ids, names, addresses, time zones).
|
|
21
|
+
* 4. The host maps a Keeta store to its own, then
|
|
22
|
+
* {@link KeetaAuthorization.onboard}: `PUT /v1/merchantOnboarding?merchantId=`
|
|
23
|
+
* binds the SOFTWARE's merchant id (the connection's `externalMerchantId`)
|
|
24
|
+
* to `keetaMerchantId` and registers the `GET /v1/merchant` URL and the
|
|
25
|
+
* orders webhook. "Without onboarding there are no order events"; sending
|
|
26
|
+
* it again for the same id REPLACES the mapping. Answer 201.
|
|
27
|
+
*
|
|
28
|
+
* ESTIMATED: the JSON answer the authorization webhook wants ("200 within
|
|
29
|
+
* ~5 s, with JSON containing `code` and `message`": the values are not
|
|
30
|
+
* given, {@link KEETA_AUTHORIZATION_WEBHOOK_ANSWER} sends 0 and "success").
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/** What the authorization webhook is answered with, 200, within ~5 s. ESTIMATED values. */
|
|
34
|
+
export const KEETA_AUTHORIZATION_WEBHOOK_ANSWER = { code: 0, message: "success" } as const;
|
|
35
|
+
|
|
36
|
+
/** One authorization change Keeta reported (event 1301 added, 1302 revoked). */
|
|
37
|
+
export interface KeetaAuthorizationEvent {
|
|
38
|
+
authId: string;
|
|
39
|
+
change: "AUTHORIZED" | "REVOKED";
|
|
40
|
+
/** Keeta's store id (an integer on the wire, text here). */
|
|
41
|
+
shopId: string;
|
|
42
|
+
shopName: string | null;
|
|
43
|
+
/** The application's id. */
|
|
44
|
+
clientId: string | null;
|
|
45
|
+
at: Date | null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Read the authorization webhook's body (`WebhookNotification`). Null when it names no authorization or store. */
|
|
49
|
+
export function normalizeKeetaAuthorizationEvent(payload: unknown): KeetaAuthorizationEvent | null {
|
|
50
|
+
const authId = firstString(payload, [["authId"]]);
|
|
51
|
+
const shopId = firstString(payload, [["shopId"]]);
|
|
52
|
+
const opType = pick(payload, "opType");
|
|
53
|
+
const change = opType === 1 ? "AUTHORIZED" : opType === 2 ? "REVOKED" : null;
|
|
54
|
+
if (!authId || !shopId || !change) return null;
|
|
55
|
+
const millis = pick(payload, "createTime");
|
|
56
|
+
return {
|
|
57
|
+
authId,
|
|
58
|
+
change,
|
|
59
|
+
shopId,
|
|
60
|
+
shopName: firstString(payload, [["shopName"]]),
|
|
61
|
+
clientId: firstString(payload, [["clientId"]]),
|
|
62
|
+
at: typeof millis === "number" && Number.isFinite(millis) ? new Date(millis) : null,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One store of an authorization, as `merchantInfo` lists it. */
|
|
67
|
+
export interface KeetaAuthorizedShop {
|
|
68
|
+
/** Keeta's store id: the `keetaMerchantId` the onboarding takes. */
|
|
69
|
+
id: string;
|
|
70
|
+
name: string | null;
|
|
71
|
+
address: string | null;
|
|
72
|
+
latitude: number | null;
|
|
73
|
+
longitude: number | null;
|
|
74
|
+
timeZone: string | null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** One page of an authorization's stores. */
|
|
78
|
+
export interface KeetaAuthorizedShops {
|
|
79
|
+
brandId: string | null;
|
|
80
|
+
brandName: string | null;
|
|
81
|
+
shops: KeetaAuthorizedShop[];
|
|
82
|
+
page: { pageNum: number; totalPage: number; totalCount: number };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** What the host registers for one store at onboarding. */
|
|
86
|
+
export interface KeetaOnboarding {
|
|
87
|
+
/** The SOFTWARE's merchant id: the connection's `externalMerchantId`, the `Merchant.id` the host serves. */
|
|
88
|
+
merchantId: string;
|
|
89
|
+
/** Keeta's store id, from `authorizedShops` or Keeta's portal. */
|
|
90
|
+
keetaMerchantId: number;
|
|
91
|
+
/** Where Keeta reads this store's `GET /v1/merchant` (one URL per store), and its key if it wants one. */
|
|
92
|
+
merchantDocument?: { url: string; apiKey?: string };
|
|
93
|
+
/** The engine's webhook for this store: `…/webhooks/marketplace/:tenantSlug/KEETA`. */
|
|
94
|
+
ordersWebhookUrl?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type KeetaAuthorizationResult<T> = { kind: "ok"; value: T } | OpenDeliveryStop;
|
|
98
|
+
|
|
99
|
+
const numberOr = (value: unknown, fallback: number | null): number | null =>
|
|
100
|
+
typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
101
|
+
|
|
102
|
+
function shopOf(raw: unknown): KeetaAuthorizedShop | null {
|
|
103
|
+
const id = firstString(raw, [["id"]]);
|
|
104
|
+
if (!id) return null;
|
|
105
|
+
return {
|
|
106
|
+
id,
|
|
107
|
+
name: firstString(raw, [["name"]]),
|
|
108
|
+
address: firstString(raw, [["address"]]),
|
|
109
|
+
latitude: numberOr(pick(raw, "latitude"), null),
|
|
110
|
+
longitude: numberOr(pick(raw, "longitude"), null),
|
|
111
|
+
timeZone: firstString(raw, [["timeZone"]]),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function shopsOf(body: unknown): KeetaAuthorizedShops {
|
|
116
|
+
const raw = pick(body, "authorizedShops");
|
|
117
|
+
return {
|
|
118
|
+
brandId: asString(pick(body, "brandId")),
|
|
119
|
+
brandName: firstString(body, [["brandName"]]),
|
|
120
|
+
shops: (Array.isArray(raw) ? raw : []).map(shopOf).filter((shop): shop is KeetaAuthorizedShop => shop !== null),
|
|
121
|
+
page: {
|
|
122
|
+
pageNum: numberOr(pick(body, "page", "pageNum"), 1) ?? 1,
|
|
123
|
+
totalPage: numberOr(pick(body, "page", "totalPage"), 1) ?? 1,
|
|
124
|
+
totalCount: numberOr(pick(body, "page", "totalCount"), 0) ?? 0,
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** One call whose 2xx answer is read by `read`: the value, or the result that ends it. */
|
|
130
|
+
async function readCall<T>(
|
|
131
|
+
ctx: AdapterCallContext,
|
|
132
|
+
dialect: OpenDeliveryDialect,
|
|
133
|
+
call: Parameters<typeof openDeliveryCall>[2],
|
|
134
|
+
read: (body: unknown) => T | null,
|
|
135
|
+
): Promise<KeetaAuthorizationResult<T>> {
|
|
136
|
+
try {
|
|
137
|
+
const response = await openDeliveryCall(ctx, dialect, call);
|
|
138
|
+
if (isStop(response)) return response;
|
|
139
|
+
const result = outboundResultOf(response);
|
|
140
|
+
if (result.kind !== "accepted") return result;
|
|
141
|
+
let body: unknown = null;
|
|
142
|
+
try {
|
|
143
|
+
body = response.body === "" ? null : JSON.parse(response.body);
|
|
144
|
+
} catch {
|
|
145
|
+
body = null;
|
|
146
|
+
}
|
|
147
|
+
const value = read(body);
|
|
148
|
+
return value === null
|
|
149
|
+
? { kind: "refused", status: response.status, message: "Keeta's answer is not the documented shape" }
|
|
150
|
+
: { kind: "ok", value };
|
|
151
|
+
} catch (error) {
|
|
152
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The self-serve authorization calls, bound to Keeta's dialect. */
|
|
157
|
+
export interface KeetaAuthorization {
|
|
158
|
+
authorizationUrl(ctx: AdapterCallContext, input: { redirectUri?: string }): Promise<KeetaAuthorizationResult<string>>;
|
|
159
|
+
authorizedShops(
|
|
160
|
+
ctx: AdapterCallContext,
|
|
161
|
+
input: { authId: string; pageNum?: number; pageSize?: number },
|
|
162
|
+
): Promise<KeetaAuthorizationResult<KeetaAuthorizedShops>>;
|
|
163
|
+
onboard(ctx: AdapterCallContext, input: KeetaOnboarding): Promise<KeetaAuthorizationResult<true>>;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** An https URL Keeta answered, or null. */
|
|
167
|
+
function httpsUrl(body: unknown): string | null {
|
|
168
|
+
const url = firstString(body, [["merchantAuthorizationUrl"]]);
|
|
169
|
+
if (!url) return null;
|
|
170
|
+
try {
|
|
171
|
+
return new URL(url).protocol === "https:" ? url : null;
|
|
172
|
+
} catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function keetaAuthorization(dialect: OpenDeliveryDialect): KeetaAuthorization {
|
|
178
|
+
return {
|
|
179
|
+
authorizationUrl: (ctx, input) =>
|
|
180
|
+
readCall(
|
|
181
|
+
ctx,
|
|
182
|
+
dialect,
|
|
183
|
+
{
|
|
184
|
+
method: "GET",
|
|
185
|
+
path: "/oauth/authorization/url",
|
|
186
|
+
query: { clientId: ctx.credentials.clientId, ...(input.redirectUri ? { redirectUri: input.redirectUri } : {}) },
|
|
187
|
+
authenticated: false,
|
|
188
|
+
},
|
|
189
|
+
httpsUrl,
|
|
190
|
+
),
|
|
191
|
+
authorizedShops: (ctx, input) =>
|
|
192
|
+
readCall(
|
|
193
|
+
ctx,
|
|
194
|
+
dialect,
|
|
195
|
+
{
|
|
196
|
+
method: "GET",
|
|
197
|
+
path: `/oauth/authorized/${encodeURIComponent(input.authId)}/merchantInfo`,
|
|
198
|
+
query: { pageNum: String(input.pageNum ?? 1), pageSize: String(Math.min(input.pageSize ?? 100, 100)) },
|
|
199
|
+
},
|
|
200
|
+
(body) => (body === null ? null : shopsOf(body)),
|
|
201
|
+
),
|
|
202
|
+
onboard: (ctx, input) =>
|
|
203
|
+
readCall(
|
|
204
|
+
ctx,
|
|
205
|
+
dialect,
|
|
206
|
+
{
|
|
207
|
+
method: "PUT",
|
|
208
|
+
path: "/v1/merchantOnboarding",
|
|
209
|
+
query: { merchantId: input.merchantId },
|
|
210
|
+
body: {
|
|
211
|
+
keetaMerchantId: input.keetaMerchantId,
|
|
212
|
+
...(input.merchantDocument
|
|
213
|
+
? {
|
|
214
|
+
getMerchantURL: {
|
|
215
|
+
baseURL: input.merchantDocument.url,
|
|
216
|
+
...(input.merchantDocument.apiKey ? { apiKey: input.merchantDocument.apiKey } : {}),
|
|
217
|
+
},
|
|
218
|
+
}
|
|
219
|
+
: {}),
|
|
220
|
+
...(input.ordersWebhookUrl ? { ordersWebhookURL: input.ordersWebhookUrl } : {}),
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
() => true as const,
|
|
224
|
+
),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { OPEN_DELIVERY_MERCHANT_REASON_CODES } from "../open-delivery/reasons";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The words the Keeta adapter needs from its host, and nothing else.
|
|
5
|
+
*
|
|
6
|
+
* Required and defaultless, like every copy port in this repo: the adapter
|
|
7
|
+
* ships no language of its own. Two packs sit beside it (`./pt-BR`,
|
|
8
|
+
* `./en-US`); a host passes one by hand, or its own.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The cancellation codes a merchant may send: Keeta's "códigos de
|
|
13
|
+
* cancelamento (v1.0.7+)", the same eleven as Open Delivery's
|
|
14
|
+
* (`../open-delivery/reasons.ts`). Keeta still accepts its legacy codes
|
|
15
|
+
* (`INSUFFICIENT_DISHES`, `SUSPENSION_OF_BUSINESS`, `INSUFFICIENT_MANPOWER`,
|
|
16
|
+
* `OTHERS`) and recommends the new ones, so only the new ones are offered.
|
|
17
|
+
*/
|
|
18
|
+
export const KEETA_REASON_CODES = OPEN_DELIVERY_MERCHANT_REASON_CODES;
|
|
19
|
+
|
|
20
|
+
export type KeetaReasonCode = (typeof KEETA_REASON_CODES)[number];
|
|
21
|
+
|
|
22
|
+
export interface KeetaAdapterCopy {
|
|
23
|
+
/** One label per reason code. Sent as the request's `reason` text when the store wrote none. */
|
|
24
|
+
reasonLabels: Readonly<Record<KeetaReasonCode, string>>;
|
|
25
|
+
/** What an address with no street number (or an encrypted one Keeta would not reveal) says instead. */
|
|
26
|
+
missingStreetNumber: string;
|
|
27
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { KeetaAdapterCopy } from "./copy";
|
|
2
|
+
|
|
3
|
+
/** The Keeta adapter's en-US pack: the same reasons, in English. */
|
|
4
|
+
export const KEETA_ADAPTER_COPY_EN_US = {
|
|
5
|
+
reasonLabels: {
|
|
6
|
+
SYSTEMIC_ISSUES: "System problems",
|
|
7
|
+
DUPLICATE_APPLICATION: "Duplicate order",
|
|
8
|
+
UNAVAILABLE_ITEM: "Item unavailable",
|
|
9
|
+
RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available",
|
|
10
|
+
OUTDATED_MENU: "Menu out of date",
|
|
11
|
+
ORDER_OUTSIDE_THE_DELIVERY_AREA: "Outside the delivery area",
|
|
12
|
+
BLOCKED_CUSTOMER: "Blocked customer",
|
|
13
|
+
OUTSIDE_DELIVERY_HOURS: "Outside delivery hours",
|
|
14
|
+
INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties",
|
|
15
|
+
RISK_AREA: "Risk area",
|
|
16
|
+
DELIVERY_PROBLEM: "Delivery problem",
|
|
17
|
+
},
|
|
18
|
+
missingStreetNumber: "no number",
|
|
19
|
+
} as const satisfies KeetaAdapterCopy;
|