@tallyui/connector-medusa 3.20.0 → 4.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 +20 -4
- package/dist/index.js +316 -110
- package/package.json +4 -5
- package/src/admin-get.ts +21 -0
- package/src/index.ts +6 -0
- package/src/money.ts +33 -0
- package/src/orders.ts +259 -0
- package/src/reconcile/calculated-prices.ts +2 -2
- package/src/reconcile/ids.ts +3 -16
- package/src/reconcile/prices.ts +8 -27
- package/src/reconcile/stock.ts +2 -11
- package/src/replication/products.ts +4 -29
- package/src/replication/variant-feed.ts +6 -19
- package/src/store-settings.ts +49 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/connector-medusa",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "MedusaJS v2 connector for Tally UI",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -28,15 +28,14 @@
|
|
|
28
28
|
"directory": "connectors/medusa"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"@tallyui/core": "^
|
|
31
|
+
"@tallyui/core": "^4.0.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
|
-
"@tallyui/database": "
|
|
34
|
+
"@tallyui/database": "4.0.0",
|
|
35
35
|
"rxdb": "17.5.0"
|
|
36
36
|
},
|
|
37
37
|
"scripts": {
|
|
38
38
|
"build": "tsup",
|
|
39
|
-
"typecheck": "tsc --noEmit"
|
|
40
|
-
"test": "echo \"no tests yet\""
|
|
39
|
+
"typecheck": "tsc --noEmit"
|
|
41
40
|
}
|
|
42
41
|
}
|
package/src/admin-get.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
|
+
import type { SyncContext } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* GETs an Admin API path (with its query string) and returns the JSON body. A 401 or 403
|
|
6
|
+
* throws ConnectorUnauthorizedError, any other non-2xx an Error, both with the message
|
|
7
|
+
* `Medusa API error: <status>[: <body message>]`.
|
|
8
|
+
*/
|
|
9
|
+
export async function adminGet(path: string, context: SyncContext) {
|
|
10
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
11
|
+
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
12
|
+
signal: context.signal,
|
|
13
|
+
});
|
|
14
|
+
if (!response.ok) {
|
|
15
|
+
const error = await response.json().catch(() => ({}));
|
|
16
|
+
const message = `Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`;
|
|
17
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(message, response.status as 401 | 403);
|
|
18
|
+
throw new Error(message);
|
|
19
|
+
}
|
|
20
|
+
return response.json();
|
|
21
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { fetchByIds, fetchPages, MAX_IDS_PER_REQUEST, variantIds } from './recon
|
|
|
12
12
|
import { fetchPages as fetchPricePages, fingerprint as priceFingerprint } from './reconcile/prices';
|
|
13
13
|
import { fetchPages as fetchCalculatedPricePages, fingerprint as calculatedPriceFingerprint } from './reconcile/calculated-prices';
|
|
14
14
|
import { medusaStoreSettings } from './store-settings';
|
|
15
|
+
import { createMedusaOrders, MEDUSA_ORDER_FILTERS } from './orders';
|
|
15
16
|
|
|
16
17
|
export const medusaSecretKeyAuth: ConnectorAuth = {
|
|
17
18
|
type: 'Medusa Admin API',
|
|
@@ -167,6 +168,7 @@ const medusaConnectorParts = {
|
|
|
167
168
|
export const createMedusaAdminUserConnector = (): TallyConnector => ({
|
|
168
169
|
...createMedusaConnector(), auth: medusaAdminUserAuth, capabilities: medusaCapabilities,
|
|
169
170
|
searchCustomers: medusaSearchCustomers, createCustomer: medusaCreateCustomer, getCustomer: medusaGetCustomer, updateCustomer: medusaUpdateCustomer,
|
|
171
|
+
...createMedusaOrders(), orderFilters: MEDUSA_ORDER_FILTERS,
|
|
170
172
|
});
|
|
171
173
|
|
|
172
174
|
/**
|
|
@@ -190,6 +192,10 @@ export { createMedusaVariantFeedReplication } from './replication/variant-feed';
|
|
|
190
192
|
export { medusaStockReconcile } from './reconcile/stock';
|
|
191
193
|
export { medusaStoreSettings } from './store-settings';
|
|
192
194
|
export { searchMedusaCustomers, createMedusaCustomer, getMedusaCustomer, updateMedusaCustomer, toCustomer } from './customers';
|
|
195
|
+
export {
|
|
196
|
+
createMedusaOrders, toMedusaStoreOrder, MEDUSA_ORDER_FILTERS, medusaOrderFilters, MEDUSA_DISPLAY_NUMBER_MAX_DIGITS, MEDUSA_ORDERS_PLUGIN_CONTRACT,
|
|
197
|
+
MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT,
|
|
198
|
+
} from './orders';
|
|
193
199
|
export { withCalculatedPrices } from './pricing/calculated';
|
|
194
200
|
export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS } from './reconcile/calculated-prices';
|
|
195
201
|
export type { MedusaCalculatedPrice, MedusaProductDocument, MedusaVariantDocument } from './schemas/products';
|
package/src/money.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { CustomerServiceError, minorUnitDigits } from '@tallyui/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Medusa v2 sends money as JSON numbers in major units with sub-cent fractions (ADR-037), so every conversion here is
|
|
5
|
+
* exact: BigInt on the number's shortest round-trip text (`String(n)`), rounded once, half away from zero.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** A finite number as `digits × 10^-scale`, exactly as `String(n)` spells it (exponent form included). */
|
|
9
|
+
function decimal(value: unknown): { digits: bigint; scale: number } {
|
|
10
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) throw new CustomerServiceError('server', 'unexpected response');
|
|
11
|
+
const [, int = '', frac = '', exp = '0'] = /^(-?\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/.exec(String(value))!;
|
|
12
|
+
const scale = frac.length - Number(exp);
|
|
13
|
+
const digits = BigInt(`${int}${frac}`);
|
|
14
|
+
return scale >= 0 ? { digits, scale } : { digits: digits * 10n ** BigInt(-scale), scale: 0 };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The exact decimal sum of `add` minus `subtract`, rounded once to the currency's minor units, half away from zero. */
|
|
18
|
+
export function medusaSumMinor(currency: string, add: readonly unknown[], subtract: readonly unknown[] = []): number {
|
|
19
|
+
const minorDigits = minorUnitDigits(currency);
|
|
20
|
+
const terms = [...add.map((value) => [decimal(value), 1n] as const), ...subtract.map((value) => [decimal(value), -1n] as const)];
|
|
21
|
+
const scale = Math.max(minorDigits, ...terms.map(([term]) => term.scale));
|
|
22
|
+
let total = 0n;
|
|
23
|
+
for (const [term, sign] of terms) total += sign * term.digits * 10n ** BigInt(scale - term.scale);
|
|
24
|
+
const divisor = 10n ** BigInt(scale - minorDigits);
|
|
25
|
+
const rounded = ((total < 0n ? -total : total) + divisor / 2n) / divisor;
|
|
26
|
+
return Number(total < 0n ? -rounded : rounded);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One Medusa amount in minor units. */
|
|
30
|
+
export const medusaMinor = (amount: unknown, currency: string): number => medusaSumMinor(currency, [amount]);
|
|
31
|
+
|
|
32
|
+
/** `gross − tax`, exactly, rounded once: the net such that net + tax is the gross rounded once. */
|
|
33
|
+
export const medusaNetMinor = (gross: unknown, tax: unknown, currency: string): number => medusaSumMinor(currency, [gross], [tax]);
|
package/src/orders.ts
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assertOrderFiltersSupported, ConnectorUnauthorizedError, CustomerServiceError,
|
|
3
|
+
type OrderFilterField, type ServerCapabilities, type StoreOrder, type StoreOrderLine, type StoreOrderPage, type SyncContext,
|
|
4
|
+
type TallyConnector,
|
|
5
|
+
} from '@tallyui/core';
|
|
6
|
+
import { medusaMinor, medusaNetMinor, medusaSumMinor } from './money';
|
|
7
|
+
|
|
8
|
+
type Row = Record<string, unknown>;
|
|
9
|
+
|
|
10
|
+
const MAX_PER_PAGE = 100;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The admin order fields the mapper reads. `credit_line_total` is there because Medusa lowers `total` by each refund's
|
|
14
|
+
* credit line; the mapper adds it back so the order reads as sold, with the refunds beside it.
|
|
15
|
+
*/
|
|
16
|
+
export const ORDER_FIELDS = 'id,display_id,status,created_at,currency_code,email,customer_id,metadata,total,subtotal,tax_total,'
|
|
17
|
+
+ 'discount_total,discount_tax_total,credit_line_total,*customer,*items,*items.tax_lines,*shipping_methods,*shipping_methods.tax_lines,'
|
|
18
|
+
+ '*payment_collections,*payment_collections.payments,*payment_collections.payments.refunds';
|
|
19
|
+
|
|
20
|
+
const unexpected = () => new CustomerServiceError('server', 'unexpected response');
|
|
21
|
+
const isRow = (value: unknown): value is Row => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
22
|
+
const rows = (value: unknown): Row[] => (Array.isArray(value) ? value.filter(isRow) : []);
|
|
23
|
+
const nonEmpty = (value: unknown) => (typeof value === 'string' && value.length > 0 ? value : undefined);
|
|
24
|
+
const required = (value: unknown): string => {
|
|
25
|
+
if (typeof value !== 'string' || value.length === 0) throw unexpected();
|
|
26
|
+
return value;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Maps a Medusa v2 admin order (selected with ORDER_FIELDS) to a `StoreOrder` (ADR-081). Reads plain numbers only, never `raw_*` or `summary`. */
|
|
30
|
+
export function toMedusaStoreOrder(raw: unknown): StoreOrder {
|
|
31
|
+
if (!isRow(raw) || typeof raw.created_at !== 'string' || typeof raw.status !== 'string') throw unexpected();
|
|
32
|
+
const placed = new Date(raw.created_at);
|
|
33
|
+
if (Number.isNaN(placed.getTime())) throw unexpected();
|
|
34
|
+
const currency = required(raw.currency_code).toUpperCase();
|
|
35
|
+
const minor = (amount: unknown) => medusaMinor(amount, currency);
|
|
36
|
+
/** A gross amount and its tax as net + tax, the gross rounded once. */
|
|
37
|
+
const split = (gross: unknown, tax: unknown) => {
|
|
38
|
+
const totalMinor = medusaNetMinor(gross, tax, currency);
|
|
39
|
+
return { totalMinor, taxMinor: minor(gross) - totalMinor };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const metadata = isRow(raw.metadata) ? raw.metadata : {};
|
|
43
|
+
const clientOrderId = nonEmpty(metadata.tally_client_id);
|
|
44
|
+
const items = rows(raw.items);
|
|
45
|
+
const shippingMethods = rows(raw.shipping_methods);
|
|
46
|
+
|
|
47
|
+
const person = isRow(raw.customer) ? raw.customer : {};
|
|
48
|
+
const customerId = nonEmpty(person.id) ?? nonEmpty(raw.customer_id);
|
|
49
|
+
const name = [person.first_name, person.last_name].filter((part) => typeof part === 'string').join(' ').trim();
|
|
50
|
+
const email = nonEmpty(person.email) ?? nonEmpty(raw.email);
|
|
51
|
+
|
|
52
|
+
const taxGroups = new Map<string, { label: string; code?: string; rate: number; totals: unknown[] }>();
|
|
53
|
+
for (const taxLine of [...items, ...shippingMethods].flatMap((owner) => rows(owner.tax_lines))) {
|
|
54
|
+
const { rate } = taxLine;
|
|
55
|
+
if (typeof rate !== 'number' || !Number.isFinite(rate)) throw unexpected();
|
|
56
|
+
const code = nonEmpty(taxLine.code);
|
|
57
|
+
const key = JSON.stringify([code ?? null, rate]);
|
|
58
|
+
const group = taxGroups.get(key) ?? { label: nonEmpty(taxLine.description) ?? code ?? `${rate}%`, code, rate, totals: [] };
|
|
59
|
+
group.totals.push(taxLine.total);
|
|
60
|
+
taxGroups.set(key, group);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Medusa lowers `total` by each refund's credit line; the sale as sold is total + credit_line_total.
|
|
64
|
+
const gross = [raw.total, raw.credit_line_total ?? 0];
|
|
65
|
+
const totalMinor = medusaSumMinor(currency, gross);
|
|
66
|
+
const discount = split(raw.discount_total, raw.discount_tax_total);
|
|
67
|
+
// Every payment across every collection; a collection's own `amount` is what was asked, not what was paid.
|
|
68
|
+
const payments = rows(raw.payment_collections).flatMap((collection) => rows(collection.payments));
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
id: required(raw.id),
|
|
72
|
+
reference: String(raw.display_id ?? raw.id),
|
|
73
|
+
...(clientOrderId ? { clientOrderId } : {}),
|
|
74
|
+
status: raw.status,
|
|
75
|
+
placedAt: placed.toISOString(),
|
|
76
|
+
currency,
|
|
77
|
+
pricesIncludeTax: items.length > 0 && items.every((item) => item.is_tax_inclusive === true),
|
|
78
|
+
customer: customerId || name || email
|
|
79
|
+
? { ...(customerId ? { id: customerId } : {}), ...(name ? { name } : {}), ...(email ? { email } : {}) }
|
|
80
|
+
: null,
|
|
81
|
+
lines: items.map((item): StoreOrderLine => {
|
|
82
|
+
const lineMetadata = isRow(item.metadata) ? item.metadata : {};
|
|
83
|
+
const clientLineId = nonEmpty(lineMetadata.tally_line_uuid);
|
|
84
|
+
const productId = nonEmpty(item.product_id);
|
|
85
|
+
const variantId = nonEmpty(item.variant_id);
|
|
86
|
+
const sku = nonEmpty(item.variant_sku);
|
|
87
|
+
const { quantity } = item;
|
|
88
|
+
if (typeof quantity !== 'number' || !Number.isInteger(quantity) || quantity <= 0) throw unexpected();
|
|
89
|
+
// Before discount from original_total / original_tax_total; after it from total / tax_total (both gross).
|
|
90
|
+
const before = split(item.original_total, item.original_tax_total);
|
|
91
|
+
return {
|
|
92
|
+
id: required(item.id), ...(clientLineId ? { clientLineId } : {}), ...(productId ? { productId } : {}), ...(variantId ? { variantId } : {}),
|
|
93
|
+
name: nonEmpty(item.title) ?? nonEmpty(item.product_title) ?? '', ...(sku ? { sku } : {}), quantity,
|
|
94
|
+
subtotalMinor: before.totalMinor, subtotalTaxMinor: before.taxMinor, ...split(item.total, item.tax_total),
|
|
95
|
+
};
|
|
96
|
+
}),
|
|
97
|
+
fees: [],
|
|
98
|
+
shipping: shippingMethods.map((method) => {
|
|
99
|
+
const id = nonEmpty(method.id);
|
|
100
|
+
const methodId = nonEmpty(method.shipping_option_id);
|
|
101
|
+
return { ...(id ? { id } : {}), name: nonEmpty(method.name) ?? '', ...split(method.total, method.tax_total), ...(methodId ? { methodId } : {}) };
|
|
102
|
+
}),
|
|
103
|
+
coupons: [],
|
|
104
|
+
// Each rate's tax lines summed exactly, then rounded once.
|
|
105
|
+
taxLines: [...taxGroups.values()].map(({ label, code, rate, totals }) => ({
|
|
106
|
+
label, ...(code ? { code } : {}), ratePpm: Math.round(rate * 10000), amountMinor: medusaSumMinor(currency, totals),
|
|
107
|
+
})),
|
|
108
|
+
discountMinor: discount.totalMinor,
|
|
109
|
+
discountTaxMinor: discount.taxMinor,
|
|
110
|
+
taxMinor: totalMinor - medusaSumMinor(currency, gross, [raw.tax_total]),
|
|
111
|
+
totalMinor,
|
|
112
|
+
payments: payments.filter((payment) => payment.canceled_at == null).map((payment) => {
|
|
113
|
+
const id = nonEmpty(payment.id);
|
|
114
|
+
return { ...(id ? { id } : {}), method: required(payment.provider_id), amountMinor: minor(payment.amount) };
|
|
115
|
+
}),
|
|
116
|
+
refunds: payments.flatMap((payment) => rows(payment.refunds)).map((refund) => {
|
|
117
|
+
const reason = nonEmpty(refund.note);
|
|
118
|
+
return { id: required(refund.id), amountMinor: Math.abs(minor(refund.amount)), ...(reason ? { reason } : {}) };
|
|
119
|
+
}),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The ListOrdersQuery filters Medusa's admin order list honours; it has no cashier, register, payment-method, store or created-via filter. */
|
|
124
|
+
export const MEDUSA_ORDER_FILTERS: readonly OrderFilterField[] = ['status', 'customerId', 'dateRange'];
|
|
125
|
+
|
|
126
|
+
/** An all-digits search this long or shorter is a display number (front desk, 2026-11-20); longer goes to `q`, so phone searches keep working. */
|
|
127
|
+
export const MEDUSA_DISPLAY_NUMBER_MAX_DIGITS = 6;
|
|
128
|
+
/** The MedusaPOS plugin contract that adds GET /tally/v1/orders (medusapos versions.ts:18-19). */
|
|
129
|
+
export const MEDUSA_ORDERS_PLUGIN_CONTRACT = 3;
|
|
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
|
+
export const MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT = 4;
|
|
132
|
+
|
|
133
|
+
// The plugin sends its contract as /tally/v1/info's top-level `pluginContract`; a contract-2 plugin has no orders route.
|
|
134
|
+
const hasOrdersRoute = (capabilities?: ServerCapabilities) => (capabilities?.pluginContract ?? 0) >= MEDUSA_ORDERS_PLUGIN_CONTRACT;
|
|
135
|
+
|
|
136
|
+
/** The filter fields `listOrders` honours for a store with these capabilities: `registerId` needs the plugin's orders route. */
|
|
137
|
+
export function medusaOrderFilters(capabilities?: ServerCapabilities): readonly OrderFilterField[] {
|
|
138
|
+
return hasOrdersRoute(capabilities) ? [...MEDUSA_ORDER_FILTERS, 'registerId'] : MEDUSA_ORDER_FILTERS;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** GET on the admin API: network → `network`, 401/403 → ConnectorUnauthorizedError, 400 → `invalid`, other failures → `server`. */
|
|
142
|
+
async function ordersRequest(context: SyncContext, path: string, params: URLSearchParams, missing?: 'null'): Promise<Row | null> {
|
|
143
|
+
let res: Response;
|
|
144
|
+
try {
|
|
145
|
+
res = await fetch(`${context.baseUrl}${path}?${params}`, { method: 'GET', headers: context.headers, signal: context.signal });
|
|
146
|
+
} catch (error) {
|
|
147
|
+
throw new CustomerServiceError('network', error instanceof Error ? error.message : String(error));
|
|
148
|
+
}
|
|
149
|
+
if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorizedError(`Medusa rejected the credentials (HTTP ${res.status})`, res.status as 401 | 403);
|
|
150
|
+
if (res.status === 404 && missing === 'null') return null;
|
|
151
|
+
if (!res.ok) throw new CustomerServiceError(res.status === 400 ? 'invalid' : 'server', `HTTP ${res.status}`, { status: res.status });
|
|
152
|
+
const body: unknown = await res.json().catch(() => undefined);
|
|
153
|
+
if (!isRow(body)) throw new CustomerServiceError('server', 'unexpected response', { status: res.status });
|
|
154
|
+
return body;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const wholeNumber = (value: number | undefined, fallback: number) => (value === undefined || !Number.isFinite(value) ? fallback : Math.trunc(value));
|
|
158
|
+
|
|
159
|
+
/** Maps the rows, leaving out and counting each one the mapper cannot read. */
|
|
160
|
+
function readOrders(raws: readonly unknown[]): { orders: StoreOrder[]; unreadable: number } {
|
|
161
|
+
let unreadable = 0;
|
|
162
|
+
const orders = raws.flatMap((raw) => {
|
|
163
|
+
try {
|
|
164
|
+
return [toMedusaStoreOrder(raw)];
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (!(error instanceof CustomerServiceError)) throw error;
|
|
167
|
+
unreadable += 1;
|
|
168
|
+
return [];
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
return { orders, unreadable };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 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
|
+
const DISPLAY_NUMBER = new RegExp(`^\\d{1,${MEDUSA_DISPLAY_NUMBER_MAX_DIGITS}}$`);
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The plugin's `GET /tally/v1/orders` picks the page's ids; the admin API reads those rows, so every order maps the same way.
|
|
179
|
+
* The route takes only page, perPage, search, status, customerId, registerId, after and before (plus allChannels from contract 4); any other key is a 400 (list.ts:18, 30-34).
|
|
180
|
+
*/
|
|
181
|
+
async function listThroughPlugin(context: SyncContext, params: URLSearchParams): Promise<StoreOrderPage> {
|
|
182
|
+
const found = (await ordersRequest(context, '/tally/v1/orders', params))!;
|
|
183
|
+
const { orders: hits, hasMore, total } = found;
|
|
184
|
+
if (!Array.isArray(hits) || typeof hasMore !== 'boolean') throw unexpected();
|
|
185
|
+
// Each row's id is the Medusa order id, newest first (list.ts:202-204, 244-247; orders/route.ts:19-22).
|
|
186
|
+
const ids = hits.map((hit: unknown) => required(isRow(hit) ? hit.id : undefined));
|
|
187
|
+
const counted = typeof total === 'number' && Number.isInteger(total) && total >= 0 ? { total } : {};
|
|
188
|
+
if (ids.length === 0) return { orders: [], hasMore, ...counted };
|
|
189
|
+
const lookup = new URLSearchParams({ limit: String(ids.length), fields: ORDER_FIELDS });
|
|
190
|
+
for (const id of ids) lookup.append('id[]', id);
|
|
191
|
+
const body = (await ordersRequest(context, '/admin/orders', lookup))!;
|
|
192
|
+
if (!Array.isArray(body.orders)) throw unexpected();
|
|
193
|
+
// `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
|
+
const byId = new Map(rows(body.orders).map((row) => [row.id, row]));
|
|
195
|
+
const picked = ids.flatMap((id) => byId.get(id) ?? []);
|
|
196
|
+
const { orders, unreadable } = readOrders(picked);
|
|
197
|
+
// An id the admin answer lacks is left out and counted like a row the mapper cannot read.
|
|
198
|
+
const left = unreadable + ids.length - picked.length;
|
|
199
|
+
return { orders, hasMore, ...(left ? { unreadable: left } : {}), ...counted };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Medusa v2 admin orders (`GET /admin/orders`): order history, read-only (ADR-081). */
|
|
203
|
+
export function createMedusaOrders(): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>> {
|
|
204
|
+
return {
|
|
205
|
+
/**
|
|
206
|
+
* Newest first. Filters on the server: status (verbatim; Medusa answers an unknown word with a 500, which rejects
|
|
207
|
+
* as `server`), customerId (customer_id) and dateRange (created_at[$gte] / created_at[$lt]); search is Medusa's
|
|
208
|
+
* `q`. Any other filter field is refused. An empty status matches no order, so it resolves an empty page without a request.
|
|
209
|
+
* Register filters and 1-6 digit searches go through the plugin's orders route at contract 3, which reads every sales channel from contract 4 (`allChannels=true`) and only the till's channel at contract 3 (#1125).
|
|
210
|
+
*/
|
|
211
|
+
async listOrders(context: SyncContext, query = {}) {
|
|
212
|
+
assertOrderFiltersSupported(query, medusaOrderFilters(context.capabilities));
|
|
213
|
+
if (query.status === '' || query.registerId === '') return { orders: [], hasMore: false };
|
|
214
|
+
const page = Math.max(1, wholeNumber(query.page, 1));
|
|
215
|
+
const perPage = Math.max(1, Math.min(MAX_PER_PAGE, wholeNumber(query.perPage, 25)));
|
|
216
|
+
const search = query.search?.trim();
|
|
217
|
+
const { after, before } = query.dateRange ?? {};
|
|
218
|
+
// A registerId only gets past the filter check at contract 3, so it always has the route here.
|
|
219
|
+
if (query.registerId !== undefined || (search && DISPLAY_NUMBER.test(search) && hasOrdersRoute(context.capabilities))) {
|
|
220
|
+
// The route clamps perPage to 1..100, needs page >= 1 (list.ts:38-48) and wants an admin user (middlewares.ts:62-64).
|
|
221
|
+
const params = new URLSearchParams({ page: String(page), perPage: String(perPage) });
|
|
222
|
+
if (search) params.set('search', search);
|
|
223
|
+
if (query.status !== undefined) params.set('status', query.status);
|
|
224
|
+
if (query.customerId !== undefined) params.set('customerId', query.customerId);
|
|
225
|
+
// The route matches registerId against metadata tally_register_id (list.ts:73).
|
|
226
|
+
if (query.registerId !== undefined) params.set('registerId', query.registerId);
|
|
227
|
+
// after / before are ISO instants ending in Z, applied as created_at $gte and $lt (list.ts:53-62, 74-77).
|
|
228
|
+
if (after !== undefined) params.set('after', after);
|
|
229
|
+
if (before !== undefined) params.set('before', before);
|
|
230
|
+
if ((context.capabilities?.pluginContract ?? 0) >= MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT) params.set('allChannels', 'true'); // #1125: at contract 4 the route reads every sales channel, like the admin list.
|
|
231
|
+
return listThroughPlugin(context, params);
|
|
232
|
+
}
|
|
233
|
+
const offset = (page - 1) * perPage;
|
|
234
|
+
const params = new URLSearchParams({ limit: String(perPage), offset: String(offset), order: '-created_at', fields: ORDER_FIELDS });
|
|
235
|
+
if (search) params.set('q', search);
|
|
236
|
+
if (query.status !== undefined) params.set('status', query.status);
|
|
237
|
+
if (query.customerId !== undefined) params.set('customer_id', query.customerId);
|
|
238
|
+
if (after !== undefined) params.set('created_at[$gte]', after);
|
|
239
|
+
if (before !== undefined) params.set('created_at[$lt]', before);
|
|
240
|
+
const body = (await ordersRequest(context, '/admin/orders', params))!;
|
|
241
|
+
if (!Array.isArray(body.orders)) throw unexpected();
|
|
242
|
+
const { orders, unreadable } = readOrders(body.orders);
|
|
243
|
+
const { count } = body;
|
|
244
|
+
const counted = typeof count === 'number' && Number.isInteger(count) && count >= 0;
|
|
245
|
+
const hasMore = counted ? offset + body.orders.length < count : body.orders.length === perPage;
|
|
246
|
+
return { orders, hasMore, ...(unreadable ? { unreadable } : {}), ...(counted ? { total: count } : {}) };
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
/** One request per id, in the order asked; an id the store does not have (404) is left out. */
|
|
250
|
+
async getOrders(context: SyncContext, ids: readonly string[]) {
|
|
251
|
+
const orders: StoreOrder[] = [];
|
|
252
|
+
for (const id of new Set(ids.filter((id) => id.length > 0))) {
|
|
253
|
+
const body = await ordersRequest(context, `/admin/orders/${encodeURIComponent(id)}`, new URLSearchParams({ fields: ORDER_FIELDS }), 'null');
|
|
254
|
+
if (body) orders.push(toMedusaStoreOrder(body.order));
|
|
255
|
+
}
|
|
256
|
+
return orders;
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
@@ -23,8 +23,8 @@ function fingerprintOf(variants: Variant[]): string {
|
|
|
23
23
|
* counts them as `unreported`.
|
|
24
24
|
*
|
|
25
25
|
* The app runs it as `reconcile.calculatedPrices` with
|
|
26
|
-
* `startFingerprintReconcile({ …, intervalMs: MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS
|
|
27
|
-
* the runner's
|
|
26
|
+
* `startFingerprintReconcile({ …, intervalMs: MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS })`;
|
|
27
|
+
* the runner's request budget bounds a pass, so a large catalogue does not truncate (#248).
|
|
28
28
|
*/
|
|
29
29
|
export async function* fetchPages(context: SyncContext): AsyncIterable<Map<string, string>> {
|
|
30
30
|
const pricing = context.pricingContext;
|
package/src/reconcile/ids.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
1
|
import type { SyncContext } from '@tallyui/core';
|
|
2
|
+
import { adminGet } from '../admin-get';
|
|
3
3
|
import { MEDUSA_PRODUCT_FIELDS, toDocument } from '../replication/products';
|
|
4
4
|
import { withCalculatedPrices } from '../pricing/calculated';
|
|
5
5
|
import type { MedusaProductDocument } from '../schemas/products';
|
|
@@ -13,24 +13,11 @@ const PAGE_SIZE = 1000;
|
|
|
13
13
|
*/
|
|
14
14
|
export const MAX_IDS_PER_REQUEST = 100;
|
|
15
15
|
|
|
16
|
-
async function get(path: string, context: SyncContext) {
|
|
17
|
-
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
18
|
-
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
19
|
-
signal: context.signal,
|
|
20
|
-
});
|
|
21
|
-
if (!response.ok) {
|
|
22
|
-
const error = await response.json().catch(() => ({}));
|
|
23
|
-
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status as 401 | 403);
|
|
24
|
-
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
25
|
-
}
|
|
26
|
-
return response.json();
|
|
27
|
-
}
|
|
28
|
-
|
|
29
16
|
/** Every live product id with its live variant ids, one request per page (ADR-060). */
|
|
30
17
|
export async function* fetchPages(context: SyncContext): AsyncIterable<Array<{ id: string; variantIds: string[] }>> {
|
|
31
18
|
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
|
|
32
19
|
const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), order: 'id', fields: 'id,variants.id' });
|
|
33
|
-
const data = await
|
|
20
|
+
const data = await adminGet(`/admin/products?${params}`, context);
|
|
34
21
|
const products: Array<{ id: string; variants?: Array<{ id: string }> }> = data.products ?? [];
|
|
35
22
|
count = data.count;
|
|
36
23
|
yield products.map((p) => ({ id: String(p.id), variantIds: (p.variants ?? []).map((v) => String(v.id)) }));
|
|
@@ -49,7 +36,7 @@ export async function fetchByIds(ids: string[], context: SyncContext): Promise<R
|
|
|
49
36
|
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
50
37
|
const params = new URLSearchParams({ fields: MEDUSA_PRODUCT_FIELDS, limit: String(chunk.length) });
|
|
51
38
|
for (const id of chunk) params.append('id[]', id);
|
|
52
|
-
const data = await
|
|
39
|
+
const data = await adminGet(`/admin/products?${params}`, context);
|
|
53
40
|
const products: Array<Record<string, unknown>> = data.products ?? [];
|
|
54
41
|
results.push(...products.map(toDocument));
|
|
55
42
|
}
|
package/src/reconcile/prices.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
1
|
import type { SyncContext } from '@tallyui/core';
|
|
2
|
+
import { adminGet } from '../admin-get';
|
|
3
3
|
|
|
4
4
|
/** Admin API list limit; also the price-listing page size (ADR-060). */
|
|
5
5
|
const PAGE_SIZE = 1000;
|
|
@@ -10,22 +10,13 @@ export const MEDUSA_PRICE_RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
|
10
10
|
type Price = { amount: number; currency_code: string; price_list_id?: string | null };
|
|
11
11
|
type Variant = { id: string; product_id: string; prices?: Price[] };
|
|
12
12
|
|
|
13
|
-
async function get(path: string, context: SyncContext) {
|
|
14
|
-
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
15
|
-
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
16
|
-
signal: context.signal,
|
|
17
|
-
});
|
|
18
|
-
if (!response.ok) {
|
|
19
|
-
const error = await response.json().catch(() => ({}));
|
|
20
|
-
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status as 401 | 403);
|
|
21
|
-
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
22
|
-
}
|
|
23
|
-
return response.json();
|
|
24
|
-
}
|
|
25
|
-
|
|
26
13
|
/** Base prices only (a null `price_list_id`), as `${variantId}:${currencyCode}:${amount}`, sorted and joined. */
|
|
27
14
|
const fingerprintOf = (entries: string[]): string => [...entries].sort().join('|');
|
|
28
15
|
|
|
16
|
+
/** A variant's base-price entries (prices with no `price_list_id`), as `${variantId}:${currencyCode}:${amount}`. */
|
|
17
|
+
const baseEntries = (variant: { id: unknown; prices?: Price[] | null }): string[] =>
|
|
18
|
+
(variant.prices ?? []).filter((price) => !price.price_list_id).map((price) => `${variant.id}:${price.currency_code}:${price.amount}`);
|
|
19
|
+
|
|
29
20
|
/**
|
|
30
21
|
* Every product's base-price fingerprint, one `/admin/product-variants`
|
|
31
22
|
* request per page (ADR-060 amendment 8's nightly backstop). The listing is
|
|
@@ -42,7 +33,7 @@ export async function* fetchPages(context: SyncContext): AsyncIterable<Map<strin
|
|
|
42
33
|
limit: String(PAGE_SIZE), offset: String(offset), order: 'id',
|
|
43
34
|
fields: 'id,product_id,prices.amount,prices.currency_code,prices.price_list_id',
|
|
44
35
|
});
|
|
45
|
-
const data = await
|
|
36
|
+
const data = await adminGet(`/admin/product-variants?${params}`, context);
|
|
46
37
|
const variants: Variant[] = data.variants ?? [];
|
|
47
38
|
count = data.count;
|
|
48
39
|
const touched = new Set<string>();
|
|
@@ -51,10 +42,7 @@ export async function* fetchPages(context: SyncContext): AsyncIterable<Map<strin
|
|
|
51
42
|
touched.add(productId);
|
|
52
43
|
const entries = byProduct.get(productId) ?? [];
|
|
53
44
|
byProduct.set(productId, entries);
|
|
54
|
-
|
|
55
|
-
if (price.price_list_id) continue;
|
|
56
|
-
entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
|
|
57
|
-
}
|
|
45
|
+
entries.push(...baseEntries(variant));
|
|
58
46
|
}
|
|
59
47
|
yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
|
|
60
48
|
}
|
|
@@ -62,12 +50,5 @@ export async function* fetchPages(context: SyncContext): AsyncIterable<Map<strin
|
|
|
62
50
|
|
|
63
51
|
/** The same fingerprint, computed from a local product document's base prices. Replicated Medusa documents carry only base prices today (ADR-060 amendment 8); any `price_list_id` is still skipped, for consistency. */
|
|
64
52
|
export function fingerprint(doc: any): string {
|
|
65
|
-
|
|
66
|
-
for (const variant of doc.variants ?? []) {
|
|
67
|
-
for (const price of variant.prices ?? []) {
|
|
68
|
-
if (price.price_list_id) continue;
|
|
69
|
-
entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
return fingerprintOf(entries);
|
|
53
|
+
return fingerprintOf((doc.variants ?? []).flatMap(baseEntries));
|
|
73
54
|
}
|
package/src/reconcile/stock.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
1
|
import type { StockReconcileAdapter } from '@tallyui/core';
|
|
2
|
+
import { adminGet } from '../admin-get';
|
|
3
3
|
|
|
4
4
|
type Level = { stocked_quantity: number; reserved_quantity: number };
|
|
5
5
|
|
|
@@ -24,16 +24,7 @@ export const medusaStockReconcile: StockReconcileAdapter = {
|
|
|
24
24
|
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
|
|
25
25
|
// Offset paging needs a total order, or items can be skipped or repeated between pages.
|
|
26
26
|
const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), fields: FIELDS, order: 'id' });
|
|
27
|
-
const
|
|
28
|
-
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
29
|
-
signal: context.signal,
|
|
30
|
-
});
|
|
31
|
-
if (!response.ok) {
|
|
32
|
-
const error = await response.json().catch(() => ({}));
|
|
33
|
-
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status as 401 | 403);
|
|
34
|
-
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
35
|
-
}
|
|
36
|
-
const data = await response.json() as { inventory_items: Array<{ id: string; location_levels?: Level[] }>; count: number };
|
|
27
|
+
const data = await adminGet(`/admin/inventory-items?${params}`, context) as { inventory_items: Array<{ id: string; location_levels?: Level[] }>; count: number };
|
|
37
28
|
count = data.count;
|
|
38
29
|
yield new Map(data.inventory_items.map((item) => [item.id, (item.location_levels ?? [])
|
|
39
30
|
.map(({ stocked_quantity, reserved_quantity }) => ({ stocked_quantity, reserved_quantity }))]));
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { compareIds
|
|
1
|
+
import { compareIds } from '@tallyui/core';
|
|
2
2
|
import type { ReplicationAdapter } from '@tallyui/core';
|
|
3
3
|
|
|
4
|
+
import { adminGet } from '../admin-get';
|
|
4
5
|
import { medusaProductSchema, type MedusaProductDocument } from '../schemas/products';
|
|
5
6
|
import { withCalculatedPrices } from '../pricing/calculated';
|
|
6
7
|
|
|
@@ -63,16 +64,7 @@ export const medusaProductReplication: ReplicationAdapter<any, MedusaProductChec
|
|
|
63
64
|
const offset = lastCheckpoint?.offset ?? 0;
|
|
64
65
|
let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? '';
|
|
65
66
|
if (offset === 0 && lastCheckpoint?.pass_mark === undefined) {
|
|
66
|
-
const
|
|
67
|
-
`${context.baseUrl}/admin/products?limit=1&order=-updated_at&fields=id,updated_at`,
|
|
68
|
-
{ headers: { ...context.headers, 'Content-Type': 'application/json' }, signal: context.signal },
|
|
69
|
-
);
|
|
70
|
-
if (!markResponse.ok) {
|
|
71
|
-
const error = await markResponse.json().catch(() => ({}));
|
|
72
|
-
if (markResponse.status === 401 || markResponse.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ''}`, markResponse.status as 401 | 403);
|
|
73
|
-
throw new Error(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
74
|
-
}
|
|
75
|
-
const markData = await markResponse.json();
|
|
67
|
+
const markData = await adminGet('/admin/products?limit=1&order=-updated_at&fields=id,updated_at', context);
|
|
76
68
|
passMark = markData.products?.[0]?.updated_at ?? passMark;
|
|
77
69
|
if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
|
|
78
70
|
return { documents: [], checkpoint: lastCheckpoint };
|
|
@@ -93,24 +85,7 @@ export const medusaProductReplication: ReplicationAdapter<any, MedusaProductChec
|
|
|
93
85
|
params.set('updated_at[$gte]', lastCheckpoint.updated_at);
|
|
94
86
|
}
|
|
95
87
|
|
|
96
|
-
const
|
|
97
|
-
`${context.baseUrl}/admin/products?${params}`,
|
|
98
|
-
{
|
|
99
|
-
headers: {
|
|
100
|
-
...context.headers,
|
|
101
|
-
'Content-Type': 'application/json',
|
|
102
|
-
},
|
|
103
|
-
signal: context.signal,
|
|
104
|
-
},
|
|
105
|
-
);
|
|
106
|
-
|
|
107
|
-
if (!response.ok) {
|
|
108
|
-
const error = await response.json().catch(() => ({}));
|
|
109
|
-
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status as 401 | 403);
|
|
110
|
-
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const data = await response.json();
|
|
88
|
+
const data = await adminGet(`/admin/products?${params}`, context);
|
|
114
89
|
const products: any[] = data.products ?? [];
|
|
115
90
|
if (offset > 0 && (products.length === 0 || data.count < (lastCheckpoint?.pass_count ?? data.count))) {
|
|
116
91
|
return medusaProductReplication.pull.handler({
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
1
|
+
import type { ReplicationAdapter } from '@tallyui/core';
|
|
2
|
+
import { adminGet } from '../admin-get';
|
|
3
3
|
import { fetchByIds } from '../reconcile/ids';
|
|
4
4
|
import { MEDUSA_PRODUCT_FIELDS, toDocument, type MedusaProductCheckpoint } from './products';
|
|
5
5
|
import { withCalculatedPrices } from '../pricing/calculated';
|
|
@@ -10,19 +10,6 @@ const MAX_LIMIT = 1000;
|
|
|
10
10
|
/** The newest variant's `updated_at`: each pass's mark, and a fresh install's seed. */
|
|
11
11
|
const MARK_PATH = '/admin/product-variants?limit=1&order=-updated_at&fields=id,updated_at';
|
|
12
12
|
|
|
13
|
-
async function get(path: string, context: SyncContext) {
|
|
14
|
-
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
15
|
-
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
16
|
-
signal: context.signal,
|
|
17
|
-
});
|
|
18
|
-
if (!response.ok) {
|
|
19
|
-
const error = await response.json().catch(() => ({}));
|
|
20
|
-
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status as 401 | 403);
|
|
21
|
-
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
|
|
22
|
-
}
|
|
23
|
-
return response.json();
|
|
24
|
-
}
|
|
25
|
-
|
|
26
13
|
/**
|
|
27
14
|
* Variant feed for Medusa products (ADR-060, amendment 8).
|
|
28
15
|
*
|
|
@@ -50,7 +37,7 @@ export const createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT):
|
|
|
50
37
|
// The next call's unchanged-mark check then ends at one mark read, unless
|
|
51
38
|
// a variant changed since.
|
|
52
39
|
async seedCheckpoint(context) {
|
|
53
|
-
const markData = await
|
|
40
|
+
const markData = await adminGet(MARK_PATH, context);
|
|
54
41
|
return { offset: 0, updated_at: markData.variants?.[0]?.updated_at ?? '', pass_mark: undefined, pass_count: undefined };
|
|
55
42
|
},
|
|
56
43
|
async handler(lastCheckpoint, batchSize, context) {
|
|
@@ -58,7 +45,7 @@ export const createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT):
|
|
|
58
45
|
let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? '';
|
|
59
46
|
let passCount = lastCheckpoint?.pass_count;
|
|
60
47
|
if (offset === 0 && lastCheckpoint?.pass_mark === undefined) {
|
|
61
|
-
const markData = await
|
|
48
|
+
const markData = await adminGet(MARK_PATH, context);
|
|
62
49
|
passMark = markData.variants?.[0]?.updated_at ?? passMark;
|
|
63
50
|
if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
|
|
64
51
|
return { documents: [], checkpoint: lastCheckpoint };
|
|
@@ -70,7 +57,7 @@ export const createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT):
|
|
|
70
57
|
// Medusa 2.21 honours only the operator form; `updated_at[gte]` is silently dropped.
|
|
71
58
|
// The columns are timestamptz and `$gte` includes ties, as in the product feed.
|
|
72
59
|
if (lastCheckpoint?.updated_at) params.set('updated_at[$gte]', lastCheckpoint.updated_at);
|
|
73
|
-
return
|
|
60
|
+
return adminGet(`/admin/product-variants?${params}`, context);
|
|
74
61
|
};
|
|
75
62
|
|
|
76
63
|
// RxDB stops pulling on a page shorter than batchSize, so keep reading
|
|
@@ -109,7 +96,7 @@ export const createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT):
|
|
|
109
96
|
const moved = (['offset', 'updated_at', 'pass_mark', 'pass_count'] as const)
|
|
110
97
|
.some((key) => checkpoint[key] !== lastCheckpoint?.[key]);
|
|
111
98
|
if (!documents.length && moved) {
|
|
112
|
-
const carrier = await
|
|
99
|
+
const carrier = await adminGet(`/admin/products?${new URLSearchParams({ limit: '1', fields: MEDUSA_PRODUCT_FIELDS })}`, context);
|
|
113
100
|
const priced = await withCalculatedPrices((carrier.products ?? []).map(toDocument) as MedusaProductDocument[], context);
|
|
114
101
|
documents.push(...priced.map((doc) => ({ ...doc, _deleted: false })));
|
|
115
102
|
}
|