@simpleapps-com/augur-hooks 2.2.13 → 2.2.15

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.
@@ -0,0 +1,225 @@
1
+ // src/hooks/use-payment-flow.ts
2
+ import { useCallback, useEffect, useState } from "react";
3
+ function usePaymentFlow({
4
+ callbacks,
5
+ customerId,
6
+ billingAddress,
7
+ paymentMethod,
8
+ shippingAccepted
9
+ }) {
10
+ const [isOpen, setIsOpen] = useState(false);
11
+ const [unified, setUnified] = useState(null);
12
+ const [unifiedCc, setUnifiedCc] = useState(null);
13
+ const [unifiedResponse, setUnifiedResponse] = useState(false);
14
+ const [unifiedBilling, setUnifiedBilling] = useState(false);
15
+ const [unifiedPayment, setUnifiedPayment] = useState(null);
16
+ const [capturedBin, setCapturedBin] = useState(null);
17
+ const [editCc, setEditCc] = useState(false);
18
+ const handleBinCapture = useCallback((bin) => {
19
+ setCapturedBin(bin);
20
+ }, []);
21
+ const postUnified = useCallback(async () => {
22
+ if (!customerId) return;
23
+ try {
24
+ const result = await callbacks.transactionSetup({ customerId: String(customerId) });
25
+ if (!result) {
26
+ callbacks.toast?.error?.("Unable to initialize payment. Please try again.");
27
+ return;
28
+ }
29
+ setUnified(result);
30
+ } catch (error) {
31
+ console.error("transactionSetup failed:", error);
32
+ callbacks.toast?.error?.("Unable to initialize payment. Please try again.");
33
+ }
34
+ }, [customerId, callbacks]);
35
+ const getCardInfo = useCallback(async () => {
36
+ if (!unified?.transactionSetupId) return;
37
+ try {
38
+ const result = await callbacks.cardInfo({ transactionSetupId: unified.transactionSetupId });
39
+ if (!result) {
40
+ callbacks.toast?.error?.("Unable to verify card details. Please try again.");
41
+ return;
42
+ }
43
+ setUnifiedCc(result);
44
+ } catch (error) {
45
+ console.error("cardInfo failed:", error);
46
+ callbacks.toast?.error?.("Unable to verify card details. Please try again.");
47
+ }
48
+ }, [unified, callbacks]);
49
+ const verifyUnified = useCallback(async () => {
50
+ if (!unified?.transactionSetupId || !customerId) return;
51
+ try {
52
+ const result = await callbacks.validatePayment({
53
+ transactionSetupId: unified.transactionSetupId,
54
+ customerId: String(customerId)
55
+ });
56
+ if (!result) {
57
+ callbacks.toast?.error?.("Payment verification failed. Please try again.");
58
+ return;
59
+ }
60
+ setUnifiedResponse(result.valid);
61
+ if (result.valid) {
62
+ await getCardInfo();
63
+ }
64
+ } catch (error) {
65
+ console.error("validatePayment failed:", error);
66
+ callbacks.toast?.error?.("Payment verification failed. Please try again.");
67
+ }
68
+ }, [unified, customerId, getCardInfo, callbacks]);
69
+ const getUnifiedPayment = useCallback(async () => {
70
+ if (!unified?.transactionSetupId || !customerId) return;
71
+ try {
72
+ const result = await callbacks.accountQuery({
73
+ transactionSetupId: unified.transactionSetupId,
74
+ customerId: String(customerId)
75
+ });
76
+ if (!result) {
77
+ callbacks.toast?.error?.("Unable to retrieve payment account. Please try again.");
78
+ return;
79
+ }
80
+ const payment = capturedBin && !result.Bin ? { ...result, Bin: capturedBin } : result;
81
+ setUnifiedPayment(payment);
82
+ } catch (error) {
83
+ console.error("accountQuery failed:", error);
84
+ callbacks.toast?.error?.("Unable to retrieve payment account. Please try again.");
85
+ }
86
+ }, [unified, customerId, capturedBin, callbacks]);
87
+ const updateUnifiedBilling = useCallback(async () => {
88
+ if (!unified?.transactionSetupId || !billingAddress) return;
89
+ try {
90
+ const result = await callbacks.billingUpdate({
91
+ transactionSetupId: unified.transactionSetupId,
92
+ address1: billingAddress.address1,
93
+ address2: billingAddress.address2,
94
+ city: billingAddress.city,
95
+ state: billingAddress.state,
96
+ zip: billingAddress.postalCode
97
+ });
98
+ if (!result) {
99
+ callbacks.toast?.error?.("Billing update failed. Please try again.");
100
+ return;
101
+ }
102
+ setUnifiedBilling(true);
103
+ void getUnifiedPayment();
104
+ } catch (error) {
105
+ console.error("billingUpdate failed:", error);
106
+ callbacks.toast?.error?.("Billing update failed. Please try again.");
107
+ }
108
+ }, [unified, billingAddress, getUnifiedPayment, callbacks]);
109
+ useEffect(() => {
110
+ if (isOpen && (!shippingAccepted || paymentMethod !== "credit-card")) {
111
+ setIsOpen(false);
112
+ }
113
+ }, [isOpen, shippingAccepted, paymentMethod]);
114
+ useEffect(() => {
115
+ if (isOpen && shippingAccepted && paymentMethod === "credit-card" && unified === null) {
116
+ void postUnified();
117
+ }
118
+ }, [isOpen, shippingAccepted, paymentMethod, unified, postUnified]);
119
+ useEffect(() => {
120
+ if (!isOpen && unified !== null && shippingAccepted && paymentMethod === "credit-card") {
121
+ void verifyUnified();
122
+ }
123
+ }, [isOpen, unified, shippingAccepted, paymentMethod, verifyUnified]);
124
+ useEffect(() => {
125
+ if (unifiedResponse && billingAddress !== void 0 && unifiedCc?.transactionSetupId && paymentMethod === "credit-card") {
126
+ void updateUnifiedBilling();
127
+ }
128
+ }, [
129
+ unifiedResponse,
130
+ billingAddress,
131
+ unifiedCc?.transactionSetupId,
132
+ updateUnifiedBilling,
133
+ paymentMethod
134
+ ]);
135
+ useEffect(() => {
136
+ if (editCc) {
137
+ setIsOpen(true);
138
+ setUnified(null);
139
+ setUnifiedCc(null);
140
+ setUnifiedPayment(null);
141
+ setUnifiedBilling(false);
142
+ setUnifiedResponse(false);
143
+ setCapturedBin(null);
144
+ }
145
+ }, [editCc]);
146
+ return {
147
+ isOpen,
148
+ setIsOpen,
149
+ editCc,
150
+ setEditCc,
151
+ unified,
152
+ unifiedCc,
153
+ unifiedResponse,
154
+ unifiedBilling,
155
+ unifiedPayment,
156
+ capturedBin,
157
+ handleBinCapture
158
+ };
159
+ }
160
+
161
+ // src/hooks/use-order-readiness.ts
162
+ import { useEffect as useEffect2, useState as useState2 } from "react";
163
+ function determineOrderReadiness(params) {
164
+ if (params.customReadinessCheck) {
165
+ return params.customReadinessCheck(params);
166
+ }
167
+ if (!params.cartHdrUid) return false;
168
+ const blockers = [
169
+ params.isEditShippingInfo,
170
+ params.isEditShippingMethods,
171
+ params.isEditBillingInfo,
172
+ params.editCc,
173
+ params.shippingAddress === void 0,
174
+ params.billingAddress === void 0,
175
+ !params.shippingMethodSaved,
176
+ !params.showBillingInfoSummary,
177
+ params.processingOrder
178
+ ];
179
+ if (blockers.some(Boolean)) return false;
180
+ if (params.paymentMethod === "credit-card" && (!params.unifiedPaymentAccountId || !params.unifiedBilling)) {
181
+ return false;
182
+ }
183
+ if (!params.isFreeShipping && params.shippingFee === void 0) {
184
+ return false;
185
+ }
186
+ return true;
187
+ }
188
+ function useOrderReadiness(params) {
189
+ const [enableProcessOrderBtn, setEnableProcessOrderBtn] = useState2(false);
190
+ const [processingValidation, setProcessingValidation] = useState2(false);
191
+ useEffect2(() => {
192
+ setProcessingValidation(true);
193
+ const timeoutId = setTimeout(() => {
194
+ const ready = determineOrderReadiness(params);
195
+ setEnableProcessOrderBtn(ready);
196
+ setProcessingValidation(false);
197
+ }, 300);
198
+ return () => clearTimeout(timeoutId);
199
+ }, [
200
+ params.billingAddress,
201
+ params.shippingAddress,
202
+ params.isEditShippingInfo,
203
+ params.isEditShippingMethods,
204
+ params.isEditBillingInfo,
205
+ params.editCc,
206
+ params.isFreeShipping,
207
+ params.unifiedPaymentAccountId,
208
+ params.unifiedBilling,
209
+ params.paymentMethod,
210
+ params.processingOrder,
211
+ params.carrierId,
212
+ params.shippingFee,
213
+ params.shippingMethodSaved,
214
+ params.showBillingInfoSummary,
215
+ params.cartHdrUid
216
+ ]);
217
+ return { enableProcessOrderBtn, processingValidation };
218
+ }
219
+
220
+ export {
221
+ usePaymentFlow,
222
+ determineOrderReadiness,
223
+ useOrderReadiness
224
+ };
225
+ //# sourceMappingURL=chunk-AJ2TD5BG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-payment-flow.ts","../src/hooks/use-order-readiness.ts"],"sourcesContent":["import { useCallback, useEffect, useState } from \"react\";\nimport type {\n TTransactionSetup,\n TCardInfo,\n TPaymentValidation,\n TAccountQuery,\n TBillingUpdate,\n} from \"@simpleapps-com/augur-utils\";\n\n/** Site-specific payment action callbacks injected into usePaymentFlow. */\nexport interface PaymentFlowCallbacks {\n /** Initialize a payment session. Returns transaction setup or undefined on failure. */\n transactionSetup: (params: { customerId: string }) => Promise<TTransactionSetup | undefined>;\n /** Retrieve card details after iframe entry. */\n cardInfo: (params: { transactionSetupId: string }) => Promise<TCardInfo | undefined>;\n /** Verify card is valid. */\n validatePayment: (params: {\n transactionSetupId: string;\n customerId: string;\n }) => Promise<TPaymentValidation | undefined>;\n /** Get payment account ID. */\n accountQuery: (params: {\n transactionSetupId: string;\n customerId: string;\n }) => Promise<TAccountQuery | undefined>;\n /** Send billing address to payment processor. */\n billingUpdate: (params: {\n transactionSetupId: string;\n address1: string;\n address2?: string;\n city: string;\n state: string;\n zip: string;\n }) => Promise<TBillingUpdate | undefined>;\n /** Optional toast notification callback. */\n toast?: {\n error?: (message: string) => void;\n };\n}\n\n/** Billing address shape accepted by the payment flow. */\nexport interface PaymentBillingAddress {\n address1: string;\n address2?: string;\n city: string;\n state: string;\n postalCode: string;\n}\n\ninterface UsePaymentFlowParams {\n callbacks: PaymentFlowCallbacks;\n customerId: string | number | undefined;\n billingAddress: PaymentBillingAddress | undefined;\n paymentMethod: string;\n shippingAccepted: boolean;\n}\n\n/**\n * Manages the full Element/Unified payment lifecycle:\n * transactionSetup -> cardInfo -> validatePayment -> accountQuery -> billingUpdate\n *\n * Accepts site-specific server action callbacks so the hook has no dependency\n * on any particular server action implementation.\n *\n * @example\n * ```tsx\n * import { usePaymentFlow } from \"@simpleapps-com/augur-hooks\";\n * import { transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate } from \"@/lib/actions/payments\";\n *\n * const payment = usePaymentFlow({\n * callbacks: { transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate },\n * customerId,\n * billingAddress,\n * paymentMethod: \"credit-card\",\n * shippingAccepted: true,\n * });\n * ```\n */\nexport function usePaymentFlow({\n callbacks,\n customerId,\n billingAddress,\n paymentMethod,\n shippingAccepted,\n}: UsePaymentFlowParams) {\n const [isOpen, setIsOpen] = useState(false);\n const [unified, setUnified] = useState<TTransactionSetup | null>(null);\n const [unifiedCc, setUnifiedCc] = useState<TCardInfo | null>(null);\n const [unifiedResponse, setUnifiedResponse] = useState(false);\n const [unifiedBilling, setUnifiedBilling] = useState(false);\n const [unifiedPayment, setUnifiedPayment] = useState<TAccountQuery | null>(null);\n const [capturedBin, setCapturedBin] = useState<string | null>(null);\n const [editCc, setEditCc] = useState(false);\n\n const handleBinCapture = useCallback((bin: string) => {\n setCapturedBin(bin);\n }, []);\n\n // Step 1: Initialize payment session\n const postUnified = useCallback(async () => {\n if (!customerId) return;\n try {\n const result = await callbacks.transactionSetup({ customerId: String(customerId) });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to initialize payment. Please try again.\");\n return;\n }\n setUnified(result);\n } catch (error) {\n console.error(\"transactionSetup failed:\", error);\n callbacks.toast?.error?.(\"Unable to initialize payment. Please try again.\");\n }\n }, [customerId, callbacks]);\n\n // Step 2: Get card info after iframe entry\n const getCardInfo = useCallback(async () => {\n /* v8 ignore next -- defensive: caller (verifyUnified) already guards */\n if (!unified?.transactionSetupId) return;\n try {\n const result = await callbacks.cardInfo({ transactionSetupId: unified.transactionSetupId });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to verify card details. Please try again.\");\n return;\n }\n setUnifiedCc(result);\n } catch (error) {\n console.error(\"cardInfo failed:\", error);\n callbacks.toast?.error?.(\"Unable to verify card details. Please try again.\");\n }\n }, [unified, callbacks]);\n\n // Step 3: Validate payment\n const verifyUnified = useCallback(async () => {\n if (!unified?.transactionSetupId || !customerId) return;\n try {\n const result = await callbacks.validatePayment({\n transactionSetupId: unified.transactionSetupId,\n customerId: String(customerId),\n });\n if (!result) {\n callbacks.toast?.error?.(\"Payment verification failed. Please try again.\");\n return;\n }\n setUnifiedResponse(result.valid);\n if (result.valid) {\n await getCardInfo();\n }\n } catch (error) {\n console.error(\"validatePayment failed:\", error);\n callbacks.toast?.error?.(\"Payment verification failed. Please try again.\");\n }\n }, [unified, customerId, getCardInfo, callbacks]);\n\n // Step 4: Get payment account info\n const getUnifiedPayment = useCallback(async () => {\n if (!unified?.transactionSetupId || !customerId) return;\n try {\n const result = await callbacks.accountQuery({\n transactionSetupId: unified.transactionSetupId,\n customerId: String(customerId),\n });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to retrieve payment account. Please try again.\");\n return;\n }\n const payment = capturedBin && !result.Bin ? { ...result, Bin: capturedBin } : result;\n setUnifiedPayment(payment);\n } catch (error) {\n console.error(\"accountQuery failed:\", error);\n callbacks.toast?.error?.(\"Unable to retrieve payment account. Please try again.\");\n }\n }, [unified, customerId, capturedBin, callbacks]);\n\n // Step 5: Update billing info\n const updateUnifiedBilling = useCallback(async () => {\n /* v8 ignore next -- defensive: effect already guards billingAddress/unified */\n if (!unified?.transactionSetupId || !billingAddress) return;\n try {\n const result = await callbacks.billingUpdate({\n transactionSetupId: unified.transactionSetupId,\n address1: billingAddress.address1,\n address2: billingAddress.address2,\n city: billingAddress.city,\n state: billingAddress.state,\n zip: billingAddress.postalCode,\n });\n if (!result) {\n callbacks.toast?.error?.(\"Billing update failed. Please try again.\");\n return;\n }\n setUnifiedBilling(true);\n void getUnifiedPayment();\n } catch (error) {\n console.error(\"billingUpdate failed:\", error);\n callbacks.toast?.error?.(\"Billing update failed. Please try again.\");\n }\n }, [unified, billingAddress, getUnifiedPayment, callbacks]);\n\n // Close payment modal if preconditions are lost\n useEffect(() => {\n if (isOpen && (!shippingAccepted || paymentMethod !== \"credit-card\")) {\n setIsOpen(false);\n }\n }, [isOpen, shippingAccepted, paymentMethod]);\n\n // Initialize payment setup when modal opens with no transaction\n useEffect(() => {\n if (isOpen && shippingAccepted && paymentMethod === \"credit-card\" && unified === null) {\n void postUnified();\n }\n }, [isOpen, shippingAccepted, paymentMethod, unified, postUnified]);\n\n // Verify payment after modal closes\n useEffect(() => {\n if (!isOpen && unified !== null && shippingAccepted && paymentMethod === \"credit-card\") {\n void verifyUnified();\n }\n }, [isOpen, unified, shippingAccepted, paymentMethod, verifyUnified]);\n\n // Trigger billing update when card verified + billing address ready\n useEffect(() => {\n if (\n unifiedResponse &&\n billingAddress !== undefined &&\n unifiedCc?.transactionSetupId &&\n paymentMethod === \"credit-card\"\n ) {\n void updateUnifiedBilling();\n }\n }, [\n unifiedResponse,\n billingAddress,\n unifiedCc?.transactionSetupId,\n updateUnifiedBilling,\n paymentMethod,\n ]);\n\n // Reset all payment state when editing CC\n useEffect(() => {\n if (editCc) {\n setIsOpen(true);\n setUnified(null);\n setUnifiedCc(null);\n setUnifiedPayment(null);\n setUnifiedBilling(false);\n setUnifiedResponse(false);\n setCapturedBin(null);\n }\n }, [editCc]);\n\n return {\n isOpen,\n setIsOpen,\n editCc,\n setEditCc,\n unified,\n unifiedCc,\n unifiedResponse,\n unifiedBilling,\n unifiedPayment,\n capturedBin,\n handleBinCapture,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/** Parameters for order readiness validation. */\nexport interface OrderReadinessParams {\n cartHdrUid: string | number | undefined;\n shippingAddress: unknown;\n billingAddress: unknown;\n shippingMethodSaved: boolean;\n showBillingInfoSummary: boolean;\n processingOrder: boolean;\n paymentMethod: string;\n unifiedPaymentAccountId: string | undefined;\n unifiedBilling: boolean;\n isFreeShipping: boolean;\n carrierId: string;\n shippingFee: number | undefined;\n isEditShippingInfo: boolean;\n isEditShippingMethods: boolean;\n isEditBillingInfo: boolean;\n editCc: boolean;\n /** Site-provided function to check if the order is ready. Overrides default logic when provided. */\n customReadinessCheck?: (params: OrderReadinessParams) => boolean;\n}\n\n/**\n * Pure function that determines if an order is ready to submit.\n *\n * Checks all gates: cart exists, addresses present, shipping method saved,\n * billing shown, payment complete (for credit card), shipping fee present\n * (for non-free, non-pickup orders), and no sections being edited.\n */\nexport function determineOrderReadiness(params: OrderReadinessParams): boolean {\n if (params.customReadinessCheck) {\n return params.customReadinessCheck(params);\n }\n\n if (!params.cartHdrUid) return false;\n\n // Block if any section is being edited or addresses are missing\n const blockers = [\n params.isEditShippingInfo,\n params.isEditShippingMethods,\n params.isEditBillingInfo,\n params.editCc,\n params.shippingAddress === undefined,\n params.billingAddress === undefined,\n !params.shippingMethodSaved,\n !params.showBillingInfoSummary,\n params.processingOrder,\n ];\n if (blockers.some(Boolean)) return false;\n\n // Credit card requires completed payment flow\n if (\n params.paymentMethod === \"credit-card\" &&\n (!params.unifiedPaymentAccountId || !params.unifiedBilling)\n ) {\n return false;\n }\n\n // Non-free shipping requires a fee (unless carrier is pickup/freight)\n if (!params.isFreeShipping && params.shippingFee === undefined) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Debounced order readiness hook.\n *\n * Recomputes readiness 300ms after any dependency changes to avoid\n * excessive re-renders during rapid state transitions (e.g., typing\n * in address fields).\n */\nexport function useOrderReadiness(params: OrderReadinessParams) {\n const [enableProcessOrderBtn, setEnableProcessOrderBtn] = useState(false);\n const [processingValidation, setProcessingValidation] = useState(false);\n\n useEffect(() => {\n setProcessingValidation(true);\n\n const timeoutId = setTimeout(() => {\n const ready = determineOrderReadiness(params);\n setEnableProcessOrderBtn(ready);\n setProcessingValidation(false);\n }, 300);\n\n return () => clearTimeout(timeoutId);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n params.billingAddress,\n params.shippingAddress,\n params.isEditShippingInfo,\n params.isEditShippingMethods,\n params.isEditBillingInfo,\n params.editCc,\n params.isFreeShipping,\n params.unifiedPaymentAccountId,\n params.unifiedBilling,\n params.paymentMethod,\n params.processingOrder,\n params.carrierId,\n params.shippingFee,\n params.shippingMethodSaved,\n params.showBillingInfoSummary,\n params.cartHdrUid,\n ]);\n\n return { enableProcessOrderBtn, processingValidation };\n}\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,gBAAgB;AA8E1C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAyB;AACvB,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAS,KAAK;A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P,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,IACP,OAAO;AAAA,EACT,CAAC;AAED,SAAO,EAAE,uBAAuB,qBAAqB;AACvD;","names":["useEffect","useState"]}
@@ -141,4 +141,4 @@ export {
141
141
  executeBatchQuery,
142
142
  getCartPricingQueryOptions
143
143
  };
