@tallyui/connector-medusa 3.20.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _tallyui_core from '@tallyui/core';
2
- import { ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, CustomerPatch, TallyConnector, ConnectorAuth, ServerCapabilities } from '@tallyui/core';
2
+ import { ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, CustomerPatch, OrderFilterField, TallyConnector, ServerCapabilities, StoreOrder, ConnectorAuth } from '@tallyui/core';
3
3
  export { ConnectorUnauthorizedError } from '@tallyui/core';
4
4
  import { RxJsonSchema } from 'rxdb';
5
5
 
@@ -122,8 +122,9 @@ declare const createMedusaVariantFeedReplication: (variantPageSize?: number) =>
122
122
  declare const medusaStockReconcile: StockReconcileAdapter;
123
123
 
124
124
  /**
125
- * Reads the store's currency, tax inclusivity and location tax rate, and the
126
- * publishable-key channel, from Medusa's admin API only (TV4b). Read-only
125
+ * Reads the store's currency, tax inclusivity and location tax rate, the
126
+ * publishable-key channel, and once every choice is made, every tax region's
127
+ * rates (`allTaxRates`), from Medusa's admin API only (TV4b). Read-only
127
128
  * (ADR-048). Region, then country, then channel: the first ambiguity that
128
129
  * needs a choice reports every choice known at that point, so the app asks
129
130
  * once.
@@ -159,6 +160,21 @@ declare function getMedusaCustomer(baseUrl: string, headers: Record<string, stri
159
160
  */
160
161
  declare function updateMedusaCustomer(baseUrl: string, headers: Record<string, string>, id: string, patch: CustomerPatch, init?: CustomerInit): Promise<Customer>;
161
162
 
163
+ /** Maps a Medusa v2 admin order (selected with ORDER_FIELDS) to a `StoreOrder` (ADR-081). Reads plain numbers only, never `raw_*` or `summary`. */
164
+ declare function toMedusaStoreOrder(raw: unknown): StoreOrder;
165
+ /** The ListOrdersQuery filters Medusa's admin order list honours; it has no cashier, register, payment-method, store or created-via filter. */
166
+ declare const MEDUSA_ORDER_FILTERS: readonly OrderFilterField[];
167
+ /** An all-digits search this long or shorter is a display number (front desk, 2026-11-20); longer goes to `q`, so phone searches keep working. */
168
+ declare const MEDUSA_DISPLAY_NUMBER_MAX_DIGITS = 6;
169
+ /** The MedusaPOS plugin contract that adds GET /tally/v1/orders (medusapos versions.ts:18-19). */
170
+ declare const MEDUSA_ORDERS_PLUGIN_CONTRACT = 3;
171
+ /** The MedusaPOS plugin contract at which GET /tally/v1/orders takes allChannels=true (medusapos/app#516); a contract-3 plugin answers the key with a 400. */
172
+ declare const MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT = 4;
173
+ /** The filter fields `listOrders` honours for a store with these capabilities: `registerId` needs the plugin's orders route. */
174
+ declare function medusaOrderFilters(capabilities?: ServerCapabilities): readonly OrderFilterField[];
175
+ /** Medusa v2 admin orders (`GET /admin/orders`): order history, read-only (ADR-081). */
176
+ declare function createMedusaOrders(): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>>;
177
+
162
178
  /**
163
179
  * Fills each variant's `calculated_price` from the store API, priced with
164
180
  * `context.pricingContext` (`region_id`, `publishable_key`): what Medusa
@@ -217,4 +233,4 @@ declare const medusaConnector: TallyConnector;
217
233
  */
218
234
  declare const medusaAdminUserConnector: TallyConnector;
219
235
 
220
- export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS, type MedusaCalculatedPrice, type MedusaProductDocument, type MedusaVariantDocument, createMedusaAdminUserConnector, createMedusaConnector, createMedusaCustomer, createMedusaVariantFeedReplication, getMedusaCustomer, medusaAdminUserAuth, medusaAdminUserConnector, medusaCapabilities, medusaConnector, medusaCreateCustomer, medusaGetCustomer, medusaProductReplication, medusaProductSchema, medusaProductSync, medusaProductTraits, medusaSearchCustomers, medusaSecretKeyAuth, medusaSignIn, medusaStockReconcile, medusaStoreSettings, medusaUpdateCustomer, searchMedusaCustomers, toCustomer, updateMedusaCustomer, withCalculatedPrices };
236
+ export { MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT, MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS, MEDUSA_DISPLAY_NUMBER_MAX_DIGITS, MEDUSA_ORDERS_PLUGIN_CONTRACT, MEDUSA_ORDER_FILTERS, type MedusaCalculatedPrice, type MedusaProductDocument, type MedusaVariantDocument, createMedusaAdminUserConnector, createMedusaConnector, createMedusaCustomer, createMedusaOrders, createMedusaVariantFeedReplication, getMedusaCustomer, medusaAdminUserAuth, medusaAdminUserConnector, medusaCapabilities, medusaConnector, medusaCreateCustomer, medusaGetCustomer, medusaOrderFilters, medusaProductReplication, medusaProductSchema, medusaProductSync, medusaProductTraits, medusaSearchCustomers, medusaSecretKeyAuth, medusaSignIn, medusaStockReconcile, medusaStoreSettings, medusaUpdateCustomer, searchMedusaCustomers, toCustomer, toMedusaStoreOrder, updateMedusaCustomer, withCalculatedPrices };
package/dist/index.js CHANGED
@@ -569,7 +569,23 @@ var medusaProductSync = {
569
569
  };
