@viu/emporix-sdk-react 1.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/hooks.cjs ADDED
@@ -0,0 +1,1212 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var reactQuery = require('@tanstack/react-query');
5
+ var emporixSdk = require('@viu/emporix-sdk');
6
+ require('react/jsx-runtime');
7
+
8
+ // src/hooks/use-customer-session.ts
9
+ var NULL_CTX = {
10
+ activeCompany: null,
11
+ myCompanies: [],
12
+ mode: "b2c",
13
+ status: "idle",
14
+ error: null,
15
+ setActiveCompany: async () => {
16
+ throw new Error("CompanyContextProvider not mounted");
17
+ },
18
+ refetchMyCompanies: async () => {
19
+ }
20
+ };
21
+ var EmporixCompanyContext = react.createContext(NULL_CTX);
22
+ function useActiveCompany() {
23
+ return react.useContext(EmporixCompanyContext);
24
+ }
25
+ var EmporixContext = react.createContext(null);
26
+ var EmporixSiteContext = react.createContext(null);
27
+ function useEmporix() {
28
+ const ctx = react.useContext(EmporixContext);
29
+ if (!ctx) throw new Error("useEmporix must be used within an EmporixProvider");
30
+ return ctx;
31
+ }
32
+
33
+ // src/hooks/internal/bootstrap-cart.ts
34
+ async function bootstrapCart(opts) {
35
+ return opts.qc.fetchQuery({
36
+ queryKey: [
37
+ "emporix",
38
+ "cart-bootstrap",
39
+ {
40
+ tenant: opts.client.tenant,
41
+ // ctx.kind is the discriminator of AuthContext — same string as the
42
+ // legacy `authKind` param, derived directly so callers can't drift.
43
+ authKind: opts.ctx.kind,
44
+ siteCode: opts.siteCode,
45
+ ...opts.type !== void 0 ? { type: opts.type } : {},
46
+ ...opts.legalEntityId !== void 0 ? { legalEntityId: opts.legalEntityId } : {}
47
+ }
48
+ ],
49
+ queryFn: () => opts.client.carts.getCurrent(opts.ctx, {
50
+ siteCode: opts.siteCode,
51
+ ...opts.type !== void 0 ? { type: opts.type } : {},
52
+ ...opts.legalEntityId !== void 0 ? { legalEntityId: opts.legalEntityId } : {},
53
+ create: true
54
+ }),
55
+ staleTime: Infinity
56
+ });
57
+ }
58
+
59
+ // src/hooks/use-customer-session.ts
60
+ var EMPTY_SESSION = {
61
+ token: null,
62
+ refreshToken: null,
63
+ saasToken: null
64
+ };
65
+ function useCustomerSession() {
66
+ const { client, storage } = useEmporix();
67
+ const qc = reactQuery.useQueryClient();
68
+ const siteCtx = react.useContext(EmporixSiteContext);
69
+ const [session, setSession] = react.useState(() => ({
70
+ token: storage.getCustomerToken(),
71
+ refreshToken: null,
72
+ saasToken: null
73
+ }));
74
+ react.useEffect(() => {
75
+ return storage.subscribe?.((t) => setSession((s) => ({ ...s, token: t })));
76
+ }, [storage]);
77
+ const meQuery = reactQuery.useQuery({
78
+ queryKey: ["emporix", "customer", "me", { tenant: client.tenant, hasToken: session.token !== null }],
79
+ enabled: session.token !== null,
80
+ queryFn: () => client.customers.me(emporixSdk.auth.customer(session.token)),
81
+ // 30s — matches Balanced default. Lets honourPreferredSite's fetchQuery
82
+ // (with staleTime: Infinity) reuse the cache instead of refetching.
83
+ staleTime: 3e4
84
+ });
85
+ const login = react.useCallback(
86
+ async (input) => {
87
+ const result = await client.customers.login(input);
88
+ storage.setCustomerToken(result.customerToken);
89
+ storage.setRefreshToken(result.refreshToken || null);
90
+ setSession({
91
+ token: result.customerToken,
92
+ refreshToken: result.refreshToken || null,
93
+ saasToken: result.saasToken || null
94
+ });
95
+ await onboardCustomerCart({
96
+ qc,
97
+ client,
98
+ storage,
99
+ customerToken: result.customerToken
100
+ });
101
+ await honourPreferredSite({
102
+ qc,
103
+ client,
104
+ customerToken: result.customerToken,
105
+ siteCtx
106
+ });
107
+ await qc.invalidateQueries({ queryKey: ["emporix", "customer"], refetchType: "none" });
108
+ await qc.invalidateQueries({ queryKey: ["emporix", "cart"], refetchType: "none" });
109
+ },
110
+ [client, storage, qc, siteCtx]
111
+ );
112
+ const signup = react.useCallback(
113
+ async (input) => {
114
+ await client.customers.signup(input);
115
+ },
116
+ [client]
117
+ );
118
+ const applySession = react.useCallback(
119
+ async (incoming) => {
120
+ storage.setCustomerToken(incoming.customerToken);
121
+ storage.setRefreshToken(incoming.refreshToken || null);
122
+ setSession({
123
+ token: incoming.customerToken,
124
+ refreshToken: incoming.refreshToken || null,
125
+ saasToken: incoming.saasToken || null
126
+ });
127
+ await onboardCustomerCart({
128
+ qc,
129
+ client,
130
+ storage,
131
+ customerToken: incoming.customerToken
132
+ });
133
+ await honourPreferredSite({
134
+ qc,
135
+ client,
136
+ customerToken: incoming.customerToken,
137
+ siteCtx
138
+ });
139
+ await qc.invalidateQueries({ queryKey: ["emporix", "customer"], refetchType: "none" });
140
+ await qc.invalidateQueries({ queryKey: ["emporix", "cart"], refetchType: "none" });
141
+ },
142
+ [client, storage, qc, siteCtx]
143
+ );
144
+ const socialLogin = react.useCallback(
145
+ async (input) => {
146
+ await applySession(await client.customers.socialLogin(input));
147
+ },
148
+ [client, applySession]
149
+ );
150
+ const exchangeToken = react.useCallback(
151
+ async (input) => {
152
+ await applySession(await client.customers.exchangeToken(input));
153
+ },
154
+ [client, applySession]
155
+ );
156
+ const logout = react.useCallback(async () => {
157
+ if (session.token) {
158
+ try {
159
+ await client.customers.logout(emporixSdk.auth.customer(session.token));
160
+ } catch {
161
+ }
162
+ }
163
+ storage.setCustomerToken(null);
164
+ storage.setRefreshToken(null);
165
+ storage.setActiveLegalEntityId(null);
166
+ setSession(EMPTY_SESSION);
167
+ qc.removeQueries({ queryKey: ["emporix", "customer"] });
168
+ qc.removeQueries({ queryKey: ["emporix", "cart"] });
169
+ }, [client, session.token, storage, qc]);
170
+ const refresh = react.useCallback(async () => {
171
+ await meQuery.refetch();
172
+ }, [meQuery]);
173
+ const refreshSession = react.useCallback(async () => {
174
+ if (!session.refreshToken) return;
175
+ const refreshed = await client.customers.refresh({
176
+ refreshToken: session.refreshToken,
177
+ ...session.saasToken ? { saasToken: session.saasToken } : {}
178
+ });
179
+ storage.setCustomerToken(refreshed.customerToken);
180
+ if (refreshed.refreshToken) storage.setRefreshToken(refreshed.refreshToken);
181
+ setSession((s) => ({
182
+ token: refreshed.customerToken,
183
+ refreshToken: refreshed.refreshToken || s.refreshToken,
184
+ saasToken: refreshed.saasToken || s.saasToken
185
+ }));
186
+ await qc.invalidateQueries({ queryKey: ["emporix", "customer"] });
187
+ await qc.invalidateQueries({ queryKey: ["emporix", "cart"] });
188
+ }, [client, storage, qc, session.refreshToken, session.saasToken]);
189
+ return {
190
+ customerToken: session.token,
191
+ refreshToken: session.refreshToken,
192
+ customer: meQuery.data ?? null,
193
+ isAuthenticated: session.token !== null,
194
+ isLoading: meQuery.isLoading && session.token !== null,
195
+ login,
196
+ signup,
197
+ socialLogin,
198
+ exchangeToken,
199
+ logout,
200
+ refresh,
201
+ refreshSession
202
+ };
203
+ }
204
+ async function honourPreferredSite(opts) {
205
+ const { qc, client, customerToken, siteCtx } = opts;
206
+ if (!siteCtx) return;
207
+ try {
208
+ const me = await qc.fetchQuery({
209
+ queryKey: [
210
+ "emporix",
211
+ "customer",
212
+ "me",
213
+ { tenant: client.tenant, hasToken: true }
214
+ ],
215
+ queryFn: () => client.customers.me(emporixSdk.auth.customer(customerToken)),
216
+ // Reuse whatever meQuery already wrote (login flow runs meQuery in
217
+ // parallel). Without this, fetchQuery refetches if meQuery's data is
218
+ // already stale (default staleTime: 0 on meQuery).
219
+ staleTime: Infinity
220
+ });
221
+ const preferred = me.preferredSite;
222
+ if (preferred && siteCtx.siteCode !== preferred) {
223
+ await siteCtx.setSite(preferred);
224
+ }
225
+ } catch {
226
+ }
227
+ }
228
+ async function onboardCustomerCart(opts) {
229
+ const { qc, client, storage, customerToken } = opts;
230
+ const siteCode = client.config?.credentials?.storefront?.context?.siteCode;
231
+ if (!siteCode) return;
232
+ const ctx = emporixSdk.auth.customer(customerToken);
233
+ try {
234
+ const customerCart = await bootstrapCart({
235
+ qc,
236
+ client,
237
+ ctx,
238
+ siteCode
239
+ });
240
+ const customerCartId = customerCart?.id;
241
+ if (!customerCartId) return;
242
+ const anonCartId = storage.getCartId();
243
+ if (anonCartId && anonCartId !== customerCartId) {
244
+ await client.carts.merge(customerCartId, [anonCartId], ctx);
245
+ }
246
+ storage.setCartId(customerCartId);
247
+ } catch {
248
+ }
249
+ }
250
+ function useReadAuth(override) {
251
+ const { storage } = useEmporix();
252
+ if (override) return { ctx: override };
253
+ const token = storage.getCustomerToken();
254
+ return token ? { ctx: emporixSdk.auth.customer(token) } : { ctx: emporixSdk.auth.anonymous() };
255
+ }
256
+ function useCustomerOnlyCtx() {
257
+ const { storage } = useEmporix();
258
+ const token = storage.getCustomerToken();
259
+ if (!token) {
260
+ throw new Error("Requires a logged-in customer (no token in storage)");
261
+ }
262
+ return emporixSdk.auth.customer(token);
263
+ }
264
+ function useReadSite() {
265
+ const ctx = react.useContext(EmporixSiteContext);
266
+ return { siteCode: ctx?.siteCode ?? null };
267
+ }
268
+
269
+ // src/hooks/internal/query-keys.ts
270
+ function emporixKey(resource, args, context) {
271
+ const meta = {
272
+ tenant: context.tenant,
273
+ authKind: context.authKind
274
+ };
275
+ if (context.siteCode !== void 0) {
276
+ meta.siteCode = context.siteCode;
277
+ }
278
+ return ["emporix", resource, ...args, meta];
279
+ }
280
+ function useEmporixInfinite(opts) {
281
+ return reactQuery.useInfiniteQuery({
282
+ queryKey: opts.queryKey,
283
+ initialPageParam: 1,
284
+ queryFn: ({ pageParam }) => opts.fetchPage(pageParam),
285
+ getNextPageParam: (last) => last.hasNextPage ? last.pageNumber + 1 : void 0,
286
+ ...opts.enabled !== void 0 ? { enabled: opts.enabled } : {},
287
+ ...opts.staleTime !== void 0 ? { staleTime: opts.staleTime } : {}
288
+ });
289
+ }
290
+
291
+ // src/hooks/use-products.ts
292
+ var PRODUCTS_STALE_TIME = 6e4;
293
+ function useProduct(productId, options = {}) {
294
+ const { client } = useEmporix();
295
+ const { ctx } = useReadAuth(options.auth);
296
+ const { siteCode } = useReadSite();
297
+ return reactQuery.useQuery({
298
+ queryKey: emporixKey("product", [productId], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
299
+ queryFn: () => client.products.get(productId, void 0, ctx),
300
+ staleTime: PRODUCTS_STALE_TIME
301
+ });
302
+ }
303
+ function useProducts(params = {}, options = {}) {
304
+ const { client } = useEmporix();
305
+ const { ctx } = useReadAuth(options.auth);
306
+ const { siteCode } = useReadSite();
307
+ return reactQuery.useQuery({
308
+ queryKey: emporixKey("products", [params], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
309
+ queryFn: () => client.products.list(params, ctx),
310
+ staleTime: PRODUCTS_STALE_TIME
311
+ });
312
+ }
313
+ function useProductsInfinite(params = {}, options = {}) {
314
+ const { client } = useEmporix();
315
+ const { ctx } = useReadAuth(options.auth);
316
+ const { siteCode } = useReadSite();
317
+ return useEmporixInfinite({
318
+ queryKey: emporixKey("products-infinite", [params], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
319
+ fetchPage: (pageNumber) => client.products.list(
320
+ params.pageSize !== void 0 ? { pageNumber, pageSize: params.pageSize } : { pageNumber },
321
+ ctx
322
+ ),
323
+ staleTime: PRODUCTS_STALE_TIME
324
+ });
325
+ }
326
+ function useProductByCode(code, options = {}) {
327
+ const { client } = useEmporix();
328
+ const { ctx } = useReadAuth(options.auth);
329
+ const { siteCode } = useReadSite();
330
+ return reactQuery.useQuery({
331
+ queryKey: emporixKey("product-by-code", [code], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
332
+ enabled: typeof code === "string" && code !== "",
333
+ queryFn: () => client.products.getByCode(code, ctx),
334
+ staleTime: PRODUCTS_STALE_TIME
335
+ });
336
+ }
337
+ function useProductSearch(query, params = {}, options = {}) {
338
+ const { client } = useEmporix();
339
+ const { ctx } = useReadAuth(options.auth);
340
+ const { siteCode } = useReadSite();
341
+ return reactQuery.useQuery({
342
+ queryKey: emporixKey("product-search", [query, params], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
343
+ enabled: typeof query === "string" && query.trim() !== "",
344
+ queryFn: () => client.products.search(query, params, ctx),
345
+ staleTime: PRODUCTS_STALE_TIME
346
+ });
347
+ }
348
+ var CATEGORIES_STALE_TIME = 5 * 6e4;
349
+ function useCategory(categoryId, options = {}) {
350
+ const { client } = useEmporix();
351
+ const { ctx } = useReadAuth(options.auth);
352
+ const { siteCode } = useReadSite();
353
+ return reactQuery.useQuery({
354
+ queryKey: emporixKey("category", [categoryId], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
355
+ queryFn: () => client.categories.get(categoryId, ctx),
356
+ staleTime: CATEGORIES_STALE_TIME
357
+ });
358
+ }
359
+ function useCategories(params = {}, options = {}) {
360
+ const { client } = useEmporix();
361
+ const { ctx } = useReadAuth(options.auth);
362
+ const { siteCode } = useReadSite();
363
+ return reactQuery.useQuery({
364
+ queryKey: emporixKey("categories", [params], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
365
+ queryFn: () => client.categories.list(params, ctx),
366
+ staleTime: CATEGORIES_STALE_TIME
367
+ });
368
+ }
369
+ function useCategoriesInfinite(params = {}, options = {}) {
370
+ const { client } = useEmporix();
371
+ const { ctx } = useReadAuth(options.auth);
372
+ const { siteCode } = useReadSite();
373
+ return useEmporixInfinite({
374
+ queryKey: emporixKey("categories-infinite", [params], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
375
+ fetchPage: (pageNumber) => client.categories.list(
376
+ params.pageSize !== void 0 ? { pageNumber, pageSize: params.pageSize } : { pageNumber },
377
+ ctx
378
+ ),
379
+ staleTime: CATEGORIES_STALE_TIME
380
+ });
381
+ }
382
+ function useCategoryTree(rootId, options = {}) {
383
+ const { client } = useEmporix();
384
+ const { ctx } = useReadAuth(options.auth);
385
+ const { siteCode } = useReadSite();
386
+ return reactQuery.useQuery({
387
+ queryKey: emporixKey("category-tree", [rootId ?? null], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
388
+ queryFn: () => client.categories.tree(rootId, ctx),
389
+ staleTime: CATEGORIES_STALE_TIME
390
+ });
391
+ }
392
+ function useProductsInCategory(categoryId, params = {}, options = {}) {
393
+ const { client } = useEmporix();
394
+ const { ctx } = useReadAuth(options.auth);
395
+ const { siteCode } = useReadSite();
396
+ return reactQuery.useQuery({
397
+ queryKey: emporixKey("products-in-category", [categoryId, params], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
398
+ enabled: typeof categoryId === "string" && categoryId !== "",
399
+ queryFn: () => client.categories.productsIn(categoryId, params, ctx),
400
+ staleTime: CATEGORIES_STALE_TIME
401
+ });
402
+ }
403
+ function useProductsInCategoryInfinite(categoryId, params = {}, options = {}) {
404
+ const { client } = useEmporix();
405
+ const { ctx } = useReadAuth(options.auth);
406
+ const { siteCode } = useReadSite();
407
+ return useEmporixInfinite({
408
+ queryKey: emporixKey("products-in-category-infinite", [categoryId, params], { tenant: client.tenant, authKind: ctx.kind, siteCode }),
409
+ enabled: typeof categoryId === "string" && categoryId !== "",
410
+ fetchPage: (pageNumber) => client.categories.productsIn(
411
+ categoryId,
412
+ params.pageSize !== void 0 ? { pageNumber, pageSize: params.pageSize } : { pageNumber },
413
+ ctx
414
+ ),
415
+ staleTime: CATEGORIES_STALE_TIME
416
+ });
417
+ }
418
+ function useCart(cartId, options = {}) {
419
+ const { client, storage } = useEmporix();
420
+ const { ctx } = useReadAuth(options.auth);
421
+ const { siteCode } = useReadSite();
422
+ const { activeCompany } = useActiveCompany();
423
+ const resolvedId = cartId ?? storage.getCartId() ?? void 0;
424
+ return reactQuery.useQuery({
425
+ queryKey: emporixKey(
426
+ "cart",
427
+ [resolvedId ?? null, activeCompany?.id ?? null],
428
+ { tenant: client.tenant, authKind: ctx.kind, siteCode }
429
+ ),
430
+ enabled: resolvedId !== void 0,
431
+ queryFn: () => client.carts.get(resolvedId, ctx)
432
+ });
433
+ }
434
+ function useCartMutations(cartId) {
435
+ const { client, storage } = useEmporix();
436
+ const qc = reactQuery.useQueryClient();
437
+ const { ctx } = useReadAuth();
438
+ const { siteCode } = useReadSite();
439
+ const { activeCompany } = useActiveCompany();
440
+ const resolveId = () => {
441
+ const id = cartId ?? storage.getCartId();
442
+ if (!id) {
443
+ throw new emporixSdk.EmporixError(
444
+ "useCartMutations: no cartId available \u2014 pass one explicitly or call useActiveCart({ create: true }) first"
445
+ );
446
+ }
447
+ return id;
448
+ };
449
+ const keyFor = (id) => emporixKey(
450
+ "cart",
451
+ [id, activeCompany?.id ?? null],
452
+ { tenant: client.tenant, authKind: ctx.kind, siteCode }
453
+ );
454
+ function make(run, optimistic) {
455
+ return reactQuery.useMutation({
456
+ mutationFn: async (vars) => run(resolveId(), vars),
457
+ onMutate: async (vars) => {
458
+ const id = resolveId();
459
+ const key = keyFor(id);
460
+ await qc.cancelQueries({ queryKey: key });
461
+ const previous = qc.getQueryData(key);
462
+ if (optimistic) qc.setQueryData(key, optimistic(previous, vars));
463
+ return { previous, key };
464
+ },
465
+ onError: (_e, _v, c) => {
466
+ if (c) qc.setQueryData(c.key, c.previous);
467
+ },
468
+ onSuccess: (cart, _v, c) => {
469
+ if (c) qc.setQueryData(c.key, cart);
470
+ }
471
+ });
472
+ }
473
+ return {
474
+ addItem: make(
475
+ (id, v) => client.carts.addItem(id, v, ctx),
476
+ (prev, v) => prev ? {
477
+ ...prev,
478
+ // Optimistic placeholder; replaced by the real item on success.
479
+ items: [
480
+ ...prev.items ?? [],
481
+ {
482
+ id: `optimistic-${v.product?.id ?? "item"}`,
483
+ ...v
484
+ }
485
+ ]
486
+ } : prev
487
+ ),
488
+ updateItem: make((id, v) => client.carts.updateItem(id, v.itemId, v.patch, ctx)),
489
+ removeItem: make(
490
+ (id, v) => client.carts.removeItem(id, v.itemId, ctx),
491
+ (prev, v) => prev ? { ...prev, items: (prev.items ?? []).filter((i) => i.id !== v.itemId) } : prev
492
+ ),
493
+ clear: make(
494
+ (id) => client.carts.clear(id, ctx),
495
+ (prev) => prev ? { ...prev, items: [] } : prev
496
+ ),
497
+ applyCoupon: make((id, v) => client.carts.applyCoupon(id, v.code, ctx)),
498
+ removeCoupon: make((id, v) => client.carts.removeCoupon(id, v.code, ctx)),
499
+ setShippingAddress: make((id, v) => client.carts.setShippingAddress(id, v, ctx)),
500
+ setBillingAddress: make((id, v) => client.carts.setBillingAddress(id, v, ctx))
501
+ };
502
+ }
503
+ function useCreateCart() {
504
+ const { client, storage } = useEmporix();
505
+ const qc = reactQuery.useQueryClient();
506
+ const { ctx } = useReadAuth();
507
+ return reactQuery.useMutation({
508
+ mutationFn: (input) => client.carts.create(input, ctx),
509
+ onSuccess: async (cart) => {
510
+ if (cart.cartId) storage.setCartId(cart.cartId);
511
+ await qc.invalidateQueries({ queryKey: ["emporix", "cart"] });
512
+ }
513
+ });
514
+ }
515
+ function useActiveCart(opts) {
516
+ const { client, storage } = useEmporix();
517
+ const qc = reactQuery.useQueryClient();
518
+ const { ctx } = useReadAuth(opts?.auth);
519
+ const { siteCode: activeSite } = useReadSite();
520
+ const { activeCompany } = useActiveCompany();
521
+ const [cartId, setCartId] = react.useState(() => storage.getCartId());
522
+ const effectiveLegalEntityId = opts?.legalEntityId ?? activeCompany?.id;
523
+ react.useEffect(() => {
524
+ if (cartId !== null) return;
525
+ if (!opts?.create) return;
526
+ const siteCode = activeSite ?? client.config?.credentials?.storefront?.context?.siteCode;
527
+ if (!siteCode) return;
528
+ let cancelled = false;
529
+ bootstrapCart({
530
+ qc,
531
+ client,
532
+ ctx,
533
+ siteCode,
534
+ ...opts.type !== void 0 ? { type: opts.type } : {},
535
+ ...effectiveLegalEntityId !== void 0 ? { legalEntityId: effectiveLegalEntityId } : {}
536
+ }).then((cart) => {
537
+ if (cancelled) return;
538
+ if (cart?.id) {
539
+ storage.setCartId(cart.id);
540
+ setCartId(cart.id);
541
+ }
542
+ }).catch(() => {
543
+ });
544
+ return () => {
545
+ cancelled = true;
546
+ };
547
+ }, [cartId, opts?.create, opts?.type, effectiveLegalEntityId, ctx.kind, activeSite]);
548
+ const inner = useCart(cartId ?? void 0, opts?.auth ? { auth: opts.auth } : {});
549
+ const data = cartId === null ? null : inner.data;
550
+ return { ...inner, data };
551
+ }
552
+ var PAYMENT_MODES_STALE_TIME = 10 * 6e4;
553
+ function customerOnlyCtx(token) {
554
+ if (!token) throw new Error("usePaymentModes requires a logged-in customer token");
555
+ return emporixSdk.auth.customer(token);
556
+ }
557
+ function useCheckout() {
558
+ const { client } = useEmporix();
559
+ const { ctx } = useReadAuth();
560
+ const { activeCompany } = useActiveCompany();
561
+ const withLE = (input) => {
562
+ if (!activeCompany?.id) return input;
563
+ if ("legalEntityId" in input) return input;
564
+ return { ...input, legalEntityId: activeCompany.id };
565
+ };
566
+ const placeOrder = reactQuery.useMutation({
567
+ mutationFn: (v) => client.checkout.placeOrder(withLE(v.input), ctx, {
568
+ ...v.saasToken !== void 0 ? { saasToken: v.saasToken } : {},
569
+ ...v.siteCode !== void 0 ? { siteCode: v.siteCode } : {}
570
+ })
571
+ });
572
+ const placeOrderFromQuote = reactQuery.useMutation({
573
+ mutationFn: (v) => client.checkout.placeOrderFromQuote(withLE(v.input), ctx, {
574
+ ...v.saasToken !== void 0 ? { saasToken: v.saasToken } : {},
575
+ ...v.siteCode !== void 0 ? { siteCode: v.siteCode } : {}
576
+ })
577
+ });
578
+ return { placeOrder, placeOrderFromQuote };
579
+ }
580
+ function usePaymentModes(options = {}) {
581
+ const { client, storage } = useEmporix();
582
+ const token = storage.getCustomerToken();
583
+ const { siteCode } = useReadSite();
584
+ const { activeCompany } = useActiveCompany();
585
+ return reactQuery.useQuery({
586
+ queryKey: emporixKey(
587
+ "payment-modes",
588
+ [activeCompany?.id ?? null],
589
+ { tenant: client.tenant, authKind: "customer", siteCode }
590
+ ),
591
+ enabled: (options.enabled ?? true) && token !== null,
592
+ queryFn: () => client.payments.listPaymentModes(customerOnlyCtx(token)),
593
+ staleTime: PAYMENT_MODES_STALE_TIME
594
+ });
595
+ }
596
+ var PRICES_STALE_TIME = 6e4;
597
+ function useMatchPrices(input, options = {}) {
598
+ const { client } = useEmporix();
599
+ const { siteCode } = useReadSite();
600
+ const ctx = options.customerToken ? emporixSdk.auth.customer(options.customerToken) : emporixSdk.auth.anonymous();
601
+ return reactQuery.useQuery({
602
+ queryKey: [
603
+ "emporix",
604
+ "match-prices",
605
+ { tenant: client.tenant, input, anon: !options.customerToken, siteCode }
606
+ ],
607
+ enabled: (options.enabled ?? true) && (input.items?.length ?? 0) > 0,
608
+ queryFn: () => client.prices.matchByContext(input, ctx),
609
+ staleTime: PRICES_STALE_TIME
610
+ });
611
+ }
612
+
613
+ // src/hooks/use-product-media.ts
614
+ function useProductMedia(productId) {
615
+ const q = useProduct(productId);
616
+ const data = q.data?.productMedia;
617
+ return { data, isLoading: q.isLoading, error: q.error };
618
+ }
619
+ var SEGMENTS_STALE_TIME = 5 * 6e4;
620
+ function customerCtx(token) {
621
+ if (!token) throw new Error("requires a customer token in storage");
622
+ return emporixSdk.auth.customer(token);
623
+ }
624
+ function useMySegments(query = {}) {
625
+ const { client, storage } = useEmporix();
626
+ const token = storage.getCustomerToken();
627
+ const { siteCode } = useReadSite();
628
+ return reactQuery.useQuery({
629
+ queryKey: ["emporix", "segment", "list", { tenant: client.tenant, query, siteCode }],
630
+ enabled: token !== null,
631
+ queryFn: () => client.segments.list(query, customerCtx(token)),
632
+ staleTime: SEGMENTS_STALE_TIME
633
+ });
634
+ }
635
+ function useMySegmentItems(query = {}) {
636
+ const { client, storage } = useEmporix();
637
+ const token = storage.getCustomerToken();
638
+ const { siteCode } = useReadSite();
639
+ return reactQuery.useQuery({
640
+ queryKey: ["emporix", "segment", "items", { tenant: client.tenant, query, siteCode }],
641
+ enabled: token !== null,
642
+ queryFn: () => client.segments.listItems(query, customerCtx(token)),
643
+ staleTime: SEGMENTS_STALE_TIME
644
+ });
645
+ }
646
+ function useMySegmentCategoryTree(query = {}) {
647
+ const { client, storage } = useEmporix();
648
+ const token = storage.getCustomerToken();
649
+ const { siteCode } = useReadSite();
650
+ return reactQuery.useQuery({
651
+ queryKey: ["emporix", "segment", "categoryTree", { tenant: client.tenant, query, siteCode }],
652
+ enabled: token !== null,
653
+ queryFn: () => client.segments.getCategoryTree(query, customerCtx(token)),
654
+ staleTime: SEGMENTS_STALE_TIME
655
+ });
656
+ }
657
+ function useMySegmentProducts(query = {}) {
658
+ const { client, storage } = useEmporix();
659
+ const token = storage.getCustomerToken();
660
+ const { siteCode } = useReadSite();
661
+ return reactQuery.useQuery({
662
+ queryKey: ["emporix", "segment", "myProducts", { tenant: client.tenant, query, siteCode }],
663
+ enabled: token !== null,
664
+ queryFn: () => client.segments.listMyProducts(query, customerCtx(token)),
665
+ staleTime: SEGMENTS_STALE_TIME
666
+ });
667
+ }
668
+ function useMySegmentProductsInfinite(query = {}) {
669
+ const { client, storage } = useEmporix();
670
+ const token = storage.getCustomerToken();
671
+ const { siteCode } = useReadSite();
672
+ return useEmporixInfinite({
673
+ queryKey: [
674
+ "emporix",
675
+ "segment",
676
+ "myProductsInfinite",
677
+ { tenant: client.tenant, query, siteCode }
678
+ ],
679
+ enabled: token !== null,
680
+ fetchPage: (pageNumber) => client.segments.listMyProducts(
681
+ { ...query, pageNumber, pageSize: query.pageSize ?? 20 },
682
+ customerCtx(token)
683
+ ),
684
+ staleTime: SEGMENTS_STALE_TIME
685
+ });
686
+ }
687
+ function useMySegmentCategories(query = {}) {
688
+ const { client, storage } = useEmporix();
689
+ const token = storage.getCustomerToken();
690
+ const { siteCode } = useReadSite();
691
+ return reactQuery.useQuery({
692
+ queryKey: ["emporix", "segment", "myCategories", { tenant: client.tenant, query, siteCode }],
693
+ enabled: token !== null,
694
+ queryFn: () => client.segments.listMyCategories(query, customerCtx(token)),
695
+ staleTime: SEGMENTS_STALE_TIME
696
+ });
697
+ }
698
+ function useMySegmentCategoriesInfinite(query = {}) {
699
+ const { client, storage } = useEmporix();
700
+ const token = storage.getCustomerToken();
701
+ const { siteCode } = useReadSite();
702
+ return useEmporixInfinite({
703
+ queryKey: [
704
+ "emporix",
705
+ "segment",
706
+ "myCategoriesInfinite",
707
+ { tenant: client.tenant, query, siteCode }
708
+ ],
709
+ enabled: token !== null,
710
+ fetchPage: (pageNumber) => client.segments.listMyCategories(
711
+ { ...query, pageNumber, pageSize: query.pageSize ?? 20 },
712
+ customerCtx(token)
713
+ ),
714
+ staleTime: SEGMENTS_STALE_TIME
715
+ });
716
+ }
717
+ function useUpdateCustomer() {
718
+ const { client } = useEmporix();
719
+ const ctx = useCustomerOnlyCtx();
720
+ const qc = reactQuery.useQueryClient();
721
+ return reactQuery.useMutation({
722
+ mutationFn: (patch) => client.customers.update(patch, ctx),
723
+ onSuccess: () => {
724
+ void qc.invalidateQueries({ queryKey: ["emporix", "customer", "me"] });
725
+ }
726
+ });
727
+ }
728
+ function useChangePassword() {
729
+ const { client } = useEmporix();
730
+ const ctx = useCustomerOnlyCtx();
731
+ return reactQuery.useMutation({
732
+ mutationFn: (input) => client.customers.changePassword(input, ctx)
733
+ });
734
+ }
735
+ var ADDRESSES_KEY = ["emporix", "customer", "addresses"];
736
+ function useCustomerAddresses(options = {}) {
737
+ const { client, storage } = useEmporix();
738
+ const token = storage.getCustomerToken();
739
+ const { activeCompany } = useActiveCompany();
740
+ const ctx = options.auth ?? (token ? emporixSdk.auth.customer(token) : null);
741
+ return reactQuery.useQuery({
742
+ queryKey: [
743
+ ...ADDRESSES_KEY,
744
+ { tenant: client.tenant, hasToken: token !== null, legalEntityId: activeCompany?.id ?? null }
745
+ ],
746
+ enabled: ctx !== null,
747
+ queryFn: () => client.customers.addresses.list(ctx)
748
+ });
749
+ }
750
+ function useAddressMutations() {
751
+ const { client } = useEmporix();
752
+ const ctx = useCustomerOnlyCtx();
753
+ const qc = reactQuery.useQueryClient();
754
+ const invalidate = () => {
755
+ void qc.invalidateQueries({ queryKey: ADDRESSES_KEY });
756
+ };
757
+ return {
758
+ add: reactQuery.useMutation({
759
+ mutationFn: (input) => client.customers.addresses.add(input, ctx),
760
+ onSuccess: invalidate
761
+ }),
762
+ update: reactQuery.useMutation({
763
+ mutationFn: ({ id, patch }) => client.customers.addresses.update(id, patch, ctx),
764
+ onSuccess: invalidate
765
+ }),
766
+ remove: reactQuery.useMutation({
767
+ mutationFn: ({ id }) => client.customers.addresses.remove(id, ctx),
768
+ onSuccess: invalidate
769
+ })
770
+ };
771
+ }
772
+ function usePasswordReset() {
773
+ const { client } = useEmporix();
774
+ const anonCtx = emporixSdk.auth.anonymous();
775
+ return {
776
+ request: reactQuery.useMutation({
777
+ mutationFn: (input) => client.customers.requestPasswordReset(input, anonCtx)
778
+ }),
779
+ confirm: reactQuery.useMutation({
780
+ mutationFn: (input) => client.customers.confirmPasswordReset(input, anonCtx)
781
+ })
782
+ };
783
+ }
784
+ var SITES_STALE_TIME = 10 * 6e4;
785
+ function useSites(options = {}) {
786
+ const { client } = useEmporix();
787
+ const { ctx } = useReadAuth(options.auth);
788
+ return reactQuery.useQuery({
789
+ queryKey: emporixKey("sites", [], { tenant: client.tenant, authKind: ctx.kind }),
790
+ queryFn: () => client.sites.list(ctx),
791
+ staleTime: SITES_STALE_TIME
792
+ });
793
+ }
794
+ function useDefaultSite(options = {}) {
795
+ const { client } = useEmporix();
796
+ const { ctx } = useReadAuth(options.auth);
797
+ return reactQuery.useQuery({
798
+ queryKey: emporixKey("site-default", [], { tenant: client.tenant, authKind: ctx.kind }),
799
+ queryFn: () => client.sites.current(ctx),
800
+ staleTime: SITES_STALE_TIME
801
+ });
802
+ }
803
+ function useSiteContext() {
804
+ const ctx = react.useContext(EmporixSiteContext);
805
+ if (!ctx) {
806
+ throw new Error("useSiteContext must be used within an EmporixProvider");
807
+ }
808
+ return ctx;
809
+ }
810
+ function useMyCompanies() {
811
+ const { client, storage } = useEmporix();
812
+ const token = storage.getCustomerToken();
813
+ return reactQuery.useQuery({
814
+ queryKey: emporixKey("companies", ["mine"], {
815
+ tenant: client.tenant,
816
+ authKind: token ? "customer" : "anonymous"
817
+ }),
818
+ enabled: token !== null,
819
+ queryFn: () => client.companies.listMine(emporixSdk.auth.customer(token))
820
+ });
821
+ }
822
+ function useCompany(legalEntityId) {
823
+ const { client, storage } = useEmporix();
824
+ const token = storage.getCustomerToken();
825
+ return reactQuery.useQuery({
826
+ queryKey: emporixKey("companies", [legalEntityId ?? null], {
827
+ tenant: client.tenant,
828
+ authKind: token ? "customer" : "anonymous"
829
+ }),
830
+ enabled: token !== null && legalEntityId !== void 0,
831
+ queryFn: () => client.companies.get(legalEntityId, emporixSdk.auth.customer(token))
832
+ });
833
+ }
834
+ function useCompanyContacts(legalEntityId) {
835
+ const { client, storage } = useEmporix();
836
+ const token = storage.getCustomerToken();
837
+ return reactQuery.useQuery({
838
+ queryKey: emporixKey("companies", ["contacts", legalEntityId ?? null], {
839
+ tenant: client.tenant,
840
+ authKind: token ? "customer" : "anonymous"
841
+ }),
842
+ enabled: token !== null && legalEntityId !== void 0,
843
+ queryFn: () => client.contacts.listForCompany(legalEntityId, emporixSdk.auth.customer(token))
844
+ });
845
+ }
846
+ function useCompanyLocations(legalEntityId) {
847
+ const { client, storage } = useEmporix();
848
+ const token = storage.getCustomerToken();
849
+ return reactQuery.useQuery({
850
+ queryKey: emporixKey("companies", ["locations", legalEntityId ?? null], {
851
+ tenant: client.tenant,
852
+ authKind: token ? "customer" : "anonymous"
853
+ }),
854
+ enabled: token !== null && legalEntityId !== void 0,
855
+ queryFn: () => client.locations.listForCompany(legalEntityId, emporixSdk.auth.customer(token))
856
+ });
857
+ }
858
+ function useCompanyGroups(legalEntityId) {
859
+ const { client, storage } = useEmporix();
860
+ const token = storage.getCustomerToken();
861
+ return reactQuery.useQuery({
862
+ queryKey: emporixKey("companies", ["groups", legalEntityId ?? null], {
863
+ tenant: client.tenant,
864
+ authKind: token ? "customer" : "anonymous"
865
+ }),
866
+ enabled: token !== null && legalEntityId !== void 0,
867
+ queryFn: () => client.customerGroups.listForCompany(legalEntityId, emporixSdk.auth.customer(token))
868
+ });
869
+ }
870
+ function useCustomerAuthResolver() {
871
+ const { storage } = useEmporix();
872
+ return () => {
873
+ const token = storage.getCustomerToken();
874
+ if (!token) throw new Error("Mutation requires a logged-in customer token");
875
+ return emporixSdk.auth.customer(token);
876
+ };
877
+ }
878
+ function useCreateCompany() {
879
+ const { client } = useEmporix();
880
+ const resolveAuth = useCustomerAuthResolver();
881
+ const qc = reactQuery.useQueryClient();
882
+ return reactQuery.useMutation({
883
+ mutationFn: (input) => client.companies.create(input, resolveAuth()),
884
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["emporix", "companies", "mine"] })
885
+ });
886
+ }
887
+ function useUpdateCompany() {
888
+ const { client } = useEmporix();
889
+ const resolveAuth = useCustomerAuthResolver();
890
+ const qc = reactQuery.useQueryClient();
891
+ return reactQuery.useMutation({
892
+ mutationFn: ({ id, patch }) => client.companies.update(id, patch, resolveAuth()),
893
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["emporix", "companies"] })
894
+ });
895
+ }
896
+ function useDeleteCompany() {
897
+ const { client } = useEmporix();
898
+ const resolveAuth = useCustomerAuthResolver();
899
+ const qc = reactQuery.useQueryClient();
900
+ return reactQuery.useMutation({
901
+ mutationFn: (id) => client.companies.delete(id, resolveAuth()),
902
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["emporix", "companies"] })
903
+ });
904
+ }
905
+ function useAssignContact() {
906
+ const { client } = useEmporix();
907
+ const resolveAuth = useCustomerAuthResolver();
908
+ const qc = reactQuery.useQueryClient();
909
+ return reactQuery.useMutation({
910
+ mutationFn: (input) => client.contacts.assign(input, resolveAuth()),
911
+ onSuccess: () => qc.invalidateQueries({ predicate: (q) => q.queryKey.includes("contacts") })
912
+ });
913
+ }
914
+ function useUpdateContactAssignment() {
915
+ const { client } = useEmporix();
916
+ const resolveAuth = useCustomerAuthResolver();
917
+ const qc = reactQuery.useQueryClient();
918
+ return reactQuery.useMutation({
919
+ mutationFn: ({ id, patch }) => client.contacts.update(id, patch, resolveAuth()),
920
+ onSuccess: () => qc.invalidateQueries({ predicate: (q) => q.queryKey.includes("contacts") })
921
+ });
922
+ }
923
+ function useUnassignContact() {
924
+ const { client } = useEmporix();
925
+ const resolveAuth = useCustomerAuthResolver();
926
+ const qc = reactQuery.useQueryClient();
927
+ return reactQuery.useMutation({
928
+ mutationFn: (id) => client.contacts.unassign(id, resolveAuth()),
929
+ onSuccess: () => qc.invalidateQueries({ predicate: (q) => q.queryKey.includes("contacts") })
930
+ });
931
+ }
932
+ function useCreateLocation() {
933
+ const { client } = useEmporix();
934
+ const resolveAuth = useCustomerAuthResolver();
935
+ const qc = reactQuery.useQueryClient();
936
+ return reactQuery.useMutation({
937
+ mutationFn: (input) => client.locations.create(input, resolveAuth()),
938
+ onSuccess: () => qc.invalidateQueries({ predicate: (q) => q.queryKey.includes("locations") })
939
+ });
940
+ }
941
+ function useUpdateLocation() {
942
+ const { client } = useEmporix();
943
+ const resolveAuth = useCustomerAuthResolver();
944
+ const qc = reactQuery.useQueryClient();
945
+ return reactQuery.useMutation({
946
+ mutationFn: ({ id, patch }) => client.locations.update(id, patch, resolveAuth()),
947
+ onSuccess: () => qc.invalidateQueries({ predicate: (q) => q.queryKey.includes("locations") })
948
+ });
949
+ }
950
+ function useDeleteLocation() {
951
+ const { client } = useEmporix();
952
+ const resolveAuth = useCustomerAuthResolver();
953
+ const qc = reactQuery.useQueryClient();
954
+ return reactQuery.useMutation({
955
+ mutationFn: (id) => client.locations.delete(id, resolveAuth()),
956
+ onSuccess: () => qc.invalidateQueries({ predicate: (q) => q.queryKey.includes("locations") })
957
+ });
958
+ }
959
+ function useCompanySwitcher() {
960
+ const ctx = useActiveCompany();
961
+ const switchFn = react.useCallback(
962
+ (legalEntityId) => ctx.setActiveCompany(legalEntityId),
963
+ [ctx]
964
+ );
965
+ const clearFn = react.useCallback(() => ctx.setActiveCompany(null), [ctx]);
966
+ return {
967
+ companies: ctx.myCompanies,
968
+ active: ctx.activeCompany,
969
+ status: ctx.status,
970
+ switch: switchFn,
971
+ clear: clearFn
972
+ };
973
+ }
974
+ function useMyOrders(options = {}) {
975
+ const { client, storage } = useEmporix();
976
+ const { activeCompany } = useActiveCompany();
977
+ const { siteCode } = useReadSite();
978
+ const token = storage.getCustomerToken();
979
+ const effectiveLE = options.legalEntityId === null ? void 0 : options.legalEntityId ?? activeCompany?.id;
980
+ return reactQuery.useQuery({
981
+ queryKey: emporixKey(
982
+ "orders",
983
+ ["mine", effectiveLE ?? null, options.status ?? null, options.pageNumber ?? 1, options.pageSize ?? null],
984
+ { tenant: client.tenant, authKind: token ? "customer" : "anonymous", siteCode }
985
+ ),
986
+ enabled: token !== null,
987
+ queryFn: () => client.orders.listMine(emporixSdk.auth.customer(token), {
988
+ ...options.pageNumber !== void 0 ? { pageNumber: options.pageNumber } : {},
989
+ ...options.pageSize !== void 0 ? { pageSize: options.pageSize } : {},
990
+ ...options.status !== void 0 ? { status: options.status } : {},
991
+ ...effectiveLE !== void 0 ? { legalEntityId: effectiveLE } : {},
992
+ ...siteCode ? { siteCode } : {},
993
+ ...options.saasToken !== void 0 ? { saasToken: options.saasToken } : {}
994
+ })
995
+ });
996
+ }
997
+ function useMyOrdersInfinite(options = {}) {
998
+ const { client, storage } = useEmporix();
999
+ const { activeCompany } = useActiveCompany();
1000
+ const { siteCode } = useReadSite();
1001
+ const token = storage.getCustomerToken();
1002
+ const effectiveLE = options.legalEntityId === null ? void 0 : options.legalEntityId ?? activeCompany?.id;
1003
+ return useEmporixInfinite({
1004
+ queryKey: emporixKey(
1005
+ "orders",
1006
+ ["mine-infinite", effectiveLE ?? null, options.status ?? null, options.pageSize ?? null],
1007
+ { tenant: client.tenant, authKind: token ? "customer" : "anonymous", siteCode }
1008
+ ),
1009
+ enabled: token !== null,
1010
+ fetchPage: (pageNumber) => client.orders.listMine(emporixSdk.auth.customer(token), {
1011
+ pageNumber,
1012
+ ...options.pageSize !== void 0 ? { pageSize: options.pageSize } : {},
1013
+ ...options.status !== void 0 ? { status: options.status } : {},
1014
+ ...effectiveLE !== void 0 ? { legalEntityId: effectiveLE } : {},
1015
+ ...siteCode ? { siteCode } : {},
1016
+ ...options.saasToken !== void 0 ? { saasToken: options.saasToken } : {}
1017
+ })
1018
+ });
1019
+ }
1020
+ function useOrder(orderId, options = {}) {
1021
+ const { client, storage } = useEmporix();
1022
+ const token = storage.getCustomerToken();
1023
+ return reactQuery.useQuery({
1024
+ queryKey: emporixKey("orders", [orderId ?? null], {
1025
+ tenant: client.tenant,
1026
+ authKind: token ? "customer" : "anonymous"
1027
+ }),
1028
+ enabled: token !== null && orderId !== void 0,
1029
+ queryFn: () => client.orders.get(
1030
+ orderId,
1031
+ emporixSdk.auth.customer(token),
1032
+ options.saasToken ? { saasToken: options.saasToken } : {}
1033
+ )
1034
+ });
1035
+ }
1036
+ function useCancelOrder() {
1037
+ const { client, storage } = useEmporix();
1038
+ const qc = reactQuery.useQueryClient();
1039
+ return reactQuery.useMutation({
1040
+ mutationKey: ["emporix", "orders", "cancel"],
1041
+ mutationFn: async (input) => {
1042
+ const token = storage.getCustomerToken();
1043
+ if (!token) throw new Error("useCancelOrder: requires a logged-in customer");
1044
+ const { orderId, saasToken } = typeof input === "string" ? { orderId: input, saasToken: void 0 } : input;
1045
+ await client.orders.cancel(
1046
+ orderId,
1047
+ emporixSdk.auth.customer(token),
1048
+ saasToken ? { saasToken } : {}
1049
+ );
1050
+ },
1051
+ onSuccess: () => qc.invalidateQueries({
1052
+ predicate: (q) => Array.isArray(q.queryKey) && q.queryKey[1] === "orders"
1053
+ })
1054
+ });
1055
+ }
1056
+ function useOrderTransition() {
1057
+ const { client, storage } = useEmporix();
1058
+ const qc = reactQuery.useQueryClient();
1059
+ return reactQuery.useMutation({
1060
+ mutationKey: ["emporix", "orders", "transition"],
1061
+ mutationFn: async ({ orderId, status, comment, saasToken }) => {
1062
+ const token = storage.getCustomerToken();
1063
+ if (!token) throw new Error("useOrderTransition: requires a logged-in customer");
1064
+ await client.orders.transition(
1065
+ orderId,
1066
+ status,
1067
+ emporixSdk.auth.customer(token),
1068
+ {
1069
+ ...comment !== void 0 ? { comment } : {},
1070
+ ...saasToken !== void 0 ? { saasToken } : {}
1071
+ }
1072
+ );
1073
+ },
1074
+ onSuccess: () => qc.invalidateQueries({
1075
+ predicate: (q) => Array.isArray(q.queryKey) && q.queryKey[1] === "orders"
1076
+ })
1077
+ });
1078
+ }
1079
+ function useReorder() {
1080
+ const { client, storage } = useEmporix();
1081
+ const qc = reactQuery.useQueryClient();
1082
+ return reactQuery.useMutation({
1083
+ mutationKey: ["emporix", "orders", "reorder"],
1084
+ mutationFn: async ({ orderId, saasToken }) => {
1085
+ const token = storage.getCustomerToken();
1086
+ if (!token) throw new Error("useReorder: requires a logged-in customer");
1087
+ const ctx = emporixSdk.auth.customer(token);
1088
+ const order = await qc.fetchQuery({
1089
+ queryKey: emporixKey("orders", [orderId], { tenant: client.tenant, authKind: ctx.kind }),
1090
+ queryFn: () => client.orders.get(orderId, ctx, saasToken ? { saasToken } : {})
1091
+ });
1092
+ const cartId = storage.getCartId();
1093
+ if (!cartId) throw new Error("useReorder: no active cart id in storage");
1094
+ if (order.items.length === 0) return { added: 0, errors: [] };
1095
+ const batchBody = order.items.map((item) => ({
1096
+ product: { id: item.productId },
1097
+ quantity: item.quantity
1098
+ }));
1099
+ const res = await client.carts.addItemsBatch(cartId, batchBody, ctx);
1100
+ let added = 0;
1101
+ const errors = [];
1102
+ for (const entry of res) {
1103
+ if (entry.status >= 200 && entry.status < 300) {
1104
+ added += 1;
1105
+ } else {
1106
+ errors.push(
1107
+ new Error(
1108
+ `addItemsBatch entry ${entry.index ?? "?"}: status=${entry.status}${entry.errorMessage ? " " + entry.errorMessage : ""}`
1109
+ )
1110
+ );
1111
+ }
1112
+ }
1113
+ return { added, errors };
1114
+ },
1115
+ onSuccess: () => {
1116
+ qc.invalidateQueries({ predicate: (q) => Array.isArray(q.queryKey) && q.queryKey[1] === "cart" });
1117
+ }
1118
+ });
1119
+ }
1120
+ function useSalesOrder(orderId, authCtx) {
1121
+ const { client } = useEmporix();
1122
+ return reactQuery.useQuery({
1123
+ queryKey: emporixKey("salesorders", [orderId ?? null], {
1124
+ tenant: client.tenant,
1125
+ authKind: authCtx?.kind ?? "anonymous"
1126
+ }),
1127
+ enabled: orderId !== void 0 && authCtx !== void 0,
1128
+ queryFn: () => client.salesOrders.get(orderId, authCtx)
1129
+ });
1130
+ }
1131
+ function useUpdateSalesOrder() {
1132
+ const { client } = useEmporix();
1133
+ const qc = reactQuery.useQueryClient();
1134
+ return reactQuery.useMutation({
1135
+ mutationKey: ["emporix", "salesorders", "update"],
1136
+ mutationFn: async ({ orderId, patch, auth: auth22, recalculate }) => {
1137
+ if (!auth22) throw new Error("useUpdateSalesOrder: requires an auth context");
1138
+ return client.salesOrders.update(
1139
+ orderId,
1140
+ patch,
1141
+ auth22,
1142
+ recalculate !== void 0 ? { recalculate } : {}
1143
+ );
1144
+ },
1145
+ onSuccess: (_data, vars) => {
1146
+ qc.invalidateQueries({
1147
+ predicate: (q) => Array.isArray(q.queryKey) && (q.queryKey[1] === "salesorders" || q.queryKey[1] === "orders" && q.queryKey[2] === vars.orderId)
1148
+ });
1149
+ }
1150
+ });
1151
+ }
1152
+
1153
+ exports.useActiveCart = useActiveCart;
1154
+ exports.useAddressMutations = useAddressMutations;
1155
+ exports.useAssignContact = useAssignContact;
1156
+ exports.useCancelOrder = useCancelOrder;
1157
+ exports.useCart = useCart;
1158
+ exports.useCartMutations = useCartMutations;
1159
+ exports.useCategories = useCategories;
1160
+ exports.useCategoriesInfinite = useCategoriesInfinite;
1161
+ exports.useCategory = useCategory;
1162
+ exports.useCategoryTree = useCategoryTree;
1163
+ exports.useChangePassword = useChangePassword;
1164
+ exports.useCheckout = useCheckout;
1165
+ exports.useCompany = useCompany;
1166
+ exports.useCompanyContacts = useCompanyContacts;
1167
+ exports.useCompanyGroups = useCompanyGroups;
1168
+ exports.useCompanyLocations = useCompanyLocations;
1169
+ exports.useCompanySwitcher = useCompanySwitcher;
1170
+ exports.useCreateCart = useCreateCart;
1171
+ exports.useCreateCompany = useCreateCompany;
1172
+ exports.useCreateLocation = useCreateLocation;
1173
+ exports.useCustomerAddresses = useCustomerAddresses;
1174
+ exports.useCustomerSession = useCustomerSession;
1175
+ exports.useDefaultSite = useDefaultSite;
1176
+ exports.useDeleteCompany = useDeleteCompany;
1177
+ exports.useDeleteLocation = useDeleteLocation;
1178
+ exports.useMatchPrices = useMatchPrices;
1179
+ exports.useMyCompanies = useMyCompanies;
1180
+ exports.useMyOrders = useMyOrders;
1181
+ exports.useMyOrdersInfinite = useMyOrdersInfinite;
1182
+ exports.useMySegmentCategories = useMySegmentCategories;
1183
+ exports.useMySegmentCategoriesInfinite = useMySegmentCategoriesInfinite;
1184
+ exports.useMySegmentCategoryTree = useMySegmentCategoryTree;
1185
+ exports.useMySegmentItems = useMySegmentItems;
1186
+ exports.useMySegmentProducts = useMySegmentProducts;
1187
+ exports.useMySegmentProductsInfinite = useMySegmentProductsInfinite;
1188
+ exports.useMySegments = useMySegments;
1189
+ exports.useOrder = useOrder;
1190
+ exports.useOrderTransition = useOrderTransition;
1191
+ exports.usePasswordReset = usePasswordReset;
1192
+ exports.usePaymentModes = usePaymentModes;
1193
+ exports.useProduct = useProduct;
1194
+ exports.useProductByCode = useProductByCode;
1195
+ exports.useProductMedia = useProductMedia;
1196
+ exports.useProductSearch = useProductSearch;
1197
+ exports.useProducts = useProducts;
1198
+ exports.useProductsInCategory = useProductsInCategory;
1199
+ exports.useProductsInCategoryInfinite = useProductsInCategoryInfinite;
1200
+ exports.useProductsInfinite = useProductsInfinite;
1201
+ exports.useReorder = useReorder;
1202
+ exports.useSalesOrder = useSalesOrder;
1203
+ exports.useSiteContext = useSiteContext;
1204
+ exports.useSites = useSites;
1205
+ exports.useUnassignContact = useUnassignContact;
1206
+ exports.useUpdateCompany = useUpdateCompany;
1207
+ exports.useUpdateContactAssignment = useUpdateContactAssignment;
1208
+ exports.useUpdateCustomer = useUpdateCustomer;
1209
+ exports.useUpdateLocation = useUpdateLocation;
1210
+ exports.useUpdateSalesOrder = useUpdateSalesOrder;
1211
+ //# sourceMappingURL=hooks.cjs.map
1212
+ //# sourceMappingURL=hooks.cjs.map