@tallyui/connector-woocommerce 1.0.0 → 3.0.0-next.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/src/index.ts CHANGED
@@ -1,33 +1,69 @@
1
- import type { TallyConnector } from '@tallyui/core';
1
+ import { combinePullAdapters, ConnectorUnauthorizedError, type TallyConnector } from '@tallyui/core';
2
2
 
3
3
  import { wooProductSchema } from './schemas/products';
4
4
  import { wooProductTraits } from './traits/product';
5
5
  import { wooProductSync } from './sync/products';
6
6
  import { wooProductReplication } from './replication/products';
7
+ import { wooCatalogueReconcile } from './reconcile/catalogue';
8
+ import { createWooReconcileFeed, MAX_IDS_PER_REQUEST } from './reconcile/feed';
9
+ import { version } from '../package.json';
10
+
11
+ /** One part of X-WCPOS-Client as WCPOS keeps it: lowercase [a-z0-9._-], at most 32 characters. */
12
+ export function wcposClientPart(part: string): string {
13
+ return part.toLowerCase().replace(/[^a-z0-9._-]/g, '').slice(0, 32);
14
+ }
15
+
16
+ export class WooMissingTokenError extends ConnectorUnauthorizedError {
17
+ constructor() {
18
+ super('WooCommerce credentials have no WCPOS access token: sign in again');
19
+ this.name = 'WooMissingTokenError';
20
+ }
21
+ }
7
22
 
8
23
  /**
9
- * WooCommerce connector for Tally UI.
24
+ * WooCommerce connector for Tally UI. Build one per store session, anew on each sign-in or store change:
25
+ * it owns the reconcile feed, whose queued work must never reach another store's database (#307).
10
26
  *
11
- * Connects to WooCommerce sites via the REST API (v3) or WCPOS API.
27
+ * Requires the WCPOS Free plugin 1.10.0 or later. SyncContext.baseUrl must
28
+ * be the store's wcpos/v2 root: <site>/wp-json/wcpos/v2.
12
29
  * Products are stored in RxDB using a schema that mirrors the WC API shape.
13
30
  *
14
31
  * ```ts
15
- * import { woocommerceConnector } from '@tallyui/connector-woocommerce';
32
+ * import { createWooCommerceConnector } from '@tallyui/connector-woocommerce';
16
33
  * import { ConnectorProvider } from '@tallyui/core';
17
34
  *
18
- * <ConnectorProvider connector={woocommerceConnector}>
35
+ * const connector = useMemo(() => createWooCommerceConnector(), [storeUrl]);
36
+ * <ConnectorProvider connector={connector}>
19
37
  * <App />
20
38
  * </ConnectorProvider>
21
39
  * ```
22
40
  */