570
570
 
571
571
  // src/replication/products.ts
572
- import { compareIds, ConnectorUnauthorizedError as ConnectorUnauthorizedError2 } from "@tallyui/core";
572
+ import { compareIds } from "@tallyui/core";
573
+
574
+ // src/admin-get.ts
575
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError2 } from "@tallyui/core";
576
+ async function adminGet(path, context) {
577
+ const response = await fetch(`${context.baseUrl}${path}`, {
578
+ headers: { ...context.headers, "Content-Type": "application/json" },
579
+ signal: context.signal
580
+ });
581
+ if (!response.ok) {
582
+ const error = await response.json().catch(() => ({}));
583
+ const message = `Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`;
584
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError2(message, response.status);
585
+ throw new Error(message);
586
+ }
587
+ return response.json();
588
+ }
573
589
 
574
590
  // src/pricing/calculated.ts
575
591
  var STORE_PAGE_SIZE = 100;
@@ -651,16 +667,7 @@ var medusaProductReplication = {
651
667
  const offset = lastCheckpoint?.offset ?? 0;
652
668
  let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? "";
653
669
  if (offset === 0 && lastCheckpoint?.pass_mark === void 0) {
654
- const markResponse = await fetch(
655
- `${context.baseUrl}/admin/products?limit=1&order=-updated_at&fields=id,updated_at`,
656
- { headers: { ...context.headers, "Content-Type": "application/json" }, signal: context.signal }
657
- );
658
- if (!markResponse.ok) {
659
- const error = await markResponse.json().catch(() => ({}));
660
- if (markResponse.status === 401 || markResponse.status === 403) throw new ConnectorUnauthorizedError2(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ""}`, markResponse.status);
661
- throw new Error(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ""}`);
662
- }
663
- const markData = await markResponse.json();
670
+ const markData = await adminGet("/admin/products?limit=1&order=-updated_at&fields=id,updated_at", context);
664
671
  passMark = markData.products?.[0]?.updated_at ?? passMark;
665
672
  if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
666
673
  return { documents: [], checkpoint: lastCheckpoint };
@@ -678,22 +685,7 @@ var medusaProductReplication = {
678
685
  if (lastCheckpoint?.updated_at) {
679
686
  params.set("updated_at[$gte]", lastCheckpoint.updated_at);
680
687
  }
681
- const response = await fetch(
682
- `${context.baseUrl}/admin/products?${params}`,
683
- {
684
- headers: {
685
- ...context.headers,
686
- "Content-Type": "application/json"
687
- },
688
- signal: context.signal
689
- }
690
- );
691
- if (!response.ok) {
692
- const error = await response.json().catch(() => ({}));
693
- if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError2(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
694
- throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
695
- }
696
- const data = await response.json();
688
+ const data = await adminGet(`/admin/products?${params}`, context);
697
689
  const products = data.products ?? [];
698
690
  if (offset > 0 && (products.length === 0 || data.count < (lastCheckpoint?.pass_count ?? data.count))) {
699
691
  return medusaProductReplication.pull.handler({
@@ -715,29 +707,13 @@ var medusaProductReplication = {
715
707
  }
716
708
  };
717
709
 
718
- // src/replication/variant-feed.ts
719
- import { ConnectorUnauthorizedError as ConnectorUnauthorizedError4 } from "@tallyui/core";
720
-
721
710
  // src/reconcile/ids.ts
722
- import { ConnectorUnauthorizedError as ConnectorUnauthorizedError3 } from "@tallyui/core";
723
711
  var PAGE_SIZE = 1e3;
724
712
  var MAX_IDS_PER_REQUEST = 100;
725
- async function get(path, context) {
726
- const response = await fetch(`${context.baseUrl}${path}`, {
727
- headers: { ...context.headers, "Content-Type": "application/json" },
728
- signal: context.signal
729
- });
730
- if (!response.ok) {
731
- const error = await response.json().catch(() => ({}));
732
- if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError3(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
733
- throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
734
- }
735
- return response.json();
736
- }
737
713
  async function* fetchPages(context) {
738
714
  for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
739
715
  const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), order: "id", fields: "id,variants.id" });
740
- const data = await get(`/admin/products?${params}`, context);
716
+ const data = await adminGet(`/admin/products?${params}`, context);
741
717
  const products = data.products ?? [];
742
718
  count = data.count;
743
719
  yield products.map((p) => ({ id: String(p.id), variantIds: (p.variants ?? []).map((v) => String(v.id)) }));
@@ -752,7 +728,7 @@ async function fetchByIds(ids, context) {
752
728
  const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
753
729
  const params = new URLSearchParams({ fields: MEDUSA_PRODUCT_FIELDS, limit: String(chunk.length) });
754
730
  for (const id of chunk) params.append("id[]", id);
755
- const data = await get(`/admin/products?${params}`, context);
731
+ const data = await adminGet(`/admin/products?${params}`, context);
756
732
  const products = data.products ?? [];
757
733
  results.push(...products.map(toDocument));
758
734
  }
@@ -762,24 +738,12 @@ async function fetchByIds(ids, context) {
762
738
  // src/replication/variant-feed.ts
763
739
  var MAX_LIMIT = 1e3;
764
740
  var MARK_PATH = "/admin/product-variants?limit=1&order=-updated_at&fields=id,updated_at";
765
- async function get2(path, context) {
766
- const response = await fetch(`${context.baseUrl}${path}`, {
767
- headers: { ...context.headers, "Content-Type": "application/json" },
768
- signal: context.signal
769
- });
770
- if (!response.ok) {
771
- const error = await response.json().catch(() => ({}));
772
- if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError4(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
773
- throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
774
- }
775
- return response.json();
776
- }
777
741
  var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
778
742
  pull: {
779
743
  // The next call's unchanged-mark check then ends at one mark read, unless
780
744
  // a variant changed since.
781
745
  async seedCheckpoint(context) {
782
- const markData = await get2(MARK_PATH, context);
746
+ const markData = await adminGet(MARK_PATH, context);
783
747
  return { offset: 0, updated_at: markData.variants?.[0]?.updated_at ?? "", pass_mark: void 0, pass_count: void 0 };
784
748
  },
785
749
  async handler(lastCheckpoint, batchSize, context) {
@@ -787,7 +751,7 @@ var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
787
751
  let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? "";
788
752
  let passCount = lastCheckpoint?.pass_count;
789
753
  if (offset === 0 && lastCheckpoint?.pass_mark === void 0) {
790
- const markData = await get2(MARK_PATH, context);
754
+ const markData = await adminGet(MARK_PATH, context);
791
755
  passMark = markData.variants?.[0]?.updated_at ?? passMark;
792
756
  if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
793
757
  return { documents: [], checkpoint: lastCheckpoint };
@@ -796,7 +760,7 @@ var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
796
760
  const page = (from) => {
797
761
  const params = new URLSearchParams({ limit: String(variantPageSize), offset: String(from), order: "id", fields: "id,product_id" });
798
762
  if (lastCheckpoint?.updated_at) params.set("updated_at[$gte]", lastCheckpoint.updated_at);
799
- return get2(`/admin/product-variants?${params}`, context);
763
+ return adminGet(`/admin/product-variants?${params}`, context);
800
764
  };
801
765
  const seen = /* @__PURE__ */ new Set();
802
766
  const documents = [];
@@ -820,7 +784,7 @@ var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
820
784
  const checkpoint = complete ? { offset: 0, updated_at: passMark, pass_mark: void 0, pass_count: void 0 } : { offset, updated_at: lastCheckpoint?.updated_at ?? "", pass_mark: passMark, pass_count: passCount };
821
785
  const moved = ["offset", "updated_at", "pass_mark", "pass_count"].some((key) => checkpoint[key] !== lastCheckpoint?.[key]);
822
786
  if (!documents.length && moved) {
823
- const carrier = await get2(`/admin/products?${new URLSearchParams({ limit: "1", fields: MEDUSA_PRODUCT_FIELDS })}`, context);
787
+ const carrier = await adminGet(`/admin/products?${new URLSearchParams({ limit: "1", fields: MEDUSA_PRODUCT_FIELDS })}`, context);
824
788
  const priced = await withCalculatedPrices((carrier.products ?? []).map(toDocument), context);
825
789
  documents.push(...priced.map((doc) => ({ ...doc, _deleted: false })));
826
790
  }
@@ -830,7 +794,6 @@ var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
830
794
  });
831
795
 
832
796
  // src/reconcile/stock.ts
833
- import { ConnectorUnauthorizedError as ConnectorUnauthorizedError5 } from "@tallyui/core";
834
797
  var PAGE_SIZE2 = 1e3;
835
798
  var FIELDS = "id,location_levels.stocked_quantity,location_levels.reserved_quantity,location_levels.location_id";
836
799
  var pairsKey = (levels = []) => levels.map((l) => JSON.stringify([l.stocked_quantity, l.reserved_quantity])).sort().join();
@@ -838,16 +801,7 @@ var medusaStockReconcile = {
838
801
  async *fetchPages(context) {
839
802
  for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE2) {
840
803
  const params = new URLSearchParams({ limit: String(PAGE_SIZE2), offset: String(offset), fields: FIELDS, order: "id" });
841
- const response = await fetch(`${context.baseUrl}/admin/inventory-items?${params}`, {
842
- headers: { ...context.headers, "Content-Type": "application/json" },
843
- signal: context.signal
844
- });
845
- if (!response.ok) {
846
- const error = await response.json().catch(() => ({}));
847
- if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError5(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
848
- throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
849
- }
850
- const data = await response.json();
804
+ const data = await adminGet(`/admin/inventory-items?${params}`, context);
851
805
  count = data.count;
852
806
  yield new Map(data.inventory_items.map((item) => [item.id, (item.location_levels ?? []).map(({ stocked_quantity, reserved_quantity }) => ({ stocked_quantity, reserved_quantity }))]));
853
807
  }
@@ -871,22 +825,10 @@ var medusaStockReconcile = {
871
825
  };
872
826
 
873
827
  // src/reconcile/prices.ts
874
- import { ConnectorUnauthorizedError as ConnectorUnauthorizedError6 } from "@tallyui/core";
875
828
  var PAGE_SIZE3 = 1e3;
876
829
  var MEDUSA_PRICE_RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1e3;
877
- async function get3(path, context) {
878
- const response = await fetch(`${context.baseUrl}${path}`, {
879
- headers: { ...context.headers, "Content-Type": "application/json" },
880
- signal: context.signal
881
- });
882
- if (!response.ok) {
883
- const error = await response.json().catch(() => ({}));
884
- if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError6(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
885
- throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
886
- }
887
- return response.json();
888
- }
889
830
  var fingerprintOf = (entries) => [...entries].sort().join("|");
831
+ var baseEntries = (variant) => (variant.prices ?? []).filter((price) => !price.price_list_id).map((price) => `${variant.id}:${price.currency_code}:${price.amount}`);
890
832
  async function* fetchPages2(context) {
891
833
  const byProduct = /* @__PURE__ */ new Map();
892
834
  for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE3) {
@@ -896,7 +838,7 @@ async function* fetchPages2(context) {
896
838
  order: "id",
897
839
  fields: "id,product_id,prices.amount,prices.currency_code,prices.price_list_id"
898
840
  });
899
- const data = await get3(`/admin/product-variants?${params}`, context);
841
+ const data = await adminGet(`/admin/product-variants?${params}`, context);
900
842
  const variants = data.variants ?? [];
901
843
  count = data.count;
902
844
  const touched = /* @__PURE__ */ new Set();
@@ -905,23 +847,13 @@ async function* fetchPages2(context) {
905
847
  touched.add(productId);
906
848
  const entries = byProduct.get(productId) ?? [];
907
849
  byProduct.set(productId, entries);
908
- for (const price of variant.prices ?? []) {
909
- if (price.price_list_id) continue;
910
- entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
911
- }
850
+ entries.push(...baseEntries(variant));
912
851
  }
913
852
  yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
914
853
  }
915
854
  }
916
855
  function fingerprint(doc) {
917
- const entries = [];
918
- for (const variant of doc.variants ?? []) {
919
- for (const price of variant.prices ?? []) {
920
- if (price.price_list_id) continue;
921
- entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
922
- }
923
- }
924
- return fingerprintOf(entries);
856
+ return fingerprintOf((doc.variants ?? []).flatMap(baseEntries));
925
857
  }
926
858
 
927
859
  // src/reconcile/calculated-prices.ts
@@ -950,15 +882,17 @@ function fingerprint2(doc) {
950
882
  }
951
883
 
952
884
  // src/store-settings.ts
953
- import { ConnectorUnauthorizedError as ConnectorUnauthorizedError7, StoreSettingsError } from "@tallyui/core";
954
- async function get4(context, path) {
885
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError3, StoreSettingsError } from "@tallyui/core";
886
+ var TAX_REGIONS_PAGE_SIZE = 100;
887
+ var MAX_TAX_REGION_PAGES = 100;
888
+ async function get(context, path) {
955
889
  const response = await fetch(`${context.baseUrl}${path}`, {
956
890
  headers: { ...context.headers, "Content-Type": "application/json" },
957
891
  signal: context.signal
958
892
  });
959
893
  if (!response.ok) {
960
894
  const body = await response.json().catch(() => ({}));
961
- if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError7(`Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ""}`, response.status);
895
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError3(`Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ""}`, response.status);
962
896
  throw new StoreSettingsError("failed", `Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ""}`);
963
897
  }
964
898
  return response.json();
@@ -972,12 +906,35 @@ function channelName(key) {
972
906
  const names = (key.sales_channels ?? []).map((c) => c.name).filter((name) => name?.trim());
973
907
  return names.length > 0 ? names.join(", ") : key.title;
974
908
  }
909
+ async function allMedusaTaxRates(context) {
910
+ const rates = [];
911
+ for (let page = 0; page < MAX_TAX_REGION_PAGES; page++) {
912
+ const offset = page * TAX_REGIONS_PAGE_SIZE;
913
+ const res = await get(context, `/admin/tax-regions?limit=${TAX_REGIONS_PAGE_SIZE}&offset=${offset}&fields=id,country_code,province_code,parent_id,*tax_rates,*tax_rates.rules`);
914
+ const regions = res.tax_regions ?? [];
915
+ for (const region of regions) {
916
+ for (const rate of region.tax_rates ?? []) {
917
+ if (rate.rate == null) continue;
918
+ rates.push({
919
+ id: rate.id,
920
+ name: rate.name || rate.code || rate.id,
921
+ rate: String(rate.rate),
922
+ // Codes as Medusa stores them (lower case); the app formats them.
923
+ location: region.province_code !== null ? { country: region.country_code, region: region.province_code } : { country: region.country_code },
924
+ ...rate.rules?.length ? { rules: rate.rules.map((r) => ({ reference: r.reference, referenceId: r.reference_id })) } : {}
925
+ });
926
+ }
927
+ }
928
+ if (regions.length < TAX_REGIONS_PAGE_SIZE || offset + regions.length >= res.count) break;
929
+ }
930
+ return rates;
931
+ }
975
932
  var medusaStoreSettings = async (context, choice) => {
976
933
  const [storeRes, regionsRes, pricePrefRes, apiKeysRes] = await Promise.all([
977
- get4(context, "/admin/stores?fields=id,default_region_id"),
978
- get4(context, "/admin/regions?limit=1000&fields=id,name,currency_code,*countries"),
979
- get4(context, "/admin/price-preferences?limit=1000"),
980
- get4(context, "/admin/api-keys?type=publishable&limit=1000&fields=id,title,token,revoked_at,sales_channels.id,sales_channels.name")
934
+ get(context, "/admin/stores?fields=id,default_region_id"),
935
+ get(context, "/admin/regions?limit=1000&fields=id,name,currency_code,*countries"),
936
+ get(context, "/admin/price-preferences?limit=1000"),
937
+ get(context, "/admin/api-keys?type=publishable&limit=1000&fields=id,title,token,revoked_at,sales_channels.id,sales_channels.name")
981
938
  ]);
982
939
  const region = resolveRegion(regionsRes.regions ?? [], storeRes.stores?.[0], choice);
983
940
  const pricePreferences = pricePrefRes.price_preferences ?? [];
@@ -988,7 +945,7 @@ var medusaStoreSettings = async (context, choice) => {
988
945
  const countryCode = chosenCountry ? countries.find((c) => c.iso_2.toLowerCase() === chosenCountry)?.iso_2 : countries.length === 1 ? countries[0].iso_2 : void 0;
989
946
  let taxRegions = [];
990
947
  if (countryCode !== void 0) {
991
- const taxRegionsRes = await get4(context, `/admin/tax-regions?country_code=${encodeURIComponent(countryCode)}&limit=1000&fields=id,country_code,province_code,*tax_rates`);
948
+ const taxRegionsRes = await get(context, `/admin/tax-regions?country_code=${encodeURIComponent(countryCode)}&limit=1000&fields=id,country_code,province_code,*tax_rates`);
992
949
  taxRegions = taxRegionsRes.tax_regions ?? [];
993
950
  }
994
951
  const apiKeys = apiKeysRes.api_keys ?? [];
@@ -1006,6 +963,7 @@ var medusaStoreSettings = async (context, choice) => {
1006
963
  const eligibleRates = (countryTaxRegion?.tax_rates ?? []).filter((r) => !r.rules || r.rules.length === 0);
1007
964
  const defaultRate = eligibleRates.find((r) => r.is_default);
1008
965
  const taxRatesPpm = { default: defaultRate?.rate != null ? Math.round(defaultRate.rate * 1e4) : 0 };
966
+ const allTaxRates = await allMedusaTaxRates(context);
1009
967
  return {
1010
968
  currency: region.currency_code.toUpperCase(),
1011
969
  pricesIncludeTax,
@@ -1016,12 +974,251 @@ var medusaStoreSettings = async (context, choice) => {
1016
974
  region_id: region.id,
1017
975
  currency_code: region.currency_code.toLowerCase(),
1018
976
  publishable_key: channelKey.token
1019
- }
977
+ },
978
+ allTaxRates
1020
979
  };
1021
980
  };
1022
981
 
982
+ // src/orders.ts
983
+ import {
984
+ assertOrderFiltersSupported,
985
+ ConnectorUnauthorizedError as ConnectorUnauthorizedError4,
986
+ CustomerServiceError as CustomerServiceError3
987
+ } from "@tallyui/core";
988
+
989
+ // src/money.ts
990
+ import { CustomerServiceError as CustomerServiceError2, minorUnitDigits as minorUnitDigits2 } from "@tallyui/core";
991
+ function decimal(value) {
992
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new CustomerServiceError2("server", "unexpected response");
993
+ const [, int = "", frac = "", exp = "0"] = /^(-?\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/.exec(String(value));
994
+ const scale = frac.length - Number(exp);
995
+ const digits = BigInt(`${int}${frac}`);
996
+ return scale >= 0 ? { digits, scale } : { digits: digits * 10n ** BigInt(-scale), scale: 0 };
997
+ }
998
+ function medusaSumMinor(currency, add, subtract = []) {
999
+ const minorDigits = minorUnitDigits2(currency);
1000
+ const terms = [...add.map((value) => [decimal(value), 1n]), ...subtract.map((value) => [decimal(value), -1n])];
1001
+ const scale = Math.max(minorDigits, ...terms.map(([term]) => term.scale));
1002
+ let total = 0n;
1003
+ for (const [term, sign] of terms) total += sign * term.digits * 10n ** BigInt(scale - term.scale);
1004
+ const divisor = 10n ** BigInt(scale - minorDigits);
1005
+ const rounded = ((total < 0n ? -total : total) + divisor / 2n) / divisor;
1006
+ return Number(total < 0n ? -rounded : rounded);
1007
+ }
1008
+ var medusaMinor = (amount, currency) => medusaSumMinor(currency, [amount]);
1009
+ var medusaNetMinor = (gross, tax, currency) => medusaSumMinor(currency, [gross], [tax]);
1010
+
1011
+ // src/orders.ts
1012
+ var MAX_PER_PAGE = 100;
1013
+ var ORDER_FIELDS = "id,display_id,status,created_at,currency_code,email,customer_id,metadata,total,subtotal,tax_total,discount_total,discount_tax_total,credit_line_total,*customer,*items,*items.tax_lines,*shipping_methods,*shipping_methods.tax_lines,*payment_collections,*payment_collections.payments,*payment_collections.payments.refunds";
1014
+ var unexpected = () => new CustomerServiceError3("server", "unexpected response");
1015
+ var isRow = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1016
+ var rows = (value) => Array.isArray(value) ? value.filter(isRow) : [];
1017
+ var nonEmpty = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
1018
+ var required = (value) => {
1019
+ if (typeof value !== "string" || value.length === 0) throw unexpected();
1020
+ return value;
1021
+ };
1022
+ function toMedusaStoreOrder(raw) {
1023
+ if (!isRow(raw) || typeof raw.created_at !== "string" || typeof raw.status !== "string") throw unexpected();
1024
+ const placed = new Date(raw.created_at);
1025
+ if (Number.isNaN(placed.getTime())) throw unexpected();
1026
+ const currency = required(raw.currency_code).toUpperCase();
1027
+ const minor = (amount) => medusaMinor(amount, currency);
1028
+ const split = (gross2, tax) => {
1029
+ const totalMinor2 = medusaNetMinor(gross2, tax, currency);
1030
+ return { totalMinor: totalMinor2, taxMinor: minor(gross2) - totalMinor2 };
1031
+ };
1032
+ const metadata = isRow(raw.metadata) ? raw.metadata : {};
1033
+ const clientOrderId = nonEmpty(metadata.tally_client_id);
1034
+ const items = rows(raw.items);
1035
+ const shippingMethods = rows(raw.shipping_methods);
1036
+ const person = isRow(raw.customer) ? raw.customer : {};
1037
+ const customerId = nonEmpty(person.id) ?? nonEmpty(raw.customer_id);
1038
+ const name = [person.first_name, person.last_name].filter((part) => typeof part === "string").join(" ").trim();
1039
+ const email = nonEmpty(person.email) ?? nonEmpty(raw.email);
1040
+ const taxGroups = /* @__PURE__ */ new Map();
1041
+ for (const taxLine of [...items, ...shippingMethods].flatMap((owner) => rows(owner.tax_lines))) {
1042
+ const { rate } = taxLine;
1043
+ if (typeof rate !== "number" || !Number.isFinite(rate)) throw unexpected();
1044
+ const code = nonEmpty(taxLine.code);
1045
+ const key = JSON.stringify([code ?? null, rate]);
1046
+ const group = taxGroups.get(key) ?? { label: nonEmpty(taxLine.description) ?? code ?? `${rate}%`, code, rate, totals: [] };
1047
+ group.totals.push(taxLine.total);
1048
+ taxGroups.set(key, group);
1049
+ }
1050
+ const gross = [raw.total, raw.credit_line_total ?? 0];
1051
+ const totalMinor = medusaSumMinor(currency, gross);
1052
+ const discount = split(raw.discount_total, raw.discount_tax_total);
1053
+ const payments = rows(raw.payment_collections).flatMap((collection) => rows(collection.payments));
1054
+ return {
1055
+ id: required(raw.id),
1056
+ reference: String(raw.display_id ?? raw.id),
1057
+ ...clientOrderId ? { clientOrderId } : {},
1058
+ status: raw.status,
1059
+ placedAt: placed.toISOString(),
1060
+ currency,
1061
+ pricesIncludeTax: items.length > 0 && items.every((item) => item.is_tax_inclusive === true),
1062
+ customer: customerId || name || email ? { ...customerId ? { id: customerId } : {}, ...name ? { name } : {}, ...email ? { email } : {} } : null,
1063
+ lines: items.map((item) => {
1064
+ const lineMetadata = isRow(item.metadata) ? item.metadata : {};
1065
+ const clientLineId = nonEmpty(lineMetadata.tally_line_uuid);
1066
+ const productId = nonEmpty(item.product_id);
1067
+ const variantId = nonEmpty(item.variant_id);
1068
+ const sku = nonEmpty(item.variant_sku);
1069
+ const { quantity } = item;
1070
+ if (typeof quantity !== "number" || !Number.isInteger(quantity) || quantity <= 0) throw unexpected();
1071
+ const before = split(item.original_total, item.original_tax_total);
1072
+ return {
1073
+ id: required(item.id),
1074
+ ...clientLineId ? { clientLineId } : {},
1075
+ ...productId ? { productId } : {},
1076
+ ...variantId ? { variantId } : {},
1077
+ name: nonEmpty(item.title) ?? nonEmpty(item.product_title) ?? "",
1078
+ ...sku ? { sku } : {},
1079
+ quantity,
1080
+ subtotalMinor: before.totalMinor,
1081
+ subtotalTaxMinor: before.taxMinor,
1082
+ ...split(item.total, item.tax_total)
1083
+ };
1084
+ }),
1085
+ fees: [],
1086
+ shipping: shippingMethods.map((method) => {
1087
+ const id = nonEmpty(method.id);
1088
+ const methodId = nonEmpty(method.shipping_option_id);
1089
+ return { ...id ? { id } : {}, name: nonEmpty(method.name) ?? "", ...split(method.total, method.tax_total), ...methodId ? { methodId } : {} };
1090
+ }),
1091
+ coupons: [],
1092
+ // Each rate's tax lines summed exactly, then rounded once.
1093
+ taxLines: [...taxGroups.values()].map(({ label, code, rate, totals }) => ({
1094
+ label,
1095
+ ...code ? { code } : {},
1096
+ ratePpm: Math.round(rate * 1e4),
1097
+ amountMinor: medusaSumMinor(currency, totals)
1098
+ })),
1099
+ discountMinor: discount.totalMinor,
1100
+ discountTaxMinor: discount.taxMinor,
1101
+ taxMinor: totalMinor - medusaSumMinor(currency, gross, [raw.tax_total]),
1102
+ totalMinor,
1103
+ payments: payments.filter((payment) => payment.canceled_at == null).map((payment) => {
1104
+ const id = nonEmpty(payment.id);
1105
+ return { ...id ? { id } : {}, method: required(payment.provider_id), amountMinor: minor(payment.amount) };
1106
+ }),
1107
+ refunds: payments.flatMap((payment) => rows(payment.refunds)).map((refund) => {
1108
+ const reason = nonEmpty(refund.note);
1109
+ return { id: required(refund.id), amountMinor: Math.abs(minor(refund.amount)), ...reason ? { reason } : {} };
1110
+ })
1111
+ };
1112
+ }
1113
+ var MEDUSA_ORDER_FILTERS = ["status", "customerId", "dateRange"];
1114
+ var MEDUSA_DISPLAY_NUMBER_MAX_DIGITS = 6;
1115
+ var MEDUSA_ORDERS_PLUGIN_CONTRACT = 3;
1116
+ var MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT = 4;
1117
+ var hasOrdersRoute = (capabilities) => (capabilities?.pluginContract ?? 0) >= MEDUSA_ORDERS_PLUGIN_CONTRACT;
1118
+ function medusaOrderFilters(capabilities) {
1119
+ return hasOrdersRoute(capabilities) ? [...MEDUSA_ORDER_FILTERS, "registerId"] : MEDUSA_ORDER_FILTERS;
1120
+ }
1121
+ async function ordersRequest(context, path, params, missing) {
1122
+ let res;
1123
+ try {
1124
+ res = await fetch(`${context.baseUrl}${path}?${params}`, { method: "GET", headers: context.headers, signal: context.signal });
1125
+ } catch (error) {
1126
+ throw new CustomerServiceError3("network", error instanceof Error ? error.message : String(error));
1127
+ }
1128
+ if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorizedError4(`Medusa rejected the credentials (HTTP ${res.status})`, res.status);
1129
+ if (res.status === 404 && missing === "null") return null;
1130
+ if (!res.ok) throw new CustomerServiceError3(res.status === 400 ? "invalid" : "server", `HTTP ${res.status}`, { status: res.status });
1131
+ const body = await res.json().catch(() => void 0);
1132
+ if (!isRow(body)) throw new CustomerServiceError3("server", "unexpected response", { status: res.status });
1133
+ return body;
1134
+ }
1135
+ var wholeNumber = (value, fallback) => value === void 0 || !Number.isFinite(value) ? fallback : Math.trunc(value);
1136
+ function readOrders(raws) {
1137
+ let unreadable = 0;
1138
+ const orders = raws.flatMap((raw) => {
1139
+ try {
1140
+ return [toMedusaStoreOrder(raw)];
1141
+ } catch (error) {
1142
+ if (!(error instanceof CustomerServiceError3)) throw error;
1143
+ unreadable += 1;
1144
+ return [];
1145
+ }
1146
+ });
1147
+ return { orders, unreadable };
1148
+ }
1149
+ var DISPLAY_NUMBER = new RegExp(`^\\d{1,${MEDUSA_DISPLAY_NUMBER_MAX_DIGITS}}$`);
1150
+ async function listThroughPlugin(context, params) {
1151
+ const found = await ordersRequest(context, "/tally/v1/orders", params);
1152
+ const { orders: hits, hasMore, total } = found;
1153
+ if (!Array.isArray(hits) || typeof hasMore !== "boolean") throw unexpected();
1154
+ const ids = hits.map((hit) => required(isRow(hit) ? hit.id : void 0));
1155
+ const counted = typeof total === "number" && Number.isInteger(total) && total >= 0 ? { total } : {};
1156
+ if (ids.length === 0) return { orders: [], hasMore, ...counted };
1157
+ const lookup = new URLSearchParams({ limit: String(ids.length), fields: ORDER_FIELDS });
1158
+ for (const id of ids) lookup.append("id[]", id);
1159
+ const body = await ordersRequest(context, "/admin/orders", lookup);
1160
+ if (!Array.isArray(body.orders)) throw unexpected();
1161
+ const byId = new Map(rows(body.orders).map((row) => [row.id, row]));
1162
+ const picked = ids.flatMap((id) => byId.get(id) ?? []);
1163
+ const { orders, unreadable } = readOrders(picked);
1164
+ const left = unreadable + ids.length - picked.length;
1165
+ return { orders, hasMore, ...left ? { unreadable: left } : {}, ...counted };
1166
+ }
1167
+ function createMedusaOrders() {
1168
+ return {
1169
+ /**
1170
+ * Newest first. Filters on the server: status (verbatim; Medusa answers an unknown word with a 500, which rejects
1171
+ * as `server`), customerId (customer_id) and dateRange (created_at[$gte] / created_at[$lt]); search is Medusa's
1172
+ * `q`. Any other filter field is refused. An empty status matches no order, so it resolves an empty page without a request.
1173
+ * Register filters and 1-6 digit searches go through the plugin's orders route at contract 3, which reads every sales channel from contract 4 (`allChannels=true`) and only the till's channel at contract 3 (#1125).
1174
+ */
1175
+ async listOrders(context, query = {}) {
1176
+ assertOrderFiltersSupported(query, medusaOrderFilters(context.capabilities));
1177
+ if (query.status === "" || query.registerId === "") return { orders: [], hasMore: false };
1178
+ const page = Math.max(1, wholeNumber(query.page, 1));
1179
+ const perPage = Math.max(1, Math.min(MAX_PER_PAGE, wholeNumber(query.perPage, 25)));
1180
+ const search = query.search?.trim();
1181
+ const { after, before } = query.dateRange ?? {};
1182
+ if (query.registerId !== void 0 || search && DISPLAY_NUMBER.test(search) && hasOrdersRoute(context.capabilities)) {
1183
+ const params2 = new URLSearchParams({ page: String(page), perPage: String(perPage) });
1184
+ if (search) params2.set("search", search);
1185
+ if (query.status !== void 0) params2.set("status", query.status);
1186
+ if (query.customerId !== void 0) params2.set("customerId", query.customerId);
1187
+ if (query.registerId !== void 0) params2.set("registerId", query.registerId);
1188
+ if (after !== void 0) params2.set("after", after);
1189
+ if (before !== void 0) params2.set("before", before);
1190
+ if ((context.capabilities?.pluginContract ?? 0) >= MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT) params2.set("allChannels", "true");
1191
+ return listThroughPlugin(context, params2);
1192
+ }
1193
+ const offset = (page - 1) * perPage;
1194
+ const params = new URLSearchParams({ limit: String(perPage), offset: String(offset), order: "-created_at", fields: ORDER_FIELDS });
1195
+ if (search) params.set("q", search);
1196
+ if (query.status !== void 0) params.set("status", query.status);
1197
+ if (query.customerId !== void 0) params.set("customer_id", query.customerId);
1198
+ if (after !== void 0) params.set("created_at[$gte]", after);
1199
+ if (before !== void 0) params.set("created_at[$lt]", before);
1200
+ const body = await ordersRequest(context, "/admin/orders", params);
1201
+ if (!Array.isArray(body.orders)) throw unexpected();
1202
+ const { orders, unreadable } = readOrders(body.orders);
1203
+ const { count } = body;
1204
+ const counted = typeof count === "number" && Number.isInteger(count) && count >= 0;
1205
+ const hasMore = counted ? offset + body.orders.length < count : body.orders.length === perPage;
1206
+ return { orders, hasMore, ...unreadable ? { unreadable } : {}, ...counted ? { total: count } : {} };
1207
+ },
1208
+ /** One request per id, in the order asked; an id the store does not have (404) is left out. */
1209
+ async getOrders(context, ids) {
1210
+ const orders = [];
1211
+ for (const id of new Set(ids.filter((id2) => id2.length > 0))) {
1212
+ const body = await ordersRequest(context, `/admin/orders/${encodeURIComponent(id)}`, new URLSearchParams({ fields: ORDER_FIELDS }), "null");
1213
+ if (body) orders.push(toMedusaStoreOrder(body.order));
1214
+ }
1215
+ return orders;
1216
+ }
1217
+ };
1218
+ }
1219
+
1023
1220
  // src/index.ts
1024
- import { ConnectorUnauthorizedError as ConnectorUnauthorizedError8 } from "@tallyui/core";
1221
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError5 } from "@tallyui/core";
1025
1222
  var medusaSecretKeyAuth = {
1026
1223
  type: "Medusa Admin API",
1027
1224
  fields: [
@@ -1139,16 +1336,23 @@ var createMedusaAdminUserConnector = () => ({
1139
1336
  searchCustomers: medusaSearchCustomers,
1140
1337
  createCustomer: medusaCreateCustomer,
1141
1338
  getCustomer: medusaGetCustomer,
1142
- updateCustomer: medusaUpdateCustomer
1339
+ updateCustomer: medusaUpdateCustomer,
1340
+ ...createMedusaOrders(),
1341
+ orderFilters: MEDUSA_ORDER_FILTERS
1143
1342
  });
1144
1343
  var medusaConnector = createMedusaConnector();
1145
1344
  var medusaAdminUserConnector = createMedusaAdminUserConnector();
1146
1345
  export {
1147
- ConnectorUnauthorizedError8 as ConnectorUnauthorizedError,
1346
+ ConnectorUnauthorizedError5 as ConnectorUnauthorizedError,
1347
+ MEDUSA_ALL_CHANNELS_PLUGIN_CONTRACT,
1148
1348
  MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS,
1349
+ MEDUSA_DISPLAY_NUMBER_MAX_DIGITS,
1350
+ MEDUSA_ORDERS_PLUGIN_CONTRACT,
1351
+ MEDUSA_ORDER_FILTERS,
1149
1352
  createMedusaAdminUserConnector,
1150
1353
  createMedusaConnector,
1151
1354
  createMedusaCustomer,
1355
+ createMedusaOrders,
1152
1356
  createMedusaVariantFeedReplication,
1153
1357
  getMedusaCustomer,
1154
1358
  medusaAdminUserAuth,
@@ -1157,6 +1361,7 @@ export {
1157
1361
  medusaConnector,
1158
1362
  medusaCreateCustomer,
1159
1363
  medusaGetCustomer,
1364
+ medusaOrderFilters,
1160
1365
  medusaProductReplication,
1161
1366
  medusaProductSchema,
1162
1367
  medusaProductSync,
@@ -1169,6 +1374,7 @@ export {
1169
1374
  medusaUpdateCustomer,
1170
1375
  searchMedusaCustomers,
1171
1376
  toCustomer,
1377
+ toMedusaStoreOrder,
1172
1378
  updateMedusaCustomer,
1173
1379
  withCalculatedPrices
1174
1380
  };