144
- //# sourceMappingURL=chunk-Q7OENJHD.js.map
144
+ //# sourceMappingURL=chunk-GHON6UMJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query-action-registry.ts","../src/queries/cache-helper.ts","../src/queries/stock.ts","../src/queries/batch-query.ts","../src/queries/cart-pricing.ts"],"sourcesContent":["/**\n * Lightweight registry for a query action function.\n *\n * augur-server/hooks.ts registers its queryAction as a side effect when\n * imported. augur-hooks consumers (useCartPricing, useStock, the provider)\n * read from this registry to route data through server actions automatically.\n *\n * No circular dependency: augur-server depends on augur-hooks and writes here.\n * augur-hooks reads from its own module.\n */\n\ntype QueryActionFn = (methodPath: string, ...args: unknown[]) => Promise<unknown>;\n\nlet _queryAction: QueryActionFn | null = null;\n\n/** Register a query action function (called by augur-server/hooks.ts on import). */\nexport function registerQueryAction(fn: QueryActionFn): void {\n _queryAction = fn;\n}\n\n/** Returns the registered query action, or null if none registered. */\nexport function getRegisteredQueryAction(): QueryActionFn | null {\n return _queryAction;\n}\n\n/** Clears the registered query action. Used in tests only. @internal */\nexport function clearRegisteredQueryAction(): void {\n _queryAction = null;\n}\n","import type { CacheProvider, CacheTierConfig } from \"../types\";\nimport { stableStringify } from \"@simpleapps-com/augur-core\";\n\n/**\n * FNV-1a 32-bit hash. Fast, cross-platform (no Node crypto needed).\n */\nfunction fnv1a(str: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Wraps an async function with optional Redis caching.\n *\n * - When `provider` and `tier.redis` are both set, checks Redis before\n * calling `fn`, then caches the result on miss.\n * - When either is missing, calls `fn` directly (no-op passthrough).\n *\n * @param provider Redis-compatible get/set + prefix. Undefined = skip Redis.\n * @param tier Cache tier config. Undefined or missing `redis` = skip Redis.\n * @param methodPath Dot-separated SDK method path (used as cache key segment).\n * @param fn The async function to cache (typically the SDK call).\n * @param keyArgs Values to hash for the cache key (e.g. query params).\n */\nexport async function withCache<T>(\n provider: CacheProvider | undefined,\n tier: CacheTierConfig | undefined,\n methodPath: string,\n fn: () => Promise<T>,\n ...keyArgs: unknown[]\n): Promise<T> {\n const redisTtl = tier?.redis;\n if (!provider || !redisTtl) return fn();\n\n const key = `${provider.prefix}sdk:${methodPath}:${fnv1a(stableStringify(keyArgs))}`;\n\n try {\n const cached = await provider.get(key);\n if (cached != null) return JSON.parse(cached) as T;\n } catch {\n /* Redis read error — fall through to SDK call */\n }\n\n const result = await fn();\n\n try {\n provider.set(key, JSON.stringify(result), redisTtl).catch(() => {});\n } catch {\n /* Non-serializable or write error — skip caching */\n }\n\n return result;\n}\n","import type { TStock } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\n/** Returns the React Query cache key for a stock lookup by invMastUid. */\nexport const getStockKey = (invMastUid: number | string) => {\n return [\"stock\", invMastUid] as const;\n};\n\n/** @deprecated Use createServerQueryProxy() from augur-server/hooks instead. */\nexport const getStockOptions = (\n api: AugurApiClient,\n invMastUid: number | string,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getStockKey(invMastUid),\n queryFn: async (): Promise<TStock> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"items.invMast.stock.get\",\n async () => {\n const response = await api.items.invMast.stock.get(Number(invMastUid), {\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n const stockData = response.data?.stockData ?? [];\n const companySummary = response.data?.companySummary ?? {};\n return { stockData, companySummary } as TStock;\n },\n invMastUid,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n };\n};\n","import type { QueryClient } from \"@tanstack/react-query\";\n\nexport interface BatchQueryConfig<TParam, TData> {\n params: TParam[];\n queryClient: QueryClient;\n /** Build individual cache key for a single param. */\n getItemKey: (param: TParam) => readonly unknown[];\n /** Build the string key for the result Record from a param. */\n getResultKey: (param: TParam) => string;\n /** Fetch only uncached items, return keyed Record. */\n fetchItems: (uncached: TParam[]) => Promise<Record<string, TData>>;\n /** Extract individual cache key from a fetched result entry (for seeding). */\n getSeedKey: (resultKey: string, data: TData) => readonly unknown[];\n}\n\n/**\n * Generic batch query executor.\n *\n * 1. Checks queryClient cache for each param\n * 2. Fetches only uncached items in a single batch call\n * 3. Seeds individual cache entries from the response\n * 4. Returns merged cached + fetched record\n */\nexport async function executeBatchQuery<TParam, TData>(\n config: BatchQueryConfig<TParam, TData>,\n): Promise<Record<string, TData>> {\n const { params, queryClient, getItemKey, getResultKey, fetchItems, getSeedKey } = config;\n\n if (params.length === 0) {\n return {};\n }\n\n const cached: Record<string, TData> = {};\n const uncached: TParam[] = [];\n\n for (const param of params) {\n const existing = queryClient.getQueryData<TData>(getItemKey(param));\n if (existing !== undefined) {\n cached[getResultKey(param)] = existing;\n } else {\n uncached.push(param);\n }\n }\n\n if (uncached.length === 0) {\n return cached;\n }\n\n const fetched = await fetchItems(uncached);\n\n for (const [key, data] of Object.entries(fetched)) {\n queryClient.setQueryData(getSeedKey(key, data as TData), data);\n }\n\n return { ...cached, ...fetched };\n}\n","import type { TPriceData } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\n/**\n * Generates a consistent query key for item price queries.\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n */\nexport const getItemPriceKey = (\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n) => {\n return [\"price\", itemId?.toUpperCase() || \"\", customerId, quantity] as const;\n};\n\n/**\n * Query options for item price. Accepts the SDK instance so it works\n * in both client (via provider) and server (via direct construction).\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport const getItemPriceOptions = (\n api: AugurApiClient,\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getItemPriceKey(itemId, customerId, quantity),\n queryFn: async (): Promise<TPriceData> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"pricing.priceEngine.list\",\n async () => {\n const response = await api.pricing.priceEngine.list({\n itemId: itemId?.toUpperCase() || \"\",\n customerId: Number(customerId),\n quantity,\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n return response.data;\n },\n itemId,\n customerId,\n quantity,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n };\n};\n\n/**\n * Get cart pricing query options for prefetching or parent components.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport function getCartPricingQueryOptions(\n api: AugurApiClient,\n cartLines: Array<{ itemId: string; quantity: number }>,\n customerId: string | number | undefined,\n cache?: CacheConfig,\n) {\n return cartLines.map((line) => ({\n ...getItemPriceOptions(api, line.itemId, customerId, line.quantity, cache),\n enabled: !!customerId && !!line.itemId,\n }));\n}\n"],"mappings":";AAaA,IAAI,eAAqC;AAGlC,SAAS,oBAAoB,IAAyB;AAC3D,iBAAe;AACjB;AAGO,SAAS,2B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;AAAA,QACL,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,YAAY;AACV,gBAAM,WAAW,MAAM,IAAI,QAAQ,YAAY,KAAK;AAAA,YAClD,QAAQ,QAAQ,YAAY,KAAK;AAAA,YACjC,YAAY,OAAO,UAAU;AAAA,YAC7B;AAAA,YACA,GAAI,aAAa,OAAO,EAAE,UAAU,IAAI,CAAC;AAAA,UAC3C,CAAC;AACD,iBAAO,SAAS;AAAA,QAClB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,IACA,WAAW,MAAM;AAAA,IACjB,QAAQ,MAAM;AAAA,IACd,oBAAoB;AAAA,IACpB,sBAAsB;AAAA,IACtB,MAAM,EAAE,SAAS,KAAK;AAAA,EACxB;AACF;AAOO,SAAS,2BACd,KACA,WACA,YACA,OACA;AACA,SAAO,UAAU,IAAI,CAAC,UAAU;AAAA,IAC9B,GAAG,oBAAoB,KAAK,KAAK,QAAQ,YAAY,KAAK,UAAU,KAAK;AAAA,IACzE,SAAS,CAAC,CAAC,cAAc,CAAC,CAAC,KAAK;AAAA,EAClC,EAAE;AACJ;","names":[]}
@@ -0,0 +1,225 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/hooks/use-payment-flow.ts
2
+ var _react = require('react');
3
+ function usePaymentFlow({
4
+ callbacks,
5
+ customerId,
6
+ billingAddress,
7
+ paymentMethod,
8
+ shippingAccepted
9
+ }) {
10
+ const [isOpen, setIsOpen] = _react.useState.call(void 0, false);
11
+ const [unified, setUnified] = _react.useState.call(void 0, null);
12
+ const [unifiedCc, setUnifiedCc] = _react.useState.call(void 0, null);
13
+ const [unifiedResponse, setUnifiedResponse] = _react.useState.call(void 0, false);
14
+ const [unifiedBilling, setUnifiedBilling] = _react.useState.call(void 0, false);
15
+ const [unifiedPayment, setUnifiedPayment] = _react.useState.call(void 0, null);
16
+ const [capturedBin, setCapturedBin] = _react.useState.call(void 0, null);
17
+ const [editCc, setEditCc] = _react.useState.call(void 0, false);
18
+ const handleBinCapture = _react.useCallback.call(void 0, (bin) => {
19
+ setCapturedBin(bin);
20
+ }, []);
21
+ const postUnified = _react.useCallback.call(void 0, async () => {
22
+ if (!customerId) return;
23
+ try {
24
+ const result = await callbacks.transactionSetup({ customerId: String(customerId) });
25
+ if (!result) {
26
+ _optionalChain([callbacks, 'access', _ => _.toast, 'optionalAccess', _2 => _2.error, 'optionalCall', _3 => _3("Unable to initialize payment. Please try again.")]);
27
+ return;
28
+ }
29
+ setUnified(result);
30
+ } catch (error) {
31
+ console.error("transactionSetup failed:", error);
32
+ _optionalChain([callbacks, 'access', _4 => _4.toast, 'optionalAccess', _5 => _5.error, 'optionalCall', _6 => _6("Unable to initialize payment. Please try again.")]);
33
+ }
34
+ }, [customerId, callbacks]);
35
+ const getCardInfo = _react.useCallback.call(void 0, async () => {
36
+ if (!_optionalChain([unified, 'optionalAccess', _7 => _7.transactionSetupId])) return;
37
+ try {
38
+ const result = await callbacks.cardInfo({ transactionSetupId: unified.transactionSetupId });
39
+ if (!result) {
40
+ _optionalChain([callbacks, 'access', _8 => _8.toast, 'optionalAccess', _9 => _9.error, 'optionalCall', _10 => _10("Unable to verify card details. Please try again.")]);
41
+ return;
42
+ }
43
+ setUnifiedCc(result);
44
+ } catch (error) {
45
+ console.error("cardInfo failed:", error);
46
+ _optionalChain([callbacks, 'access', _11 => _11.toast, 'optionalAccess', _12 => _12.error, 'optionalCall', _13 => _13("Unable to verify card details. Please try again.")]);
47
+ }
48
+ }, [unified, callbacks]);
49
+ const verifyUnified = _react.useCallback.call(void 0, async () => {
50
+ if (!_optionalChain([unified, 'optionalAccess', _14 => _14.transactionSetupId]) || !customerId) return;
51
+ try {
52
+ const result = await callbacks.validatePayment({
53
+ transactionSetupId: unified.transactionSetupId,
54
+ customerId: String(customerId)
55
+ });
56
+ if (!result) {
57
+ _optionalChain([callbacks, 'access', _15 => _15.toast, 'optionalAccess', _16 => _16.error, 'optionalCall', _17 => _17("Payment verification failed. Please try again.")]);
58
+ return;
59
+ }
60
+ setUnifiedResponse(result.valid);
61
+ if (result.valid) {
62
+ await getCardInfo();
63
+ }
64
+ } catch (error) {
65
+ console.error("validatePayment failed:", error);
66
+ _optionalChain([callbacks, 'access', _18 => _18.toast, 'optionalAccess', _19 => _19.error, 'optionalCall', _20 => _20("Payment verification failed. Please try again.")]);
67
+ }
68
+ }, [unified, customerId, getCardInfo, callbacks]);
69
+ const getUnifiedPayment = _react.useCallback.call(void 0, async () => {
70
+ if (!_optionalChain([unified, 'optionalAccess', _21 => _21.transactionSetupId]) || !customerId) return;
71
+ try {
72
+ const result = await callbacks.accountQuery({
73
+ transactionSetupId: unified.transactionSetupId,
74
+ customerId: String(customerId)
75
+ });
76
+ if (!result) {
77
+ _optionalChain([callbacks, 'access', _22 => _22.toast, 'optionalAccess', _23 => _23.error, 'optionalCall', _24 => _24("Unable to retrieve payment account. Please try again.")]);
78
+ return;
79
+ }
80
+ const payment = capturedBin && !result.Bin ? { ...result, Bin: capturedBin } : result;
81
+ setUnifiedPayment(payment);
82
+ } catch (error) {
83
+ console.error("accountQuery failed:", error);
84
+ _optionalChain([callbacks, 'access', _25 => _25.toast, 'optionalAccess', _26 => _26.error, 'optionalCall', _27 => _27("Unable to retrieve payment account. Please try again.")]);
85
+ }
86
+ }, [unified, customerId, capturedBin, callbacks]);
87
+ const updateUnifiedBilling = _react.useCallback.call(void 0, async () => {
88
+ if (!_optionalChain([unified, 'optionalAccess', _28 => _28.transactionSetupId]) || !billingAddress) return;
89
+ try {
90
+ const result = await callbacks.billingUpdate({
91
+ transactionSetupId: unified.transactionSetupId,
92
+ address1: billingAddress.address1,
93
+ address2: billingAddress.address2,
94
+ city: billingAddress.city,
95
+ state: billingAddress.state,
96
+ zip: billingAddress.postalCode
97
+ });
98
+ if (!result) {
99
+ _optionalChain([callbacks, 'access', _29 => _29.toast, 'optionalAccess', _30 => _30.error, 'optionalCall', _31 => _31("Billing update failed. Please try again.")]);
100
+ return;
101
+ }
102
+ setUnifiedBilling(true);
103
+ void getUnifiedPayment();
104
+ } catch (error) {
105
+ console.error("billingUpdate failed:", error);
106
+ _optionalChain([callbacks, 'access', _32 => _32.toast, 'optionalAccess', _33 => _33.error, 'optionalCall', _34 => _34("Billing update failed. Please try again.")]);
107
+ }
108
+ }, [unified, billingAddress, getUnifiedPayment, callbacks]);
109
+ _react.useEffect.call(void 0, () => {
110
+ if (isOpen && (!shippingAccepted || paymentMethod !== "credit-card")) {
111
+ setIsOpen(false);
112
+ }
113
+ }, [isOpen, shippingAccepted, paymentMethod]);
114
+ _react.useEffect.call(void 0, () => {
115
+ if (isOpen && shippingAccepted && paymentMethod === "credit-card" && unified === null) {
116
+ void postUnified();
117
+ }
118
+ }, [isOpen, shippingAccepted, paymentMethod, unified, postUnified]);
119
+ _react.useEffect.call(void 0, () => {
120
+ if (!isOpen && unified !== null && shippingAccepted && paymentMethod === "credit-card") {
121
+ void verifyUnified();
122
+ }
123
+ }, [isOpen, unified, shippingAccepted, paymentMethod, verifyUnified]);
124
+ _react.useEffect.call(void 0, () => {
125
+ if (unifiedResponse && billingAddress !== void 0 && _optionalChain([unifiedCc, 'optionalAccess', _35 => _35.transactionSetupId]) && paymentMethod === "credit-card") {
126
+ void updateUnifiedBilling();
127
+ }
128
+ }, [
129
+ unifiedResponse,
130
+ billingAddress,
131
+ _optionalChain([unifiedCc, 'optionalAccess', _36 => _36.transactionSetupId]),
132
+ updateUnifiedBilling,
133
+ paymentMethod
134
+ ]);
135
+ _react.useEffect.call(void 0, () => {
136
+ if (editCc) {
137
+ setIsOpen(true);
138
+ setUnified(null);
139
+ setUnifiedCc(null);
140
+ setUnifiedPayment(null);
141
+ setUnifiedBilling(false);
142
+ setUnifiedResponse(false);
143
+ setCapturedBin(null);
144
+ }
145
+ }, [editCc]);
146
+ return {
147
+ isOpen,
148
+ setIsOpen,
149
+ editCc,
150
+ setEditCc,
151
+ unified,
152
+ unifiedCc,
153
+ unifiedResponse,
154
+ unifiedBilling,
155
+ unifiedPayment,
156
+ capturedBin,
157
+ handleBinCapture
158
+ };
159
+ }
160
+
161
+ // src/hooks/use-order-readiness.ts
162
+
163
+ function determineOrderReadiness(params) {
164
+ if (params.customReadinessCheck) {
165
+ return params.customReadinessCheck(params);
166
+ }
167
+ if (!params.cartHdrUid) return false;
168
+ const blockers = [
169
+ params.isEditShippingInfo,
170
+ params.isEditShippingMethods,
171
+ params.isEditBillingInfo,
172
+ params.editCc,
173
+ params.shippingAddress === void 0,
174
+ params.billingAddress === void 0,
175
+ !params.shippingMethodSaved,
176
+ !params.showBillingInfoSummary,
177
+ params.processingOrder
178
+ ];
179
+ if (blockers.some(Boolean)) return false;
180
+ if (params.paymentMethod === "credit-card" && (!params.unifiedPaymentAccountId || !params.unifiedBilling)) {
181
+ return false;
182
+ }
183
+ if (!params.isFreeShipping && params.shippingFee === void 0) {
184
+ return false;
185
+ }
186
+ return true;
187
+ }
188
+ function useOrderReadiness(params) {
189
+ const [enableProcessOrderBtn, setEnableProcessOrderBtn] = _react.useState.call(void 0, false);
190
+ const [processingValidation, setProcessingValidation] = _react.useState.call(void 0, false);
191
+ _react.useEffect.call(void 0, () => {
192
+ setProcessingValidation(true);
193
+ const timeoutId = setTimeout(() => {
194
+ const ready = determineOrderReadiness(params);
195
+ setEnableProcessOrderBtn(ready);
196
+ setProcessingValidation(false);
197
+ }, 300);
198
+ return () => clearTimeout(timeoutId);
199
+ }, [
200
+ params.billingAddress,
201
+ params.shippingAddress,
202
+ params.isEditShippingInfo,
203
+ params.isEditShippingMethods,
204
+ params.isEditBillingInfo,
205
+ params.editCc,
206
+ params.isFreeShipping,
207
+ params.unifiedPaymentAccountId,
208
+ params.unifiedBilling,
209
+ params.paymentMethod,
210
+ params.processingOrder,
211
+ params.carrierId,
212
+ params.shippingFee,
213
+ params.shippingMethodSaved,
214
+ params.showBillingInfoSummary,
215
+ params.cartHdrUid
216
+ ]);
217
+ return { enableProcessOrderBtn, processingValidation };
218
+ }
219
+
220
+
221
+
222
+
223
+
224
+ exports.usePaymentFlow = usePaymentFlow; exports.determineOrderReadiness = determineOrderReadiness; exports.useOrderReadiness = useOrderReadiness;
225
+ //# sourceMappingURL=chunk-SSOW6W53.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/augur-packages/augur-packages/packages/augur-hooks/dist/chunk-SSOW6W53.cjs","../src/hooks/use-payment-flow.ts","../src/hooks/use-order-readiness.ts"],"names":["useState","useEffect"],"mappings":"AAAA;ACAA,8BAAiD;AA8E1C,SAAS,cAAA,CAAe;AAAA,EAC7B,SAAA;AAAA,EACA,UAAA;AAAA,EACA,cAAA;AAAA,EACA,aAAA;AAAA,EACA;AACF,CAAA,EAAyB;AACvB,EAAA,MAAM,CAAC,MAAA,EAAQ,SAAS,EAAA,EAAI,6BAAA,KAAc,CAAA;AAC1C,EAAA,MAAM,CAAC,OAAA,EAAS,UAAU,EAAA,EAAI,6BAAA,IAAuC,CAAA;AACrE,EAAA,MAAM,CAAC,SAAA,EAAW,YAAY,EAAA,EAAI,6BAAA,IAA+B,CAAA;AACjE,EAAA,MAAM,CAAC,eAAA,EAAiB,kBAAkB,EAAA,EAAI,6BAAA,KAAc,CAAA;AAC5D,EAAA,MAAM,CAAC,cAAA,EAAgB,iBAAiB,EAAA,EAAI,6BAAA,KAAc,CAAA;AAC1D,EAAA,MAAM,CAAC,cAAA,EAAgB,iBAAiB,EAAA,EAAI,6BAAA,IAAmC,CAAA;AAC/E,EAAA,MAAM,CAAC,WAAA,EAAa,cAAc,EAAA,EAAI,6B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xE,EAAA,MAAM,CAAC,oBAAA,EAAsB,uBAAuB,EAAA,EAAIA,6BAAAA,KAAc,CAAA;AAEtE,EAAAC,8BAAAA,CAAU,EAAA,GAAM;AACd,IAAA,uBAAA,CAAwB,IAAI,CAAA;AAE5B,IAAA,MAAM,UAAA,EAAY,UAAA,CAAW,CAAA,EAAA,GAAM;AACjC,MAAA,MAAM,MAAA,EAAQ,uBAAA,CAAwB,MAAM,CAAA;AAC5C,MAAA,wBAAA,CAAyB,KAAK,CAAA;AAC9B,MAAA,uBAAA,CAAwB,KAAK,CAAA;AAAA,IAC/B,CAAA,EAAG,GAAG,CAAA;AAEN,IAAA,OAAO,CAAA,EAAA,GAAM,YAAA,CAAa,SAAS,CAAA;AAAA,EAErC,CAAA,EAAG;AAAA,IACD,MAAA,CAAO,cAAA;AAAA,IACP,MAAA,CAAO,eAAA;AAAA,IACP,MAAA,CAAO,kBAAA;AAAA,IACP,MAAA,CAAO,qBAAA;AAAA,IACP,MAAA,CAAO,iBAAA;AAAA,IACP,MAAA,CAAO,MAAA;AAAA,IACP,MAAA,CAAO,cAAA;AAAA,IACP,MAAA,CAAO,uBAAA;AAAA,IACP,MAAA,CAAO,cAAA;AAAA,IACP,MAAA,CAAO,aAAA;AAAA,IACP,MAAA,CAAO,eAAA;AAAA,IACP,MAAA,CAAO,SAAA;AAAA,IACP,MAAA,CAAO,WAAA;AAAA,IACP,MAAA,CAAO,mBAAA;AAAA,IACP,MAAA,CAAO,sBAAA;AAAA,IACP,MAAA,CAAO;AAAA,EACT,CAAC,CAAA;AAED,EAAA,OAAO,EAAE,qBAAA,EAAuB,qBAAqB,CAAA;AACvD;AF0GA;AACA;AACE;AACA;AACA;AACF,kJAAC","file":"/home/runner/work/augur-packages/augur-packages/packages/augur-hooks/dist/chunk-SSOW6W53.cjs","sourcesContent":[null,"import { useCallback, useEffect, useState } from \"react\";\nimport type {\n TTransactionSetup,\n TCardInfo,\n TPaymentValidation,\n TAccountQuery,\n TBillingUpdate,\n} from \"@simpleapps-com/augur-utils\";\n\n/** Site-specific payment action callbacks injected into usePaymentFlow. */\nexport interface PaymentFlowCallbacks {\n /** Initialize a payment session. Returns transaction setup or undefined on failure. */\n transactionSetup: (params: { customerId: string }) => Promise<TTransactionSetup | undefined>;\n /** Retrieve card details after iframe entry. */\n cardInfo: (params: { transactionSetupId: string }) => Promise<TCardInfo | undefined>;\n /** Verify card is valid. */\n validatePayment: (params: {\n transactionSetupId: string;\n customerId: string;\n }) => Promise<TPaymentValidation | undefined>;\n /** Get payment account ID. */\n accountQuery: (params: {\n transactionSetupId: string;\n customerId: string;\n }) => Promise<TAccountQuery | undefined>;\n /** Send billing address to payment processor. */\n billingUpdate: (params: {\n transactionSetupId: string;\n address1: string;\n address2?: string;\n city: string;\n state: string;\n zip: string;\n }) => Promise<TBillingUpdate | undefined>;\n /** Optional toast notification callback. */\n toast?: {\n error?: (message: string) => void;\n };\n}\n\n/** Billing address shape accepted by the payment flow. */\nexport interface PaymentBillingAddress {\n address1: string;\n address2?: string;\n city: string;\n state: string;\n postalCode: string;\n}\n\ninterface UsePaymentFlowParams {\n callbacks: PaymentFlowCallbacks;\n customerId: string | number | undefined;\n billingAddress: PaymentBillingAddress | undefined;\n paymentMethod: string;\n shippingAccepted: boolean;\n}\n\n/**\n * Manages the full Element/Unified payment lifecycle:\n * transactionSetup -> cardInfo -> validatePayment -> accountQuery -> billingUpdate\n *\n * Accepts site-specific server action callbacks so the hook has no dependency\n * on any particular server action implementation.\n *\n * @example\n * ```tsx\n * import { usePaymentFlow } from \"@simpleapps-com/augur-hooks\";\n * import { transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate } from \"@/lib/actions/payments\";\n *\n * const payment = usePaymentFlow({\n * callbacks: { transactionSetup, cardInfo, validatePayment, accountQuery, billingUpdate },\n * customerId,\n * billingAddress,\n * paymentMethod: \"credit-card\",\n * shippingAccepted: true,\n * });\n * ```\n */\nexport function usePaymentFlow({\n callbacks,\n customerId,\n billingAddress,\n paymentMethod,\n shippingAccepted,\n}: UsePaymentFlowParams) {\n const [isOpen, setIsOpen] = useState(false);\n const [unified, setUnified] = useState<TTransactionSetup | null>(null);\n const [unifiedCc, setUnifiedCc] = useState<TCardInfo | null>(null);\n const [unifiedResponse, setUnifiedResponse] = useState(false);\n const [unifiedBilling, setUnifiedBilling] = useState(false);\n const [unifiedPayment, setUnifiedPayment] = useState<TAccountQuery | null>(null);\n const [capturedBin, setCapturedBin] = useState<string | null>(null);\n const [editCc, setEditCc] = useState(false);\n\n const handleBinCapture = useCallback((bin: string) => {\n setCapturedBin(bin);\n }, []);\n\n // Step 1: Initialize payment session\n const postUnified = useCallback(async () => {\n if (!customerId) return;\n try {\n const result = await callbacks.transactionSetup({ customerId: String(customerId) });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to initialize payment. Please try again.\");\n return;\n }\n setUnified(result);\n } catch (error) {\n console.error(\"transactionSetup failed:\", error);\n callbacks.toast?.error?.(\"Unable to initialize payment. Please try again.\");\n }\n }, [customerId, callbacks]);\n\n // Step 2: Get card info after iframe entry\n const getCardInfo = useCallback(async () => {\n /* v8 ignore next -- defensive: caller (verifyUnified) already guards */\n if (!unified?.transactionSetupId) return;\n try {\n const result = await callbacks.cardInfo({ transactionSetupId: unified.transactionSetupId });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to verify card details. Please try again.\");\n return;\n }\n setUnifiedCc(result);\n } catch (error) {\n console.error(\"cardInfo failed:\", error);\n callbacks.toast?.error?.(\"Unable to verify card details. Please try again.\");\n }\n }, [unified, callbacks]);\n\n // Step 3: Validate payment\n const verifyUnified = useCallback(async () => {\n if (!unified?.transactionSetupId || !customerId) return;\n try {\n const result = await callbacks.validatePayment({\n transactionSetupId: unified.transactionSetupId,\n customerId: String(customerId),\n });\n if (!result) {\n callbacks.toast?.error?.(\"Payment verification failed. Please try again.\");\n return;\n }\n setUnifiedResponse(result.valid);\n if (result.valid) {\n await getCardInfo();\n }\n } catch (error) {\n console.error(\"validatePayment failed:\", error);\n callbacks.toast?.error?.(\"Payment verification failed. Please try again.\");\n }\n }, [unified, customerId, getCardInfo, callbacks]);\n\n // Step 4: Get payment account info\n const getUnifiedPayment = useCallback(async () => {\n if (!unified?.transactionSetupId || !customerId) return;\n try {\n const result = await callbacks.accountQuery({\n transactionSetupId: unified.transactionSetupId,\n customerId: String(customerId),\n });\n if (!result) {\n callbacks.toast?.error?.(\"Unable to retrieve payment account. Please try again.\");\n return;\n }\n const payment = capturedBin && !result.Bin ? { ...result, Bin: capturedBin } : result;\n setUnifiedPayment(payment);\n } catch (error) {\n console.error(\"accountQuery failed:\", error);\n callbacks.toast?.error?.(\"Unable to retrieve payment account. Please try again.\");\n }\n }, [unified, customerId, capturedBin, callbacks]);\n\n // Step 5: Update billing info\n const updateUnifiedBilling = useCallback(async () => {\n /* v8 ignore next -- defensive: effect already guards billingAddress/unified */\n if (!unified?.transactionSetupId || !billingAddress) return;\n try {\n const result = await callbacks.billingUpdate({\n transactionSetupId: unified.transactionSetupId,\n address1: billingAddress.address1,\n address2: billingAddress.address2,\n city: billingAddress.city,\n state: billingAddress.state,\n zip: billingAddress.postalCode,\n });\n if (!result) {\n callbacks.toast?.error?.(\"Billing update failed. Please try again.\");\n return;\n }\n setUnifiedBilling(true);\n void getUnifiedPayment();\n } catch (error) {\n console.error(\"billingUpdate failed:\", error);\n callbacks.toast?.error?.(\"Billing update failed. Please try again.\");\n }\n }, [unified, billingAddress, getUnifiedPayment, callbacks]);\n\n // Close payment modal if preconditions are lost\n useEffect(() => {\n if (isOpen && (!shippingAccepted || paymentMethod !== \"credit-card\")) {\n setIsOpen(false);\n }\n }, [isOpen, shippingAccepted, paymentMethod]);\n\n // Initialize payment setup when modal opens with no transaction\n useEffect(() => {\n if (isOpen && shippingAccepted && paymentMethod === \"credit-card\" && unified === null) {\n void postUnified();\n }\n }, [isOpen, shippingAccepted, paymentMethod, unified, postUnified]);\n\n // Verify payment after modal closes\n useEffect(() => {\n if (!isOpen && unified !== null && shippingAccepted && paymentMethod === \"credit-card\") {\n void verifyUnified();\n }\n }, [isOpen, unified, shippingAccepted, paymentMethod, verifyUnified]);\n\n // Trigger billing update when card verified + billing address ready\n useEffect(() => {\n if (\n unifiedResponse &&\n billingAddress !== undefined &&\n unifiedCc?.transactionSetupId &&\n paymentMethod === \"credit-card\"\n ) {\n void updateUnifiedBilling();\n }\n }, [\n unifiedResponse,\n billingAddress,\n unifiedCc?.transactionSetupId,\n updateUnifiedBilling,\n paymentMethod,\n ]);\n\n // Reset all payment state when editing CC\n useEffect(() => {\n if (editCc) {\n setIsOpen(true);\n setUnified(null);\n setUnifiedCc(null);\n setUnifiedPayment(null);\n setUnifiedBilling(false);\n setUnifiedResponse(false);\n setCapturedBin(null);\n }\n }, [editCc]);\n\n return {\n isOpen,\n setIsOpen,\n editCc,\n setEditCc,\n unified,\n unifiedCc,\n unifiedResponse,\n unifiedBilling,\n unifiedPayment,\n capturedBin,\n handleBinCapture,\n };\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/** Parameters for order readiness validation. */\nexport interface OrderReadinessParams {\n cartHdrUid: string | number | undefined;\n shippingAddress: unknown;\n billingAddress: unknown;\n shippingMethodSaved: boolean;\n showBillingInfoSummary: boolean;\n processingOrder: boolean;\n paymentMethod: string;\n unifiedPaymentAccountId: string | undefined;\n unifiedBilling: boolean;\n isFreeShipping: boolean;\n carrierId: string;\n shippingFee: number | undefined;\n isEditShippingInfo: boolean;\n isEditShippingMethods: boolean;\n isEditBillingInfo: boolean;\n editCc: boolean;\n /** Site-provided function to check if the order is ready. Overrides default logic when provided. */\n customReadinessCheck?: (params: OrderReadinessParams) => boolean;\n}\n\n/**\n * Pure function that determines if an order is ready to submit.\n *\n * Checks all gates: cart exists, addresses present, shipping method saved,\n * billing shown, payment complete (for credit card), shipping fee present\n * (for non-free, non-pickup orders), and no sections being edited.\n */\nexport function determineOrderReadiness(params: OrderReadinessParams): boolean {\n if (params.customReadinessCheck) {\n return params.customReadinessCheck(params);\n }\n\n if (!params.cartHdrUid) return false;\n\n // Block if any section is being edited or addresses are missing\n const blockers = [\n params.isEditShippingInfo,\n params.isEditShippingMethods,\n params.isEditBillingInfo,\n params.editCc,\n params.shippingAddress === undefined,\n params.billingAddress === undefined,\n !params.shippingMethodSaved,\n !params.showBillingInfoSummary,\n params.processingOrder,\n ];\n if (blockers.some(Boolean)) return false;\n\n // Credit card requires completed payment flow\n if (\n params.paymentMethod === \"credit-card\" &&\n (!params.unifiedPaymentAccountId || !params.unifiedBilling)\n ) {\n return false;\n }\n\n // Non-free shipping requires a fee (unless carrier is pickup/freight)\n if (!params.isFreeShipping && params.shippingFee === undefined) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Debounced order readiness hook.\n *\n * Recomputes readiness 300ms after any dependency changes to avoid\n * excessive re-renders during rapid state transitions (e.g., typing\n * in address fields).\n */\nexport function useOrderReadiness(params: OrderReadinessParams) {\n const [enableProcessOrderBtn, setEnableProcessOrderBtn] = useState(false);\n const [processingValidation, setProcessingValidation] = useState(false);\n\n useEffect(() => {\n setProcessingValidation(true);\n\n const timeoutId = setTimeout(() => {\n const ready = determineOrderReadiness(params);\n setEnableProcessOrderBtn(ready);\n setProcessingValidation(false);\n }, 300);\n\n return () => clearTimeout(timeoutId);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n params.billingAddress,\n params.shippingAddress,\n params.isEditShippingInfo,\n params.isEditShippingMethods,\n params.isEditBillingInfo,\n params.editCc,\n params.isFreeShipping,\n params.unifiedPaymentAccountId,\n params.unifiedBilling,\n params.paymentMethod,\n params.processingOrder,\n params.carrierId,\n params.shippingFee,\n params.shippingMethodSaved,\n params.showBillingInfoSummary,\n params.cartHdrUid,\n ]);\n\n return { enableProcessOrderBtn, processingValidation };\n}\n"]}
@@ -141,4 +141,4 @@ function getCartPricingQueryOptions(api, cartLines, customerId, cache) {
141
141
 
142
142
 
143
143
  exports.registerQueryAction = registerQueryAction; exports.getRegisteredQueryAction = getRegisteredQueryAction; exports.getStockKey = getStockKey; exports.getStockOptions = getStockOptions; exports.executeBatchQuery = executeBatchQuery; exports.getCartPricingQueryOptions = getCartPricingQueryOptions;
144
- //# sourceMappingURL=chunk-PBKAAR53.cjs.map
144
+ //# sourceMappingURL=chunk-XJJ6DZDK.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/augur-packages/augur-packages/packages/augur-hooks/dist/chunk-XJJ6DZDK.cjs","../src/query-action-registry.ts","../src/queries/cache-helper.ts","../src/queries/stock.ts","../src/queries/batch-query.ts","../src/queries/cart-pricing.ts"],"names":[],"mappings":"AAAA;ACaA,IAAI,aAAA,EAAqC,IAAA;AAGlC,SAAS,mBAAA,CAAoB,EAAA,EAAyB;AAC3D,EAAA,aAAA,EAAe,EAAA;AACjB;AAGO,SAAS,wBAAA,CAAA,EAAiD;AAC/D,EAAA,OAAO,YAAA;AACT;ADfA;AACA;AERA,uDAAgC;AAKhC,SAAS,KAAA,CAAM,GAAA,EAAqB;AAClC,EAAA,IAAI,EAAA,EAAI,UAAA;AACR,EAAA,IAAA,CAAA,IAAS,EAAA,EAAI,CAAA,EAAG,EAAA,EAAI,GAAA,CAAI,MAAA,EAAQ,CAAA,EAAA,EAAK;AACnC,IAAA,EAAA,GAAK,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA;AACrB,IAAA,EAAA,EAAI,IAAA,CAAK,IAAA,CAAK,CAAA,EAAG,QAAU,CAAA;AAAA,EAC7B;AACA,EAAA,OAAA,CAAQ,EAAA,IAAM,CAAA,CAAA,CAAG,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAA;AAC/C;AAeA,MAAA,SAAsB,SAAA,CACpB,QAAA,EACA,IAAA,EACA,UAAA,EACA,EAAA,EAAA,GACG,OAAA,EACS;AACZ,EAAA,MAAM,SAAA,kBAAW,IAAA,2BAAM,OAAA;AACvB,EAAA,GAAA,CAAI,CAAC,SAAA,GAAY,CAAC,QAAA,EAA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;AACA;AACA;AACA;AACA","file":"/home/runner/work/augur-packages/augur-packages/packages/augur-hooks/dist/chunk-XJJ6DZDK.cjs","sourcesContent":[null,"/**\n * Lightweight registry for a query action function.\n *\n * augur-server/hooks.ts registers its queryAction as a side effect when\n * imported. augur-hooks consumers (useCartPricing, useStock, the provider)\n * read from this registry to route data through server actions automatically.\n *\n * No circular dependency: augur-server depends on augur-hooks and writes here.\n * augur-hooks reads from its own module.\n */\n\ntype QueryActionFn = (methodPath: string, ...args: unknown[]) => Promise<unknown>;\n\nlet _queryAction: QueryActionFn | null = null;\n\n/** Register a query action function (called by augur-server/hooks.ts on import). */\nexport function registerQueryAction(fn: QueryActionFn): void {\n _queryAction = fn;\n}\n\n/** Returns the registered query action, or null if none registered. */\nexport function getRegisteredQueryAction(): QueryActionFn | null {\n return _queryAction;\n}\n\n/** Clears the registered query action. Used in tests only. @internal */\nexport function clearRegisteredQueryAction(): void {\n _queryAction = null;\n}\n","import type { CacheProvider, CacheTierConfig } from \"../types\";\nimport { stableStringify } from \"@simpleapps-com/augur-core\";\n\n/**\n * FNV-1a 32-bit hash. Fast, cross-platform (no Node crypto needed).\n */\nfunction fnv1a(str: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Wraps an async function with optional Redis caching.\n *\n * - When `provider` and `tier.redis` are both set, checks Redis before\n * calling `fn`, then caches the result on miss.\n * - When either is missing, calls `fn` directly (no-op passthrough).\n *\n * @param provider Redis-compatible get/set + prefix. Undefined = skip Redis.\n * @param tier Cache tier config. Undefined or missing `redis` = skip Redis.\n * @param methodPath Dot-separated SDK method path (used as cache key segment).\n * @param fn The async function to cache (typically the SDK call).\n * @param keyArgs Values to hash for the cache key (e.g. query params).\n */\nexport async function withCache<T>(\n provider: CacheProvider | undefined,\n tier: CacheTierConfig | undefined,\n methodPath: string,\n fn: () => Promise<T>,\n ...keyArgs: unknown[]\n): Promise<T> {\n const redisTtl = tier?.redis;\n if (!provider || !redisTtl) return fn();\n\n const key = `${provider.prefix}sdk:${methodPath}:${fnv1a(stableStringify(keyArgs))}`;\n\n try {\n const cached = await provider.get(key);\n if (cached != null) return JSON.parse(cached) as T;\n } catch {\n /* Redis read error — fall through to SDK call */\n }\n\n const result = await fn();\n\n try {\n provider.set(key, JSON.stringify(result), redisTtl).catch(() => {});\n } catch {\n /* Non-serializable or write error — skip caching */\n }\n\n return result;\n}\n","import type { TStock } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\n/** Returns the React Query cache key for a stock lookup by invMastUid. */\nexport const getStockKey = (invMastUid: number | string) => {\n return [\"stock\", invMastUid] as const;\n};\n\n/** @deprecated Use createServerQueryProxy() from augur-server/hooks instead. */\nexport const getStockOptions = (\n api: AugurApiClient,\n invMastUid: number | string,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getStockKey(invMastUid),\n queryFn: async (): Promise<TStock> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"items.invMast.stock.get\",\n async () => {\n const response = await api.items.invMast.stock.get(Number(invMastUid), {\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n const stockData = response.data?.stockData ?? [];\n const companySummary = response.data?.companySummary ?? {};\n return { stockData, companySummary } as TStock;\n },\n invMastUid,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n };\n};\n","import type { QueryClient } from \"@tanstack/react-query\";\n\nexport interface BatchQueryConfig<TParam, TData> {\n params: TParam[];\n queryClient: QueryClient;\n /** Build individual cache key for a single param. */\n getItemKey: (param: TParam) => readonly unknown[];\n /** Build the string key for the result Record from a param. */\n getResultKey: (param: TParam) => string;\n /** Fetch only uncached items, return keyed Record. */\n fetchItems: (uncached: TParam[]) => Promise<Record<string, TData>>;\n /** Extract individual cache key from a fetched result entry (for seeding). */\n getSeedKey: (resultKey: string, data: TData) => readonly unknown[];\n}\n\n/**\n * Generic batch query executor.\n *\n * 1. Checks queryClient cache for each param\n * 2. Fetches only uncached items in a single batch call\n * 3. Seeds individual cache entries from the response\n * 4. Returns merged cached + fetched record\n */\nexport async function executeBatchQuery<TParam, TData>(\n config: BatchQueryConfig<TParam, TData>,\n): Promise<Record<string, TData>> {\n const { params, queryClient, getItemKey, getResultKey, fetchItems, getSeedKey } = config;\n\n if (params.length === 0) {\n return {};\n }\n\n const cached: Record<string, TData> = {};\n const uncached: TParam[] = [];\n\n for (const param of params) {\n const existing = queryClient.getQueryData<TData>(getItemKey(param));\n if (existing !== undefined) {\n cached[getResultKey(param)] = existing;\n } else {\n uncached.push(param);\n }\n }\n\n if (uncached.length === 0) {\n return cached;\n }\n\n const fetched = await fetchItems(uncached);\n\n for (const [key, data] of Object.entries(fetched)) {\n queryClient.setQueryData(getSeedKey(key, data as TData), data);\n }\n\n return { ...cached, ...fetched };\n}\n","import type { TPriceData } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\n/**\n * Generates a consistent query key for item price queries.\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n */\nexport const getItemPriceKey = (\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n) => {\n return [\"price\", itemId?.toUpperCase() || \"\", customerId, quantity] as const;\n};\n\n/**\n * Query options for item price. Accepts the SDK instance so it works\n * in both client (via provider) and server (via direct construction).\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport const getItemPriceOptions = (\n api: AugurApiClient,\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getItemPriceKey(itemId, customerId, quantity),\n queryFn: async (): Promise<TPriceData> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"pricing.priceEngine.list\",\n async () => {\n const response = await api.pricing.priceEngine.list({\n itemId: itemId?.toUpperCase() || \"\",\n customerId: Number(customerId),\n quantity,\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n return response.data;\n },\n itemId,\n customerId,\n quantity,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n };\n};\n\n/**\n * Get cart pricing query options for prefetching or parent components.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport function getCartPricingQueryOptions(\n api: AugurApiClient,\n cartLines: Array<{ itemId: string; quantity: number }>,\n customerId: string | number | undefined,\n cache?: CacheConfig,\n) {\n return cartLines.map((line) => ({\n ...getItemPriceOptions(api, line.itemId, customerId, line.quantity, cache),\n enabled: !!customerId && !!line.itemId,\n }));\n}\n"]}