@tallyui/connector-vendure 3.11.0 → 3.13.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 +25 -2
- package/dist/index.js +201 -19
- package/package.json +4 -4
- package/src/__tests__/fixtures/customers/4a-updateCustomer-success.json +23 -0
- package/src/__tests__/fixtures/customers/4b-updateCustomer-duplicate-email.json +20 -0
- package/src/customers.ts +81 -3
- package/src/index.ts +12 -4
- package/src/orders.ts +23 -5
- package/src/replication/products.ts +7 -2
- package/src/store-orders.ts +95 -0
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ConnectorAuth, AuthField, ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, TallyConnector } from '@tallyui/core';
|
|
1
|
+
import { ConnectorAuth, AuthField, ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, CustomerPatch, TallyConnector, StoreOrder } from '@tallyui/core';
|
|
2
2
|
export { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
3
3
|
import { RxJsonSchema } from 'rxdb';
|
|
4
4
|
|
|
@@ -126,6 +126,13 @@ declare function searchVendureCustomers(context: SyncContext, query: string, opt
|
|
|
126
126
|
limit?: number;
|
|
127
127
|
}): Promise<Customer[]>;
|
|
128
128
|
declare function createVendureCustomer(context: SyncContext, input: CustomerInput): Promise<Customer>;
|
|
129
|
+
/**
|
|
130
|
+
* Edits the customer through Vendure's own mutations: `updateCustomer` for its fields, then the address book, where
|
|
131
|
+
* billing and shipping are the addresses flagged `defaultBillingAddress` / `defaultShippingAddress`. A default shared by
|
|
132
|
+
* both kinds is never rewritten for one kind: that kind gets a new default address instead. Vendure stores no customer
|
|
133
|
+
* company or tax ids and no address email, so those are dropped, as `createVendureCustomer` drops them.
|
|
134
|
+
*/
|
|
135
|
+
declare function updateVendureCustomer(context: SyncContext, id: string, patch: CustomerPatch): Promise<Customer>;
|
|
129
136
|
declare function getVendureCustomer(context: SyncContext, id: string): Promise<Customer | null>;
|
|
130
137
|
|
|
131
138
|
interface VendureOrderListOptions {
|
|
@@ -194,6 +201,8 @@ interface VendureOrder extends VendureOrderSummary {
|
|
|
194
201
|
proratedUnitPrice: number;
|
|
195
202
|
/** Vendure's per-unit refund value, rounded per unit: for display, never multiplied by a quantity for `order.refund`'s `totalMinor` (ADR-080 amendment 2). */
|
|
196
203
|
proratedUnitPriceWithTax: number;
|
|
204
|
+
/** The line's total without tax after order-level discounts. */
|
|
205
|
+
proratedLinePrice: number;
|
|
197
206
|
/** The line's total with tax after order-level discounts; a refund's line amount is its share of this (vendurepos ADR 0007, decision 4.9). */
|
|
198
207
|
proratedLinePriceWithTax: number;
|
|
199
208
|
taxRate: number;
|
|
@@ -227,6 +236,8 @@ interface VendureOrder extends VendureOrderSummary {
|
|
|
227
236
|
};
|
|
228
237
|
price: number;
|
|
229
238
|
priceWithTax: number;
|
|
239
|
+
discountedPrice: number;
|
|
240
|
+
discountedPriceWithTax: number;
|
|
230
241
|
}[];
|
|
231
242
|
surcharges: {
|
|
232
243
|
description: string;
|
|
@@ -286,10 +297,20 @@ interface VendureOrder extends VendureOrderSummary {
|
|
|
286
297
|
};
|
|
287
298
|
}
|
|
288
299
|
declare function listVendureOrders(context: SyncContext, options?: VendureOrderListOptions): Promise<VendureOrderList<VendureOrderSummary>>;
|
|
300
|
+
/** As listVendureOrders, with each row's full detail (the getVendureOrder fields): one request per page. */
|
|
301
|
+
declare function listVendureOrderDetails(context: SyncContext, options?: VendureOrderListOptions): Promise<VendureOrderList<VendureOrder>>;
|
|
289
302
|
declare function getVendureOrder(context: SyncContext, id: string, options?: {
|
|
290
303
|
tallyFields?: boolean;
|
|
291
304
|
}): Promise<VendureOrder | null>;
|
|
292
305
|
|
|
306
|
+
/** Maps a Vendure Admin API order (getVendureOrder's fields) to a `StoreOrder` (ADR-081). */
|
|
307
|
+
declare function toVendureStoreOrder(order: VendureOrder, pricesIncludeTax: boolean): StoreOrder;
|
|
308
|
+
/** Vendure order history (ADR-081), read-only through the Admin API; needs the ReadOrder permission. */
|
|
309
|
+
declare function createVendureOrders(options?: {
|
|
310
|
+
pricesIncludeTax?: boolean;
|
|
311
|
+
tallyFields?: boolean;
|
|
312
|
+
}): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>>;
|
|
313
|
+
|
|
293
314
|
interface VendureRefundableLine {
|
|
294
315
|
orderLineId: string;
|
|
295
316
|
quantity: number;
|
|
@@ -340,6 +361,7 @@ declare function vendureLineRefundWithTax(line: VendureRefundableLine, quantity:
|
|
|
340
361
|
* and `globalOutOfStockThreshold` are the channel's stock defaults; read them
|
|
341
362
|
* with `vendureGlobalStockSettings` after sign-in, like `pricesIncludeTax`
|
|
342
363
|
* from `storeSettings`.
|
|
364
|
+
* `tallyFields: false` is for a server without the vendurepos plugin: order history then reads no till ids.
|
|
343
365
|
*/
|
|
344
366
|
declare const createVendureConnector: (options?: {
|
|
345
367
|
barcodeField?: string;
|
|
@@ -348,6 +370,7 @@ declare const createVendureConnector: (options?: {
|
|
|
348
370
|
updatedAtSkewMs?: number;
|
|
349
371
|
globalTrackInventory?: boolean;
|
|
350
372
|
globalOutOfStockThreshold?: number;
|
|
373
|
+
tallyFields?: boolean;
|
|
351
374
|
}) => TallyConnector;
|
|
352
375
|
/**
|
|
353
376
|
* @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
|
|
@@ -355,4 +378,4 @@ declare const createVendureConnector: (options?: {
|
|
|
355
378
|
*/
|
|
356
379
|
declare const vendureConnector: TallyConnector;
|
|
357
380
|
|
|
358
|
-
export { type VendureCredentialKind, type VendureCredentials, type VendureOrder, type VendureOrderList, type VendureOrderListOptions, type VendureOrderSummary, type VendureRefundable, type VendureRefundableLine, VendureTimezoneConfigError, createVendureConnector, createVendureCustomer, createVendureProductReplication, createVendureVariantFeedReplication, getVendureCustomer, getVendureOrder, listVendureOrders, searchVendureCustomers, toVendureCustomer, vendureAuth, vendureAuthFieldSets, vendureConnector, vendureGlobalStockSettings, vendureLineRefundWithTax, vendureProductReplication, vendureProductSchema, vendureProductSync, vendureProductTraits, vendureRefundable, vendureSignIn, vendureStockReconcile, vendureStoreSettings };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -531,6 +531,12 @@ var PRODUCT_MARK_QUERY = `
|
|
|
531
531
|
}
|
|
532
532
|
}
|
|
533
533
|
`;
|
|
534
|
+
var VendureApiError = class extends Error {
|
|
535
|
+
constructor(message, status) {
|
|
536
|
+
super(message);
|
|
537
|
+
this.status = status;
|
|
538
|
+
}
|
|
539
|
+
};
|
|
534
540
|
async function gql2(context, query2, variables) {
|
|
535
541
|
const res = await fetch(`${context.baseUrl}/admin-api`, {
|
|
536
542
|
method: "POST",
|
|
@@ -545,12 +551,12 @@ async function gql2(context, query2, variables) {
|
|
|
545
551
|
const body2 = await res.json().catch(() => void 0);
|
|
546
552
|
const message = body2?.errors?.[0]?.message;
|
|
547
553
|
if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorizedError4(`Vendure API error: ${res.status}${message ? `: ${message}` : ""}`, res.status);
|
|
548
|
-
throw new
|
|
554
|
+
throw new VendureApiError(`Vendure API error: ${res.status}${message ? `: ${message}` : ""}`, res.status);
|
|
549
555
|
}
|
|
550
556
|
const body = await res.json();
|
|
551
557
|
const forbidden = body.errors?.filter((error) => error.extensions?.code === "FORBIDDEN") ?? [];
|
|
552
558
|
if (forbidden.length) throw await forbiddenError(context, forbidden);
|
|
553
|
-
if (body.errors?.length) throw new
|
|
559
|
+
if (body.errors?.length) throw new VendureApiError(`Vendure GraphQL error: ${body.errors[0].message}`, res.status);
|
|
554
560
|
return body;
|
|
555
561
|
}
|
|
556
562
|
var TIMEZONE_MESSAGE = "Vendure updatedAt filters miss changes: run Vendure with TZ=UTC or set updatedAtSkewMs to at least the magnitude of the server UTC offset in milliseconds.";
|
|
@@ -883,7 +889,10 @@ var vendureStoreSettings = async (context, _choice) => {
|
|
|
883
889
|
};
|
|
884
890
|
|
|
885
891
|
// src/customers.ts
|
|
886
|
-
import {
|
|
892
|
+
import {
|
|
893
|
+
ConnectorUnauthorizedError as ConnectorUnauthorizedError5,
|
|
894
|
+
CustomerServiceError
|
|
895
|
+
} from "@tallyui/core";
|
|
887
896
|
var WALK_IN_EMAIL = "walk-in@vendurepos.local";
|
|
888
897
|
var SEARCH_QUERY = `query Search($q: String!, $take: Int!) {
|
|
889
898
|
customers(options: {
|
|
@@ -904,6 +913,22 @@ var CREATE_QUERY = `mutation Create($input: CreateCustomerInput!) {
|
|
|
904
913
|
var GET_QUERY = `query One($id: ID!) {
|
|
905
914
|
customer(id: $id) { id firstName lastName emailAddress phoneNumber }
|
|
906
915
|
}`;
|
|
916
|
+
var UPDATE_QUERY = `mutation Update($input: UpdateCustomerInput!) {
|
|
917
|
+
updateCustomer(input: $input) {
|
|
918
|
+
__typename
|
|
919
|
+
... on Customer { id firstName lastName emailAddress phoneNumber }
|
|
920
|
+
... on ErrorResult { errorCode message }
|
|
921
|
+
}
|
|
922
|
+
}`;
|
|
923
|
+
var ADDRESSES_QUERY = `query Addresses($id: ID!) {
|
|
924
|
+
customer(id: $id) { id firstName lastName emailAddress phoneNumber addresses { id defaultShippingAddress defaultBillingAddress } }
|
|
925
|
+
}`;
|
|
926
|
+
var CREATE_ADDRESS_QUERY = `mutation CreateAddress($customerId: ID!, $input: CreateAddressInput!) {
|
|
927
|
+
createCustomerAddress(customerId: $customerId, input: $input) { id }
|
|
928
|
+
}`;
|
|
929
|
+
var UPDATE_ADDRESS_QUERY = `mutation UpdateAddress($input: UpdateAddressInput!) {
|
|
930
|
+
updateCustomerAddress(input: $input) { id }
|
|
931
|
+
}`;
|
|
907
932
|
function toVendureCustomer(raw) {
|
|
908
933
|
const customer = { id: raw.id, name: raw.id };
|
|
909
934
|
for (const [key, value] of [
|
|
@@ -939,12 +964,62 @@ async function createVendureCustomer(context, input) {
|
|
|
939
964
|
if (result?.__typename && result.message) throw new CustomerServiceError("invalid", result.message);
|
|
940
965
|
throw new CustomerServiceError("server", "unexpected response");
|
|
941
966
|
}
|
|
967
|
+
var SCALARS = [["firstName", "firstName"], ["lastName", "lastName"], ["email", "emailAddress"], ["phone", "phoneNumber"]];
|
|
968
|
+
var GRAPHQL_STATUS = { status: 200 };
|
|
969
|
+
function toVendureAddressInput(address) {
|
|
970
|
+
return {
|
|
971
|
+
fullName: [address.firstName, address.lastName].filter(Boolean).join(" "),
|
|
972
|
+
company: address.company ?? "",
|
|
973
|
+
streetLine1: address.address1 ?? "",
|
|
974
|
+
streetLine2: address.address2 ?? "",
|
|
975
|
+
city: address.city ?? "",
|
|
976
|
+
province: address.state ?? "",
|
|
977
|
+
postalCode: address.postcode ?? "",
|
|
978
|
+
countryCode: address.country ?? "",
|
|
979
|
+
phoneNumber: address.phone ?? ""
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
async function updateVendureCustomer(context, id, patch) {
|
|
983
|
+
const kinds = [["billing", "defaultBillingAddress", "defaultShippingAddress"], ["shipping", "defaultShippingAddress", "defaultBillingAddress"]].filter(([kind]) => patch[kind] !== void 0);
|
|
984
|
+
if (kinds.some(([kind]) => !patch[kind]?.address1 || !patch[kind]?.country)) {
|
|
985
|
+
throw new CustomerServiceError("invalid", "Vendure addresses need address1 and country");
|
|
986
|
+
}
|
|
987
|
+
const current = (await customerGql(context, ADDRESSES_QUERY, { id }))?.data?.customer;
|
|
988
|
+
if (current === null) throw new CustomerServiceError("invalid", "unknown customer", GRAPHQL_STATUS);
|
|
989
|
+
if (typeof current?.id !== "string") throw new CustomerServiceError("server", "unexpected response");
|
|
990
|
+
let saved = current;
|
|
991
|
+
const fields = SCALARS.filter(([key]) => patch[key] !== void 0);
|
|
992
|
+
if (fields.length) {
|
|
993
|
+
const input = Object.fromEntries([["id", id], ...fields.map(([key, field]) => [field, patch[key]])]);
|
|
994
|
+
const result = (await customerGql(context, UPDATE_QUERY, { input }))?.data?.updateCustomer;
|
|
995
|
+
if (result?.__typename !== "Customer") {
|
|
996
|
+
if (result?.__typename && result.message) throw new CustomerServiceError("invalid", result.message, GRAPHQL_STATUS);
|
|
997
|
+
throw new CustomerServiceError("server", "unexpected response");
|
|
998
|
+
}
|
|
999
|
+
saved = result;
|
|
1000
|
+
}
|
|
1001
|
+
const addresses = Array.isArray(current.addresses) ? current.addresses : [];
|
|
1002
|
+
for (const [kind, flag, other] of kinds) {
|
|
1003
|
+
const address = toVendureAddressInput(patch[kind]);
|
|
1004
|
+
const existing = addresses.find((entry) => entry[flag]);
|
|
1005
|
+
if (existing && !existing[other]) {
|
|
1006
|
+
await customerGql(context, UPDATE_ADDRESS_QUERY, { input: { id: existing.id, ...address } });
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
await customerGql(context, CREATE_ADDRESS_QUERY, { customerId: id, input: { ...address, [flag]: true } });
|
|
1010
|
+
if (existing) {
|
|
1011
|
+
await customerGql(context, UPDATE_ADDRESS_QUERY, { input: { id: existing.id, [flag]: false } });
|
|
1012
|
+
existing[flag] = false;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
return toVendureCustomer(saved);
|
|
1016
|
+
}
|
|
942
1017
|
async function customerGql(context, query2, variables) {
|
|
943
1018
|
try {
|
|
944
1019
|
return await gql2(context, query2, variables);
|
|
945
1020
|
} catch (error) {
|
|
946
1021
|
if (error instanceof ConnectorUnauthorizedError5) throw error;
|
|
947
|
-
throw new CustomerServiceError(error instanceof Error && error.message.startsWith("Vendure ") ? "server" : "network", error instanceof Error ? error.message : String(error));
|
|
1022
|
+
throw new CustomerServiceError(error instanceof Error && error.message.startsWith("Vendure ") ? "server" : "network", error instanceof Error ? error.message : String(error), { status: error instanceof VendureApiError ? error.status : void 0 });
|
|
948
1023
|
}
|
|
949
1024
|
}
|
|
950
1025
|
async function getVendureCustomer(context, id) {
|
|
@@ -955,17 +1030,6 @@ async function getVendureCustomer(context, id) {
|
|
|
955
1030
|
return toVendureCustomer(raw);
|
|
956
1031
|
}
|
|
957
1032
|
|
|
958
|
-
// src/global-settings.ts
|
|
959
|
-
var GLOBAL_SETTINGS_QUERY = `
|
|
960
|
-
query GlobalStockSettings {
|
|
961
|
-
globalSettings { trackInventory outOfStockThreshold }
|
|
962
|
-
}
|
|
963
|
-
`;
|
|
964
|
-
async function vendureGlobalStockSettings(context) {
|
|
965
|
-
const res = await gql2(context, GLOBAL_SETTINGS_QUERY);
|
|
966
|
-
return res.data.globalSettings;
|
|
967
|
-
}
|
|
968
|
-
|
|
969
1033
|
// src/orders.ts
|
|
970
1034
|
var ORDER_ROW_FIELDS = `
|
|
971
1035
|
id code state orderPlacedAt updatedAt currencyCode totalQuantity total totalWithTax
|
|
@@ -978,11 +1042,11 @@ var ORDER_DETAIL_FIELDS_START = `
|
|
|
978
1042
|
customer { id firstName lastName emailAddress }
|
|
979
1043
|
lines {`;
|
|
980
1044
|
var ORDER_DETAIL_FIELDS_END = `
|
|
981
|
-
id quantity orderPlacedQuantity proratedUnitPrice proratedUnitPriceWithTax proratedLinePriceWithTax taxRate productVariant { id name sku }
|
|
1045
|
+
id quantity orderPlacedQuantity proratedUnitPrice proratedUnitPriceWithTax proratedLinePriceWithTax proratedLinePrice taxRate productVariant { id name sku }
|
|
982
1046
|
unitPrice unitPriceWithTax linePrice linePriceWithTax discountedLinePrice discountedLinePriceWithTax
|
|
983
1047
|
discounts { description amount amountWithTax }
|
|
984
1048
|
}
|
|
985
|
-
shippingLines { shippingMethod { name } price priceWithTax }
|
|
1049
|
+
shippingLines { shippingMethod { name } price priceWithTax discountedPrice discountedPriceWithTax }
|
|
986
1050
|
surcharges { description sku price priceWithTax }
|
|
987
1051
|
subTotal subTotalWithTax shipping shippingWithTax total totalWithTax
|
|
988
1052
|
taxSummary { description taxRate taxBase taxTotal }
|
|
@@ -1003,6 +1067,10 @@ var CUSTOMER_LIST_QUERY = `query CustomerOrders($customerId: ID!, $options: Orde
|
|
|
1003
1067
|
customer(id: $customerId) { orders(options: $options) { items { ${ORDER_ROW_FIELDS} } totalItems } }
|
|
1004
1068
|
}`;
|
|
1005
1069
|
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);
|
|
1072
|
+
var CUSTOMER_DETAIL_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, ORDER_DETAIL_FIELDS);
|
|
1073
|
+
var TALLY_CUSTOMER_DETAIL_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_DETAIL_FIELDS);
|
|
1006
1074
|
var DETAIL_QUERY = `query Order($id: ID!) {
|
|
1007
1075
|
order(id: $id) { ${ORDER_DETAIL_FIELDS} }
|
|
1008
1076
|
}`;
|
|
@@ -1010,6 +1078,12 @@ var TALLY_DETAIL_QUERY = `query Order($id: ID!) {
|
|
|
1010
1078
|
order(id: $id) { ${TALLY_ORDER_DETAIL_FIELDS} }
|
|
1011
1079
|
}`;
|
|
1012
1080
|
async function listVendureOrders(context, options = {}) {
|
|
1081
|
+
return listOrders(context, options, LIST_QUERY, TALLY_LIST_QUERY, CUSTOMER_LIST_QUERY, TALLY_CUSTOMER_LIST_QUERY);
|
|
1082
|
+
}
|
|
1083
|
+
async function listVendureOrderDetails(context, options = {}) {
|
|
1084
|
+
return listOrders(context, options, DETAIL_LIST_QUERY, TALLY_DETAIL_LIST_QUERY, CUSTOMER_DETAIL_LIST_QUERY, TALLY_CUSTOMER_DETAIL_LIST_QUERY);
|
|
1085
|
+
}
|
|
1086
|
+
async function listOrders(context, options, listQuery, tallyListQuery, customerListQuery, tallyCustomerListQuery) {
|
|
1013
1087
|
const skip = Math.max(0, Math.trunc(Number.isFinite(options.skip) ? options.skip : 0));
|
|
1014
1088
|
const take = Math.max(1, Math.min(100, Math.trunc(Number.isFinite(options.take) ? options.take : 25)));
|
|
1015
1089
|
const date = options.orderPlacedAt;
|
|
@@ -1030,7 +1104,7 @@ async function listVendureOrders(context, options = {}) {
|
|
|
1030
1104
|
options: { skip, take, sort: { orderPlacedAt: "DESC", id: "DESC" }, filter },
|
|
1031
1105
|
...options.customerId ? { customerId: options.customerId } : {}
|
|
1032
1106
|
};
|
|
1033
|
-
const query2 = options.customerId ? options.tallyFields === false ?
|
|
1107
|
+
const query2 = options.customerId ? options.tallyFields === false ? customerListQuery : tallyCustomerListQuery : options.tallyFields === false ? listQuery : tallyListQuery;
|
|
1034
1108
|
const body = await gql2(context, query2, variables);
|
|
1035
1109
|
if (options.customerId && body?.data?.customer === null) return { items: [], totalItems: 0 };
|
|
1036
1110
|
const result = options.customerId ? body?.data?.customer?.orders : body?.data?.orders;
|
|
@@ -1049,6 +1123,107 @@ async function getVendureOrder(context, id, options) {
|
|
|
1049
1123
|
return order;
|
|
1050
1124
|
}
|
|
1051
1125
|
|
|
1126
|
+
// src/store-orders.ts
|
|
1127
|
+
var nonEmpty = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1128
|
+
var UNPAID_PAYMENT_STATES = ["Declined", "Error", "Cancelled"];
|
|
1129
|
+
function toVendureStoreOrder(order, pricesIncludeTax) {
|
|
1130
|
+
if (typeof order.orderPlacedAt !== "string" || Number.isNaN(new Date(order.orderPlacedAt).getTime())) {
|
|
1131
|
+
throw new Error("Vendure sent an unexpected order response");
|
|
1132
|
+
}
|
|
1133
|
+
const clientOrderId = nonEmpty(order.customFields?.tallyClientOrderId);
|
|
1134
|
+
const name = order.customer ? `${order.customer.firstName} ${order.customer.lastName}`.trim() : "";
|
|
1135
|
+
const email = nonEmpty(order.customer?.emailAddress);
|
|
1136
|
+
return {
|
|
1137
|
+
id: order.id,
|
|
1138
|
+
reference: order.code,
|
|
1139
|
+
...clientOrderId ? { clientOrderId } : {},
|
|
1140
|
+
status: order.state,
|
|
1141
|
+
placedAt: new Date(order.orderPlacedAt).toISOString(),
|
|
1142
|
+
currency: order.currencyCode,
|
|
1143
|
+
// The channel's setting: Vendure's order carries none.
|
|
1144
|
+
pricesIncludeTax,
|
|
1145
|
+
customer: order.customer === null ? null : {
|
|
1146
|
+
id: order.customer.id,
|
|
1147
|
+
...name ? { name } : {},
|
|
1148
|
+
...email ? { email } : {}
|
|
1149
|
+
},
|
|
1150
|
+
lines: order.lines.map((line) => {
|
|
1151
|
+
const clientLineId = nonEmpty(line.customFields?.tallyClientLineId);
|
|
1152
|
+
const sku = nonEmpty(line.customFields?.tallyCustomSku) ?? nonEmpty(line.productVariant.sku);
|
|
1153
|
+
return {
|
|
1154
|
+
id: line.id,
|
|
1155
|
+
...clientLineId ? { clientLineId } : {},
|
|
1156
|
+
// The order query selects no product id; variantId names the sellable.
|
|
1157
|
+
variantId: line.productVariant.id,
|
|
1158
|
+
name: nonEmpty(line.customFields?.tallyCustomName) ?? line.productVariant.name,
|
|
1159
|
+
...sku ? { sku } : {},
|
|
1160
|
+
quantity: line.quantity,
|
|
1161
|
+
subtotalMinor: line.linePrice,
|
|
1162
|
+
subtotalTaxMinor: line.linePriceWithTax - line.linePrice,
|
|
1163
|
+
totalMinor: line.proratedLinePrice,
|
|
1164
|
+
taxMinor: line.proratedLinePriceWithTax - line.proratedLinePrice
|
|
1165
|
+
};
|
|
1166
|
+
}),
|
|
1167
|
+
fees: order.surcharges.map((s) => ({ name: s.description, totalMinor: s.price, taxMinor: s.priceWithTax - s.price })),
|
|
1168
|
+
shipping: order.shippingLines.map((l) => ({
|
|
1169
|
+
name: l.shippingMethod.name,
|
|
1170
|
+
totalMinor: l.discountedPrice,
|
|
1171
|
+
taxMinor: l.discountedPriceWithTax - l.discountedPrice
|
|
1172
|
+
})),
|
|
1173
|
+
// Vendure's couponCodes carry no amount and its discounts name no coupon, so no coupon line can be built; the discount is in the line totals and discountMinor.
|
|
1174
|
+
coupons: [],
|
|
1175
|
+
taxLines: order.taxSummary.map((t) => ({ label: t.description, ratePpm: Math.round(t.taxRate * 1e4), amountMinor: t.taxTotal })),
|
|
1176
|
+
// Vendure records a discount as a negative amount.
|
|
1177
|
+
discountMinor: order.discounts.reduce((sum, d) => sum - d.amount, 0),
|
|
1178
|
+
discountTaxMinor: order.discounts.reduce((sum, d) => sum - (d.amountWithTax - d.amount), 0),
|
|
1179
|
+
taxMinor: order.totalWithTax - order.total,
|
|
1180
|
+
totalMinor: order.totalWithTax,
|
|
1181
|
+
// No title or kind: a Vendure payment names only its method code.
|
|
1182
|
+
payments: (order.payments ?? []).filter((p) => !UNPAID_PAYMENT_STATES.includes(p.state)).map((p) => ({ method: p.method, amountMinor: p.amount })),
|
|
1183
|
+
refunds: (order.payments ?? []).flatMap((p) => p.refunds).filter((r) => r.state !== "Failed").map((r) => {
|
|
1184
|
+
const reason = nonEmpty(r.reason);
|
|
1185
|
+
return { id: r.id, amountMinor: r.total, ...reason ? { reason } : {} };
|
|
1186
|
+
})
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
var wholeNumber = (value, fallback) => value === void 0 || !Number.isFinite(value) ? fallback : Math.trunc(value);
|
|
1190
|
+
function createVendureOrders(options = {}) {
|
|
1191
|
+
const tally = options.tallyFields === false ? { tallyFields: false } : {};
|
|
1192
|
+
const pricesIncludeTax = options.pricesIncludeTax === true;
|
|
1193
|
+
return {
|
|
1194
|
+
async listOrders(context, query2 = {}) {
|
|
1195
|
+
const page = Math.max(1, wholeNumber(query2.page, 1));
|
|
1196
|
+
const perPage = Math.max(1, Math.min(100, wholeNumber(query2.perPage, 25)));
|
|
1197
|
+
const skip = (page - 1) * perPage;
|
|
1198
|
+
const search = query2.search?.trim();
|
|
1199
|
+
const { items, totalItems } = await listVendureOrderDetails(context, { skip, take: perPage, ...search ? { search } : {}, ...tally });
|
|
1200
|
+
return { orders: items.map((o) => toVendureStoreOrder(o, pricesIncludeTax)), hasMore: skip + items.length < totalItems };
|
|
1201
|
+
},
|
|
1202
|
+
async getOrders(context, ids) {
|
|
1203
|
+
const wanted = [...new Set(ids.filter((id) => id.length > 0))];
|
|
1204
|
+
const orders = [];
|
|
1205
|
+
for (const id of wanted) {
|
|
1206
|
+
const order = await getVendureOrder(context, id, options.tallyFields === false ? { tallyFields: false } : void 0);
|
|
1207
|
+
if (order === null) continue;
|
|
1208
|
+
if (order.orderPlacedAt === null) continue;
|
|
1209
|
+
orders.push(toVendureStoreOrder(order, pricesIncludeTax));
|
|
1210
|
+
}
|
|
1211
|
+
return orders;
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
// src/global-settings.ts
|
|
1217
|
+
var GLOBAL_SETTINGS_QUERY = `
|
|
1218
|
+
query GlobalStockSettings {
|
|
1219
|
+
globalSettings { trackInventory outOfStockThreshold }
|
|
1220
|
+
}
|
|
1221
|
+
`;
|
|
1222
|
+
async function vendureGlobalStockSettings(context) {
|
|
1223
|
+
const res = await gql2(context, GLOBAL_SETTINGS_QUERY);
|
|
1224
|
+
return res.data.globalSettings;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1052
1227
|
// src/refunds.ts
|
|
1053
1228
|
function vendureRefundable(order) {
|
|
1054
1229
|
const refundedQuantities = /* @__PURE__ */ new Map();
|
|
@@ -1137,10 +1312,13 @@ var createVendureConnector = (options = {}) => {
|
|
|
1137
1312
|
prices: { fetchPages: fetchPages2, fingerprint, enqueue: idFeed.enqueue, refetchBatchSize: VENDURE_IDS_PER_REQUEST }
|
|
1138
1313
|
},
|
|
1139
1314
|
storeSettings: vendureStoreSettings,
|
|
1140
|
-
// Needs the administrator's ReadCustomer permission (
|
|
1315
|
+
// Needs the administrator's ReadCustomer permission (CreateCustomer to create, UpdateCustomer to edit).
|
|
1141
1316
|
searchCustomers: searchVendureCustomers,
|
|
1142
1317
|
createCustomer: createVendureCustomer,
|
|
1143
1318
|
getCustomer: getVendureCustomer,
|
|
1319
|
+
updateCustomer: updateVendureCustomer,
|
|
1320
|
+
// Order history (ADR-081): needs the administrator's ReadOrder permission.
|
|
1321
|
+
...createVendureOrders({ pricesIncludeTax: options.pricesIncludeTax, tallyFields: options.tallyFields }),
|
|
1144
1322
|
// Re-reads a restored session's capabilities; with an API key and no sign-in, the only reader.
|
|
1145
1323
|
capabilities: (context) => readVendureCapabilities(context.baseUrl, context.headers, { signal: context.signal })
|
|
1146
1324
|
};
|
|
@@ -1151,13 +1329,17 @@ export {
|
|
|
1151
1329
|
VendureTimezoneConfigError,
|
|
1152
1330
|
createVendureConnector,
|
|
1153
1331
|
createVendureCustomer,
|
|
1332
|
+
createVendureOrders,
|
|
1154
1333
|
createVendureProductReplication,
|
|
1155
1334
|
createVendureVariantFeedReplication,
|
|
1156
1335
|
getVendureCustomer,
|
|
1157
1336
|
getVendureOrder,
|
|
1337
|
+
listVendureOrderDetails,
|
|
1158
1338
|
listVendureOrders,
|
|
1159
1339
|
searchVendureCustomers,
|
|
1160
1340
|
toVendureCustomer,
|
|
1341
|
+
toVendureStoreOrder,
|
|
1342
|
+
updateVendureCustomer,
|
|
1161
1343
|
vendureAuth,
|
|
1162
1344
|
vendureAuthFieldSets,
|
|
1163
1345
|
vendureConnector,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/connector-vendure",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.13.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Vendure connector for Tally UI",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -27,11 +27,11 @@
|
|
|
27
27
|
"directory": "connectors/vendure"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
30
|
-
"@tallyui/core": "^3.
|
|
30
|
+
"@tallyui/core": "^3.13.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@tallyui/database": "3.
|
|
34
|
-
"@tallyui/pos": "3.
|
|
33
|
+
"@tallyui/database": "3.13.0",
|
|
34
|
+
"@tallyui/pos": "3.13.0",
|
|
35
35
|
"rxdb": "17.5.0"
|
|
36
36
|
},
|
|
37
37
|
"scripts": {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"source": "Written from the Vendure 3 Admin API reference (UpdateCustomerInput, UpdateCustomerResult) with the recorded customer 2 of 2a; not recorded.",
|
|
3
|
+
"query": "mutation Update($input: UpdateCustomerInput!) {\n updateCustomer(input: $input) {\n __typename\n ... on Customer { id firstName lastName emailAddress phoneNumber }\n ... on ErrorResult { errorCode message }\n }\n}",
|
|
4
|
+
"variables": {
|
|
5
|
+
"input": {
|
|
6
|
+
"id": "2",
|
|
7
|
+
"phoneNumber": "+44 20 7946 0002"
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"httpStatus": 200,
|
|
11
|
+
"response": {
|
|
12
|
+
"data": {
|
|
13
|
+
"updateCustomer": {
|
|
14
|
+
"__typename": "Customer",
|
|
15
|
+
"id": "2",
|
|
16
|
+
"firstName": "Ada",
|
|
17
|
+
"lastName": "Lovelace",
|
|
18
|
+
"emailAddress": "ada.fixture@example.com",
|
|
19
|
+
"phoneNumber": "+44 20 7946 0002"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"source": "Written from the Vendure 3 Admin API reference (UpdateCustomerResult = Customer | EmailAddressConflictError) with the recorded error of 2b; not recorded.",
|
|
3
|
+
"query": "mutation Update($input: UpdateCustomerInput!) {\n updateCustomer(input: $input) {\n __typename\n ... on Customer { id firstName lastName emailAddress phoneNumber }\n ... on ErrorResult { errorCode message }\n }\n}",
|
|
4
|
+
"variables": {
|
|
5
|
+
"input": {
|
|
6
|
+
"id": "2",
|
|
7
|
+
"emailAddress": "adam.fixture@example.com"
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"httpStatus": 200,
|
|
11
|
+
"response": {
|
|
12
|
+
"data": {
|
|
13
|
+
"updateCustomer": {
|
|
14
|
+
"__typename": "EmailAddressConflictError",
|
|
15
|
+
"errorCode": "EMAIL_ADDRESS_CONFLICT_ERROR",
|
|
16
|
+
"message": "The email address is not available."
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
package/src/customers.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
ConnectorUnauthorizedError, CustomerServiceError, type Customer, type CustomerAddress, type CustomerInput, type CustomerPatch, type SyncContext,
|
|
3
|
+
} from '@tallyui/core';
|
|
4
|
+
import { gql, VendureApiError } from './replication/products';
|
|
3
5
|
|
|
4
6
|
// The vendurepos plugin's walk-in customer is never a person to attach to a sale.
|
|
5
7
|
const WALK_IN_EMAIL = 'walk-in@vendurepos.local';
|
|
@@ -23,6 +25,22 @@ const CREATE_QUERY = `mutation Create($input: CreateCustomerInput!) {
|
|
|
23
25
|
const GET_QUERY = `query One($id: ID!) {
|
|
24
26
|
customer(id: $id) { id firstName lastName emailAddress phoneNumber }
|
|
25
27
|
}`;
|
|
28
|
+
const UPDATE_QUERY = `mutation Update($input: UpdateCustomerInput!) {
|
|
29
|
+
updateCustomer(input: $input) {
|
|
30
|
+
__typename
|
|
31
|
+
... on Customer { id firstName lastName emailAddress phoneNumber }
|
|
32
|
+
... on ErrorResult { errorCode message }
|
|
33
|
+
}
|
|
34
|
+
}`;
|
|
35
|
+
const ADDRESSES_QUERY = `query Addresses($id: ID!) {
|
|
36
|
+
customer(id: $id) { id firstName lastName emailAddress phoneNumber addresses { id defaultShippingAddress defaultBillingAddress } }
|
|
37
|
+
}`;
|
|
38
|
+
const CREATE_ADDRESS_QUERY = `mutation CreateAddress($customerId: ID!, $input: CreateAddressInput!) {
|
|
39
|
+
createCustomerAddress(customerId: $customerId, input: $input) { id }
|
|
40
|
+
}`;
|
|
41
|
+
const UPDATE_ADDRESS_QUERY = `mutation UpdateAddress($input: UpdateAddressInput!) {
|
|
42
|
+
updateCustomerAddress(input: $input) { id }
|
|
43
|
+
}`;
|
|
26
44
|
|
|
27
45
|
export function toVendureCustomer(raw: { id: string; firstName?: string | null; lastName?: string | null; emailAddress?: string | null; phoneNumber?: string | null }): Customer {
|
|
28
46
|
const customer: Customer = { id: raw.id, name: raw.id };
|
|
@@ -58,12 +76,72 @@ export async function createVendureCustomer(context: SyncContext, input: Custome
|
|
|
58
76
|
throw new CustomerServiceError('server', 'unexpected response');
|
|
59
77
|
}
|
|
60
78
|
|
|
79
|
+
type VendureAddressRef = { id: string; defaultShippingAddress?: boolean | null; defaultBillingAddress?: boolean | null };
|
|
80
|
+
const SCALARS = [['firstName', 'firstName'], ['lastName', 'lastName'], ['email', 'emailAddress'], ['phone', 'phoneNumber']] as const;
|
|
81
|
+
// gql hands back only a 2xx body, and Vendure's recorded ErrorResult refusal (fixture 2b) came with HTTP 200.
|
|
82
|
+
const GRAPHQL_STATUS = { status: 200 };
|
|
83
|
+
|
|
84
|
+
/** A CustomerAddress as Vendure's address input; the patch replaces the stored address whole, so an absent field is ''. */
|
|
85
|
+
function toVendureAddressInput(address: CustomerAddress) {
|
|
86
|
+
return {
|
|
87
|
+
fullName: [address.firstName, address.lastName].filter(Boolean).join(' '), company: address.company ?? '',
|
|
88
|
+
streetLine1: address.address1 ?? '', streetLine2: address.address2 ?? '', city: address.city ?? '',
|
|
89
|
+
province: address.state ?? '', postalCode: address.postcode ?? '', countryCode: address.country ?? '',
|
|
90
|
+
phoneNumber: address.phone ?? '',
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Edits the customer through Vendure's own mutations: `updateCustomer` for its fields, then the address book, where
|
|
96
|
+
* billing and shipping are the addresses flagged `defaultBillingAddress` / `defaultShippingAddress`. A default shared by
|
|
97
|
+
* both kinds is never rewritten for one kind: that kind gets a new default address instead. Vendure stores no customer
|
|
98
|
+
* company or tax ids and no address email, so those are dropped, as `createVendureCustomer` drops them.
|
|
99
|
+
*/
|
|
100
|
+
export async function updateVendureCustomer(context: SyncContext, id: string, patch: CustomerPatch): Promise<Customer> {
|
|
101
|
+
const kinds = ([['billing', 'defaultBillingAddress', 'defaultShippingAddress'], ['shipping', 'defaultShippingAddress', 'defaultBillingAddress']] as const)
|
|
102
|
+
.filter(([kind]) => patch[kind] !== undefined);
|
|
103
|
+
if (kinds.some(([kind]) => !patch[kind]?.address1 || !patch[kind]?.country)) {
|
|
104
|
+
throw new CustomerServiceError('invalid', 'Vendure addresses need address1 and country');
|
|
105
|
+
}
|
|
106
|
+
const current = (await customerGql(context, ADDRESSES_QUERY, { id }))?.data?.customer;
|
|
107
|
+
if (current === null) throw new CustomerServiceError('invalid', 'unknown customer', GRAPHQL_STATUS);
|
|
108
|
+
if (typeof current?.id !== 'string') throw new CustomerServiceError('server', 'unexpected response');
|
|
109
|
+
|
|
110
|
+
let saved = current;
|
|
111
|
+
const fields = SCALARS.filter(([key]) => patch[key] !== undefined);
|
|
112
|
+
if (fields.length) {
|
|
113
|
+
const input = Object.fromEntries([['id', id], ...fields.map(([key, field]) => [field, patch[key]])]);
|
|
114
|
+
const result = (await customerGql(context, UPDATE_QUERY, { input }))?.data?.updateCustomer;
|
|
115
|
+
if (result?.__typename !== 'Customer') {
|
|
116
|
+
if (result?.__typename && result.message) throw new CustomerServiceError('invalid', result.message, GRAPHQL_STATUS);
|
|
117
|
+
throw new CustomerServiceError('server', 'unexpected response');
|
|
118
|
+
}
|
|
119
|
+
saved = result;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const addresses: VendureAddressRef[] = Array.isArray(current.addresses) ? current.addresses : [];
|
|
123
|
+
for (const [kind, flag, other] of kinds) {
|
|
124
|
+
const address = toVendureAddressInput(patch[kind]!);
|
|
125
|
+
const existing = addresses.find((entry) => entry[flag]);
|
|
126
|
+
if (existing && !existing[other]) {
|
|
127
|
+
await customerGql(context, UPDATE_ADDRESS_QUERY, { input: { id: existing.id, ...address } });
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
await customerGql(context, CREATE_ADDRESS_QUERY, { customerId: id, input: { ...address, [flag]: true } });
|
|
131
|
+
if (existing) {
|
|
132
|
+
await customerGql(context, UPDATE_ADDRESS_QUERY, { input: { id: existing.id, [flag]: false } });
|
|
133
|
+
existing[flag] = false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return toVendureCustomer(saved);
|
|
137
|
+
}
|
|
138
|
+
|
|
61
139
|
async function customerGql(context: SyncContext, query: string, variables: Record<string, unknown>): Promise<any> {
|
|
62
140
|
try {
|
|
63
141
|
return await gql(context, query, variables);
|
|
64
142
|
} catch (error) {
|
|
65
143
|
if (error instanceof ConnectorUnauthorizedError) throw error;
|
|
66
|
-
throw new CustomerServiceError(error instanceof Error && error.message.startsWith('Vendure ') ? 'server' : 'network', error instanceof Error ? error.message : String(error));
|
|
144
|
+
throw new CustomerServiceError(error instanceof Error && error.message.startsWith('Vendure ') ? 'server' : 'network', error instanceof Error ? error.message : String(error), { status: error instanceof VendureApiError ? error.status : undefined });
|
|
67
145
|
}
|
|
68
146
|
}
|
|
69
147
|
|
package/src/index.ts
CHANGED
|
@@ -12,7 +12,8 @@ import { createFetchByIds, fetchPages, variantIds } from './reconcile/ids';
|
|
|
12
12
|
import { fetchPages as fetchPricePages, fingerprint as priceFingerprint } from './reconcile/prices';
|
|
13
13
|
import { vendureStoreSettings } from './store-settings';
|
|
14
14
|
import { vendureGlobalStockSettings } from './global-settings';
|
|
15
|
-
import { searchVendureCustomers, createVendureCustomer, getVendureCustomer } from './customers';
|
|
15
|
+
import { searchVendureCustomers, createVendureCustomer, getVendureCustomer, updateVendureCustomer } from './customers';
|
|
16
|
+
import { createVendureOrders } from './store-orders';
|
|
16
17
|
|
|
17
18
|
/** Ids per fetchByIds request: it sends the reconcile feed's whole chunk (at most 1,000 ids, ADR-060) in one query. */
|
|
18
19
|
const VENDURE_IDS_PER_REQUEST = 1000;
|
|
@@ -39,10 +40,12 @@ const VENDURE_IDS_PER_REQUEST = 1000;
|
|
|
39
40
|
* and `globalOutOfStockThreshold` are the channel's stock defaults; read them
|
|
40
41
|
* with `vendureGlobalStockSettings` after sign-in, like `pricesIncludeTax`
|
|
41
42
|
* from `storeSettings`.
|
|
43
|
+
* `tallyFields: false` is for a server without the vendurepos plugin: order history then reads no till ids.
|
|
42
44
|
*/
|
|
43
45
|
export const createVendureConnector = (options: {
|
|
44
46
|
barcodeField?: string; stockLocationId?: string; pricesIncludeTax?: boolean; updatedAtSkewMs?: number;
|
|
45
47
|
globalTrackInventory?: boolean; globalOutOfStockThreshold?: number;
|
|
48
|
+
tallyFields?: boolean;
|
|
46
49
|
} = {}): TallyConnector => {
|
|
47
50
|
// The id reconcile's corrections reach `products` only through this pull adapter (ADR-060).
|
|
48
51
|
const idFeed = createReconcileFeed({ fetchByIds: createFetchByIds(options.barcodeField) });
|
|
@@ -87,10 +90,14 @@ export const createVendureConnector = (options: {
|
|
|
87
90
|
|
|
88
91
|
storeSettings: vendureStoreSettings,
|
|
89
92
|
|
|
90
|
-
// Needs the administrator's ReadCustomer permission (
|
|
93
|
+
// Needs the administrator's ReadCustomer permission (CreateCustomer to create, UpdateCustomer to edit).
|
|
91
94
|
searchCustomers: searchVendureCustomers,
|
|
92
95
|
createCustomer: createVendureCustomer,
|
|
93
96
|
getCustomer: getVendureCustomer,
|
|
97
|
+
updateCustomer: updateVendureCustomer,
|
|
98
|
+
|
|
99
|
+
// Order history (ADR-081): needs the administrator's ReadOrder permission.
|
|
100
|
+
...createVendureOrders({ pricesIncludeTax: options.pricesIncludeTax, tallyFields: options.tallyFields }),
|
|
94
101
|
|
|
95
102
|
// Re-reads a restored session's capabilities; with an API key and no sign-in, the only reader.
|
|
96
103
|
capabilities: (context) => readVendureCapabilities(context.baseUrl, context.headers, { signal: context.signal }),
|
|
@@ -113,8 +120,9 @@ export { createVendureVariantFeedReplication } from './replication/variant-feed'
|
|
|
113
120
|
export { vendureStockReconcile } from './reconcile/stock';
|
|
114
121
|
export { vendureStoreSettings } from './store-settings';
|
|
115
122
|
export { vendureGlobalStockSettings } from './global-settings';
|
|
116
|
-
export { searchVendureCustomers, createVendureCustomer, getVendureCustomer, toVendureCustomer } from './customers';
|
|
117
|
-
export { listVendureOrders, getVendureOrder, type VendureOrderListOptions, type VendureOrderList, type VendureOrderSummary, type VendureOrder } from './orders';
|
|
123
|
+
export { searchVendureCustomers, createVendureCustomer, getVendureCustomer, updateVendureCustomer, toVendureCustomer } from './customers';
|
|
124
|
+
export { listVendureOrders, getVendureOrder, listVendureOrderDetails, type VendureOrderListOptions, type VendureOrderList, type VendureOrderSummary, type VendureOrder } from './orders';
|
|
125
|
+
export { createVendureOrders, toVendureStoreOrder } from './store-orders';
|
|
118
126
|
export { vendureRefundable, vendureLineRefundWithTax, type VendureRefundableLine, type VendureRefundable } from './refunds';
|
|
119
127
|
|
|
120
128
|
export { ConnectorUnauthorizedError } from '@tallyui/core';
|
package/src/orders.ts
CHANGED
|
@@ -55,6 +55,8 @@ export interface VendureOrder extends VendureOrderSummary {
|
|
|
55
55
|
proratedUnitPrice: number;
|
|
56
56
|
/** Vendure's per-unit refund value, rounded per unit: for display, never multiplied by a quantity for `order.refund`'s `totalMinor` (ADR-080 amendment 2). */
|
|
57
57
|
proratedUnitPriceWithTax: number;
|
|
58
|
+
/** The line's total without tax after order-level discounts. */
|
|
59
|
+
proratedLinePrice: number;
|
|
58
60
|
/** The line's total with tax after order-level discounts; a refund's line amount is its share of this (vendurepos ADR 0007, decision 4.9). */
|
|
59
61
|
proratedLinePriceWithTax: number;
|
|
60
62
|
taxRate: number;
|
|
@@ -74,7 +76,7 @@ export interface VendureOrder extends VendureOrderSummary {
|
|
|
74
76
|
tallyClientLineId: string | null;
|
|
75
77
|
};
|
|
76
78
|
}[];
|
|
77
|
-
shippingLines: { shippingMethod: { name: string }; price: number; priceWithTax: number }[];
|
|
79
|
+
shippingLines: { shippingMethod: { name: string }; price: number; priceWithTax: number; discountedPrice: number; discountedPriceWithTax: number }[];
|
|
78
80
|
surcharges: { description: string; sku: string; price: number; priceWithTax: number }[];
|
|
79
81
|
subTotal: number;
|
|
80
82
|
subTotalWithTax: number;
|
|
@@ -112,11 +114,11 @@ const ORDER_DETAIL_FIELDS_START = `
|
|
|
112
114
|
customer { id firstName lastName emailAddress }
|
|
113
115
|
lines {`;
|
|
114
116
|
const ORDER_DETAIL_FIELDS_END = `
|
|
115
|
-
id quantity orderPlacedQuantity proratedUnitPrice proratedUnitPriceWithTax proratedLinePriceWithTax taxRate productVariant { id name sku }
|
|
117
|
+
id quantity orderPlacedQuantity proratedUnitPrice proratedUnitPriceWithTax proratedLinePriceWithTax proratedLinePrice taxRate productVariant { id name sku }
|
|
116
118
|
unitPrice unitPriceWithTax linePrice linePriceWithTax discountedLinePrice discountedLinePriceWithTax
|
|
117
119
|
discounts { description amount amountWithTax }
|
|
118
120
|
}
|
|
119
|
-
shippingLines { shippingMethod { name } price priceWithTax }
|
|
121
|
+
shippingLines { shippingMethod { name } price priceWithTax discountedPrice discountedPriceWithTax }
|
|
120
122
|
surcharges { description sku price priceWithTax }
|
|
121
123
|
subTotal subTotalWithTax shipping shippingWithTax total totalWithTax
|
|
122
124
|
taxSummary { description taxRate taxBase taxTotal }
|
|
@@ -138,6 +140,10 @@ const CUSTOMER_LIST_QUERY = `query CustomerOrders($customerId: ID!, $options: Or
|
|
|
138
140
|
customer(id: $customerId) { orders(options: $options) { items { ${ORDER_ROW_FIELDS} } totalItems } }
|
|
139
141
|
}`;
|
|
140
142
|
const TALLY_CUSTOMER_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_ROW_FIELDS);
|
|
143
|
+
const DETAIL_LIST_QUERY = LIST_QUERY.replace(ORDER_ROW_FIELDS, ORDER_DETAIL_FIELDS);
|
|
144
|
+
const TALLY_DETAIL_LIST_QUERY = LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_DETAIL_FIELDS);
|
|
145
|
+
const CUSTOMER_DETAIL_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, ORDER_DETAIL_FIELDS);
|
|
146
|
+
const TALLY_CUSTOMER_DETAIL_LIST_QUERY = CUSTOMER_LIST_QUERY.replace(ORDER_ROW_FIELDS, TALLY_ORDER_DETAIL_FIELDS);
|
|
141
147
|
const DETAIL_QUERY = `query Order($id: ID!) {
|
|
142
148
|
order(id: $id) { ${ORDER_DETAIL_FIELDS} }
|
|
143
149
|
}`;
|
|
@@ -146,6 +152,18 @@ const TALLY_DETAIL_QUERY = `query Order($id: ID!) {
|
|
|
146
152
|
}`;
|
|
147
153
|
|
|
148
154
|
export async function listVendureOrders(context: SyncContext, options: VendureOrderListOptions = {}): Promise<VendureOrderList<VendureOrderSummary>> {
|
|
155
|
+
return listOrders(context, options, LIST_QUERY, TALLY_LIST_QUERY, CUSTOMER_LIST_QUERY, TALLY_CUSTOMER_LIST_QUERY);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** As listVendureOrders, with each row's full detail (the getVendureOrder fields): one request per page. */
|
|
159
|
+
export async function listVendureOrderDetails(context: SyncContext, options: VendureOrderListOptions = {}): Promise<VendureOrderList<VendureOrder>> {
|
|
160
|
+
return listOrders(context, options, DETAIL_LIST_QUERY, TALLY_DETAIL_LIST_QUERY, CUSTOMER_DETAIL_LIST_QUERY, TALLY_CUSTOMER_DETAIL_LIST_QUERY);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function listOrders<T>(
|
|
164
|
+
context: SyncContext, options: VendureOrderListOptions,
|
|
165
|
+
listQuery: string, tallyListQuery: string, customerListQuery: string, tallyCustomerListQuery: string,
|
|
166
|
+
): Promise<VendureOrderList<T>> {
|
|
149
167
|
const skip = Math.max(0, Math.trunc(Number.isFinite(options.skip) ? options.skip! : 0));
|
|
150
168
|
const take = Math.max(1, Math.min(100, Math.trunc(Number.isFinite(options.take) ? options.take! : 25)));
|
|
151
169
|
const date = options.orderPlacedAt;
|
|
@@ -167,8 +185,8 @@ export async function listVendureOrders(context: SyncContext, options: VendureOr
|
|
|
167
185
|
...(options.customerId ? { customerId: options.customerId } : {}),
|
|
168
186
|
};
|
|
169
187
|
const query = options.customerId
|
|
170
|
-
? (options.tallyFields === false ?
|
|
171
|
-
: (options.tallyFields === false ?
|
|
188
|
+
? (options.tallyFields === false ? customerListQuery : tallyCustomerListQuery)
|
|
189
|
+
: (options.tallyFields === false ? listQuery : tallyListQuery);
|
|
172
190
|
const body = await gql(context, query, variables);
|
|
173
191
|
if (options.customerId && body?.data?.customer === null) return { items: [], totalItems: 0 };
|
|
174
192
|
const result = options.customerId ? body?.data?.customer?.orders : body?.data?.orders;
|
|
@@ -59,6 +59,11 @@ const PRODUCT_MARK_QUERY = `
|
|
|
59
59
|
}
|
|
60
60
|
`;
|
|
61
61
|
|
|
62
|
+
/** A Vendure Admin API failure, with the HTTP status of the response (200 for GraphQL errors, which Vendure answers with HTTP 200). */
|
|
63
|
+
export class VendureApiError extends Error {
|
|
64
|
+
constructor(message: string, readonly status: number) { super(message); }
|
|
65
|
+
}
|
|
66
|
+
|
|
62
67
|
/**
|
|
63
68
|
* Helper to execute a GraphQL query against the Vendure Admin API.
|
|
64
69
|
*/
|
|
@@ -83,12 +88,12 @@ export async function gql(
|
|
|
83
88
|
const message = body?.errors?.[0]?.message;
|
|
84
89
|
// Vendure answers FORBIDDEN with HTTP 200; an HTTP 401/403 comes from a proxy or firewall and is taken at face value.
|
|
85
90
|
if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorizedError(`Vendure API error: ${res.status}${message ? `: ${message}` : ''}`, res.status as 401 | 403);
|
|
86
|
-
throw new
|
|
91
|
+
throw new VendureApiError(`Vendure API error: ${res.status}${message ? `: ${message}` : ''}`, res.status);
|
|
87
92
|
}
|
|
88
93
|
const body = await res.json() as GqlBody;
|
|
89
94
|
const forbidden = body.errors?.filter((error) => error.extensions?.code === 'FORBIDDEN') ?? [];
|
|
90
95
|
if (forbidden.length) throw await forbiddenError(context, forbidden);
|
|
91
|
-
if (body.errors?.length) throw new
|
|
96
|
+
if (body.errors?.length) throw new VendureApiError(`Vendure GraphQL error: ${body.errors[0].message}`, res.status);
|
|
92
97
|
return body;
|
|
93
98
|
}
|
|
94
99
|
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { StoreOrder, StoreOrderLine, SyncContext, TallyConnector } from '@tallyui/core';
|
|
2
|
+
import { getVendureOrder, listVendureOrderDetails, type VendureOrder } from './orders';
|
|
3
|
+
|
|
4
|
+
const nonEmpty = (value: unknown) => (typeof value === 'string' && value.length > 0 ? value : undefined);
|
|
5
|
+
// Payments that took no money.
|
|
6
|
+
const UNPAID_PAYMENT_STATES = ['Declined', 'Error', 'Cancelled'];
|
|
7
|
+
|
|
8
|
+
/** Maps a Vendure Admin API order (getVendureOrder's fields) to a `StoreOrder` (ADR-081). */
|
|
9
|
+
export function toVendureStoreOrder(order: VendureOrder, pricesIncludeTax: boolean): StoreOrder {
|
|
10
|
+
if (typeof order.orderPlacedAt !== 'string' || Number.isNaN(new Date(order.orderPlacedAt).getTime())) {
|
|
11
|
+
throw new Error('Vendure sent an unexpected order response');
|
|
12
|
+
}
|
|
13
|
+
const clientOrderId = nonEmpty(order.customFields?.tallyClientOrderId);
|
|
14
|
+
const name = order.customer ? `${order.customer.firstName} ${order.customer.lastName}`.trim() : '';
|
|
15
|
+
const email = nonEmpty(order.customer?.emailAddress);
|
|
16
|
+
return {
|
|
17
|
+
id: order.id,
|
|
18
|
+
reference: order.code,
|
|
19
|
+
...(clientOrderId ? { clientOrderId } : {}),
|
|
20
|
+
status: order.state,
|
|
21
|
+
placedAt: new Date(order.orderPlacedAt).toISOString(),
|
|
22
|
+
currency: order.currencyCode,
|
|
23
|
+
// The channel's setting: Vendure's order carries none.
|
|
24
|
+
pricesIncludeTax,
|
|
25
|
+
customer: order.customer === null ? null : {
|
|
26
|
+
id: order.customer.id, ...(name ? { name } : {}), ...(email ? { email } : {}),
|
|
27
|
+
},
|
|
28
|
+
lines: order.lines.map((line): StoreOrderLine => {
|
|
29
|
+
const clientLineId = nonEmpty(line.customFields?.tallyClientLineId);
|
|
30
|
+
const sku = nonEmpty(line.customFields?.tallyCustomSku) ?? nonEmpty(line.productVariant.sku);
|
|
31
|
+
return {
|
|
32
|
+
id: line.id,
|
|
33
|
+
...(clientLineId ? { clientLineId } : {}),
|
|
34
|
+
// The order query selects no product id; variantId names the sellable.
|
|
35
|
+
variantId: line.productVariant.id,
|
|
36
|
+
name: nonEmpty(line.customFields?.tallyCustomName) ?? line.productVariant.name,
|
|
37
|
+
...(sku ? { sku } : {}),
|
|
38
|
+
quantity: line.quantity,
|
|
39
|
+
subtotalMinor: line.linePrice,
|
|
40
|
+
subtotalTaxMinor: line.linePriceWithTax - line.linePrice,
|
|
41
|
+
totalMinor: line.proratedLinePrice,
|
|
42
|
+
taxMinor: line.proratedLinePriceWithTax - line.proratedLinePrice,
|
|
43
|
+
};
|
|
44
|
+
}),
|
|
45
|
+
fees: order.surcharges.map((s) => ({ name: s.description, totalMinor: s.price, taxMinor: s.priceWithTax - s.price })),
|
|
46
|
+
shipping: order.shippingLines.map((l) => ({
|
|
47
|
+
name: l.shippingMethod.name, totalMinor: l.discountedPrice, taxMinor: l.discountedPriceWithTax - l.discountedPrice,
|
|
48
|
+
})),
|
|
49
|
+
// Vendure's couponCodes carry no amount and its discounts name no coupon, so no coupon line can be built; the discount is in the line totals and discountMinor.
|
|
50
|
+
coupons: [],
|
|
51
|
+
taxLines: order.taxSummary.map((t) => ({ label: t.description, ratePpm: Math.round(t.taxRate * 10000), amountMinor: t.taxTotal })),
|
|
52
|
+
// Vendure records a discount as a negative amount.
|
|
53
|
+
discountMinor: order.discounts.reduce((sum, d) => sum - d.amount, 0),
|
|
54
|
+
discountTaxMinor: order.discounts.reduce((sum, d) => sum - (d.amountWithTax - d.amount), 0),
|
|
55
|
+
taxMinor: order.totalWithTax - order.total,
|
|
56
|
+
totalMinor: order.totalWithTax,
|
|
57
|
+
// No title or kind: a Vendure payment names only its method code.
|
|
58
|
+
payments: (order.payments ?? []).filter((p) => !UNPAID_PAYMENT_STATES.includes(p.state)).map((p) => ({ method: p.method, amountMinor: p.amount })),
|
|
59
|
+
refunds: (order.payments ?? []).flatMap((p) => p.refunds).filter((r) => r.state !== 'Failed').map((r) => {
|
|
60
|
+
const reason = nonEmpty(r.reason);
|
|
61
|
+
return { id: r.id, amountMinor: r.total, ...(reason ? { reason } : {}) };
|
|
62
|
+
}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const wholeNumber = (value: number | undefined, fallback: number) => (value === undefined || !Number.isFinite(value) ? fallback : Math.trunc(value));
|
|
67
|
+
|
|
68
|
+
/** Vendure order history (ADR-081), read-only through the Admin API; needs the ReadOrder permission. */
|
|
69
|
+
export function createVendureOrders(options: { pricesIncludeTax?: boolean; tallyFields?: boolean } = {}): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>> {
|
|
70
|
+
const tally = options.tallyFields === false ? { tallyFields: false } : {};
|
|
71
|
+
const pricesIncludeTax = options.pricesIncludeTax === true;
|
|
72
|
+
return {
|
|
73
|
+
async listOrders(context: SyncContext, query = {}) {
|
|
74
|
+
const page = Math.max(1, wholeNumber(query.page, 1));
|
|
75
|
+
const perPage = Math.max(1, Math.min(100, wholeNumber(query.perPage, 25)));
|
|
76
|
+
const skip = (page - 1) * perPage;
|
|
77
|
+
const search = query.search?.trim();
|
|
78
|
+
const { items, totalItems } = await listVendureOrderDetails(context, { skip, take: perPage, ...(search ? { search } : {}), ...tally });
|
|
79
|
+
return { orders: items.map((o) => toVendureStoreOrder(o, pricesIncludeTax)), hasMore: skip + items.length < totalItems };
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
async getOrders(context: SyncContext, ids: readonly string[]) {
|
|
83
|
+
const wanted = [...new Set(ids.filter((id) => id.length > 0))];
|
|
84
|
+
const orders: StoreOrder[] = [];
|
|
85
|
+
for (const id of wanted) {
|
|
86
|
+
const order = await getVendureOrder(context, id, options.tallyFields === false ? { tallyFields: false } : undefined);
|
|
87
|
+
if (order === null) continue;
|
|
88
|
+
// Never placed: a cart, not order history.
|
|
89
|
+
if (order.orderPlacedAt === null) continue;
|
|
90
|
+
orders.push(toVendureStoreOrder(order, pricesIncludeTax));
|
|
91
|
+
}
|
|
92
|
+
return orders;
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|