@tallyui/connector-vendure 3.20.1 → 4.0.1

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 CHANGED
@@ -1,4 +1,4 @@
1
- import { ConnectorAuth, AuthField, ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, CustomerPatch, TallyConnector, StoreOrder } from '@tallyui/core';
1
+ import { ConnectorAuth, AuthField, ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, CustomerPage, CustomerPatch, TallyConnector, StoreOrder } from '@tallyui/core';
2
2
  export { ConnectorUnauthorizedError } from '@tallyui/core';
3
3
  import { RxJsonSchema } from 'rxdb';
4
4
 
@@ -115,6 +115,14 @@ declare function vendureGlobalStockSettings(context: SyncContext): Promise<{
115
115
  outOfStockThreshold: number;
116
116
  }>;
117
117
 
118
+ /** Vendure's `CustomerListOptions`, sent as given (Vendure applies its own defaults to what is left out). */
119
+ interface VendureCustomerListOptions {
120
+ skip?: number;
121
+ take?: number;
122
+ sort?: Record<string, 'ASC' | 'DESC'>;
123
+ filter?: Record<string, unknown>;
124
+ filterOperator?: 'AND' | 'OR';
125
+ }
118
126
  declare function toVendureCustomer(raw: {
119
127
  id: string;
120
128
  firstName?: string | null;
@@ -122,6 +130,14 @@ declare function toVendureCustomer(raw: {
122
130
  emailAddress?: string | null;
123
131
  phoneNumber?: string | null;
124
132
  }): Customer;
133
+ /**
134
+ * One page of the store's customers, Vendure's list options passed through (paging, sort, filter), with the
135
+ * store's count of every match. Unlike search, it keeps the vendurepos walk-in customer: filter it out with
136
+ * `options.filter` if the caller does not want it. Each customer carries `createdAt` and, from the address book,
137
+ * `billing` / `shipping` (the addresses flagged `defaultBillingAddress` / `defaultShippingAddress`).
138
+ * Credentials and missing permissions reject with `ConnectorUnauthorizedError` (401 / 403, via the session probe).
139
+ */
140
+ declare function listVendureCustomers(context: SyncContext, options?: VendureCustomerListOptions): Promise<CustomerPage>;
125
141
  declare function searchVendureCustomers(context: SyncContext, query: string, options?: {
126
142
  limit?: number;
127
143
  }): Promise<Customer[]>;
@@ -378,4 +394,4 @@ declare const createVendureConnector: (options?: {
378
394
  */
379
395
  declare const vendureConnector: TallyConnector;
380
396
 
381
- export { type VendureCredentialKind, type VendureCredentials, type VendureOrder, type VendureOrderList, type VendureOrderListOptions, type VendureOrderSummary, type VendureRefundable, type VendureRefundableLine, VendureTimezoneConfigError, createVendureConnector, createVendureCustomer, createVendureOrders, createVendureProductReplication, createVendureVariantFeedReplication, getVendureCustomer, getVendureOrder, listVendureOrderDetails, listVendureOrders, searchVendureCustomers, toVendureCustomer, toVendureStoreOrder, updateVendureCustomer, vendureAuth, vendureAuthFieldSets, vendureConnector, vendureGlobalStockSettings, vendureLineRefundWithTax, vendureProductReplication, vendureProductSchema, vendureProductSync, vendureProductTraits, vendureRefundable, vendureSignIn, vendureStockReconcile, vendureStoreSettings };
397
+ export { type VendureCredentialKind, type VendureCredentials, type VendureCustomerListOptions, type VendureOrder, type VendureOrderList, type VendureOrderListOptions, type VendureOrderSummary, type VendureRefundable, type VendureRefundableLine, VendureTimezoneConfigError, createVendureConnector, createVendureCustomer, createVendureOrders, createVendureProductReplication, createVendureVariantFeedReplication, getVendureCustomer, getVendureOrder, listVendureCustomers, listVendureOrderDetails, listVendureOrders, searchVendureCustomers, toVendureCustomer, toVendureStoreOrder, updateVendureCustomer, vendureAuth, vendureAuthFieldSets, vendureConnector, vendureGlobalStockSettings, vendureLineRefundWithTax, vendureProductReplication, vendureProductSchema, vendureProductSync, vendureProductTraits, vendureRefundable, vendureSignIn, vendureStockReconcile, vendureStoreSettings };
package/dist/index.js CHANGED
@@ -143,9 +143,10 @@ var vendureAuth = {
143
143
  // src/schemas/products.ts
144
144
  var vendureProductSchema = {
145
145
  // 1: declares variant trackInventory/outOfStockThreshold/useGlobalOutOfStockThreshold/enabled
146
- // (backlog 28). 2: declares variant taxCategory { id } (#288). A bump drops and resyncs
146
+ // (backlog 28). 2: declares variant taxCategory { id } (#288). 3: declares optionGroups and
147
+ // variant options[].groupId (vendurepos gap 2.5). A bump drops and resyncs
147
148
  // (ConnectorSchemas, ADR-060 amendment 9).
148
- version: 2,
149
+ version: 3,
149
150
  primaryKey: "id",
150
151
  type: "object",
151
152
  properties: {
@@ -242,7 +243,8 @@ var vendureProductSchema = {
242
243
  properties: {
243
244
  id: { type: "string" },
244
245
  name: { type: "string" },
245
- code: { type: "string" }
246
+ code: { type: "string" },
247
+ groupId: { type: "string" }
246
248
  }
247
249
  }
248
250
  },
@@ -251,6 +253,28 @@ var vendureProductSchema = {
251
253
  }
252
254
  }
253
255
  },
256
+ optionGroups: {
257
+ type: "array",
258
+ items: {
259
+ type: "object",
260
+ properties: {
261
+ id: { type: "string" },
262
+ code: { type: "string" },
263
+ name: { type: "string" },
264
+ options: {
265
+ type: "array",
266
+ items: {
267
+ type: "object",
268
+ properties: {
269
+ id: { type: "string" },
270
+ code: { type: "string" },
271
+ name: { type: "string" }
272
+ }
273
+ }
274
+ }
275
+ }
276
+ }
277
+ },
254
278
  updatedAt: { type: "string", maxLength: 50 }
255
279
  },
256
280
  required: ["id"],
@@ -287,6 +311,16 @@ function variantStock(variant, stockLocationId, globalTrackInventory, globalOutO
287
311
  function liveVariants(doc) {
288
312
  return (doc.variants ?? []).filter((variant) => variant.enabled !== false);
289
313
  }
314
+ function variantOptions(doc, variant) {
315
+ const groups = doc.optionGroups ?? [];
316
+ if (!variant.options?.length || !groups.length) return void 0;
317
+ const options = {};
318
+ for (const option of variant.options) {
319
+ const group = groups.find((g) => String(g.id) === String(option.groupId));
320
+ if (group) options[group.name] = option.name;
321
+ }
322
+ return Object.keys(options).length ? options : void 0;
323
+ }
290
324
  function createVendureProductTraits(barcodeField, stockLocationId, pricesIncludeTax = false, globalTrackInventory = true, globalOutOfStockThreshold = 0) {
291
325
  const priceField = pricesIncludeTax ? "priceWithTax" : "price";
292
326
  const traits = {
@@ -303,11 +337,18 @@ function createVendureProductTraits(barcodeField, stockLocationId, pricesInclude
303
337
  getVariants: (doc, context) => liveVariants(doc).map((variant) => ({
304
338
  id: String(variant.id),
305
339
  title: variant.name || void 0,
340
+ options: variantOptions(doc, variant),
306
341
  sku: variant.sku || void 0,
307
342
  barcode: barcodeField ? variant.customFields?.[barcodeField] || void 0 : void 0,
308
343
  prices: traits.getPrices({ variants: [variant] }, context),
309
344
  stock: traits.getStock({ variants: [variant] })
310
345
  })),
346
+ // Every option of each group in the order the API returns them; core asks no filter by the live variants (as WooCommerce).
347
+ getVariantOptions: (doc) => (doc.optionGroups ?? []).map((g) => ({
348
+ id: String(g.id),
349
+ name: g.name,
350
+ values: (g.options ?? []).map((o) => o.name)
351
+ })),
311
352
  // The variant's tax category id: store-settings.ts keys taxRatesPpm by the same id. No variant id: the default
312
353
  // (first live) variant, as getPrices.
313
354
  getTaxClass: (doc, variantId) => {
@@ -387,6 +428,7 @@ var PRODUCT_DETAIL_QUERY = (barcodeField) => `
387
428
  assets { id preview }
388
429
  collections { id name slug }
389
430
  facetValues { id name code facet { id name } }
431
+ optionGroups { id code name options { id code name } }
390
432
  variants {
391
433
  id
392
434
  name
@@ -397,7 +439,7 @@ var PRODUCT_DETAIL_QUERY = (barcodeField) => `
397
439
  stockLevels { stockLocationId stockOnHand stockAllocated }
398
440
  trackInventory
399
441
  featuredAsset { id preview }
400
- options { id name code }
442
+ options { id name code groupId }
401
443
  ${barcodeField ? `customFields { ${barcodeField} }` : ""}
402
444
  }
403
445
  }
@@ -501,6 +543,7 @@ var PRODUCT_LIST_QUERY2 = (barcodeField) => `
501
543
  assets { id preview }
502
544
  collections { id name slug }
503
545
  facetValues { id name code facet { id name } }
546
+ optionGroups { id code name options { id code name } }
504
547
  variants {
505
548
  id
506
549
  name
@@ -514,7 +557,7 @@ var PRODUCT_LIST_QUERY2 = (barcodeField) => `
514
557
  useGlobalOutOfStockThreshold
515
558
  enabled
516
559
  featuredAsset { id preview }
517
- options { id name code }
560
+ options { id name code groupId }
518
561
  taxCategory { id }
519
562
  ${barcodeField ? `customFields { ${barcodeField} }` : ""}
520
563
  }
@@ -806,6 +849,7 @@ var PRICE_LIST_QUERY = `
806
849
  }
807
850
  `;
808
851
  var fingerprintOf = (entries) => [...entries].sort().join("|");
852
+ var priceEntry = (v) => `${v.id}:${v.currencyCode}:${v.price}:${v.priceWithTax}`;
809
853
  async function* fetchPages2(context) {
810
854
  const byProduct = /* @__PURE__ */ new Map();
811
855
  for (let skip = 0, total = 1; skip < total; skip += PAGE_SIZE3) {
@@ -818,15 +862,13 @@ async function* fetchPages2(context) {
818
862
  touched.add(productId);
819
863
  const entries = byProduct.get(productId) ?? [];
820
864
  byProduct.set(productId, entries);
821
- entries.push(`${variant.id}:${variant.currencyCode}:${variant.price}:${variant.priceWithTax}`);
865
+ entries.push(priceEntry(variant));
822
866
  }
823
867
  yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
824
868
  }
825
869
  }
826
870
  function fingerprint(doc) {
827
- const entries = (doc.variants ?? []).map(
828
- (v) => `${v.id}:${v.currencyCode}:${v.price}:${v.priceWithTax}`
829
- );
871
+ const entries = (doc.variants ?? []).map((v) => priceEntry(v));
830
872
  return fingerprintOf(entries);
831
873
  }
832
874
 
@@ -894,6 +936,14 @@ import {
894
936
  CustomerServiceError
895
937
  } from "@tallyui/core";
896
938
  var WALK_IN_EMAIL = "walk-in@vendurepos.local";
939
+ var LIST_QUERY = `query List($options: CustomerListOptions) {
940
+ customers(options: $options) {
941
+ totalItems
942
+ items { id firstName lastName emailAddress phoneNumber createdAt
943
+ addresses { fullName company streetLine1 streetLine2 city province postalCode country { code } phoneNumber defaultShippingAddress defaultBillingAddress }
944
+ }
945
+ }
946
+ }`;
897
947
  var SEARCH_QUERY = `query Search($q: String!, $take: Int!) {
898
948
  customers(options: {
899
949
  filter: { emailAddress: { contains: $q }, firstName: { contains: $q }, lastName: { contains: $q } },
@@ -942,6 +992,34 @@ function toVendureCustomer(raw) {
942
992
  customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(" ") || customer.email || customer.id;
943
993
  return customer;
944
994
  }
995
+ function toCustomerAddress(raw) {
996
+ return Object.fromEntries([
997
+ ["firstName", raw.fullName],
998
+ ["company", raw.company],
999
+ ["address1", raw.streetLine1],
1000
+ ["address2", raw.streetLine2],
1001
+ ["city", raw.city],
1002
+ ["state", raw.province],
1003
+ ["postcode", raw.postalCode],
1004
+ ["country", raw.country?.code],
1005
+ ["phone", raw.phoneNumber]
1006
+ ].filter(([, value]) => typeof value === "string" && value.length > 0));
1007
+ }
1008
+ async function listVendureCustomers(context, options) {
1009
+ const body = await customerGql(context, LIST_QUERY, { options: options ?? {} });
1010
+ const { items, totalItems } = body?.data?.customers ?? {};
1011
+ if (!Array.isArray(items) || typeof totalItems !== "number") throw new CustomerServiceError("server", "unexpected response");
1012
+ const customers = items.map((raw) => {
1013
+ const customer = toVendureCustomer(raw);
1014
+ if (typeof raw.createdAt === "string" && raw.createdAt.length > 0) customer.createdAt = raw.createdAt;
1015
+ for (const [kind, flag] of [["billing", "defaultBillingAddress"], ["shipping", "defaultShippingAddress"]]) {
1016
+ const address = raw.addresses?.find((entry) => entry[flag] === true);
1017
+ if (address) customer[kind] = toCustomerAddress(address);
1018
+ }
1019
+ return customer;
1020
+ });
1021
+ return { customers, total: totalItems };
1022
+ }
945
1023
  async function searchVendureCustomers(context, query2, options) {
946
1024
  const q = query2.trim();
947
1025
  if (!q) return [];
@@ -1059,16 +1137,16 @@ var ORDER_DETAIL_FIELDS = `${ORDER_DETAIL_FIELDS_START}${ORDER_DETAIL_FIELDS_END
1059
1137
  var TALLY_ORDER_DETAIL_FIELDS = `${ORDER_DETAIL_FIELDS_START}
1060
1138
  customFields { tallyCustomName tallyCustomSku tallyUnitPrice tallyPriceIncludesTax tallyClientLineId }
1061
1139
  ${ORDER_DETAIL_FIELDS_END} customFields { ${ORDER_CUSTOM_FIELDS} tallyPayments tallySnapshot tallyShipping }`;
1062
- var LIST_QUERY = `query Orders($options: OrderListOptions) {
1140
+ var LIST_QUERY2 = `query Orders($options: OrderListOptions) {
1063
1141
  orders(options: $options) { items { ${ORDER_ROW_FIELDS} } totalItems }
1064
1142
  }`;
1065
- var TALLY_LIST_QUERY = LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_ROW_FIELDS);
1143
+ var TALLY_LIST_QUERY = LIST_QUERY2.replace(ORDER_ROW_FIELDS, TALLY_ORDER_ROW_FIELDS);
1066
1144
  var CUSTOMER_LIST_QUERY = `query CustomerOrders($customerId: ID!, $options: OrderListOptions) {
1067
1145
  customer(id: $customerId) { orders(options: $options) { items { ${ORDER_ROW_FIELDS} } totalItems } }
1068
1146
  }`;
1069
1147
  var TALLY_CUSTOMER_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_ROW_FIELDS);
1070
- var DETAIL_LIST_QUERY = LIST_QUERY.replace(ORDER_ROW_FIELDS, ORDER_DETAIL_FIELDS);
1071
- var TALLY_DETAIL_LIST_QUERY = LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_DETAIL_FIELDS);
1148
+ var DETAIL_LIST_QUERY = LIST_QUERY2.replace(ORDER_ROW_FIELDS, ORDER_DETAIL_FIELDS);
1149
+ var TALLY_DETAIL_LIST_QUERY = LIST_QUERY2.replace(ORDER_ROW_FIELDS, TALLY_ORDER_DETAIL_FIELDS);
1072
1150
  var CUSTOMER_DETAIL_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, ORDER_DETAIL_FIELDS);
1073
1151
  var TALLY_CUSTOMER_DETAIL_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_DETAIL_FIELDS);
1074
1152
  var DETAIL_QUERY = `query Order($id: ID!) {
@@ -1078,7 +1156,7 @@ var TALLY_DETAIL_QUERY = `query Order($id: ID!) {
1078
1156
  order(id: $id) { ${TALLY_ORDER_DETAIL_FIELDS} }
1079
1157
  }`;
1080
1158
  async function listVendureOrders(context, options = {}) {
1081
- return listOrders(context, options, LIST_QUERY, TALLY_LIST_QUERY, CUSTOMER_LIST_QUERY, TALLY_CUSTOMER_LIST_QUERY);
1159
+ return listOrders(context, options, LIST_QUERY2, TALLY_LIST_QUERY, CUSTOMER_LIST_QUERY, TALLY_CUSTOMER_LIST_QUERY);
1082
1160
  }
1083
1161
  async function listVendureOrderDetails(context, options = {}) {
1084
1162
  return listOrders(context, options, DETAIL_LIST_QUERY, TALLY_DETAIL_LIST_QUERY, CUSTOMER_DETAIL_LIST_QUERY, TALLY_CUSTOMER_DETAIL_LIST_QUERY);
@@ -1203,7 +1281,7 @@ function createVendureOrders(options = {}) {
1203
1281
  const wanted = [...new Set(ids.filter((id) => id.length > 0))];
1204
1282
  const orders = [];
1205
1283
  for (const id of wanted) {
1206
- const order = await getVendureOrder(context, id, options.tallyFields === false ? { tallyFields: false } : void 0);
1284
+ const order = await getVendureOrder(context, id, tally);
1207
1285
  if (order === null) continue;
1208
1286
  if (order.orderPlacedAt === null) continue;
1209
1287
  orders.push(toVendureStoreOrder(order, pricesIncludeTax));
@@ -1334,6 +1412,7 @@ export {
1334
1412
  createVendureVariantFeedReplication,
1335
1413
  getVendureCustomer,
1336
1414
  getVendureOrder,
1415
+ listVendureCustomers,
1337
1416
  listVendureOrderDetails,
1338
1417
  listVendureOrders,
1339
1418
  searchVendureCustomers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/connector-vendure",
3
- "version": "3.20.1",
3
+ "version": "4.0.1",
4
4
  "type": "module",
5
5
  "description": "Vendure connector for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -27,16 +27,15 @@
27
27
  "directory": "connectors/vendure"
28
28
  },
29
29
  "peerDependencies": {
30
- "@tallyui/core": "^3.20.1"
30
+ "@tallyui/core": "^4.0.1"
31
31
  },
32
32
  "devDependencies": {
33
- "@tallyui/database": "3.20.1",
34
- "@tallyui/pos": "3.20.1",
33
+ "@tallyui/database": "4.0.1",
34
+ "@tallyui/pos": "4.0.1",
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/customers.ts CHANGED
@@ -1,11 +1,28 @@
1
1
  import {
2
- ConnectorUnauthorizedError, CustomerServiceError, type Customer, type CustomerAddress, type CustomerInput, type CustomerPatch, type SyncContext,
2
+ ConnectorUnauthorizedError, CustomerServiceError, type Customer, type CustomerAddress, type CustomerInput, type CustomerPage, type CustomerPatch, type SyncContext,
3
3
  } from '@tallyui/core';
4
4
  import { gql, VendureApiError } from './replication/products';
5
5
 
6
6
  // The vendurepos plugin's walk-in customer is never a person to attach to a sale.
7
7
  const WALK_IN_EMAIL = 'walk-in@vendurepos.local';
8
8
 
9
+ /** Vendure's `CustomerListOptions`, sent as given (Vendure applies its own defaults to what is left out). */
10
+ export interface VendureCustomerListOptions {
11
+ skip?: number; take?: number;
12
+ sort?: Record<string, 'ASC' | 'DESC'>;
13
+ filter?: Record<string, unknown>;
14
+ filterOperator?: 'AND' | 'OR';
15
+ }
16
+
17
+ const LIST_QUERY = `query List($options: CustomerListOptions) {
18
+ customers(options: $options) {
19
+ totalItems
20
+ items { id firstName lastName emailAddress phoneNumber createdAt
21
+ addresses { fullName company streetLine1 streetLine2 city province postalCode country { code } phoneNumber defaultShippingAddress defaultBillingAddress }
22
+ }
23
+ }
24
+ }`;
25
+
9
26
  const SEARCH_QUERY = `query Search($q: String!, $take: Int!) {
10
27
  customers(options: {
11
28
  filter: { emailAddress: { contains: $q }, firstName: { contains: $q }, lastName: { contains: $q } },
@@ -54,6 +71,38 @@ export function toVendureCustomer(raw: { id: string; firstName?: string | null;
54
71
  return customer;
55
72
  }
56
73
 
74
+ function toCustomerAddress(raw: Record<string, unknown> & { country?: { code?: unknown } | null }): CustomerAddress {
75
+ // Vendure keeps one fullName with no reliable split: put it whole in firstName so first plus last reads as entered.
76
+ return Object.fromEntries([
77
+ ['firstName', raw.fullName], ['company', raw.company], ['address1', raw.streetLine1],
78
+ ['address2', raw.streetLine2], ['city', raw.city], ['state', raw.province],
79
+ ['postcode', raw.postalCode], ['country', raw.country?.code], ['phone', raw.phoneNumber],
80
+ ].filter(([, value]) => typeof value === 'string' && value.length > 0));
81
+ }
82
+
83
+ /**
84
+ * One page of the store's customers, Vendure's list options passed through (paging, sort, filter), with the
85
+ * store's count of every match. Unlike search, it keeps the vendurepos walk-in customer: filter it out with
86
+ * `options.filter` if the caller does not want it. Each customer carries `createdAt` and, from the address book,
87
+ * `billing` / `shipping` (the addresses flagged `defaultBillingAddress` / `defaultShippingAddress`).
88
+ * Credentials and missing permissions reject with `ConnectorUnauthorizedError` (401 / 403, via the session probe).
89
+ */
90
+ export async function listVendureCustomers(context: SyncContext, options?: VendureCustomerListOptions): Promise<CustomerPage> {
91
+ const body = await customerGql(context, LIST_QUERY, { options: options ?? {} });
92
+ const { items, totalItems } = body?.data?.customers ?? {};
93
+ if (!Array.isArray(items) || typeof totalItems !== 'number') throw new CustomerServiceError('server', 'unexpected response');
94
+ const customers = items.map((raw) => {
95
+ const customer = toVendureCustomer(raw);
96
+ if (typeof raw.createdAt === 'string' && raw.createdAt.length > 0) customer.createdAt = raw.createdAt;
97
+ for (const [kind, flag] of [['billing', 'defaultBillingAddress'], ['shipping', 'defaultShippingAddress']] as const) {
98
+ const address = raw.addresses?.find((entry: VendureAddressRef) => entry[flag] === true);
99
+ if (address) customer[kind] = toCustomerAddress(address);
100
+ }
101
+ return customer;
102
+ });
103
+ return { customers, total: totalItems };
104
+ }
105
+
57
106
  export async function searchVendureCustomers(context: SyncContext, query: string, options?: { limit?: number }): Promise<Customer[]> {
58
107
  const q = query.trim();
59
108
  if (!q) return [];
package/src/index.ts CHANGED
@@ -120,7 +120,7 @@ export { createVendureVariantFeedReplication } from './replication/variant-feed'
120
120
  export { vendureStockReconcile } from './reconcile/stock';
121
121
  export { vendureStoreSettings } from './store-settings';
122
122
  export { vendureGlobalStockSettings } from './global-settings';
123
- export { searchVendureCustomers, createVendureCustomer, getVendureCustomer, updateVendureCustomer, toVendureCustomer } from './customers';
123
+ export { searchVendureCustomers, createVendureCustomer, getVendureCustomer, updateVendureCustomer, toVendureCustomer, listVendureCustomers, type VendureCustomerListOptions } from './customers';
124
124
  export { listVendureOrders, getVendureOrder, listVendureOrderDetails, type VendureOrderListOptions, type VendureOrderList, type VendureOrderSummary, type VendureOrder } from './orders';
125
125
  export { createVendureOrders, toVendureStoreOrder } from './store-orders';
126
126
  export { vendureRefundable, vendureLineRefundWithTax, type VendureRefundableLine, type VendureRefundable } from './refunds';
@@ -19,6 +19,10 @@ const PRICE_LIST_QUERY = `
19
19
  /** `${variantId}:${currencyCode}:${price}:${priceWithTax}` entries, sorted and joined. */
20
20
  const fingerprintOf = (entries: string[]): string => [...entries].sort().join('|');
21
21
 
22
+ /** One variant's fingerprint entry; the server pages and the local document must build it the same way. */
23
+ const priceEntry = (v: { id: unknown; currencyCode: unknown; price: unknown; priceWithTax: unknown }): string =>
24
+ `${v.id}:${v.currencyCode}:${v.price}:${v.priceWithTax}`;
25
+
22
26
  /**
23
27
  * Every product's price fingerprint, one `productVariants` page at a time
24
28
  * (ADR-060's nightly backstop). The listing is not grouped by product, so a
@@ -43,7 +47,7 @@ export async function* fetchPages(context: SyncContext): AsyncIterable<Map<strin
43
47
  touched.add(productId);
44
48
  const entries = byProduct.get(productId) ?? [];
45
49
  byProduct.set(productId, entries);
46
- entries.push(`${variant.id}:${variant.currencyCode}:${variant.price}:${variant.priceWithTax}`);
50
+ entries.push(priceEntry(variant));
47
51
  }
48
52
  yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
49
53
  }
@@ -51,8 +55,6 @@ export async function* fetchPages(context: SyncContext): AsyncIterable<Map<strin
51
55
 
52
56
  /** The same fingerprint, computed from a local product document's variants. Replicated Vendure documents already carry `price`, `priceWithTax` and `currencyCode`. */
53
57
  export function fingerprint(doc: any): string {
54
- const entries: string[] = (doc.variants ?? []).map(
55
- (v: any) => `${v.id}:${v.currencyCode}:${v.price}:${v.priceWithTax}`,
56
- );
58
+ const entries: string[] = (doc.variants ?? []).map((v: any) => priceEntry(v));
57
59
  return fingerprintOf(entries);
58
60
  }
@@ -26,6 +26,7 @@ export const PRODUCT_LIST_QUERY = (barcodeField?: string) => `
26
26
  assets { id preview }
27
27
  collections { id name slug }
28
28
  facetValues { id name code facet { id name } }
29
+ optionGroups { id code name options { id code name } }
29
30
  variants {
30
31
  id
31
32
  name
@@ -39,7 +40,7 @@ export const PRODUCT_LIST_QUERY = (barcodeField?: string) => `
39
40
  useGlobalOutOfStockThreshold
40
41
  enabled
41
42
  featuredAsset { id preview }
42
- options { id name code }
43
+ options { id name code groupId }
43
44
  taxCategory { id }
44
45
  ${barcodeField ? `customFields { ${barcodeField} }` : ''}
45
46
  }
@@ -13,9 +13,10 @@ import type { RxJsonSchema } from 'rxdb';
13
13
  */
14
14
  export const vendureProductSchema: RxJsonSchema<any> = {
15
15
  // 1: declares variant trackInventory/outOfStockThreshold/useGlobalOutOfStockThreshold/enabled
16
- // (backlog 28). 2: declares variant taxCategory { id } (#288). A bump drops and resyncs
16
+ // (backlog 28). 2: declares variant taxCategory { id } (#288). 3: declares optionGroups and
17
+ // variant options[].groupId (vendurepos gap 2.5). A bump drops and resyncs
17
18
  // (ConnectorSchemas, ADR-060 amendment 9).
18
- version: 2,
19
+ version: 3,
19
20
  primaryKey: 'id',
20
21
  type: 'object',
21
22
  properties: {
@@ -113,6 +114,7 @@ export const vendureProductSchema: RxJsonSchema<any> = {
113
114
  id: { type: 'string' },
114
115
  name: { type: 'string' },
115
116
  code: { type: 'string' },
117
+ groupId: { type: 'string' },
116
118
  },
117
119
  },
118
120
  },
@@ -121,6 +123,28 @@ export const vendureProductSchema: RxJsonSchema<any> = {
121
123
  },
122
124
  },
123
125
  },
126
+ optionGroups: {
127
+ type: 'array',
128
+ items: {
129
+ type: 'object',
130
+ properties: {
131
+ id: { type: 'string' },
132
+ code: { type: 'string' },
133
+ name: { type: 'string' },
134
+ options: {
135
+ type: 'array',
136
+ items: {
137
+ type: 'object',
138
+ properties: {
139
+ id: { type: 'string' },
140
+ code: { type: 'string' },
141
+ name: { type: 'string' },
142
+ },
143
+ },
144
+ },
145
+ },
146
+ },
147
+ },
124
148
  updatedAt: { type: 'string', maxLength: 50 },
125
149
  },
126
150
  required: ['id'],
@@ -83,7 +83,7 @@ export function createVendureOrders(options: { pricesIncludeTax?: boolean; tally
83
83
  const wanted = [...new Set(ids.filter((id) => id.length > 0))];
84
84
  const orders: StoreOrder[] = [];
85
85
  for (const id of wanted) {
86
- const order = await getVendureOrder(context, id, options.tallyFields === false ? { tallyFields: false } : undefined);
86
+ const order = await getVendureOrder(context, id, tally);
87
87
  if (order === null) continue;
88
88
  // Never placed: a cart, not order history.
89
89
  if (order.orderPlacedAt === null) continue;
@@ -22,7 +22,7 @@ type ActiveChannel = { defaultCurrencyCode: string; pricesIncludeTax: boolean; d
22
22
  type TaxCategory = { id: string; isDefault: boolean };
23
23
  type TaxRateItem = { name?: string; enabled: boolean; value: number; category: { id: string } | null; customerGroup: { id: string } | null };
24
24
 
25
- /** `gql` throws a plain `Error` for a non-OK response or a GraphQL `errors` body; both become `StoreSettingsError('failed')` here. */
25
+ /** `gql` throws `ConnectorUnauthorizedError` for a 401 or 403 and `VendureApiError` for another non-OK response or a GraphQL `errors` body; each becomes `StoreSettingsError('failed')` here. */
26
26
  async function query(context: SyncContext, source: string, variables?: Record<string, unknown>): Promise<any> {
27
27
  try {
28
28
  return await gql(context, source, variables);
@@ -31,6 +31,7 @@ const PRODUCT_DETAIL_QUERY = (barcodeField?: string) => `
31
31
  assets { id preview }
32
32
  collections { id name slug }
33
33
  facetValues { id name code facet { id name } }
34
+ optionGroups { id code name options { id code name } }
34
35
  variants {
35
36
  id
36
37
  name
@@ -41,7 +42,7 @@ const PRODUCT_DETAIL_QUERY = (barcodeField?: string) => `
41
42
  stockLevels { stockLocationId stockOnHand stockAllocated }
42
43
  trackInventory
43
44
  featuredAsset { id preview }
44
- options { id name code }
45
+ options { id name code groupId }
45
46
  ${barcodeField ? `customFields { ${barcodeField} }` : ''}
46
47
  }
47
48
  }
@@ -64,6 +64,21 @@ function liveVariants(doc: any): any[] {
64
64
  return (doc.variants ?? []).filter((variant: any) => variant.enabled !== false);
65
65
  }
66
66
 
67
+ // A variant's option values keyed by group name (vendurepos gap 2.5): `groupId` finds the group in the
68
+ // product's `optionGroups`; an option whose group is not there is left out. Undefined with no options, no groups, or no option in a group.
69
+ type VendureOption = { id?: string; code?: string; name: string; groupId?: string };
70
+ type VendureOptionGroup = { id: string; code?: string; name: string; options?: VendureOption[] };
71
+ function variantOptions(doc: { optionGroups?: VendureOptionGroup[] }, variant: { options?: VendureOption[] }): Record<string, string> | undefined {
72
+ const groups = doc.optionGroups ?? [];
73
+ if (!variant.options?.length || !groups.length) return undefined;
74
+ const options: Record<string, string> = {};
75
+ for (const option of variant.options) {
76
+ const group = groups.find((g) => String(g.id) === String(option.groupId));
77
+ if (group) options[group.name] = option.name;
78
+ }
79
+ return Object.keys(options).length ? options : undefined;
80
+ }
81
+
67
82
  /**
68
83
  * Vendure product trait implementations.
69
84
  *
@@ -104,12 +119,18 @@ const traits: ProductTraits = {
104
119
  getVariants: (doc, context) => liveVariants(doc).map((variant: any) => ({
105
120
  id: String(variant.id),
106
121
  title: variant.name || undefined,
122
+ options: variantOptions(doc, variant),
107
123
  sku: variant.sku || undefined,
108
124
  barcode: barcodeField ? variant.customFields?.[barcodeField] || undefined : undefined,
109
125
  prices: traits.getPrices({ variants: [variant] }, context),
110
126
  stock: traits.getStock({ variants: [variant] }),
111
127
  })),
112
128
 
129
+ // Every option of each group in the order the API returns them; core asks no filter by the live variants (as WooCommerce).
130
+ getVariantOptions: (doc) => ((doc.optionGroups ?? []) as VendureOptionGroup[]).map((g) => ({
131
+ id: String(g.id), name: g.name, values: (g.options ?? []).map((o) => o.name),
132
+ })),
133
+
113
134
  // The variant's tax category id: store-settings.ts keys taxRatesPpm by the same id. No variant id: the default
114
135
  // (first live) variant, as getPrices.
115
136
  getTaxClass: (doc, variantId) => {