@tallyui/core 0.2.0 → 3.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chunk-C4PWPOKO.js +18 -0
  3. package/dist/commands-BW4YYgRG.d.ts +306 -0
  4. package/dist/index.d.ts +636 -8
  5. package/dist/index.js +468 -4
  6. package/dist/rxdb/index.d.ts +37 -0
  7. package/dist/rxdb/index.js +26 -0
  8. package/dist/server/index.d.ts +213 -0
  9. package/dist/server/index.js +591 -0
  10. package/package.json +33 -3
  11. package/src/commands.ts +32 -0
  12. package/src/context/connector-context.tsx +78 -4
  13. package/src/index.ts +53 -0
  14. package/src/known-warnings.ts +77 -0
  15. package/src/money.ts +142 -0
  16. package/src/replication/combine.ts +77 -0
  17. package/src/replication/reconcile-feed.ts +116 -0
  18. package/src/rxdb/index.ts +4 -0
  19. package/src/rxdb/read-fresh.ts +32 -0
  20. package/src/rxdb/watch-fresh.ts +19 -0
  21. package/src/rxdb-remote-version-mismatch.ts +30 -0
  22. package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
  23. package/src/server/__fixtures__/order-create-v3.json +97 -0
  24. package/src/server/batch-outcome.ts +19 -0
  25. package/src/server/batch.ts +112 -0
  26. package/src/server/command-result.ts +138 -0
  27. package/src/server/fingerprint.ts +18 -0
  28. package/src/server/fiscal-figures.ts +84 -0
  29. package/src/server/index.ts +20 -0
  30. package/src/server/money.ts +34 -0
  31. package/src/server/order-payload-shape.ts +112 -0
  32. package/src/server/register-figures.ts +32 -0
  33. package/src/server/register-outcome.ts +12 -0
  34. package/src/server/register-payload-shape.ts +86 -0
  35. package/src/server/rejection-codes.ts +49 -0
  36. package/src/server/total-warnings.ts +10 -0
  37. package/src/server/versions.ts +9 -0
  38. package/src/sign-in.ts +21 -0
  39. package/src/stock-overlay.ts +35 -0
  40. package/src/store-settings.ts +29 -0
  41. package/src/sync-notice.ts +26 -0
  42. package/src/types/commands.ts +236 -0
  43. package/src/types/connector.ts +127 -0
  44. package/src/types/customers.ts +26 -0
  45. package/src/types/index.ts +23 -1
  46. package/src/types/money.ts +33 -0
  47. package/src/types/reconcile.ts +73 -0
  48. package/src/types/replication.ts +12 -0
  49. package/src/types/stock.ts +18 -0
  50. package/src/types/store-settings.ts +27 -0
  51. package/src/types/traits/product.ts +62 -6
  52. package/src/unauthorized.ts +13 -0
  53. package/src/utils/compare-ids.ts +16 -0
  54. package/src/variants.ts +14 -0
  55. package/src/__tests__/connector-context.test.tsx +0 -100
  56. package/src/types/replication.test-d.ts +0 -20
@@ -1,3 +1,29 @@
1
+ import type { ProductPrice } from '../money';
2
+ import type { StockLevel } from '../stock';
3
+
4
+ /** One purchasable variant of a product, in backend-neutral terms. */
5
+ export interface VariantSummary {
6
+ /** Backend variant id; the id sent in order lines. */
7
+ id: string;
8
+ /** Variant label, e.g. 'S / White'; undefined when the backend has none. */
9
+ title?: string;
10
+ sku?: string;
11
+ /** First non-empty of the backend's barcode fields. */
12
+ barcode?: string;
13
+ prices: ProductPrice[];
14
+ stock: StockLevel;
15
+ }
16
+
17
+ /**
18
+ * Store-level facts a connector may need to interpret a raw document, for
19
+ * backends whose documents omit them (WooCommerce product prices carry no
20
+ * currency).
21
+ */
22
+ export interface TraitContext {
23
+ /** The store's ISO 4217 currency code. */
24
+ currency?: string;
25
+ }
26
+
1
27
  /**
2
28
  * Product traits — the stable interface that UI components program against.
3
29
  *
@@ -7,6 +33,10 @@
7
33
  * Vendure, Shopify, etc.
8
34
  *
9
35
  * The generic `Doc` type is the connector's raw RxDB document type.
36
+ *
37
+ * Price and stock are read through the backend-neutral `getPrices` and
38
+ * `getStock`. The older string-price and WooCommerce-style stock accessors
39
+ * remain for existing consumers and are deprecated.
10
40
  */
