@tallyui/connector-medusa 4.2.0 → 5.0.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/dist/index.d.ts +5 -2
- package/dist/index.js +239 -26
- package/package.json +4 -3
- package/src/display-signalling.ts +190 -0
- package/src/index.ts +3 -1
- package/src/orders.ts +73 -4
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as _tallyui_core from '@tallyui/core';
|
|
2
|
-
import { ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, CustomerPatch, OrderFilterField, TallyConnector, ServerCapabilities, StoreOrder, ConnectorAuth } from '@tallyui/core';
|
|
2
|
+
import { ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, CustomerPatch, OrderFilterField, TallyConnector, ServerCapabilities, StoreOrder, DisplaySignalling, ConnectorAuth } from '@tallyui/core';
|
|
3
3
|
export { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
4
4
|
import { RxJsonSchema } from 'rxdb';
|
|
5
5
|
|
|
@@ -188,6 +188,9 @@ declare function createMedusaOrders(): Required<Pick<TallyConnector, 'listOrders
|
|
|
188
188
|
*/
|
|
189
189
|
declare function withCalculatedPrices<Doc extends MedusaProductDocument>(docs: Doc[], context: SyncContext): Promise<Doc[]>;
|
|
190
190
|
|
|
191
|
+
/** The medusapos plugin's display signalling (ADR-085 d2): the till side rides the admin user's Bearer session. */
|
|
192
|
+
declare const medusaDisplaySignalling: DisplaySignalling;
|
|
193
|
+
|
|
191
194
|
/** The calculated-price check's interval: price-list edits and sale start/end bump no timestamp (ADR-060 amendment 8). */
|
|
192
195
|
declare const MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS: number;
|
|
193
196
|
|
|
@@ -233,4 +236,4 @@ declare const medusaConnector: TallyConnector;
|
|
|
233
236
|
*/
|
|
234
237
|
declare const medusaAdminUserConnector: TallyConnector;
|
|
235
238
|
|
|
236
|
-
export { MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT, MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS, MEDUSA_DISPLAY_NUMBER_MAX_DIGITS, MEDUSA_ORDERS_PLUGIN_CONTRACT, MEDUSA_ORDER_FILTERS, type MedusaCalculatedPrice, type MedusaProductDocument, type MedusaVariantDocument, createMedusaAdminUserConnector, createMedusaConnector, createMedusaCustomer, createMedusaOrders, createMedusaVariantFeedReplication, getMedusaCustomer, medusaAdminUserAuth, medusaAdminUserConnector, medusaCapabilities, medusaConnector, medusaCreateCustomer, medusaGetCustomer, medusaOrderFilters, medusaProductReplication, medusaProductSchema, medusaProductSync, medusaProductTraits, medusaSearchCustomers, medusaSecretKeyAuth, medusaSignIn, medusaStockReconcile, medusaStoreSettings, medusaUpdateCustomer, searchMedusaCustomers, toCustomer, toMedusaStoreOrder, updateMedusaCustomer, withCalculatedPrices };
|
|
239
|
+
export { MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT, MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS, MEDUSA_DISPLAY_NUMBER_MAX_DIGITS, MEDUSA_ORDERS_PLUGIN_CONTRACT, MEDUSA_ORDER_FILTERS, type MedusaCalculatedPrice, type MedusaProductDocument, type MedusaVariantDocument, createMedusaAdminUserConnector, createMedusaConnector, createMedusaCustomer, createMedusaOrders, createMedusaVariantFeedReplication, getMedusaCustomer, medusaAdminUserAuth, medusaAdminUserConnector, medusaCapabilities, medusaConnector, medusaCreateCustomer, medusaDisplaySignalling, medusaGetCustomer, medusaOrderFilters, medusaProductReplication, medusaProductSchema, medusaProductSync, medusaProductTraits, medusaSearchCustomers, medusaSecretKeyAuth, medusaSignIn, medusaStockReconcile, medusaStoreSettings, medusaUpdateCustomer, searchMedusaCustomers, toCustomer, toMedusaStoreOrder, updateMedusaCustomer, withCalculatedPrices };
|
package/dist/index.js
CHANGED
|
@@ -109,16 +109,16 @@ async function createMedusaCustomer(baseUrl, headers, input, init = {}) {
|
|
|
109
109
|
const customer = await customerRequest(`${baseUrl}/admin/customers`, "customer", { ...init, method: "POST", headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
|
110
110
|
return toCustomer(customer);
|
|
111
111
|
}
|
|
112
|
-
async function getMedusaCustomer(baseUrl, headers,
|
|
113
|
-
const customer = await customerRequest(`${baseUrl}/admin/customers/${encodeURIComponent(
|
|
112
|
+
async function getMedusaCustomer(baseUrl, headers, id2, init = {}) {
|
|
113
|
+
const customer = await customerRequest(`${baseUrl}/admin/customers/${encodeURIComponent(id2)}`, "customer", { ...init, method: "GET", headers });
|
|
114
114
|
return customer === null || customer.deleted_at != null ? null : toCustomer(customer);
|
|
115
115
|
}
|
|
116
116
|
var blankToNull = (value) => value ? value : null;
|
|
117
117
|
function toMedusaAddress(address) {
|
|
118
118
|
return Object.fromEntries(ADDRESS_FIELDS.map(([key, field]) => [field, blankToNull(key === "country" ? address.country?.toLowerCase() : address[key])]));
|
|
119
119
|
}
|
|
120
|
-
async function updateMedusaCustomer(baseUrl, headers,
|
|
121
|
-
const url = `${baseUrl}/admin/customers/${encodeURIComponent(
|
|
120
|
+
async function updateMedusaCustomer(baseUrl, headers, id2, patch, init = {}) {
|
|
121
|
+
const url = `${baseUrl}/admin/customers/${encodeURIComponent(id2)}`;
|
|
122
122
|
const post = (path, body) => customerRequest(`${url}${path}?fields=*addresses`, "customer", {
|
|
123
123
|
...init,
|
|
124
124
|
method: "POST",
|
|
@@ -529,9 +529,9 @@ var medusaProductSync = {
|
|
|
529
529
|
},
|
|
530
530
|
async fetchByIds(ids, context) {
|
|
531
531
|
const products = [];
|
|
532
|
-
for (const
|
|
532
|
+
for (const id2 of ids) {
|
|
533
533
|
const response = await fetch(
|
|
534
|
-
`${context.baseUrl}/admin/products/${
|
|
534
|
+
`${context.baseUrl}/admin/products/${id2}?fields=*variants,*variants.prices,*images,*categories,*tags,*options,*options.values`,
|
|
535
535
|
{
|
|
536
536
|
headers: {
|
|
537
537
|
...context.headers,
|
|
@@ -541,7 +541,7 @@ var medusaProductSync = {
|
|
|
541
541
|
}
|
|
542
542
|
);
|
|
543
543
|
if (!response.ok) {
|
|
544
|
-
throw new Error(`Medusa API error: ${response.status} for product ${
|
|
544
|
+
throw new Error(`Medusa API error: ${response.status} for product ${id2}`);
|
|
545
545
|
}
|
|
546
546
|
const data = await response.json();
|
|
547
547
|
products.push(data.product);
|
|
@@ -727,7 +727,7 @@ async function fetchByIds(ids, context) {
|
|
|
727
727
|
for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
|
|
728
728
|
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
729
729
|
const params = new URLSearchParams({ fields: MEDUSA_PRODUCT_FIELDS, limit: String(chunk.length) });
|
|
730
|
-
for (const
|
|
730
|
+
for (const id2 of chunk) params.append("id[]", id2);
|
|
731
731
|
const data = await adminGet(`/admin/products?${params}`, context);
|
|
732
732
|
const products = data.products ?? [];
|
|
733
733
|
results.push(...products.map(toDocument));
|
|
@@ -773,8 +773,8 @@ var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
|
|
|
773
773
|
}
|
|
774
774
|
const variants = data.variants ?? [];
|
|
775
775
|
if (offset === 0) passCount = data.count;
|
|
776
|
-
const parentIds = [...new Set(variants.map((v) => String(v.product_id)))].filter((
|
|
777
|
-
parentIds.forEach((
|
|
776
|
+
const parentIds = [...new Set(variants.map((v) => String(v.product_id)))].filter((id2) => !seen.has(id2));
|
|
777
|
+
parentIds.forEach((id2) => seen.add(id2));
|
|
778
778
|
if (parentIds.length) {
|
|
779
779
|
documents.push(...(await fetchByIds(parentIds, context)).map((doc) => ({ ...doc, _deleted: false })));
|
|
780
780
|
}
|
|
@@ -849,7 +849,7 @@ async function* fetchPages2(context) {
|
|
|
849
849
|
byProduct.set(productId, entries);
|
|
850
850
|
entries.push(...baseEntries(variant));
|
|
851
851
|
}
|
|
852
|
-
yield new Map([...touched].map((
|
|
852
|
+
yield new Map([...touched].map((id2) => [id2, fingerprintOf(byProduct.get(id2) ?? [])]));
|
|
853
853
|
}
|
|
854
854
|
}
|
|
855
855
|
function fingerprint(doc) {
|
|
@@ -859,7 +859,7 @@ function fingerprint(doc) {
|
|
|
859
859
|
// src/reconcile/calculated-prices.ts
|
|
860
860
|
var MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS = 30 * 60 * 1e3;
|
|
861
861
|
function fingerprintOf2(variants) {
|
|
862
|
-
return variants.map(({ id, calculated_price: c }) => c ? `${
|
|
862
|
+
return variants.map(({ id: id2, calculated_price: c }) => c ? `${id2}:${c.currency_code}:${c.calculated_amount}:${c.original_amount}:${c.is_calculated_price_tax_inclusive}:${c.is_original_price_tax_inclusive}:${c.calculated_price?.price_list_type ?? ""}` : `${id2}:-`).sort().join("|");
|
|
863
863
|
}
|
|
864
864
|
async function* fetchPages3(context) {
|
|
865
865
|
const pricing = context.pricingContext;
|
|
@@ -1084,9 +1084,9 @@ function toMedusaStoreOrder(raw) {
|
|
|
1084
1084
|
}),
|
|
1085
1085
|
fees: [],
|
|
1086
1086
|
shipping: shippingMethods.map((method) => {
|
|
1087
|
-
const
|
|
1087
|
+
const id2 = nonEmpty(method.id);
|
|
1088
1088
|
const methodId = nonEmpty(method.shipping_option_id);
|
|
1089
|
-
return { ...
|
|
1089
|
+
return { ...id2 ? { id: id2 } : {}, name: nonEmpty(method.name) ?? "", ...split(method.total, method.tax_total), ...methodId ? { methodId } : {} };
|
|
1090
1090
|
}),
|
|
1091
1091
|
coupons: [],
|
|
1092
1092
|
// Each rate's tax lines summed exactly, then rounded once.
|
|
@@ -1101,8 +1101,8 @@ function toMedusaStoreOrder(raw) {
|
|
|
1101
1101
|
taxMinor: totalMinor - medusaSumMinor(currency, gross, [raw.tax_total]),
|
|
1102
1102
|
totalMinor,
|
|
1103
1103
|
payments: payments.filter((payment) => payment.canceled_at == null).map((payment) => {
|
|
1104
|
-
const
|
|
1105
|
-
return { ...
|
|
1104
|
+
const id2 = nonEmpty(payment.id);
|
|
1105
|
+
return { ...id2 ? { id: id2 } : {}, method: required(payment.provider_id), amountMinor: minor(payment.amount) };
|
|
1106
1106
|
}),
|
|
1107
1107
|
refunds: payments.flatMap((payment) => rows(payment.refunds)).map((refund) => {
|
|
1108
1108
|
const reason = nonEmpty(refund.note);
|
|
@@ -1114,6 +1114,8 @@ var MEDUSA_ORDER_FILTERS = ["status", "customerId", "dateRange"];
|
|
|
1114
1114
|
var MEDUSA_DISPLAY_NUMBER_MAX_DIGITS = 6;
|
|
1115
1115
|
var MEDUSA_ORDERS_PLUGIN_CONTRACT = 3;
|
|
1116
1116
|
var MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT = 4;
|
|
1117
|
+
var REFUND_LINES_PLUGIN_CONTRACT = 6;
|
|
1118
|
+
var REFUND_LINES_IDS_MAX = 100;
|
|
1117
1119
|
var hasOrdersRoute = (capabilities) => (capabilities?.pluginContract ?? 0) >= MEDUSA_ORDERS_PLUGIN_CONTRACT;
|
|
1118
1120
|
function medusaOrderFilters(capabilities) {
|
|
1119
1121
|
return hasOrdersRoute(capabilities) ? [...MEDUSA_ORDER_FILTERS, "registerId"] : MEDUSA_ORDER_FILTERS;
|
|
@@ -1146,6 +1148,54 @@ function readOrders(raws) {
|
|
|
1146
1148
|
});
|
|
1147
1149
|
return { orders, unreadable };
|
|
1148
1150
|
}
|
|
1151
|
+
var isCount = (value, min) => Number.isSafeInteger(value) && value >= min;
|
|
1152
|
+
function refundLinesByOrder(raws, orders) {
|
|
1153
|
+
const lineIds = new Map(orders.map((order) => [order.id, new Map(order.lines.map((line) => [line.id, line.quantity]))]));
|
|
1154
|
+
const byOrder = /* @__PURE__ */ new Map();
|
|
1155
|
+
for (const raw of rows(raws)) {
|
|
1156
|
+
const known = typeof raw.id === "string" ? lineIds.get(raw.id) : void 0;
|
|
1157
|
+
if (!known || typeof raw.id !== "string") continue;
|
|
1158
|
+
const linesById = byOrder.get(raw.id) ?? /* @__PURE__ */ new Map();
|
|
1159
|
+
byOrder.set(raw.id, linesById);
|
|
1160
|
+
for (const { id: id2, lines } of rows(raw.refunds)) {
|
|
1161
|
+
if (typeof id2 !== "string" || !Array.isArray(lines) || lines.length === 0) continue;
|
|
1162
|
+
const kept = rows(lines).flatMap(({ orderLineId, quantity, netMinor, taxMinor }) => typeof orderLineId === "string" && known.has(orderLineId) && isCount(quantity, 1) && quantity <= known.get(orderLineId) && isCount(netMinor, 0) && isCount(taxMinor, 0) ? [{ orderLineId, quantity, netMinor, taxMinor }] : []);
|
|
1163
|
+
if (kept.length === lines.length && new Set(kept.map((line) => line.orderLineId)).size === kept.length) linesById.set(id2, kept);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
for (const [orderId, linesById] of byOrder) {
|
|
1167
|
+
const ordered = lineIds.get(orderId);
|
|
1168
|
+
const refunded = /* @__PURE__ */ new Map();
|
|
1169
|
+
for (const line of [...linesById.values()].flat()) refunded.set(line.orderLineId, (refunded.get(line.orderLineId) ?? 0) + line.quantity);
|
|
1170
|
+
if ([...refunded].some(([lineId, quantity]) => quantity > ordered.get(lineId))) byOrder.delete(orderId);
|
|
1171
|
+
}
|
|
1172
|
+
return byOrder;
|
|
1173
|
+
}
|
|
1174
|
+
function withRefundLines(orders, byOrder) {
|
|
1175
|
+
return orders.map((order) => {
|
|
1176
|
+
const linesById = byOrder.get(order.id);
|
|
1177
|
+
return linesById && order.refunds.some((refund) => linesById.has(refund.id)) ? { ...order, refunds: order.refunds.map((refund) => {
|
|
1178
|
+
const lines = linesById.get(refund.id);
|
|
1179
|
+
return lines ? { ...refund, lines } : refund;
|
|
1180
|
+
}) } : order;
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
async function readRefundLines(context, orders) {
|
|
1184
|
+
if ((context.capabilities?.pluginContract ?? 0) < REFUND_LINES_PLUGIN_CONTRACT) return orders;
|
|
1185
|
+
const ids = orders.filter((order) => order.refunds.length > 0).map((order) => order.id);
|
|
1186
|
+
const raws = [];
|
|
1187
|
+
for (let start = 0; start < ids.length; start += REFUND_LINES_IDS_MAX) {
|
|
1188
|
+
const chunk = ids.slice(start, start + REFUND_LINES_IDS_MAX);
|
|
1189
|
+
const params = new URLSearchParams({ page: "1", perPage: String(chunk.length), ids: chunk.join(","), allChannels: "true" });
|
|
1190
|
+
try {
|
|
1191
|
+
const body = await ordersRequest(context, "/tally/v1/orders", params);
|
|
1192
|
+
if (Array.isArray(body?.orders)) raws.push(...body.orders);
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
if (context.signal?.aborted) throw error;
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
return raws.length > 0 ? withRefundLines(orders, refundLinesByOrder(raws, orders)) : orders;
|
|
1198
|
+
}
|
|
1149
1199
|
var DISPLAY_NUMBER = new RegExp(`^\\d{1,${MEDUSA_DISPLAY_NUMBER_MAX_DIGITS}}$`);
|
|
1150
1200
|
async function listThroughPlugin(context, params) {
|
|
1151
1201
|
const found = await ordersRequest(context, "/tally/v1/orders", params);
|
|
@@ -1155,12 +1205,13 @@ async function listThroughPlugin(context, params) {
|
|
|
1155
1205
|
const counted = typeof total === "number" && Number.isInteger(total) && total >= 0 ? { total } : {};
|
|
1156
1206
|
if (ids.length === 0) return { orders: [], hasMore, ...counted };
|
|
1157
1207
|
const lookup = new URLSearchParams({ limit: String(ids.length), fields: ORDER_FIELDS });
|
|
1158
|
-
for (const
|
|
1208
|
+
for (const id2 of ids) lookup.append("id[]", id2);
|
|
1159
1209
|
const body = await ordersRequest(context, "/admin/orders", lookup);
|
|
1160
1210
|
if (!Array.isArray(body.orders)) throw unexpected();
|
|
1161
1211
|
const byId = new Map(rows(body.orders).map((row) => [row.id, row]));
|
|
1162
|
-
const picked = ids.flatMap((
|
|
1163
|
-
const { orders, unreadable } = readOrders(picked);
|
|
1212
|
+
const picked = ids.flatMap((id2) => byId.get(id2) ?? []);
|
|
1213
|
+
const { orders: read2, unreadable } = readOrders(picked);
|
|
1214
|
+
const orders = (context.capabilities?.pluginContract ?? 0) >= REFUND_LINES_PLUGIN_CONTRACT ? withRefundLines(read2, refundLinesByOrder(hits, read2)) : read2;
|
|
1164
1215
|
const left = unreadable + ids.length - picked.length;
|
|
1165
1216
|
return { orders, hasMore, ...left ? { unreadable: left } : {}, ...counted };
|
|
1166
1217
|
}
|
|
@@ -1203,20 +1254,180 @@ function createMedusaOrders() {
|
|
|
1203
1254
|
const { count } = body;
|
|
1204
1255
|
const counted = typeof count === "number" && Number.isInteger(count) && count >= 0;
|
|
1205
1256
|
const hasMore = counted ? offset + body.orders.length < count : body.orders.length === perPage;
|
|
1206
|
-
return { orders, hasMore, ...unreadable ? { unreadable } : {}, ...counted ? { total: count } : {} };
|
|
1257
|
+
return { orders: await readRefundLines(context, orders), hasMore, ...unreadable ? { unreadable } : {}, ...counted ? { total: count } : {} };
|
|
1207
1258
|
},
|
|
1208
1259
|
/** One request per id, in the order asked; an id the store does not have (404) is left out. */
|
|
1209
1260
|
async getOrders(context, ids) {
|
|
1210
1261
|
const orders = [];
|
|
1211
|
-
for (const
|
|
1212
|
-
const body = await ordersRequest(context, `/admin/orders/${encodeURIComponent(
|
|
1262
|
+
for (const id2 of new Set(ids.filter((id3) => id3.length > 0))) {
|
|
1263
|
+
const body = await ordersRequest(context, `/admin/orders/${encodeURIComponent(id2)}`, new URLSearchParams({ fields: ORDER_FIELDS }), "null");
|
|
1213
1264
|
if (body) orders.push(toMedusaStoreOrder(body.order));
|
|
1214
1265
|
}
|
|
1215
|
-
return orders;
|
|
1266
|
+
return readRefundLines(context, orders);
|
|
1216
1267
|
}
|
|
1217
1268
|
};
|
|
1218
1269
|
}
|
|
1219
1270
|
|
|
1271
|
+
// src/display-signalling.ts
|
|
1272
|
+
import {
|
|
1273
|
+
DisplaySignallingError
|
|
1274
|
+
} from "@tallyui/core";
|
|
1275
|
+
var PREFIX = "/tally/v1";
|
|
1276
|
+
var CODES_BY_STATUS = {
|
|
1277
|
+
403: ["forbidden", "claim_refused", "collect_refused", "device_refused", "token_refused"],
|
|
1278
|
+
404: ["not_found"],
|
|
1279
|
+
429: ["limit"]
|
|
1280
|
+
};
|
|
1281
|
+
var refuse = (code) => new DisplaySignallingError(code);
|
|
1282
|
+
async function bodyCode(res) {
|
|
1283
|
+
try {
|
|
1284
|
+
const body = await res.json();
|
|
1285
|
+
const code = body !== null && typeof body === "object" ? body.code : void 0;
|
|
1286
|
+
return typeof code === "string" ? code : void 0;
|
|
1287
|
+
} catch {
|
|
1288
|
+
return void 0;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
async function refusalCode(res, till2) {
|
|
1292
|
+
if (res.status === 400 || res.status === 413) return "too_large";
|
|
1293
|
+
const code = await bodyCode(res);
|
|
1294
|
+
if (res.status === 401 && till2 && code === void 0) return "forbidden";
|
|
1295
|
+
return CODES_BY_STATUS[res.status]?.find((known) => known === code) ?? "server";
|
|
1296
|
+
}
|
|
1297
|
+
function headersOf(side, body) {
|
|
1298
|
+
const headers = side.till ? new Headers(side.ctx.headers) : new Headers();
|
|
1299
|
+
if (body !== void 0) headers.set("Content-Type", "application/json");
|
|
1300
|
+
if (side.till && side.device) {
|
|
1301
|
+
headers.set("X-Tally-Device-Id", side.device.deviceId);
|
|
1302
|
+
headers.set("X-Tally-Device-Key", side.device.deviceKey);
|
|
1303
|
+
}
|
|
1304
|
+
if (!side.till && side.token !== void 0) headers.set("X-Tally-Display-Token", side.token);
|
|
1305
|
+
return headers;
|
|
1306
|
+
}
|
|
1307
|
+
async function request(side, method, path, body) {
|
|
1308
|
+
const base = side.till ? side.ctx : side.dctx;
|
|
1309
|
+
let headers, json;
|
|
1310
|
+
try {
|
|
1311
|
+
headers = headersOf(side, body);
|
|
1312
|
+
} catch {
|
|
1313
|
+
throw refuse("network");
|
|
1314
|
+
}
|
|
1315
|
+
try {
|
|
1316
|
+
json = body === void 0 ? void 0 : JSON.stringify(body);
|
|
1317
|
+
} catch {
|
|
1318
|
+
throw refuse("too_large");
|
|
1319
|
+
}
|
|
1320
|
+
const doFetch = base.fetch ?? globalThis.fetch;
|
|
1321
|
+
let res;
|
|
1322
|
+
try {
|
|
1323
|
+
res = await doFetch(new URL(`${base.baseUrl}${PREFIX}${path}`), {
|
|
1324
|
+
method,
|
|
1325
|
+
headers,
|
|
1326
|
+
...json === void 0 ? {} : { body: json },
|
|
1327
|
+
...side.till ? { signal: side.ctx.signal } : { credentials: "omit" }
|
|
1328
|
+
});
|
|
1329
|
+
} catch {
|
|
1330
|
+
throw refuse("network");
|
|
1331
|
+
}
|
|
1332
|
+
if (!res.ok) throw refuse(await refusalCode(res, side.till));
|
|
1333
|
+
return res;
|
|
1334
|
+
}
|
|
1335
|
+
async function read(res) {
|
|
1336
|
+
let body;
|
|
1337
|
+
try {
|
|
1338
|
+
body = await res.json();
|
|
1339
|
+
} catch {
|
|
1340
|
+
throw refuse("server");
|
|
1341
|
+
}
|
|
1342
|
+
return object(body);
|
|
1343
|
+
}
|
|
1344
|
+
function object(value) {
|
|
1345
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw refuse("server");
|
|
1346
|
+
return value;
|
|
1347
|
+
}
|
|
1348
|
+
function text(value) {
|
|
1349
|
+
if (typeof value !== "string") throw refuse("server");
|
|
1350
|
+
return value;
|
|
1351
|
+
}
|
|
1352
|
+
function list(value) {
|
|
1353
|
+
if (!Array.isArray(value)) throw refuse("server");
|
|
1354
|
+
return value;
|
|
1355
|
+
}
|
|
1356
|
+
function signal(value) {
|
|
1357
|
+
const entry = object(value);
|
|
1358
|
+
const type = text(entry.type);
|
|
1359
|
+
if (type !== "offer" && type !== "answer" && type !== "ice") throw refuse("server");
|
|
1360
|
+
return { type, payload: text(entry.payload) };
|
|
1361
|
+
}
|
|
1362
|
+
function pairing(value) {
|
|
1363
|
+
const entry = object(value);
|
|
1364
|
+
return { claimId: text(entry.claimId), displayName: text(entry.displayName), checkCode: text(entry.checkCode), expiresAt: text(entry.expiresAt) };
|
|
1365
|
+
}
|
|
1366
|
+
function display(value) {
|
|
1367
|
+
const entry = object(value);
|
|
1368
|
+
if (entry.lastSeenAt !== null && typeof entry.lastSeenAt !== "string") throw refuse("server");
|
|
1369
|
+
if (typeof entry.connected !== "boolean") throw refuse("server");
|
|
1370
|
+
return { displayId: text(entry.displayId), name: text(entry.name), cashierId: text(entry.cashierId), lastSeenAt: entry.lastSeenAt, connected: entry.connected };
|
|
1371
|
+
}
|
|
1372
|
+
var id = encodeURIComponent;
|
|
1373
|
+
var till = (ctx, device) => ({ till: true, ctx, device });
|
|
1374
|
+
var shown = (dctx, token) => ({ till: false, dctx, token });
|
|
1375
|
+
var medusaDisplaySignalling = {
|
|
1376
|
+
async registerDevice(ctx, deviceId) {
|
|
1377
|
+
const body = await read(await request(till(ctx), "POST", "/display-devices", { deviceId }));
|
|
1378
|
+
return { deviceKey: text(body.deviceKey) };
|
|
1379
|
+
},
|
|
1380
|
+
async mint(ctx, device) {
|
|
1381
|
+
const body = await read(await request(till(ctx, device), "POST", "/display-codes"));
|
|
1382
|
+
return { code: text(body.code), expiresAt: text(body.expiresAt) };
|
|
1383
|
+
},
|
|
1384
|
+
async pending(ctx, device) {
|
|
1385
|
+
return list((await read(await request(till(ctx, device), "GET", "/display-pairings"))).pairings).map(pairing);
|
|
1386
|
+
},
|
|
1387
|
+
async confirm(ctx, device, claimId) {
|
|
1388
|
+
await request(till(ctx, device), "POST", `/display-pairings/${id(claimId)}/confirm`);
|
|
1389
|
+
},
|
|
1390
|
+
async decline(ctx, device, claimId) {
|
|
1391
|
+
await request(till(ctx, device), "POST", `/display-pairings/${id(claimId)}/decline`);
|
|
1392
|
+
},
|
|
1393
|
+
async list(ctx, device) {
|
|
1394
|
+
return list((await read(await request(till(ctx, device), "GET", "/displays"))).displays).map(display);
|
|
1395
|
+
},
|
|
1396
|
+
async forget(ctx, device, displayId) {
|
|
1397
|
+
await request(till(ctx, device), "DELETE", `/displays/${id(displayId)}`);
|
|
1398
|
+
},
|
|
1399
|
+
async sendSignal(ctx, device, displayId, message) {
|
|
1400
|
+
await request(till(ctx, device), "POST", `/displays/${id(displayId)}/signals`, { type: message.type, payload: message.payload });
|
|
1401
|
+
},
|
|
1402
|
+
async receiveSignals(ctx, device) {
|
|
1403
|
+
const signals = list((await read(await request(till(ctx, device), "POST", "/display-signals/drain"))).signals);
|
|
1404
|
+
return signals.map((value) => ({ ...signal(value), displayId: text(object(value).displayId) }));
|
|
1405
|
+
},
|
|
1406
|
+
async postSnapshot(ctx, device, displayId, body) {
|
|
1407
|
+
await request(till(ctx, device), "PUT", `/displays/${id(displayId)}/snapshot`, { snapshot: body });
|
|
1408
|
+
},
|
|
1409
|
+
async claim(dctx, { code, displayName, token }) {
|
|
1410
|
+
const body = await read(await request(shown(dctx), "POST", "/display/claim", { code, displayName, ...token === void 0 ? {} : { token } }));
|
|
1411
|
+
return { claimSecret: text(body.claimSecret), checkCode: text(body.checkCode) };
|
|
1412
|
+
},
|
|
1413
|
+
async collect(dctx, claimSecret) {
|
|
1414
|
+
const body = await read(await request(shown(dctx), "POST", "/display/collect", { claimSecret }));
|
|
1415
|
+
if (body.status === "pending") return { status: "pending", checkCode: text(body.checkCode) };
|
|
1416
|
+
if (body.status === "paired") return { status: "paired", displayId: text(body.displayId), token: text(body.token) };
|
|
1417
|
+
throw refuse("server");
|
|
1418
|
+
},
|
|
1419
|
+
async displaySendSignal(dctx, token, message) {
|
|
1420
|
+
await request(shown(dctx, token), "POST", "/display/signals", { type: message.type, payload: message.payload });
|
|
1421
|
+
},
|
|
1422
|
+
async displayReceiveSignals(dctx, token) {
|
|
1423
|
+
return list((await read(await request(shown(dctx, token), "POST", "/display/signals/drain"))).signals).map(signal);
|
|
1424
|
+
},
|
|
1425
|
+
async readSnapshot(dctx, token) {
|
|
1426
|
+
const { snapshot } = await read(await request(shown(dctx, token), "GET", "/display/snapshot"));
|
|
1427
|
+
return snapshot ?? null;
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
|
|
1220
1431
|
// src/index.ts
|
|
1221
1432
|
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError5 } from "@tallyui/core";
|
|
1222
1433
|
var medusaSecretKeyAuth = {
|
|
@@ -1274,8 +1485,8 @@ var medusaSignIn = async (baseUrl, { email, password }, init = {}) => {
|
|
|
1274
1485
|
var medusaCapabilities = (context) => readCapabilities(context.baseUrl, context.headers, { signal: context.signal });
|
|
1275
1486
|
var medusaSearchCustomers = (context, query, options) => searchMedusaCustomers(context.baseUrl, context.headers, query, { ...options, signal: context.signal });
|
|
1276
1487
|
var medusaCreateCustomer = (context, input) => createMedusaCustomer(context.baseUrl, context.headers, input, { signal: context.signal });
|
|
1277
|
-
var medusaGetCustomer = (context,
|
|
1278
|
-
var medusaUpdateCustomer = (context,
|
|
1488
|
+
var medusaGetCustomer = (context, id2) => getMedusaCustomer(context.baseUrl, context.headers, id2, { signal: context.signal });
|
|
1489
|
+
var medusaUpdateCustomer = (context, id2, patch) => updateMedusaCustomer(context.baseUrl, context.headers, id2, patch, { signal: context.signal });
|
|
1279
1490
|
var medusaAdminUserAuth = {
|
|
1280
1491
|
type: "Medusa admin user (Bearer JWT)",
|
|
1281
1492
|
fields: [
|
|
@@ -1338,7 +1549,8 @@ var createMedusaAdminUserConnector = () => ({
|
|
|
1338
1549
|
getCustomer: medusaGetCustomer,
|
|
1339
1550
|
updateCustomer: medusaUpdateCustomer,
|
|
1340
1551
|
...createMedusaOrders(),
|
|
1341
|
-
orderFilters: MEDUSA_ORDER_FILTERS
|
|
1552
|
+
orderFilters: MEDUSA_ORDER_FILTERS,
|
|
1553
|
+
displaySignalling: medusaDisplaySignalling
|
|
1342
1554
|
});
|
|
1343
1555
|
var medusaConnector = createMedusaConnector();
|
|
1344
1556
|
var medusaAdminUserConnector = createMedusaAdminUserConnector();
|
|
@@ -1360,6 +1572,7 @@ export {
|
|
|
1360
1572
|
medusaCapabilities,
|
|
1361
1573
|
medusaConnector,
|
|
1362
1574
|
medusaCreateCustomer,
|
|
1575
|
+
medusaDisplaySignalling,
|
|
1363
1576
|
medusaGetCustomer,
|
|
1364
1577
|
medusaOrderFilters,
|
|
1365
1578
|
medusaProductReplication,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/connector-medusa",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "MedusaJS v2 connector for Tally UI",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"src",
|
|
20
20
|
"!src/**/*.test.ts",
|
|
21
21
|
"!src/**/*.test.tsx",
|
|
22
|
+
"!src/**/__tests__/**",
|
|
22
23
|
"!src/**/*.fixture.json"
|
|
23
24
|
],
|
|
24
25
|
"license": "MIT",
|
|
@@ -28,10 +29,10 @@
|
|
|
28
29
|
"directory": "connectors/medusa"
|
|
29
30
|
},
|
|
30
31
|
"peerDependencies": {
|
|
31
|
-
"@tallyui/core": "^
|
|
32
|
+
"@tallyui/core": "^5.0.0"
|
|
32
33
|
},
|
|
33
34
|
"devDependencies": {
|
|
34
|
-
"@tallyui/database": "
|
|
35
|
+
"@tallyui/database": "5.0.0",
|
|
35
36
|
"rxdb": "17.5.0"
|
|
36
37
|
},
|
|
37
38
|
"scripts": {
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
// The customer display signalling client for the medusapos plugin's `/tally/v1` display routes (ADR-085 Medusa U7,
|
|
2
|
+
// #1219). Stateless: one request per seam call, no retry. A refusal is only ever `new DisplaySignallingError(code)`:
|
|
3
|
+
// no server text, status, URL, header, body or cause reaches it, so no key, token, secret or code can leak through it.
|
|
4
|
+
import {
|
|
5
|
+
DisplaySignallingError,
|
|
6
|
+
type DisplayRecord, type DisplaySignalling, type DisplaySignallingContext, type DisplaySignallingErrorCode,
|
|
7
|
+
type PendingPairing, type SignalMessage, type SyncContext, type TillDevice,
|
|
8
|
+
} from '@tallyui/core';
|
|
9
|
+
|
|
10
|
+
const PREFIX = '/tally/v1';
|
|
11
|
+
|
|
12
|
+
/** #1219: a body `code` counts only at its own status; any other code, or a code at another status, is `server`. */
|
|
13
|
+
const CODES_BY_STATUS: Record<number, readonly DisplaySignallingErrorCode[]> = {
|
|
14
|
+
403: ['forbidden', 'claim_refused', 'collect_refused', 'device_refused', 'token_refused'],
|
|
15
|
+
404: ['not_found'],
|
|
16
|
+
429: ['limit'],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type Side =
|
|
20
|
+
| { till: true; ctx: SyncContext; device?: TillDevice }
|
|
21
|
+
| { till: false; dctx: DisplaySignallingContext; token?: string };
|
|
22
|
+
|
|
23
|
+
const refuse = (code: DisplaySignallingErrorCode): DisplaySignallingError => new DisplaySignallingError(code);
|
|
24
|
+
|
|
25
|
+
/** The string `code` of a JSON object body, or undefined when the body is not JSON, not an object, or has none. */
|
|
26
|
+
async function bodyCode(res: Response): Promise<string | undefined> {
|
|
27
|
+
try {
|
|
28
|
+
const body: unknown = await res.json();
|
|
29
|
+
const code = body !== null && typeof body === 'object' ? (body as { code?: unknown }).code : undefined;
|
|
30
|
+
return typeof code === 'string' ? code : undefined;
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Maps a non-2xx answer to the seam's code, by the ordered rules of #1219. */
|
|
37
|
+
async function refusalCode(res: Response, till: boolean): Promise<DisplaySignallingErrorCode> {
|
|
38
|
+
// M2: a body refused with 400 or 413 is not re-sent (docs/DECISIONS.md:6142). pos re-sends `server`
|
|
39
|
+
// (packages/pos/src/customer-display/snapshot-fallback.ts:45-46) but not `too_large`, so both read by status alone.
|
|
40
|
+
if (res.status === 400 || res.status === 413) return 'too_large';
|
|
41
|
+
const code = await bodyCode(res);
|
|
42
|
+
// M5: a till-side 401 with no code is Medusa's own refusal of a missing or expired session; the plugin never answers 401.
|
|
43
|
+
if (res.status === 401 && till && code === undefined) return 'forbidden';
|
|
44
|
+
// Any other 401 is in no row of the table, so it is `server` like every unnamed answer.
|
|
45
|
+
return CODES_BY_STATUS[res.status]?.find((known) => known === code) ?? 'server';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The request's headers. Throws, naming the value, for a value `Headers` refuses. */
|
|
49
|
+
function headersOf(side: Side, body: unknown): Headers {
|
|
50
|
+
// The display side never reads ctx headers: a display holds no store credential.
|
|
51
|
+
const headers = side.till ? new Headers(side.ctx.headers) : new Headers();
|
|
52
|
+
if (body !== undefined) headers.set('Content-Type', 'application/json');
|
|
53
|
+
// Set last, so no ctx header in any case overrides them.
|
|
54
|
+
if (side.till && side.device) {
|
|
55
|
+
headers.set('X-Tally-Device-Id', side.device.deviceId);
|
|
56
|
+
headers.set('X-Tally-Device-Key', side.device.deviceKey);
|
|
57
|
+
}
|
|
58
|
+
if (!side.till && side.token !== undefined) headers.set('X-Tally-Display-Token', side.token);
|
|
59
|
+
return headers;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Sends one request and gives the 2xx response; every failure is a `DisplaySignallingError`. */
|
|
63
|
+
async function request(side: Side, method: string, path: string, body?: unknown): Promise<Response> {
|
|
64
|
+
const base = side.till ? side.ctx : side.dctx;
|
|
65
|
+
let headers: Headers, json: string | undefined;
|
|
66
|
+
// Both are built before the fetch, so a bad input sends nothing:
|
|
67
|
+
// - a header value `Headers` refuses is `network`, as M7; its error names the value, so it is dropped;
|
|
68
|
+
// - a body JSON cannot serialise is `too_large`, which pos does not re-send, as M2;
|
|
69
|
+
// - headers go first, so an input bad in both is `network`.
|
|
70
|
+
try { headers = headersOf(side, body); } catch { throw refuse('network'); }
|
|
71
|
+
try { json = body === undefined ? undefined : JSON.stringify(body); } catch { throw refuse('too_large'); }
|
|
72
|
+
const doFetch = base.fetch ?? globalThis.fetch;
|
|
73
|
+
let res: Response;
|
|
74
|
+
try {
|
|
75
|
+
// Joined like capabilities.ts: the base URL as given, then the path.
|
|
76
|
+
res = await doFetch(new URL(`${base.baseUrl}${PREFIX}${path}`), {
|
|
77
|
+
method, headers,
|
|
78
|
+
...(json === undefined ? {} : { body: json }),
|
|
79
|
+
...(side.till ? { signal: side.ctx.signal } : { credentials: 'omit' as const }),
|
|
80
|
+
});
|
|
81
|
+
} catch {
|
|
82
|
+
// M7: any rejection, an abort included.
|
|
83
|
+
throw refuse('network');
|
|
84
|
+
}
|
|
85
|
+
if (!res.ok) throw refuse(await refusalCode(res, side.till));
|
|
86
|
+
return res;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The 2xx body as a JSON object; anything else is `server`. */
|
|
90
|
+
async function read(res: Response): Promise<Record<string, unknown>> {
|
|
91
|
+
let body: unknown;
|
|
92
|
+
try {
|
|
93
|
+
body = await res.json();
|
|
94
|
+
} catch {
|
|
95
|
+
throw refuse('server');
|
|
96
|
+
}
|
|
97
|
+
return object(body);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function object(value: unknown): Record<string, unknown> {
|
|
101
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw refuse('server');
|
|
102
|
+
return value as Record<string, unknown>;
|
|
103
|
+
}
|
|
104
|
+
function text(value: unknown): string {
|
|
105
|
+
if (typeof value !== 'string') throw refuse('server');
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
function list(value: unknown): unknown[] {
|
|
109
|
+
if (!Array.isArray(value)) throw refuse('server');
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
function signal(value: unknown): SignalMessage {
|
|
113
|
+
const entry = object(value);
|
|
114
|
+
const type = text(entry.type);
|
|
115
|
+
if (type !== 'offer' && type !== 'answer' && type !== 'ice') throw refuse('server');
|
|
116
|
+
return { type, payload: text(entry.payload) };
|
|
117
|
+
}
|
|
118
|
+
function pairing(value: unknown): PendingPairing {
|
|
119
|
+
const entry = object(value);
|
|
120
|
+
return { claimId: text(entry.claimId), displayName: text(entry.displayName), checkCode: text(entry.checkCode), expiresAt: text(entry.expiresAt) };
|
|
121
|
+
}
|
|
122
|
+
function display(value: unknown): DisplayRecord {
|
|
123
|
+
const entry = object(value);
|
|
124
|
+
if (entry.lastSeenAt !== null && typeof entry.lastSeenAt !== 'string') throw refuse('server');
|
|
125
|
+
if (typeof entry.connected !== 'boolean') throw refuse('server');
|
|
126
|
+
return { displayId: text(entry.displayId), name: text(entry.name), cashierId: text(entry.cashierId), lastSeenAt: entry.lastSeenAt, connected: entry.connected };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const id = encodeURIComponent;
|
|
130
|
+
const till = (ctx: SyncContext, device?: TillDevice): Side => ({ till: true, ctx, device });
|
|
131
|
+
const shown = (dctx: DisplaySignallingContext, token?: string): Side => ({ till: false, dctx, token });
|
|
132
|
+
|
|
133
|
+
/** The medusapos plugin's display signalling (ADR-085 d2): the till side rides the admin user's Bearer session. */
|
|
134
|
+
export const medusaDisplaySignalling: DisplaySignalling = {
|
|
135
|
+
async registerDevice(ctx, deviceId) {
|
|
136
|
+
const body = await read(await request(till(ctx), 'POST', '/display-devices', { deviceId }));
|
|
137
|
+
return { deviceKey: text(body.deviceKey) };
|
|
138
|
+
},
|
|
139
|
+
async mint(ctx, device) {
|
|
140
|
+
const body = await read(await request(till(ctx, device), 'POST', '/display-codes'));
|
|
141
|
+
return { code: text(body.code), expiresAt: text(body.expiresAt) };
|
|
142
|
+
},
|
|
143
|
+
async pending(ctx, device) {
|
|
144
|
+
return list((await read(await request(till(ctx, device), 'GET', '/display-pairings'))).pairings).map(pairing);
|
|
145
|
+
},
|
|
146
|
+
async confirm(ctx, device, claimId) {
|
|
147
|
+
await request(till(ctx, device), 'POST', `/display-pairings/${id(claimId)}/confirm`);
|
|
148
|
+
},
|
|
149
|
+
async decline(ctx, device, claimId) {
|
|
150
|
+
await request(till(ctx, device), 'POST', `/display-pairings/${id(claimId)}/decline`);
|
|
151
|
+
},
|
|
152
|
+
async list(ctx, device) {
|
|
153
|
+
return list((await read(await request(till(ctx, device), 'GET', '/displays'))).displays).map(display);
|
|
154
|
+
},
|
|
155
|
+
async forget(ctx, device, displayId) {
|
|
156
|
+
await request(till(ctx, device), 'DELETE', `/displays/${id(displayId)}`);
|
|
157
|
+
},
|
|
158
|
+
async sendSignal(ctx, device, displayId, message) {
|
|
159
|
+
await request(till(ctx, device), 'POST', `/displays/${id(displayId)}/signals`, { type: message.type, payload: message.payload });
|
|
160
|
+
},
|
|
161
|
+
async receiveSignals(ctx, device) {
|
|
162
|
+
const signals = list((await read(await request(till(ctx, device), 'POST', '/display-signals/drain'))).signals);
|
|
163
|
+
return signals.map((value) => ({ ...signal(value), displayId: text(object(value).displayId) }));
|
|
164
|
+
},
|
|
165
|
+
async postSnapshot(ctx, device, displayId, body) {
|
|
166
|
+
// The server measures the 204 800-byte cap on the snapshot alone; the client sends it as given.
|
|
167
|
+
await request(till(ctx, device), 'PUT', `/displays/${id(displayId)}/snapshot`, { snapshot: body });
|
|
168
|
+
},
|
|
169
|
+
async claim(dctx, { code, displayName, token }) {
|
|
170
|
+
// The token travels only in the body here, never in the header.
|
|
171
|
+
const body = await read(await request(shown(dctx), 'POST', '/display/claim', { code, displayName, ...(token === undefined ? {} : { token }) }));
|
|
172
|
+
return { claimSecret: text(body.claimSecret), checkCode: text(body.checkCode) };
|
|
173
|
+
},
|
|
174
|
+
async collect(dctx, claimSecret) {
|
|
175
|
+
const body = await read(await request(shown(dctx), 'POST', '/display/collect', { claimSecret }));
|
|
176
|
+
if (body.status === 'pending') return { status: 'pending', checkCode: text(body.checkCode) };
|
|
177
|
+
if (body.status === 'paired') return { status: 'paired', displayId: text(body.displayId), token: text(body.token) };
|
|
178
|
+
throw refuse('server');
|
|
179
|
+
},
|
|
180
|
+
async displaySendSignal(dctx, token, message) {
|
|
181
|
+
await request(shown(dctx, token), 'POST', '/display/signals', { type: message.type, payload: message.payload });
|
|
182
|
+
},
|
|
183
|
+
async displayReceiveSignals(dctx, token) {
|
|
184
|
+
return list((await read(await request(shown(dctx, token), 'POST', '/display/signals/drain'))).signals).map(signal);
|
|
185
|
+
},
|
|
186
|
+
async readSnapshot(dctx, token) {
|
|
187
|
+
const { snapshot } = await read(await request(shown(dctx, token), 'GET', '/display/snapshot'));
|
|
188
|
+
return snapshot ?? null;
|
|
189
|
+
},
|
|
190
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { fetchPages as fetchPricePages, fingerprint as priceFingerprint } from '
|
|
|
13
13
|
import { fetchPages as fetchCalculatedPricePages, fingerprint as calculatedPriceFingerprint } from './reconcile/calculated-prices';
|
|
14
14
|
import { medusaStoreSettings } from './store-settings';
|
|
15
15
|
import { createMedusaOrders, MEDUSA_ORDER_FILTERS } from './orders';
|
|
16
|
+
import { medusaDisplaySignalling } from './display-signalling';
|
|
16
17
|
|
|
17
18
|
export const medusaSecretKeyAuth: ConnectorAuth = {
|
|
18
19
|
type: 'Medusa Admin API',
|
|
@@ -168,7 +169,7 @@ const medusaConnectorParts = {
|
|
|
168
169
|
export const createMedusaAdminUserConnector = (): TallyConnector => ({
|
|
169
170
|
...createMedusaConnector(), auth: medusaAdminUserAuth, capabilities: medusaCapabilities,
|
|
170
171
|
searchCustomers: medusaSearchCustomers, createCustomer: medusaCreateCustomer, getCustomer: medusaGetCustomer, updateCustomer: medusaUpdateCustomer,
|
|
171
|
-
...createMedusaOrders(), orderFilters: MEDUSA_ORDER_FILTERS,
|
|
172
|
+
...createMedusaOrders(), orderFilters: MEDUSA_ORDER_FILTERS, displaySignalling: medusaDisplaySignalling,
|
|
172
173
|
});
|
|
173
174
|
|
|
174
175
|
/**
|
|
@@ -197,6 +198,7 @@ export {
|
|
|
197
198
|
MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT,
|
|
198
199
|
} from './orders';
|
|
199
200
|
export { withCalculatedPrices } from './pricing/calculated';
|
|
201
|
+
export { medusaDisplaySignalling } from './display-signalling';
|
|
200
202
|
export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS } from './reconcile/calculated-prices';
|
|
201
203
|
export type { MedusaCalculatedPrice, MedusaProductDocument, MedusaVariantDocument } from './schemas/products';
|
|
202
204
|
|
package/src/orders.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
assertOrderFiltersSupported, ConnectorUnauthorizedError, CustomerServiceError,
|
|
3
|
-
type OrderFilterField, type ServerCapabilities, type StoreOrder, type StoreOrderLine, type StoreOrderPage, type SyncContext,
|
|
3
|
+
type OrderFilterField, type ServerCapabilities, type StoreOrder, type StoreOrderLine, type StoreOrderPage, type StoreOrderRefundLine, type SyncContext,
|
|
4
4
|
type TallyConnector,
|
|
5
5
|
} from '@tallyui/core';
|
|
6
6
|
import { medusaMinor, medusaNetMinor, medusaSumMinor } from './money';
|
|
@@ -129,6 +129,10 @@ export const MEDUSA_DISPLAY_NUMBER_MAX_DIGITS = 6;
|
|
|
129
129
|
export const MEDUSA_ORDERS_PLUGIN_CONTRACT = 3;
|
|
130
130
|
/** The MedusaPOS plugin contract at which GET /tally/v1/orders takes allChannels=true (medusapos/app#516); a contract-3 plugin answers the key with a 400. */
|
|
131
131
|
export const MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT = 4;
|
|
132
|
+
/** The MedusaPOS plugin contract whose GET /tally/v1/orders takes `ids=` and returns `refunds[].lines` (#1324). */
|
|
133
|
+
const REFUND_LINES_PLUGIN_CONTRACT = 6;
|
|
134
|
+
/** The plugin's cap on `ids=` per request, its ORDERS_MAX_PER_PAGE (#1324). */
|
|
135
|
+
const REFUND_LINES_IDS_MAX = 100;
|
|
132
136
|
|
|
133
137
|
// The plugin sends its contract as /tally/v1/info's top-level `pluginContract`; a contract-2 plugin has no orders route.
|
|
134
138
|
const hasOrdersRoute = (capabilities?: ServerCapabilities) => (capabilities?.pluginContract ?? 0) >= MEDUSA_ORDERS_PLUGIN_CONTRACT;
|
|
@@ -171,6 +175,69 @@ function readOrders(raws: readonly unknown[]): { orders: StoreOrder[]; unreadabl
|
|
|
171
175
|
return { orders, unreadable };
|
|
172
176
|
}
|
|
173
177
|
|
|
178
|
+
const isCount = (value: unknown, min: number): value is number => Number.isSafeInteger(value) && (value as number) >= min;
|
|
179
|
+
|
|
180
|
+
/** Each order's refund lines (order id, then refund id) from the plugin's `orders[]` rows, kept only when every line is valid for that order (#1324); an order whose refunds together name more of a line than was ordered gets none; never throws. */
|
|
181
|
+
function refundLinesByOrder(raws: readonly unknown[], orders: readonly StoreOrder[]): Map<string, Map<string, StoreOrderRefundLine[]>> {
|
|
182
|
+
const lineIds = new Map(orders.map((order) => [order.id, new Map(order.lines.map((line) => [line.id, line.quantity]))]));
|
|
183
|
+
const byOrder = new Map<string, Map<string, StoreOrderRefundLine[]>>();
|
|
184
|
+
for (const raw of rows(raws)) {
|
|
185
|
+
const known = typeof raw.id === 'string' ? lineIds.get(raw.id) : undefined;
|
|
186
|
+
if (!known || typeof raw.id !== 'string') continue;
|
|
187
|
+
const linesById = byOrder.get(raw.id) ?? new Map<string, StoreOrderRefundLine[]>();
|
|
188
|
+
byOrder.set(raw.id, linesById);
|
|
189
|
+
for (const { id, lines } of rows(raw.refunds)) {
|
|
190
|
+
if (typeof id !== 'string' || !Array.isArray(lines) || lines.length === 0) continue;
|
|
191
|
+
// An order's line ids are never empty, so `known.has` also refuses an empty orderLineId; a quantity above the ordered one is malformed.
|
|
192
|
+
const kept = rows(lines).flatMap(({ orderLineId, quantity, netMinor, taxMinor }) => (
|
|
193
|
+
typeof orderLineId === 'string' && known.has(orderLineId) && isCount(quantity, 1) && quantity <= known.get(orderLineId)! && isCount(netMinor, 0) && isCount(taxMinor, 0)
|
|
194
|
+
? [{ orderLineId, quantity, netMinor, taxMinor }] : []));
|
|
195
|
+
// A refund names each order line once.
|
|
196
|
+
if (kept.length === lines.length && new Set(kept.map((line) => line.orderLineId)).size === kept.length) linesById.set(id, kept);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// The till treats refunds' lines as cumulative, so an order whose refunds over-count a line gets none.
|
|
200
|
+
for (const [orderId, linesById] of byOrder) {
|
|
201
|
+
const ordered = lineIds.get(orderId)!;
|
|
202
|
+
const refunded = new Map<string, number>();
|
|
203
|
+
for (const line of [...linesById.values()].flat()) refunded.set(line.orderLineId, (refunded.get(line.orderLineId) ?? 0) + line.quantity);
|
|
204
|
+
if ([...refunded].some(([lineId, quantity]) => quantity > ordered.get(lineId)!)) byOrder.delete(orderId);
|
|
205
|
+
}
|
|
206
|
+
return byOrder;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** The orders with `lines` on each of their own refunds the map names; every other refund and order is returned as is. */
|
|
210
|
+
function withRefundLines(orders: StoreOrder[], byOrder: Map<string, Map<string, StoreOrderRefundLine[]>>): StoreOrder[] {
|
|
211
|
+
return orders.map((order) => {
|
|
212
|
+
const linesById = byOrder.get(order.id);
|
|
213
|
+
return linesById && order.refunds.some((refund) => linesById.has(refund.id))
|
|
214
|
+
? { ...order, refunds: order.refunds.map((refund) => { const lines = linesById.get(refund.id); return lines ? { ...refund, lines } : refund; }) }
|
|
215
|
+
: order;
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* At contract 6, the refunded lines from the plugin's orders route, asked for the orders with refunds in chunks of
|
|
221
|
+
* REFUND_LINES_IDS_MAX, one request at a time. A failed chunk leaves its refunds without lines, unless the read was cancelled.
|
|
222
|
+
*/
|
|
223
|
+
async function readRefundLines(context: SyncContext, orders: StoreOrder[]): Promise<StoreOrder[]> {
|
|
224
|
+
if ((context.capabilities?.pluginContract ?? 0) < REFUND_LINES_PLUGIN_CONTRACT) return orders;
|
|
225
|
+
const ids = orders.filter((order) => order.refunds.length > 0).map((order) => order.id);
|
|
226
|
+
const raws: unknown[] = [];
|
|
227
|
+
for (let start = 0; start < ids.length; start += REFUND_LINES_IDS_MAX) {
|
|
228
|
+
const chunk = ids.slice(start, start + REFUND_LINES_IDS_MAX);
|
|
229
|
+
// Contract 6 is past MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT; without allChannels the route reads only the till's sales channel.
|
|
230
|
+
const params = new URLSearchParams({ page: '1', perPage: String(chunk.length), ids: chunk.join(','), allChannels: 'true' });
|
|
231
|
+
try {
|
|
232
|
+
const body = await ordersRequest(context, '/tally/v1/orders', params);
|
|
233
|
+
if (Array.isArray(body?.orders)) raws.push(...(body.orders as unknown[]));
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (context.signal?.aborted) throw error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return raws.length > 0 ? withRefundLines(orders, refundLinesByOrder(raws, orders)) : orders;
|
|
239
|
+
}
|
|
240
|
+
|
|
174
241
|
// An all-digits search the plugin's route matches against display_id (medusapos orders/list.ts:78-84); the admin API has no number search.
|
|
175
242
|
const DISPLAY_NUMBER = new RegExp(`^\\d{1,${MEDUSA_DISPLAY_NUMBER_MAX_DIGITS}}$`);
|
|
176
243
|
|
|
@@ -193,7 +260,9 @@ async function listThroughPlugin(context: SyncContext, params: URLSearchParams):
|
|
|
193
260
|
// `id[]` answers in the server's own order, not the order asked (dev store, 2026-11-20), so the rows go back in the plugin's order.
|
|
194
261
|
const byId = new Map(rows(body.orders).map((row) => [row.id, row]));
|
|
195
262
|
const picked = ids.flatMap((id) => byId.get(id) ?? []);
|
|
196
|
-
const { orders, unreadable } = readOrders(picked);
|
|
263
|
+
const { orders: read, unreadable } = readOrders(picked);
|
|
264
|
+
// At contract 6 the route's own hits carry refunds[].lines, so no further request (#1324).
|
|
265
|
+
const orders = (context.capabilities?.pluginContract ?? 0) >= REFUND_LINES_PLUGIN_CONTRACT ? withRefundLines(read, refundLinesByOrder(hits, read)) : read;
|
|
197
266
|
// An id the admin answer lacks is left out and counted like a row the mapper cannot read.
|
|
198
267
|
const left = unreadable + ids.length - picked.length;
|
|
199
268
|
return { orders, hasMore, ...(left ? { unreadable: left } : {}), ...counted };
|
|
@@ -243,7 +312,7 @@ export function createMedusaOrders(): Required<Pick<TallyConnector, 'listOrders'
|
|
|
243
312
|
const { count } = body;
|
|
244
313
|
const counted = typeof count === 'number' && Number.isInteger(count) && count >= 0;
|
|
245
314
|
const hasMore = counted ? offset + body.orders.length < count : body.orders.length === perPage;
|
|
246
|
-
return { orders, hasMore, ...(unreadable ? { unreadable } : {}), ...(counted ? { total: count } : {}) };
|
|
315
|
+
return { orders: await readRefundLines(context, orders), hasMore, ...(unreadable ? { unreadable } : {}), ...(counted ? { total: count } : {}) };
|
|
247
316
|
},
|
|
248
317
|
|
|
249
318
|
/** One request per id, in the order asked; an id the store does not have (404) is left out. */
|
|
@@ -253,7 +322,7 @@ export function createMedusaOrders(): Required<Pick<TallyConnector, 'listOrders'
|
|
|
253
322
|
const body = await ordersRequest(context, `/admin/orders/${encodeURIComponent(id)}`, new URLSearchParams({ fields: ORDER_FIELDS }), 'null');
|
|
254
323
|
if (body) orders.push(toMedusaStoreOrder(body.order));
|
|
255
324
|
}
|
|
256
|
-
return orders;
|
|
325
|
+
return readRefundLines(context, orders);
|
|
257
326
|
},
|
|
258
327
|
};
|
|
259
328
|
}
|