23
- export const woocommerceConnector: TallyConnector = {
41
+ export function createWooCommerceConnector(): TallyConnector {
42
+ // The catalogue reconcile's corrections reach `products` only through this pull adapter (#248).
43
+ const catalogueFeed = createWooReconcileFeed();
44
+ return {
45
+ ...wooConnectorParts,
46
+ replication: {
47
+ // One replication per collection; the reconcile feed is last, so its fetch wins duplicates. legacyKey
48
+ // reads an existing install's plain pull checkpoint as the product feed's, so it does not resync.
49
+ products: combinePullAdapters({ products: wooProductReplication, reconcile: catalogueFeed.adapter }, { legacyKey: 'products' }),
50
+ },
51
+ reconcile: {
52
+ // The feed's fetchByIds asks for at most this many ids per request; the runner budgets by requests.
53
+ catalogue: { ...wooCatalogueReconcile(catalogueFeed), refetchBatchSize: MAX_IDS_PER_REQUEST },
54
+ },
55
+ };
56
+ }
57
+
58
+ // Everything but the reconcile feed and what is wired to it: stateless, so every instance shares it.
59
+ const wooConnectorParts = {
24
60
  id: 'woocommerce',
25
61
  name: 'WooCommerce',
26
62
  description: 'Connect to WooCommerce stores via the REST API',
27
63
  icon: undefined, // TODO: WooCommerce logo
28
64
 
29
65
  auth: {
30
- type: 'WooCommerce REST API',
66
+ type: 'WCPOS token',
31
67
  fields: [
32
68
  {
33
69
  key: 'url',
@@ -37,24 +73,23 @@ export const woocommerceConnector: TallyConnector = {
37
73
  required: true,
38
74
  },
39
75
  {
40
- key: 'consumer_key',
41
- label: 'Consumer Key',
42
- type: 'text',
43
- placeholder: 'ck_...',
44
- required: true,
45
- },
46
- {
47
- key: 'consumer_secret',
48
- label: 'Consumer Secret',
76
+ key: 'token',
77
+ label: 'Access token',
49
78
  type: 'password',
50
- placeholder: 'cs_...',
51
79
  required: true,
52
80
  },
53
81
  ],
54
82
  getHeaders: (credentials) => {
55
- const encoded = btoa(`${credentials.consumer_key}:${credentials.consumer_secret}`);
83
+ if (typeof credentials.token !== 'string' || credentials.token.length === 0) {
84
+ throw new WooMissingTokenError();
85
+ }
56
86
  return {
57
- Authorization: `Basic ${encoded}`,
87
+ Authorization: `Bearer ${credentials.token}`,
88
+ 'X-WCPOS': '1',
89
+ // WCPOS 2.0 refuses a POS request below protocol 2 (HTTP 426); the connector already speaks 2.
90
+ 'X-WCPOS-Protocol': '2',
91
+ // For WCPOS's consent-gated telemetry only.
92
+ 'X-WCPOS-Client': `tallyui/${wcposClientPart(version)}`,
58
93
  };
59
94
  },
60
95
  },
@@ -70,14 +105,18 @@ export const woocommerceConnector: TallyConnector = {
70
105
  sync: {
71
106
  products: wooProductSync,
72
107
  },
108
+ } satisfies Omit<TallyConnector, 'replication' | 'reconcile'>;
73
109
 
74
- replication: {
75
- products: wooProductReplication,
76
- },
77
- };
110
+ /**
111
+ * @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
112
+ * Use createWooCommerceConnector() per store session. Removed in 4.0.
113
+ */
114
+ export const woocommerceConnector: TallyConnector = createWooCommerceConnector();
78
115
 
79
116
  // Re-export pieces for advanced usage
117
+ export { ConnectorUnauthorizedError } from '@tallyui/core';
80
118
  export { wooProductSchema } from './schemas/products';
81
119
  export { wooProductTraits } from './traits/product';
82
120
  export { wooProductSync } from './sync/products';
83
- export { wooProductReplication } from './replication/products';
121
+ export { wooProductReplication, WooDateFilterError, WooMissingUuidError, WooTillUpdateRequiredError } from './replication/products';
122
+ export { wooCatalogueReconcile, wooReconcileFingerprint } from './reconcile/catalogue';
@@ -0,0 +1,99 @@
1
+ import { errorKind, type CatalogueReconcileAdapter, type CatalogueReconcileEntry, type ReconcileFeed, type SyncContext } from '@tallyui/core';
2
+ import { checkResponse, WooMissingUuidError } from '../replication/products';
3
+
4
+ /** The listing's page size, WordPress's per_page maximum. */
5
+ const PAGE_SIZE = 100;
6
+ /** Enough to compare: the key, the numeric id to refetch by, and the fingerprint's fields. */
7
+ const LISTING_FIELDS = 'id,uuid,date_modified_gmt,stock_quantity,stock_status';
8
+ /** The wcpos/v2/status capability that announces the bulk-id listing (wcpos/woocommerce-pos#2113). */
9
+ const ID_FAST_PATH = 'products_id_fast_path';
10
+
11
+ /**
12
+ * What the catalogue reconcile compares: the modified time and the stock (#248 A1). WooCommerce's
13
+ * `update_product_stock()` writes `_stock` by a direct query that leaves the modified time alone.
14
+ */
15
+ export const wooReconcileFingerprint = (p: { date_modified_gmt?: string | null; stock_quantity?: number | null; stock_status?: string | null }) =>
16
+ [p.date_modified_gmt ?? '', p.stock_quantity ?? '', p.stock_status ?? ''].join('|');
17
+
18
+ async function get(path: string, context: SyncContext): Promise<any> {
19
+ const response = await fetch(`${context.baseUrl}${path}`, {
20
+ headers: { ...context.headers, 'Content-Type': 'application/json' },
21
+ signal: context.signal,
22
+ });
23
+ await checkResponse(response);
24
+ return response.json();
25
+ }
26
+
27
+ /**
28
+ * The switch for the bulk-id fast path: true only when wcpos/v2/status lists `products_id_fast_path` in
29
+ * `capabilities` (a missing field is false). Never a version number, and never a failed attempt.
30
+ * A failed read (network, non-OK, non-JSON) is "no capability known", so the paged listing runs; only a
31
+ * till-class error (401, 403, 426 through checkResponse) stops the pass, since the listing would fail the same way.
32
+ */
33
+ export async function wooHasIdFastPath(context: SyncContext): Promise<boolean> {
34
+ let status: any;
35
+ try {
36
+ status = await get('/status', context);
37
+ } catch (error) {
38
+ if (errorKind(error) === 'till' || context.signal?.aborted) throw error;
39
+ return false;
40
+ }
41
+ return Array.isArray(status?.capabilities) && status.capabilities.includes(ID_FAST_PATH);
42
+ }
43
+
44
+ /**
45
+ * The fast path's one request, pinned to the contract recorded for wcpos/woocommerce-pos#2113: WCPOS's own
46
+ * `fields`, not WordPress's `_fields`, answered from SQL. The context headers carry `X-WCPOS`.
47
+ */
48
+ export function wooBulkListingUrl(baseUrl: string): string {
49
+ const params = new URLSearchParams({ per_page: '-1' });
50
+ for (const field of ['id', 'date_modified_gmt', 'stock_quantity', 'stock_status']) params.append('fields[]', field);
51
+ return `${baseUrl}/products?${params}`;
52
+ }
53
+
54
+ /**
55
+ * The daily catalogue check for WooCommerce (#248): lists every published product with its fingerprint,
56
+ * page by page with no date filter, and hands differences to `feed`, which reaches the collection only
57
+ * through the pull. `confirmGone` is the deletion proof: a by-id re-read.
58
+ */
59
+ export function wooCatalogueReconcile(feed: Pick<ReconcileFeed<any>, 'enqueue'>): CatalogueReconcileAdapter<any, number> {
60
+ return {
61
+ async *fetchPages(context, from = 1) {
62
+ // One status read per pass, yielded as an empty page so that it takes its own budget slot.
63
+ const fast = await wooHasIdFastPath(context);
64
+ yield { entries: [], cursor: from };
65
+ if (fast) {
66
+ // TODO(#2113): list with one wooBulkListingUrl request. It returns `id` but no `uuid`, and entries are
67
+ // keyed by uuid, so it needs an id-to-uuid mapping from the till's documents, which this adapter cannot
68
+ // read. Until that is designed, a store with the capability is listed page by page like any other.
69
+ }
70
+ // status=publish: a product that is not published is absent, so it becomes a deletion candidate and
71
+ // confirmGone decides; drafts cost no daily refetch.
72
+ for (let page = from; ; page++) {
73
+ const params = new URLSearchParams({
74
+ per_page: String(PAGE_SIZE), page: String(page), orderby: 'id', order: 'asc', status: 'publish', _fields: LISTING_FIELDS,
75
+ });
76
+ const rows: any[] = await get(`/products?${params}`, context);
77
+ const entries = rows.map((row): CatalogueReconcileEntry => {
78
+ if (typeof row.uuid !== 'string' || row.uuid.length === 0) throw new WooMissingUuidError(row.id);
79
+ return { key: row.uuid, fingerprint: wooReconcileFingerprint(row), remote: row.id };
80
+ });
81
+ yield { entries, cursor: page + 1 };
82
+ if (rows.length < PAGE_SIZE) return;
83
+ }
84
+ },
85
+ fingerprint: wooReconcileFingerprint,
86
+ async confirmGone(locals, context) {
87
+ const ids = locals.map((doc) => doc.id).filter((id) => Number.isInteger(id));
88
+ // An empty include= would list the whole store; a local without a numeric id has no proof and is kept.
89
+ if (!ids.length) return [];
90
+ const params = new URLSearchParams({ include: ids.join(','), per_page: String(PAGE_SIZE), status: 'any', _fields: 'id,uuid,status' });
91
+ const rows: Array<{ id: number; status: string }> = await get(`/products?${params}`, context);
92
+ const live = new Set(rows.filter((row) => row.status === 'publish').map((row) => row.id));
93
+ return locals.filter((doc) => Number.isInteger(doc.id) && !live.has(doc.id)).map((doc) => doc.uuid);
94
+ },
95
+ // An entry with no numeric id, locally or in the listing, is dropped: the store cannot be asked about it, so
96
+ // the feed would find nothing and tombstone it without proof. (The schema requires only uuid.)
97
+ enqueue: (entries) => feed.enqueue(entries.filter((e) => e.tombstone || Number.isInteger(e.local?.id) || Number.isInteger(e.remote))),
98
+ };
99
+ }
@@ -0,0 +1,34 @@
1
+ import { createReconcileFeed, type ReconcileFeed, type ReconcileFetchEntry, type SyncContext } from '@tallyui/core';
2
+ import { checkResponse, toProductDocument } from '../replication/products';
3
+
4
+ /** WordPress caps per_page at 100, so at most this many ids per include= request. */
5
+ export const MAX_IDS_PER_REQUEST = 100;
6
+
7
+ /**
8
+ * `fetchByIds` for the reconcile feed (#248): full products by numeric id (the till's own `id`, else the
9
+ * listing's `remote`), with `status=any` so that an unpublished product comes back and arrives deleted.
10
+ * The pull's rules apply through `toProductDocument`.
11
+ */
12
+ export async function wooFetchByIds(entries: Array<ReconcileFetchEntry<any>>, context: SyncContext): Promise<any[]> {
13
+ const ids = entries.map((e) => e.local?.id ?? e.remote).filter((id): id is number => Number.isInteger(id));
14
+ const documents: any[] = [];
15
+ for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
16
+ const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
17
+ const params = new URLSearchParams({ include: chunk.join(','), per_page: String(MAX_IDS_PER_REQUEST), status: 'any' });
18
+ const response = await fetch(`${context.baseUrl}/products?${params}`, {
19
+ headers: { ...context.headers, 'Content-Type': 'application/json' },
20
+ signal: context.signal,
21
+ });
22
+ await checkResponse(response);
23
+ documents.push(...(await response.json()).map(toProductDocument));
24
+ }
25
+ return documents;
26
+ }
27
+
28
+ /**
29
+ * The reconcile feed for `products`, keyed by the primary key (`uuid`): the numeric `id` is only how the
30
+ * store is asked (#248 design note, §6). Its corrections reach the collection only through the pull.
31
+ */
32
+ export function createWooReconcileFeed(): ReconcileFeed<any> {
33
+ return createReconcileFeed<any>({ key: (doc) => doc.uuid, fetchByIds: wooFetchByIds });
34
+ }
@@ -1,30 +1,140 @@
1
- import type { ReplicationAdapter, SyncContext } from '@tallyui/core';
1
+ import { ConnectorUnauthorizedError, type ReplicationAdapter } from '@tallyui/core';
2
2
 
3
3
  export type WooProductCheckpoint = {
4
- id: string;
4
+ /** Inclusive lower bound (date_modified_gmt) of the current pass; '' = the whole catalogue. */
5
5
  modified: string;
6
+ /** Rows of the current pass already returned, in id order. */
7
+ offset: number;
8
+ /** Newest date_modified_gmt in the store when the pass started; the next pass's lower bound. */
9
+ pass_mark?: string;
10
+ /** X-WP-Total of the window on the last page; undefined when the store sends none. */
11
+ pass_count?: number;
6
12
  };
7
13
 
14
+ // RxDB drops the checkpoint of an empty result, so the handler moves on to the next useful request
15
+ // in the same call instead; every fetch in one call, mark requests included, counts against this.
16
+ const MAX_REQUESTS_PER_CALL = 4;
17
+
18
+ /** The most of a foreign 426's message kept in the error, so a store's long page never floods the log; longer is cut with "…". */
19
+ const MAX_STORE_MESSAGE = 200;
20
+
21
+ export async function checkResponse(response: Response) {
22
+ if (response.ok) return;
23
+ if (response.status === 401 || response.status === 403) {
24
+ throw new ConnectorUnauthorizedError(`WooCommerce API error: ${response.status}`, response.status);
25
+ }
26
+ if (response.status === 426) {
27
+ // Only the plugin's own gate means the till needs updating; any other 426 is retried as transient, with the store's message.
28
+ const body = await response.json().catch(() => undefined);
29
+ if (body?.code === 'wcpos_update_required') throw new WooTillUpdateRequiredError(body.code);
30
+ // `426 (code): message`, each part only when the body has it.
31
+ const code = typeof body?.code === 'string' && body.code ? ` (${body.code})` : '';
32
+ const text = typeof body?.message === 'string' ? body.message : '';
33
+ const message = text ? `: ${text.length > MAX_STORE_MESSAGE ? `${text.slice(0, MAX_STORE_MESSAGE)}…` : text}` : '';
34
+ throw new Error(`WooCommerce API error: 426${code}${message}`);
35
+ }
36
+ throw new Error(`WooCommerce API error: ${response.status}`);
37
+ }
38
+
39
+ /** WCPOS's protocol gate refused this till (HTTP 426 with `wcpos_update_required`): only updating the till fixes it. */
40
+ export class WooTillUpdateRequiredError extends Error {
41
+ name = 'WooTillUpdateRequiredError';
42
+ readonly code = 'till_update_required' as const;
43
+ /** Only updating this till fixes it, so the pull pauses until resume() (`errorKind`). */
44
+ readonly fixedBy = 'till' as const;
45
+
46
+ /** The body's `code`, kept for diagnostics. */
47
+ constructor(readonly serverCode: string | undefined) {
48
+ super('WooCommerce API error: 426: this till needs updating to sync with the store');
49
+ }
50
+ }
51
+
52
+ export class WooMissingUuidError extends Error {
53
+ name = 'WooMissingUuidError';
54
+ readonly code = 'missing_plugin' as const;
55
+ /** Only the store owner can fix it, by installing or enabling the plugin, so the pull waits the store delay (`errorKind`). */
56
+ readonly fixedBy = 'store' as const;
57
+ productId: number;
58
+
59
+ constructor(id: number) {
60
+ super(`WooCommerce product ${id} has no uuid: the store must run the WCPOS Free plugin (1.10.0 or later) and be reached through its wcpos/v2 routes`);
61
+ this.productId = id;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * One product row as the till stores it, the rule the pull and the reconcile feed share: a uuid is
67
+ * required (WooMissingUuidError), and a product that is not published arrives deleted (#229).
68
+ */
69
+ export function toProductDocument(product: any): any {
70
+ if (typeof product.uuid !== 'string' || product.uuid.length === 0) throw new WooMissingUuidError(product.id);
71
+ return { ...product, _deleted: product.status !== 'publish' };
72
+ }
73
+
74
+ /** The store returned a product outside a modified_after window, so it does not apply the filter. */
75
+ export class WooDateFilterError extends Error {
76
+ name = 'WooDateFilterError';
77
+ readonly code = 'unsupported_store' as const;
78
+ /** Only the store owner can fix it, by updating WooCommerce, so the pull waits the store delay (`errorKind`). */
79
+ readonly fixedBy = 'store' as const;
80
+ /** The software to update, for `SyncStatus`'s detail; the component never names it itself. */
81
+ readonly software = 'WooCommerce';
82
+ /** The first WooCommerce version that applies `modified_after` (5.8). */
83
+ readonly minVersion = '5.8';
84
+
85
+ constructor(readonly productId: number | undefined, readonly bound: string, readonly received: string | undefined) {
86
+ super('This store needs WooCommerce 5.8 or later to sync products.');
87
+ }
88
+ }
89
+
8
90
  /**
9
91
  * Replication adapter for WooCommerce products.
10
92
  *
11
- * Implements pull (cursor-based pagination by date_modified_gmt) and push
12
- * (individual create/update via WC REST API v3). Designed for use with
13
- * RxDB's replicateRxCollection.
93
+ * Pull-only (id-ordered offset pages within a date_modified_gmt window) for RxDB's
94
+ * replicateRxCollection. Catalogue data is server-owned; the POS never
95
+ * writes products.
14
96
  */
15
97
  export const wooProductReplication: ReplicationAdapter<any, WooProductCheckpoint> = {
16
98
  pull: {
17
- async handler(lastCheckpoint, batchSize, context) {
99
+ handler: async function pull(lastCheckpoint, batchSize, context, requests = 0): Promise<{ documents: any[]; checkpoint: WooProductCheckpoint }> {
100
+ const modified = lastCheckpoint?.modified ?? '';
101
+ const offset = lastCheckpoint?.offset ?? 0;
102
+ // Budget spent: a call never fetches after gathering documents, so return [] and let the stored checkpoint stand.
103
+ const spent = { documents: [], checkpoint: lastCheckpoint ?? { modified, offset } };
104
+ let passMark = lastCheckpoint?.pass_mark ?? modified;
105
+ if (offset === 0 && lastCheckpoint?.pass_mark === undefined) {
106
+ if (requests++ >= MAX_REQUESTS_PER_CALL) return spent;
107
+ // orderby=modified sorts by local time, so the store is asked in GMT whether anything is newer than L.
108
+ // No Z or offset on modified_after: WP_Date_Query::build_mysql_datetime parses it in the site time zone and
109
+ // formats it back in that zone, so an offset would move the bound to local time before the post_modified_gmt comparison.
110
+ const newer: Record<string, string> = modified ? { modified_after: modified, dates_are_gmt: 'true' } : {};
111
+ const mark = new URLSearchParams({ per_page: '1', orderby: 'modified', order: 'desc', ...newer });
112
+ const markResponse = await fetch(
113
+ `${context.baseUrl}/products?${mark}`,
114
+ { headers: { ...context.headers, 'Content-Type': 'application/json' }, signal: context.signal },
115
+ );
116
+ await checkResponse(markResponse);
117
+ const [newest] = await markResponse.json();
118
+ // Nothing modified after L (or no product at all): every window is empty.
119
+ if (newest === undefined) return { documents: [], checkpoint: lastCheckpoint ?? { modified: '', offset: 0 } };
120
+ if (modified && !(newest.date_modified_gmt > modified)) throw new WooDateFilterError(newest.id, modified, newest.date_modified_gmt);
121
+ // The local sort may put an older GMT time first: as the next lower bound that costs a re-read, never a skip.
122
+ passMark = newest.date_modified_gmt ?? modified;
123
+ }
18
124
  const params = new URLSearchParams({
19
125
  per_page: String(batchSize),
20
- orderby: 'modified',
126
+ offset: String(offset),
127
+ orderby: 'id',
21
128
  order: 'asc',
22
129
  });
23
130
 
24
- if (lastCheckpoint?.modified) {
25
- params.set('modified_after', lastCheckpoint.modified);
131
+ if (modified) {
132
+ // GMT digits with no offset, for WP_Date_Query (see the mark request).
133
+ params.set('modified_after', new Date(Date.parse(modified + 'Z') - 1000).toISOString().slice(0, 19));
134
+ params.set('dates_are_gmt', 'true');
26
135
  }
27
136
 
137
+ if (requests++ >= MAX_REQUESTS_PER_CALL) return spent;
28
138
  const response = await fetch(`${context.baseUrl}/products?${params}`, {
29
139
  headers: {
30
140
  ...context.headers,
@@ -33,61 +143,38 @@ export const wooProductReplication: ReplicationAdapter<any, WooProductCheckpoint
33
143
  signal: context.signal,
34
144
  });
35
145
 
36
- if (!response.ok) {
37
- throw new Error(`WooCommerce API error: ${response.status}`);
38
- }
146
+ await checkResponse(response);
39
147
 
40
148
  const products: any[] = await response.json();
41
- const documents = products.map((p) => ({ ...p, _deleted: false }));
42
-
43
- const checkpoint: WooProductCheckpoint = products.length > 0
44
- ? {
45
- id: String(products[products.length - 1].uuid ?? products[products.length - 1].id),
46
- modified: products[products.length - 1].date_modified_gmt,
47
- }
48
- : lastCheckpoint ?? { id: '', modified: '' };
49
-
50
- return { documents, checkpoint };
51
- },
52
- },
53
-
54
- push: {
55
- async handler(changeRows, context) {
56
- const conflicts: any[] = [];
57
-
58
- for (const row of changeRows) {
59
- const doc = row.newDocumentState as any;
60
-
61
- try {
62
- const isCreate = !row.assumedMasterState;
63
- const method = isCreate ? 'POST' : 'PUT';
64
- const url = isCreate
65
- ? `${context.baseUrl}/products`
66
- : `${context.baseUrl}/products/${doc.id}`;
67
-
68
- const response = await fetch(url, {
69
- method,
70
- headers: {
71
- ...context.headers,
72
- 'Content-Type': 'application/json',
73
- },
74
- body: JSON.stringify(doc),
75
- signal: context.signal,
76
- });
77
-
78
- if (!response.ok) {
79
- if (row.assumedMasterState) {
80
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
81
- }
82
- }
83
- } catch {
84
- if (row.assumedMasterState) {
85
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
86
- }
149
+ const total = response.headers.get('X-WP-Total');
150
+ const count = total !== null && /^\d+$/.test(total) ? Number(total) : undefined;
151
+ if (offset > 0 && count !== undefined && (products.length === 0 || count < (lastCheckpoint?.pass_count ?? count))) {
152
+ // Restart the pass in this call, so RxDB stores its first page's checkpoint; the request budget bounds the call.
153
+ return pull({ modified, offset: 0, pass_mark: passMark }, batchSize, context, requests);
154
+ }
155
+ const documents = products.map((product) => {
156
+ const document = toProductDocument(product);
157
+ // The window is modified_after = L − 1 s, so a product missing its time or below L was not filtered.
158
+ if (modified && !(product.date_modified_gmt >= modified)) {
159
+ throw new WooDateFilterError(product.id, params.get('modified_after')!, product.date_modified_gmt);
87
160
  }
161
+ return document;
162
+ });
163
+
164
+ // RxDB merges checkpoints, so clear pass state explicitly at completion.
165
+ const complete = count === undefined ? products.length < batchSize : offset + products.length >= count;
166
+ const checkpoint: WooProductCheckpoint = complete
167
+ ? { modified: passMark, offset: 0, pass_mark: undefined, pass_count: undefined }
168
+ : { modified, offset: offset + products.length, pass_mark: passMark, pass_count: count };
169
+ if (complete && products.length === 0) {
170
+ // Chain into the next pass: RxDB would drop this completion with the empty result. While the next pass
171
+ // has nothing either, each poll re-derives these requests from the stored checkpoint, at most
172
+ // MAX_REQUESTS_PER_CALL of them.
173
+ const next = await pull({ modified: passMark, offset: 0 }, batchSize, context, requests);
174
+ return next.documents.length > 0 ? next : { documents: [], checkpoint: lastCheckpoint ?? checkpoint };
88
175
  }
89
176
 
90
- return conflicts;
177
+ return { documents, checkpoint };
91
178
  },
92
179
  },
93
180
  };
@@ -50,8 +50,13 @@ export const wooProductSync: CollectionSync = {
50
50
  },
51
51
 
52
52
  async fetchModifiedAfter(date: string, context: SyncContext): Promise<any[]> {
53
+ const params = new URLSearchParams({
54
+ modified_after: date,
55
+ dates_are_gmt: 'true',
56
+ per_page: '100',
57
+ });
53
58
  const response = await fetch(
54
- `${context.baseUrl}/products?modified_after=${date}&per_page=100`,
59
+ `${context.baseUrl}/products?${params}`,
55
60
  {
56
61
  headers: {
57
62
  ...context.headers,
@@ -1,4 +1,12 @@
1
- import type { ProductTraits } from '@tallyui/core';
1
+ import { moneyFromMajor } from '@tallyui/core';
2
+ import type { ProductPrice, ProductTraits, StockStatus } from '@tallyui/core';
3
+
4
+ /** WooCommerce's stock_status strings, mapped to the neutral enum. */
5
+ const WOO_STOCK_STATUS: Record<string, StockStatus> = {
6
+ instock: 'in_stock',
7
+ outofstock: 'out_of_stock',
8
+ onbackorder: 'backorder',
9
+ };
2
10
 
3
11
  /**
4
12
  * WooCommerce product trait implementations.
@@ -13,6 +21,22 @@ export const wooProductTraits: ProductTraits = {
13
21
 
14
22
  getSku: (doc) => doc.sku || undefined,
15
23
 
24
+ getPrices: (doc, context) => {
25
+ // Woo prices are decimal strings with no currency; the store supplies it.
26
+ const currency = context?.currency ?? 'XXX';
27
+ const prices: ProductPrice[] = [];
28
+ const base = moneyFromMajor(doc.regular_price || doc.price, currency);
29
+ if (base) prices.push({ ...base, kind: 'base' });
30
+ const sale = doc.on_sale === true ? moneyFromMajor(doc.sale_price, currency) : undefined;
31
+ if (sale) prices.push({ ...sale, kind: 'sale' });
32
+ return prices;
33
+ },
34
+
35
+ getStock: (doc) => ({
36
+ status: WOO_STOCK_STATUS[doc.stock_status] ?? 'unknown',
37
+ quantity: doc.manage_stock === false ? undefined : doc.stock_quantity ?? undefined,
38
+ }),
39
+
16
40
  getPrice: (doc) => doc.price || undefined,
17
41
 
18
42
  getRegularPrice: (doc) => doc.regular_price || undefined,
@@ -39,6 +63,10 @@ export const wooProductTraits: ProductTraits = {
39
63
 
40
64
  hasVariants: (doc) => doc.type === 'variable',
41
65
 
66
+ isSellable: (doc) => doc.status === undefined || doc.status === 'publish',
67
+
68
+ getVariantCount: (doc) => doc.type === 'variable' ? doc.variations?.length ?? 0 : 1,
69
+
42
70
  getType: (doc) => doc.type ?? 'simple',
43
71
 
44
72
  getBarcode: (doc) => doc.barcode || undefined,