11
41
  export interface ProductTraits<Doc = any> {
12
42
  /** Product display name */
@@ -15,16 +45,36 @@ export interface ProductTraits<Doc = any> {
15
45
  /** SKU / stock keeping unit */
16
46
  getSku: (doc: Doc) => string | undefined;
17
47
 
18
- /** Current selling price as a string (connector-native format) */
48
+ /**
49
+ * The product's price list: base prices, plus sale prices while a sale
50
+ * applies, per currency. Pass the list to `resolvePrice` for the price to
51
+ * charge. For variable products this describes the default variant.
52
+ */
53
+ getPrices: (doc: Doc, context?: TraitContext) => ProductPrice[];
54
+
55
+ /** Stock state of the whole product across its variants; `quantity` is the total on hand when every variant is tracked, else undefined. */
56
+ getStock: (doc: Doc) => StockLevel;
57
+
58
+ /** All purchasable variants, in id order (connectors store variants sorted by id). Optional: connectors without variant support omit it. */
59
+ getVariants?: (doc: Doc, context?: TraitContext) => VariantSummary[];
60
+
61
+ /**
62
+ * The backend's tax class id for the variant `variantId`, or for the product (its default variant) when omitted.
63
+ * The id is a key of `StoreSettings.taxRatesPpm`; undefined means the default class. Optional: without it, every
64
+ * line is taxed at the default rate.
65
+ */
66
+ getTaxClass?: (doc: Doc, variantId?: string) => string | undefined;
67
+
68
+ /** @deprecated Use `getPrices` with `resolvePrice`. */
19
69
  getPrice: (doc: Doc) => string | undefined;
20
70
 
21
- /** Regular (non-sale) price */
71
+ /** Regular (non-sale) price. @deprecated Use `getPrices` with `resolvePrice`. */
22
72
  getRegularPrice: (doc: Doc) => string | undefined;
23
73
 
24
- /** Sale price, if on sale */
74
+ /** Sale price, if on sale. @deprecated Use `getPrices` with `resolvePrice`. */
25
75
  getSalePrice: (doc: Doc) => string | undefined;
26
76
 
27
- /** Whether the product is currently on sale */
77
+ /** Whether the product is currently on sale. @deprecated Use `getPrices` with `resolvePrice`. */
28
78
  isOnSale: (doc: Doc) => boolean;
29
79
 
30
80
  /** Primary image URL */
@@ -36,15 +86,21 @@ export interface ProductTraits<Doc = any> {
36
86
  /** Short description / excerpt */
37
87
  getDescription: (doc: Doc) => string | undefined;
38
88
 
39
- /** Stock status */
89
+ /** Stock status. @deprecated Use `getStock`. */
40
90
  getStockStatus: (doc: Doc) => 'instock' | 'outofstock' | 'onbackorder' | 'unknown';
41
91
 
42
- /** Stock quantity (null if not tracked) */
92
+ /** Stock quantity (null if not tracked). @deprecated Use `getStock`. */
43
93
  getStockQuantity: (doc: Doc) => number | null;
44
94
 
45
95
  /** Whether this product has variants/variations */
46
96
  hasVariants: (doc: Doc) => boolean;
47
97
 
98
+ /** Whether the product may be sold at the register now: published/active, not a draft, archived or disabled. */
99
+ isSellable: (doc: Doc) => boolean;
100
+
101
+ /** Number of purchasable variants; 1 for a simple product. */
102
+ getVariantCount: (doc: Doc) => number;
103
+
48
104
  /** Product type (simple, variable, etc. — connector-specific but useful for UI hints) */
49
105
  getType: (doc: Doc) => string;
50
106
 
@@ -0,0 +1,13 @@
1
+ /** A backend refused the stored credentials (expired, revoked or insufficient); the app should sign in again. */
2
+ export class ConnectorUnauthorizedError extends Error {
3
+ readonly code = 'unauthorized' as const;
4
+ /** Only signing in on this till fixes it, so the pull stops until `resume()` (`errorKind`). */
5
+ readonly fixedBy = 'till' as const;
6
+ readonly status?: number;
7
+
8
+ constructor(message: string, status?: number) {
9
+ super(message);
10
+ this.name = 'ConnectorUnauthorizedError';
11
+ this.status = status;
12
+ }
13
+ }
@@ -0,0 +1,16 @@
1
+ const INTEGER_STRING = /^\d+$/;
2
+
3
+ /** Orders backend ids: numerically when both are integer strings (Vendure '9' < '10', compared with BigInt so long ids stay exact), with ties in numeric value (e.g. '01' vs '1') broken by plain string order; an integer id always sorts before a non-integer one; otherwise (neither is an integer string) by plain string order (not `localeCompare`, which is locale-dependent). This is a total order, so sorting is consistent regardless of input order. */
4
+ export function compareIds(a: string | number, b: string | number): number {
5
+ const sa = String(a);
6
+ const sb = String(b);
7
+ const aNum = INTEGER_STRING.test(sa);
8
+ const bNum = INTEGER_STRING.test(sb);
9
+ if (aNum && bNum) {
10
+ const diff = BigInt(sa) - BigInt(sb);
11
+ if (diff !== 0n) return diff < 0n ? -1 : 1;
12
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
13
+ }
14
+ if (aNum !== bNum) return aNum ? -1 : 1;
15
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
16
+ }
@@ -0,0 +1,14 @@
1
+ import type { VariantSummary } from './types';
2
+
3
+ /**
4
+ * The variant whose barcode or SKU equals `code`, compared after trimming
5
+ * both sides and ignoring case. A barcode match wins over a SKU match. When
6
+ * several variants match the same way, the first one wins. Returns undefined
7
+ * for an empty code or no match.
8
+ */
9
+ export function findVariantByCode(variants: VariantSummary[], code: string): VariantSummary | undefined {
10
+ const normalized = code.trim().toLowerCase();
11
+ if (!normalized) return undefined;
12
+ return variants.find((variant) => variant.barcode?.trim().toLowerCase() === normalized)
13
+ ?? variants.find((variant) => variant.sku?.trim().toLowerCase() === normalized);
14
+ }
@@ -1,100 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { renderHook } from '@testing-library/react';
3
- import type { ReactNode } from 'react';
4
- import { ConnectorProvider, useConnector, useProductTraits } from '../context/connector-context';
5
- import type { TallyConnector } from '../types';
6
-
7
- /**
8
- * Minimal connector stub that satisfies the TallyConnector interface
9
- * just enough for context tests.
10
- */
11
- const stubConnector: TallyConnector = {
12
- id: 'test',
13
- name: 'Test Connector',
14
- description: 'Stub for testing',
15
- auth: {
16
- type: 'none',
17
- fields: [],
18
- getHeaders: () => ({}),
19
- },
20
- schemas: {
21
- products: {
22
- version: 0,
23
- primaryKey: 'id',
24
- type: 'object',
25
- properties: { id: { type: 'string', maxLength: 100 } },
26
- required: ['id'],
27
- },
28
- },
29
- traits: {
30
- product: {
31
- getId: (doc) => doc.id,
32
- getName: (doc) => doc.name,
33
- getSku: () => undefined,
34
- getPrice: () => undefined,
35
- getRegularPrice: () => undefined,
36
- getSalePrice: () => undefined,
37
- isOnSale: () => false,
38
- getImageUrl: () => undefined,
39
- getImageUrls: () => [],
40
- getDescription: () => undefined,
41
- getStockStatus: () => 'unknown',
42
- getStockQuantity: () => null,
43
- hasVariants: () => false,
44
- getType: () => 'simple',
45
- getBarcode: () => undefined,
46
- getCategoryNames: () => [],
47
- },
48
- },
49
- sync: {
50
- products: {
51
- fetchAllIds: async () => [],
52
- fetchByIds: async () => [],
53
- },
54
- },
55
- };
56
-
57
- function wrapper({ children }: { children: ReactNode }) {
58
- return <ConnectorProvider connector={stubConnector}>{children}</ConnectorProvider>;
59
- }
60
-
61
- describe('ConnectorProvider + useConnector', () => {
62
- it('provides the connector through context', () => {
63
- const { result } = renderHook(() => useConnector(), { wrapper });
64
-
65
- expect(result.current).toBe(stubConnector);
66
- expect(result.current.id).toBe('test');
67
- expect(result.current.name).toBe('Test Connector');
68
- });
69
-
70
- it('throws when useConnector is called outside a provider', () => {
71
- expect(() => {
72
- renderHook(() => useConnector());
73
- }).toThrow('useConnector() must be used within a <ConnectorProvider>');
74
- });
75
- });
76
-
77
- describe('useProductTraits', () => {
78
- it('returns the product traits from the active connector', () => {
79
- const { result } = renderHook(() => useProductTraits(), { wrapper });
80
-
81
- expect(result.current).toBe(stubConnector.traits.product);
82
- expect(typeof result.current.getName).toBe('function');
83
- expect(typeof result.current.getPrice).toBe('function');
84
- });
85
-
86
- it('traits work against a mock document', () => {
87
- const { result } = renderHook(() => useProductTraits(), { wrapper });
88
- const traits = result.current;
89
-
90
- const doc = { id: '1', name: 'Widget' };
91
- expect(traits.getName(doc)).toBe('Widget');
92
- expect(traits.getId(doc)).toBe('1');
93
- });
94
-
95
- it('throws when called outside a provider', () => {
96
- expect(() => {
97
- renderHook(() => useProductTraits());
98
- }).toThrow('useConnector() must be used within a <ConnectorProvider>');
99
- });
100
- });
@@ -1,20 +0,0 @@
1
- import { describe, expectTypeOf, it } from 'vitest';
2
- import type { ReplicationAdapter, SyncContext } from '@tallyui/core';
3
-
4
- describe('ReplicationAdapter types', () => {
5
- it('accepts a typed adapter with custom checkpoint', () => {
6
- type Product = { id: string; name: string; _deleted: boolean };
7
- type Checkpoint = { id: string; modified: string };
8
-
9
- const adapter: ReplicationAdapter<Product, Checkpoint> = {} as any;
10
-
11
- expectTypeOf(adapter.pull.handler).toBeFunction();
12
- expectTypeOf(adapter.push).toEqualTypeOf<ReplicationAdapter<Product, Checkpoint>['push']>();
13
- });
14
-
15
- it('requires _deleted on document type', () => {
16
- type Doc = { id: string; _deleted: boolean };
17
- type Adapter = ReplicationAdapter<Doc>;
18
- expectTypeOf<Adapter['pull']['handler']>().toBeFunction();
19
- });
20
- });