@a-cube-io/ereceipts-js-sdk 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.
Files changed (49) hide show
  1. package/LICENSE +41 -0
  2. package/README.md +444 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/auth-D6UEILKY.cjs +56 -0
  5. package/dist/auth-D6UEILKY.cjs.map +1 -0
  6. package/dist/auth-RZRIC4PK.js +7 -0
  7. package/dist/auth-RZRIC4PK.js.map +1 -0
  8. package/dist/chunk-24ZJ6SNG.cjs +624 -0
  9. package/dist/chunk-24ZJ6SNG.cjs.map +1 -0
  10. package/dist/chunk-C3YEL4ED.js +511 -0
  11. package/dist/chunk-C3YEL4ED.js.map +1 -0
  12. package/dist/chunk-K65HAAAO.js +44 -0
  13. package/dist/chunk-K65HAAAO.js.map +1 -0
  14. package/dist/chunk-NARXAXFL.cjs +215 -0
  15. package/dist/chunk-NARXAXFL.cjs.map +1 -0
  16. package/dist/chunk-UBEIMFLN.js +209 -0
  17. package/dist/chunk-UBEIMFLN.js.map +1 -0
  18. package/dist/chunk-UVUWF5FV.cjs +3964 -0
  19. package/dist/chunk-UVUWF5FV.cjs.map +1 -0
  20. package/dist/chunk-UXVFQRZK.cjs +533 -0
  21. package/dist/chunk-UXVFQRZK.cjs.map +1 -0
  22. package/dist/chunk-VDHN3FKS.js +3929 -0
  23. package/dist/chunk-VDHN3FKS.js.map +1 -0
  24. package/dist/chunk-XQKCXG4I.cjs +52 -0
  25. package/dist/chunk-XQKCXG4I.cjs.map +1 -0
  26. package/dist/chunk-YX3PJ4FC.js +590 -0
  27. package/dist/chunk-YX3PJ4FC.js.map +1 -0
  28. package/dist/client-WPBRHPKX.cjs +31 -0
  29. package/dist/client-WPBRHPKX.cjs.map +1 -0
  30. package/dist/client-Z2LXQJMF.js +6 -0
  31. package/dist/client-Z2LXQJMF.js.map +1 -0
  32. package/dist/index.cjs +1326 -0
  33. package/dist/index.cjs.map +1 -0
  34. package/dist/index.d.cts +960 -0
  35. package/dist/index.d.ts +960 -0
  36. package/dist/index.js +1065 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/metafile-cjs.json +1 -0
  39. package/dist/metafile-esm.json +1 -0
  40. package/dist/queue-D7PJ536B.js +4 -0
  41. package/dist/queue-D7PJ536B.js.map +1 -0
  42. package/dist/queue-JHWXWX2B.cjs +13 -0
  43. package/dist/queue-JHWXWX2B.cjs.map +1 -0
  44. package/dist/token-3CIX4E64.cjs +13 -0
  45. package/dist/token-3CIX4E64.cjs.map +1 -0
  46. package/dist/token-4OAGWTVG.js +4 -0
  47. package/dist/token-4OAGWTVG.js.map +1 -0
  48. package/openapi.yaml +2732 -0
  49. package/package.json +115 -0
package/dist/index.js ADDED
@@ -0,0 +1,1065 @@
1
+ import { isAuthenticated, getCurrentUser, loginProvider, AuthenticationError, loginMerchant, loginCashier, logout, validateAddress, validateEmail, validateFiscalId } from './chunk-C3YEL4ED.js';
2
+ export { AuthenticationError, combineValidationResults, getCurrentUser, hasRole, isAuthenticated, loginCashier, loginMerchant, loginProvider, logout, refreshToken, validateAddress, validateEmail, validateFiscalId, validateMoneyAmount, validatePassword, validateProvinceCode, validateReceiptItem, validateRequired, validateZipCode } from './chunk-C3YEL4ED.js';
3
+ import { getAPIClient, MF1_PATHS, MF2_PATHS, isConnected, addNetworkListener } from './chunk-VDHN3FKS.js';
4
+ export { APIClient, API_ENDPOINTS, AxiosRetryInterceptor, MF1_PATHS, MF2_PATHS, addNetworkListener, calculateJitteredDelay, calculateRetryDelay, checkInternetConnectivity, configureSDK, getAPIClient, getBaseURL, getNetworkState, initializeAPIClient, isConnected, isRetryableError, removeNetworkListener, retryAsync, waitForConnection, withRetry } from './chunk-VDHN3FKS.js';
5
+ import { SecureTokenStorage, networkLogger } from './chunk-YX3PJ4FC.js';
6
+ export { SecureTokenStorage, apiLogger, authLogger, logDebug, logError, logInfo, logWarn, networkLogger, storageLogger, uiLogger } from './chunk-YX3PJ4FC.js';
7
+ import { RequestQueue } from './chunk-UBEIMFLN.js';
8
+ export { RequestQueue } from './chunk-UBEIMFLN.js';
9
+ import { __name, getMTLSCertificateKey, getMTLSPrivateKeyKey } from './chunk-K65HAAAO.js';
10
+ export { SECURE_KEYS, STORAGE_KEYS, getMTLSCertificateKey, getMTLSPrivateKeyKey } from './chunk-K65HAAAO.js';
11
+ import React2, { forwardRef, useState, useCallback, useEffect } from 'react';
12
+ import { StyleSheet, View, Text, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
13
+
14
+ /* A-Cube SDK - Professional TypeScript SDK for Italian e-receipt system */
15
+
16
+ // src/api/mf1.ts
17
+ var createCashier = /* @__PURE__ */ __name(async (data) => {
18
+ const client = getAPIClient();
19
+ const response = await client.post(MF1_PATHS.CASHIERS, data);
20
+ return response.data;
21
+ }, "createCashier");
22
+ var getCashiers = /* @__PURE__ */ __name(async (page = 1, size = 30) => {
23
+ const client = getAPIClient();
24
+ const response = await client.get(`${MF1_PATHS.CASHIERS}?page=${page}&size=${size}`);
25
+ return response.data;
26
+ }, "getCashiers");
27
+ var getCashierById = /* @__PURE__ */ __name(async (id) => {
28
+ const client = getAPIClient();
29
+ const response = await client.get(MF1_PATHS.CASHIER_BY_ID(id));
30
+ return response.data;
31
+ }, "getCashierById");
32
+ var getCurrentCashier = /* @__PURE__ */ __name(async () => {
33
+ const client = getAPIClient();
34
+ const response = await client.get(MF1_PATHS.CASHIER_ME);
35
+ return response.data;
36
+ }, "getCurrentCashier");
37
+ var deleteCashier = /* @__PURE__ */ __name(async (id) => {
38
+ const client = getAPIClient();
39
+ await client.delete(MF1_PATHS.CASHIER_BY_ID(id));
40
+ }, "deleteCashier");
41
+ var getPointOfSales = /* @__PURE__ */ __name(async (status, page = 1, size = 30) => {
42
+ const client = getAPIClient();
43
+ let url = `${MF1_PATHS.POINT_OF_SALES}?page=${page}&size=${size}`;
44
+ if (status) {
45
+ url += `&status=${status}`;
46
+ }
47
+ const response = await client.get(url);
48
+ return response.data;
49
+ }, "getPointOfSales");
50
+ var getPointOfSaleBySerial = /* @__PURE__ */ __name(async (serialNumber) => {
51
+ const client = getAPIClient();
52
+ const response = await client.get(MF1_PATHS.POINT_OF_SALE_BY_SERIAL(serialNumber));
53
+ return response.data;
54
+ }, "getPointOfSaleBySerial");
55
+ var activatePointOfSale = /* @__PURE__ */ __name(async (serialNumber, registrationKey) => {
56
+ const client = getAPIClient();
57
+ await client.post(MF1_PATHS.POINT_OF_SALE_ACTIVATION(serialNumber), {
58
+ registration_key: registrationKey
59
+ });
60
+ }, "activatePointOfSale");
61
+ var createInactivityPeriod = /* @__PURE__ */ __name(async (serialNumber) => {
62
+ const client = getAPIClient();
63
+ await client.post(MF1_PATHS.POINT_OF_SALE_INACTIVITY(serialNumber));
64
+ }, "createInactivityPeriod");
65
+ var setPointOfSaleOffline = /* @__PURE__ */ __name(async (serialNumber, timestamp, reason) => {
66
+ const client = getAPIClient();
67
+ await client.post(MF1_PATHS.POINT_OF_SALE_OFFLINE(serialNumber), {
68
+ timestamp,
69
+ reason
70
+ });
71
+ }, "setPointOfSaleOffline");
72
+ var closeJournal = /* @__PURE__ */ __name(async () => {
73
+ const client = getAPIClient();
74
+ await client.post(MF1_PATHS.CLOSE_JOURNAL);
75
+ }, "closeJournal");
76
+ var createReceipt = /* @__PURE__ */ __name(async (data) => {
77
+ const client = getAPIClient();
78
+ const response = await client.post(MF1_PATHS.RECEIPTS, data);
79
+ return response.data;
80
+ }, "createReceipt");
81
+ var getReceipts = /* @__PURE__ */ __name(async (page = 1, size = 30) => {
82
+ const client = getAPIClient();
83
+ const response = await client.get(`${MF1_PATHS.RECEIPTS}?page=${page}&size=${size}`);
84
+ return response.data;
85
+ }, "getReceipts");
86
+ var getReceiptById = /* @__PURE__ */ __name(async (uuid) => {
87
+ const client = getAPIClient();
88
+ const response = await client.get(MF1_PATHS.RECEIPT_BY_UUID(uuid));
89
+ return response.data;
90
+ }, "getReceiptById");
91
+ var getReceiptDetails = /* @__PURE__ */ __name(async (uuid, format = "json") => {
92
+ const client = getAPIClient();
93
+ const headers = format === "pdf" ? {
94
+ Accept: "application/pdf"
95
+ } : {
96
+ Accept: "application/json"
97
+ };
98
+ const response = await client.get(MF1_PATHS.RECEIPT_DETAILS(uuid), {
99
+ headers
100
+ });
101
+ if (format === "pdf") {
102
+ return new Blob([
103
+ response.data
104
+ ], {
105
+ type: "application/pdf"
106
+ });
107
+ }
108
+ return response.data;
109
+ }, "getReceiptDetails");
110
+ var voidReceipt = /* @__PURE__ */ __name(async (data) => {
111
+ const client = getAPIClient();
112
+ await client.delete(MF1_PATHS.RECEIPTS, {
113
+ data
114
+ });
115
+ }, "voidReceipt");
116
+ var voidReceiptWithProof = /* @__PURE__ */ __name(async (data) => {
117
+ const client = getAPIClient();
118
+ await client.delete(MF1_PATHS.RECEIPT_VOID_WITH_PROOF, {
119
+ data
120
+ });
121
+ }, "voidReceiptWithProof");
122
+ var returnReceiptItems = /* @__PURE__ */ __name(async (data) => {
123
+ const client = getAPIClient();
124
+ const response = await client.post(MF1_PATHS.RECEIPT_RETURN, data);
125
+ return response.data;
126
+ }, "returnReceiptItems");
127
+ var returnReceiptItemsWithProof = /* @__PURE__ */ __name(async (data) => {
128
+ const client = getAPIClient();
129
+ const response = await client.post(MF1_PATHS.RECEIPT_RETURN_WITH_PROOF, data);
130
+ return response.data;
131
+ }, "returnReceiptItemsWithProof");
132
+ var createCashRegister = /* @__PURE__ */ __name(async (data) => {
133
+ const client = getAPIClient();
134
+ const response = await client.post(MF1_PATHS.CASH_REGISTER, data);
135
+ return response.data;
136
+ }, "createCashRegister");
137
+ var getCashRegisters = /* @__PURE__ */ __name(async (page = 1, size = 30) => {
138
+ const client = getAPIClient();
139
+ const response = await client.get(`${MF1_PATHS.CASH_REGISTER}?page=${page}&size=${size}`);
140
+ return response.data;
141
+ }, "getCashRegisters");
142
+ var getCashRegisterById = /* @__PURE__ */ __name(async (id) => {
143
+ const client = getAPIClient();
144
+ const response = await client.get(MF1_PATHS.CASH_REGISTER_BY_ID(id));
145
+ return response.data;
146
+ }, "getCashRegisterById");
147
+ var getMTLSCertificate = /* @__PURE__ */ __name(async (id) => {
148
+ const client = getAPIClient();
149
+ const response = await client.get(MF1_PATHS.CASH_REGISTER_MTLS_CERT(id));
150
+ return response.data;
151
+ }, "getMTLSCertificate");
152
+
153
+ // src/api/mf2.ts
154
+ var createMerchant = /* @__PURE__ */ __name(async (data) => {
155
+ const client = getAPIClient();
156
+ const response = await client.post(MF2_PATHS.MERCHANTS, data);
157
+ return response.data;
158
+ }, "createMerchant");
159
+ var getMerchants = /* @__PURE__ */ __name(async (page = 1) => {
160
+ const client = getAPIClient();
161
+ const response = await client.get(`${MF2_PATHS.MERCHANTS}?page=${page}`);
162
+ return response.data;
163
+ }, "getMerchants");
164
+ var getMerchantById = /* @__PURE__ */ __name(async (uuid) => {
165
+ const client = getAPIClient();
166
+ const response = await client.get(MF2_PATHS.MERCHANT_BY_UUID(uuid));
167
+ return response.data;
168
+ }, "getMerchantById");
169
+ var updateMerchant = /* @__PURE__ */ __name(async (uuid, data) => {
170
+ const client = getAPIClient();
171
+ const response = await client.put(MF2_PATHS.MERCHANT_BY_UUID(uuid), data);
172
+ return response.data;
173
+ }, "updateMerchant");
174
+ var useAuth = /* @__PURE__ */ __name(() => {
175
+ const [state, setState] = useState({
176
+ isAuthenticated: false,
177
+ isLoading: true,
178
+ user: null,
179
+ token: null
180
+ });
181
+ const [error, setError] = useState(null);
182
+ const clearError = useCallback(() => {
183
+ setError(null);
184
+ }, []);
185
+ const checkAuthStatus = useCallback(async () => {
186
+ try {
187
+ setState((prev) => ({
188
+ ...prev,
189
+ isLoading: true
190
+ }));
191
+ const authenticated = await isAuthenticated();
192
+ if (authenticated) {
193
+ const user = await getCurrentUser();
194
+ setState((prev) => ({
195
+ ...prev,
196
+ isAuthenticated: true,
197
+ user,
198
+ isLoading: false
199
+ }));
200
+ } else {
201
+ setState((prev) => ({
202
+ ...prev,
203
+ isAuthenticated: false,
204
+ user: null,
205
+ token: null,
206
+ isLoading: false
207
+ }));
208
+ }
209
+ } catch (err) {
210
+ console.error("Error checking auth status:", err);
211
+ setState((prev) => ({
212
+ ...prev,
213
+ isAuthenticated: false,
214
+ user: null,
215
+ token: null,
216
+ isLoading: false
217
+ }));
218
+ }
219
+ }, []);
220
+ const loginAsProvider = useCallback(async (email, password) => {
221
+ try {
222
+ setError(null);
223
+ setState((prev) => ({
224
+ ...prev,
225
+ isLoading: true
226
+ }));
227
+ const tokenData = await loginProvider(email, password);
228
+ const user = await getCurrentUser();
229
+ setState((prev) => ({
230
+ ...prev,
231
+ isAuthenticated: true,
232
+ user,
233
+ token: tokenData.access_token,
234
+ isLoading: false
235
+ }));
236
+ } catch (err) {
237
+ const errorMessage = err instanceof AuthenticationError ? err.message : "Login failed. Please try again.";
238
+ setError(errorMessage);
239
+ setState((prev) => ({
240
+ ...prev,
241
+ isAuthenticated: false,
242
+ user: null,
243
+ token: null,
244
+ isLoading: false
245
+ }));
246
+ throw err;
247
+ }
248
+ }, []);
249
+ const loginAsMerchant = useCallback(async (email, password) => {
250
+ try {
251
+ setError(null);
252
+ setState((prev) => ({
253
+ ...prev,
254
+ isLoading: true
255
+ }));
256
+ const tokenData = await loginMerchant(email, password);
257
+ const user = await getCurrentUser();
258
+ setState((prev) => ({
259
+ ...prev,
260
+ isAuthenticated: true,
261
+ user,
262
+ token: tokenData.access_token,
263
+ isLoading: false
264
+ }));
265
+ } catch (err) {
266
+ const errorMessage = err instanceof AuthenticationError ? err.message : "Login failed. Please try again.";
267
+ setError(errorMessage);
268
+ setState((prev) => ({
269
+ ...prev,
270
+ isAuthenticated: false,
271
+ user: null,
272
+ token: null,
273
+ isLoading: false
274
+ }));
275
+ throw err;
276
+ }
277
+ }, []);
278
+ const loginAsCashier = useCallback(async (email, password) => {
279
+ try {
280
+ setError(null);
281
+ setState((prev) => ({
282
+ ...prev,
283
+ isLoading: true
284
+ }));
285
+ const tokenData = await loginCashier(email, password);
286
+ const user = await getCurrentUser();
287
+ setState((prev) => ({
288
+ ...prev,
289
+ isAuthenticated: true,
290
+ user,
291
+ token: tokenData.access_token,
292
+ isLoading: false
293
+ }));
294
+ } catch (err) {
295
+ const errorMessage = err instanceof AuthenticationError ? err.message : "Login failed. Please try again.";
296
+ setError(errorMessage);
297
+ setState((prev) => ({
298
+ ...prev,
299
+ isAuthenticated: false,
300
+ user: null,
301
+ token: null,
302
+ isLoading: false
303
+ }));
304
+ throw err;
305
+ }
306
+ }, []);
307
+ const handleLogout = useCallback(async () => {
308
+ try {
309
+ setState((prev) => ({
310
+ ...prev,
311
+ isLoading: true
312
+ }));
313
+ await logout();
314
+ setState({
315
+ isAuthenticated: false,
316
+ user: null,
317
+ token: null,
318
+ isLoading: false
319
+ });
320
+ setError(null);
321
+ } catch (err) {
322
+ console.error("Logout error:", err);
323
+ setState({
324
+ isAuthenticated: false,
325
+ user: null,
326
+ token: null,
327
+ isLoading: false
328
+ });
329
+ }
330
+ }, []);
331
+ useEffect(() => {
332
+ void checkAuthStatus();
333
+ }, [
334
+ checkAuthStatus
335
+ ]);
336
+ return {
337
+ // State
338
+ isAuthenticated: state.isAuthenticated,
339
+ isLoading: state.isLoading,
340
+ user: state.user,
341
+ token: state.token,
342
+ error,
343
+ // Actions
344
+ loginAsProvider,
345
+ loginAsMerchant,
346
+ loginAsCashier,
347
+ logout: handleLogout,
348
+ checkAuthStatus,
349
+ clearError
350
+ };
351
+ }, "useAuth");
352
+ var useRetryQueue = /* @__PURE__ */ __name(() => {
353
+ const [stats, setStats] = useState({
354
+ total: 0,
355
+ byPriority: {
356
+ high: 0,
357
+ medium: 0,
358
+ low: 0
359
+ }
360
+ });
361
+ const [isProcessing, setIsProcessing] = useState(false);
362
+ const [networkConnected, setNetworkConnected] = useState(isConnected());
363
+ const refreshStats = useCallback(async () => {
364
+ try {
365
+ const queueStats = await RequestQueue.getQueueStats();
366
+ setStats(queueStats);
367
+ } catch (error) {
368
+ networkLogger.error("Failed to refresh queue stats", error);
369
+ }
370
+ }, []);
371
+ const processQueue = useCallback(async () => {
372
+ if (isProcessing || !networkConnected) {
373
+ return;
374
+ }
375
+ try {
376
+ setIsProcessing(true);
377
+ networkLogger.info("Starting manual queue processing");
378
+ const client = getAPIClient();
379
+ await client.processOfflineQueue();
380
+ await refreshStats();
381
+ networkLogger.info("Manual queue processing completed");
382
+ } catch (error) {
383
+ networkLogger.error("Manual queue processing failed", error);
384
+ } finally {
385
+ setIsProcessing(false);
386
+ }
387
+ }, [
388
+ isProcessing,
389
+ networkConnected,
390
+ refreshStats
391
+ ]);
392
+ const clearQueue = useCallback(async () => {
393
+ try {
394
+ networkLogger.info("Clearing retry queue");
395
+ await RequestQueue.clearQueue();
396
+ await refreshStats();
397
+ networkLogger.info("Retry queue cleared");
398
+ } catch (error) {
399
+ networkLogger.error("Failed to clear retry queue", error);
400
+ }
401
+ }, [
402
+ refreshStats
403
+ ]);
404
+ useEffect(() => {
405
+ let processingTimeout;
406
+ const handleNetworkChange = /* @__PURE__ */ __name((state) => {
407
+ setNetworkConnected(state.isConnected);
408
+ if (state.isConnected && !isProcessing) {
409
+ processingTimeout = setTimeout(() => {
410
+ void (async () => {
411
+ try {
412
+ networkLogger.info("Network reconnected, auto-processing queue");
413
+ await processQueue();
414
+ } catch (error) {
415
+ networkLogger.error("Auto queue processing failed", error);
416
+ }
417
+ })();
418
+ }, 2e3);
419
+ }
420
+ }, "handleNetworkChange");
421
+ const unsubscribe = addNetworkListener(handleNetworkChange);
422
+ return () => {
423
+ unsubscribe();
424
+ if (processingTimeout) {
425
+ clearTimeout(processingTimeout);
426
+ }
427
+ };
428
+ }, [
429
+ processQueue,
430
+ isProcessing
431
+ ]);
432
+ useEffect(() => {
433
+ void refreshStats();
434
+ const interval = setInterval(() => {
435
+ void refreshStats();
436
+ }, 3e4);
437
+ return () => clearInterval(interval);
438
+ }, [
439
+ refreshStats
440
+ ]);
441
+ useEffect(() => {
442
+ const interval = setInterval(() => {
443
+ if (!isProcessing) {
444
+ void refreshStats();
445
+ }
446
+ }, 1e4);
447
+ return () => clearInterval(interval);
448
+ }, [
449
+ isProcessing,
450
+ refreshStats
451
+ ]);
452
+ return {
453
+ stats,
454
+ isProcessing,
455
+ isConnected: networkConnected,
456
+ processQueue,
457
+ clearQueue,
458
+ refreshStats
459
+ };
460
+ }, "useRetryQueue");
461
+ var TOTAL_STEPS = 3;
462
+ var useProviderFlow = /* @__PURE__ */ __name(() => {
463
+ const [state, setState] = useState({
464
+ isLoading: false,
465
+ currentStep: 1,
466
+ merchantData: {},
467
+ createdMerchant: null
468
+ });
469
+ const [error, setError] = useState(null);
470
+ const setMerchantData = useCallback((data) => {
471
+ setState((prev) => ({
472
+ ...prev,
473
+ merchantData: {
474
+ ...prev.merchantData,
475
+ ...data
476
+ }
477
+ }));
478
+ }, []);
479
+ const validateCurrentStep = useCallback(() => {
480
+ const { merchantData, currentStep } = state;
481
+ switch (currentStep) {
482
+ case 1: {
483
+ const emailValidation = validateEmail(merchantData.email ?? "");
484
+ const fiscalIdValidation = validateFiscalId(merchantData.fiscal_id ?? "");
485
+ return {
486
+ isValid: emailValidation.isValid && fiscalIdValidation.isValid,
487
+ errors: [
488
+ ...emailValidation.errors,
489
+ ...fiscalIdValidation.errors
490
+ ]
491
+ };
492
+ }
493
+ case 2:
494
+ if (!merchantData.name || merchantData.name.trim() === "") {
495
+ return {
496
+ isValid: false,
497
+ errors: [
498
+ {
499
+ field: "name",
500
+ message: "Business name is required",
501
+ code: "NAME_REQUIRED"
502
+ }
503
+ ]
504
+ };
505
+ }
506
+ return {
507
+ isValid: true,
508
+ errors: []
509
+ };
510
+ case 3:
511
+ if (merchantData.address) {
512
+ return validateAddress(merchantData.address);
513
+ }
514
+ return {
515
+ isValid: true,
516
+ errors: []
517
+ };
518
+ // Address is optional
519
+ default:
520
+ return {
521
+ isValid: true,
522
+ errors: []
523
+ };
524
+ }
525
+ }, [
526
+ state
527
+ ]);
528
+ const createMerchantFlow = useCallback(async (data) => {
529
+ try {
530
+ setError(null);
531
+ setState((prev) => ({
532
+ ...prev,
533
+ isLoading: true
534
+ }));
535
+ const merchant = await createMerchant(data);
536
+ setState((prev) => ({
537
+ ...prev,
538
+ createdMerchant: merchant,
539
+ isLoading: false
540
+ }));
541
+ return merchant;
542
+ } catch (err) {
543
+ const errorMessage = err.response?.data?.detail || "Failed to create merchant";
544
+ setError(errorMessage);
545
+ setState((prev) => ({
546
+ ...prev,
547
+ isLoading: false
548
+ }));
549
+ throw err;
550
+ }
551
+ }, []);
552
+ const nextStep = useCallback(() => {
553
+ setState((prev) => ({
554
+ ...prev,
555
+ currentStep: Math.min(prev.currentStep + 1, TOTAL_STEPS)
556
+ }));
557
+ }, []);
558
+ const previousStep = useCallback(() => {
559
+ setState((prev) => ({
560
+ ...prev,
561
+ currentStep: Math.max(prev.currentStep - 1, 1)
562
+ }));
563
+ }, []);
564
+ const resetFlow = useCallback(() => {
565
+ setState({
566
+ isLoading: false,
567
+ currentStep: 1,
568
+ merchantData: {},
569
+ createdMerchant: null
570
+ });
571
+ setError(null);
572
+ }, []);
573
+ const clearError = useCallback(() => {
574
+ setError(null);
575
+ }, []);
576
+ return {
577
+ ...state,
578
+ error,
579
+ setMerchantData,
580
+ validateCurrentStep,
581
+ createMerchantFlow,
582
+ nextStep,
583
+ previousStep,
584
+ resetFlow,
585
+ clearError
586
+ };
587
+ }, "useProviderFlow");
588
+ var Button = /* @__PURE__ */ __name(({ title, onPress, variant = "primary", size = "medium", disabled = false, loading = false, fullWidth = false, style, textStyle, testID }) => {
589
+ const isDisabled = disabled || loading;
590
+ const buttonStyle = [
591
+ styles.base,
592
+ styles[variant],
593
+ styles[size],
594
+ fullWidth && styles.fullWidth,
595
+ isDisabled && styles.disabled,
596
+ style
597
+ ].filter(Boolean);
598
+ const textColor = [
599
+ styles.baseText,
600
+ styles[`${variant}Text`],
601
+ styles[`${size}Text`],
602
+ isDisabled && styles.disabledText,
603
+ textStyle
604
+ ].filter(Boolean);
605
+ return /* @__PURE__ */ React2.createElement(TouchableOpacity, {
606
+ style: buttonStyle,
607
+ onPress,
608
+ disabled: isDisabled,
609
+ testID,
610
+ accessibilityRole: "button",
611
+ accessibilityState: {
612
+ disabled: isDisabled
613
+ },
614
+ accessibilityLabel: title
615
+ }, /* @__PURE__ */ React2.createElement(View, {
616
+ style: styles.content
617
+ }, loading && /* @__PURE__ */ React2.createElement(ActivityIndicator, {
618
+ size: "small",
619
+ color: variant === "outline" ? "#007AFF" : "#FFFFFF",
620
+ style: styles.loader
621
+ }), /* @__PURE__ */ React2.createElement(Text, {
622
+ style: textColor
623
+ }, title)));
624
+ }, "Button");
625
+ var styles = StyleSheet.create({
626
+ base: {
627
+ borderRadius: 8,
628
+ justifyContent: "center",
629
+ alignItems: "center",
630
+ borderWidth: 1,
631
+ borderColor: "transparent"
632
+ },
633
+ content: {
634
+ flexDirection: "row",
635
+ alignItems: "center",
636
+ justifyContent: "center"
637
+ },
638
+ loader: {
639
+ marginRight: 8
640
+ },
641
+ // Variants
642
+ primary: {
643
+ backgroundColor: "#007AFF",
644
+ borderColor: "#007AFF"
645
+ },
646
+ secondary: {
647
+ backgroundColor: "#6C757D",
648
+ borderColor: "#6C757D"
649
+ },
650
+ outline: {
651
+ backgroundColor: "transparent",
652
+ borderColor: "#007AFF",
653
+ borderWidth: 1
654
+ },
655
+ danger: {
656
+ backgroundColor: "#DC3545",
657
+ borderColor: "#DC3545"
658
+ },
659
+ // Sizes
660
+ small: {
661
+ paddingHorizontal: 12,
662
+ paddingVertical: 6,
663
+ minHeight: 32
664
+ },
665
+ medium: {
666
+ paddingHorizontal: 16,
667
+ paddingVertical: 10,
668
+ minHeight: 44
669
+ },
670
+ large: {
671
+ paddingHorizontal: 24,
672
+ paddingVertical: 14,
673
+ minHeight: 52
674
+ },
675
+ // States
676
+ disabled: {
677
+ opacity: 0.5
678
+ },
679
+ fullWidth: {
680
+ width: "100%"
681
+ },
682
+ // Text styles
683
+ baseText: {
684
+ fontWeight: "600",
685
+ textAlign: "center"
686
+ },
687
+ primaryText: {
688
+ color: "#FFFFFF"
689
+ },
690
+ secondaryText: {
691
+ color: "#FFFFFF"
692
+ },
693
+ outlineText: {
694
+ color: "#007AFF"
695
+ },
696
+ dangerText: {
697
+ color: "#FFFFFF"
698
+ },
699
+ smallText: {
700
+ fontSize: 14
701
+ },
702
+ mediumText: {
703
+ fontSize: 16
704
+ },
705
+ largeText: {
706
+ fontSize: 18
707
+ },
708
+ disabledText: {
709
+ opacity: 0.7
710
+ }
711
+ });
712
+ var FormInput = /* @__PURE__ */ forwardRef(({ label, error, helperText, required = false, containerStyle, labelStyle, inputStyle, errorStyle, helperStyle, leftIcon, rightIcon, showPasswordToggle = false, secureTextEntry, ...textInputProps }, ref) => {
713
+ const [isPasswordVisible, setIsPasswordVisible] = useState(false);
714
+ const [isFocused, setIsFocused] = useState(false);
715
+ const isPassword = secureTextEntry ?? showPasswordToggle;
716
+ const actualSecureTextEntry = isPassword ? !isPasswordVisible : false;
717
+ const handleTogglePassword = /* @__PURE__ */ __name(() => {
718
+ setIsPasswordVisible(!isPasswordVisible);
719
+ }, "handleTogglePassword");
720
+ const inputContainerStyle = [
721
+ styles2.inputContainer,
722
+ isFocused && styles2.inputContainerFocused,
723
+ error && styles2.inputContainerError
724
+ ].filter(Boolean);
725
+ const textInputStyle = [
726
+ styles2.input,
727
+ leftIcon && styles2.inputWithLeftIcon,
728
+ (rightIcon ?? showPasswordToggle) && styles2.inputWithRightIcon,
729
+ inputStyle
730
+ ].filter(Boolean);
731
+ return /* @__PURE__ */ React2.createElement(View, {
732
+ style: [
733
+ styles2.container,
734
+ containerStyle
735
+ ]
736
+ }, label && /* @__PURE__ */ React2.createElement(View, {
737
+ style: styles2.labelContainer
738
+ }, /* @__PURE__ */ React2.createElement(Text, {
739
+ style: [
740
+ styles2.label,
741
+ labelStyle
742
+ ]
743
+ }, label, required && /* @__PURE__ */ React2.createElement(Text, {
744
+ style: styles2.required
745
+ }, " *"))), /* @__PURE__ */ React2.createElement(View, {
746
+ style: inputContainerStyle
747
+ }, leftIcon && /* @__PURE__ */ React2.createElement(View, {
748
+ style: styles2.leftIconContainer
749
+ }, leftIcon), /* @__PURE__ */ React2.createElement(TextInput, {
750
+ ref,
751
+ style: textInputStyle,
752
+ secureTextEntry: actualSecureTextEntry,
753
+ onFocus: /* @__PURE__ */ __name(() => setIsFocused(true), "onFocus"),
754
+ onBlur: /* @__PURE__ */ __name(() => setIsFocused(false), "onBlur"),
755
+ placeholderTextColor: "#999999",
756
+ ...textInputProps
757
+ }), (rightIcon ?? showPasswordToggle) && /* @__PURE__ */ React2.createElement(View, {
758
+ style: styles2.rightIconContainer
759
+ }, showPasswordToggle ? /* @__PURE__ */ React2.createElement(TouchableOpacity, {
760
+ onPress: handleTogglePassword,
761
+ style: styles2.passwordToggle,
762
+ accessibilityRole: "button",
763
+ accessibilityLabel: isPasswordVisible ? "Hide password" : "Show password"
764
+ }, /* @__PURE__ */ React2.createElement(Text, {
765
+ style: styles2.passwordToggleText
766
+ }, isPasswordVisible ? "\u{1F648}" : "\u{1F441}\uFE0F")) : rightIcon)), error && /* @__PURE__ */ React2.createElement(Text, {
767
+ style: [
768
+ styles2.errorText,
769
+ errorStyle
770
+ ]
771
+ }, error), helperText && !error && /* @__PURE__ */ React2.createElement(Text, {
772
+ style: [
773
+ styles2.helperText,
774
+ helperStyle
775
+ ]
776
+ }, helperText));
777
+ });
778
+ FormInput.displayName = "FormInput";
779
+ var styles2 = StyleSheet.create({
780
+ container: {
781
+ marginBottom: 16
782
+ },
783
+ labelContainer: {
784
+ marginBottom: 6
785
+ },
786
+ label: {
787
+ fontSize: 16,
788
+ fontWeight: "500",
789
+ color: "#333333"
790
+ },
791
+ required: {
792
+ color: "#DC3545"
793
+ },
794
+ inputContainer: {
795
+ flexDirection: "row",
796
+ alignItems: "center",
797
+ borderWidth: 1,
798
+ borderColor: "#CCCCCC",
799
+ borderRadius: 8,
800
+ backgroundColor: "#FFFFFF",
801
+ minHeight: 44
802
+ },
803
+ inputContainerFocused: {
804
+ borderColor: "#007AFF",
805
+ shadowColor: "#007AFF",
806
+ shadowOffset: {
807
+ width: 0,
808
+ height: 0
809
+ },
810
+ shadowOpacity: 0.2,
811
+ shadowRadius: 4,
812
+ elevation: 2
813
+ },
814
+ inputContainerError: {
815
+ borderColor: "#DC3545"
816
+ },
817
+ input: {
818
+ flex: 1,
819
+ fontSize: 16,
820
+ color: "#333333",
821
+ paddingHorizontal: 12,
822
+ paddingVertical: 10
823
+ },
824
+ inputWithLeftIcon: {
825
+ paddingLeft: 8
826
+ },
827
+ inputWithRightIcon: {
828
+ paddingRight: 8
829
+ },
830
+ leftIconContainer: {
831
+ paddingLeft: 12,
832
+ justifyContent: "center",
833
+ alignItems: "center"
834
+ },
835
+ rightIconContainer: {
836
+ paddingRight: 12,
837
+ justifyContent: "center",
838
+ alignItems: "center"
839
+ },
840
+ passwordToggle: {
841
+ padding: 4
842
+ },
843
+ passwordToggleText: {
844
+ fontSize: 16
845
+ },
846
+ errorText: {
847
+ fontSize: 14,
848
+ color: "#DC3545",
849
+ marginTop: 4
850
+ },
851
+ helperText: {
852
+ fontSize: 14,
853
+ color: "#666666",
854
+ marginTop: 4
855
+ }
856
+ });
857
+
858
+ // src/storage/certificate.ts
859
+ var _CertificateStorage = class _CertificateStorage {
860
+ /**
861
+ * Store mTLS certificate securely
862
+ */
863
+ static async storeMTLSCertificate(uuid, certificate, privateKey) {
864
+ const certData = {
865
+ uuid,
866
+ certificate,
867
+ privateKey,
868
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
869
+ };
870
+ const certKey = getMTLSCertificateKey(uuid);
871
+ await SecureTokenStorage.setItem(certKey, JSON.stringify(certData));
872
+ }
873
+ /**
874
+ * Retrieve mTLS certificate
875
+ */
876
+ static async getMTLSCertificate(uuid) {
877
+ try {
878
+ const certKey = getMTLSCertificateKey(uuid);
879
+ const certDataStr = await SecureTokenStorage.getItem(certKey);
880
+ if (!certDataStr) {
881
+ return null;
882
+ }
883
+ return JSON.parse(certDataStr);
884
+ } catch (error) {
885
+ console.warn(`Failed to retrieve certificate for ${uuid}:`, error);
886
+ return null;
887
+ }
888
+ }
889
+ /**
890
+ * Remove mTLS certificate
891
+ */
892
+ static async removeMTLSCertificate(uuid) {
893
+ const certKey = getMTLSCertificateKey(uuid);
894
+ const privateKeyKey = getMTLSPrivateKeyKey(uuid);
895
+ await Promise.all([
896
+ SecureTokenStorage.removeItem(certKey),
897
+ SecureTokenStorage.removeItem(privateKeyKey)
898
+ ]);
899
+ }
900
+ /**
901
+ * List all stored certificates
902
+ */
903
+ static async listCertificates() {
904
+ try {
905
+ const certificates = [];
906
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
907
+ return certificates;
908
+ } catch (error) {
909
+ console.warn("Failed to list certificates:", error);
910
+ return [];
911
+ }
912
+ }
913
+ /**
914
+ * Check if certificate exists
915
+ */
916
+ static async hasCertificate(uuid) {
917
+ const certificate = await this.getMTLSCertificate(uuid);
918
+ return certificate !== null;
919
+ }
920
+ /**
921
+ * Validate certificate (basic checks)
922
+ */
923
+ static async validateCertificate(uuid) {
924
+ const certificate = await this.getMTLSCertificate(uuid);
925
+ if (!certificate) {
926
+ return false;
927
+ }
928
+ if (!certificate.certificate || certificate.certificate.trim() === "") {
929
+ return false;
930
+ }
931
+ if (certificate.expiresAt) {
932
+ const expiryDate = new Date(certificate.expiresAt);
933
+ if (expiryDate < /* @__PURE__ */ new Date()) {
934
+ return false;
935
+ }
936
+ }
937
+ return true;
938
+ }
939
+ /**
940
+ * Parse certificate information (basic implementation)
941
+ */
942
+ static parseCertificateInfo(certificatePEM) {
943
+ try {
944
+ const cert = certificatePEM.replace(/-----BEGIN CERTIFICATE-----/, "").replace(/-----END CERTIFICATE-----/, "").replace(/\s/g, "");
945
+ return {
946
+ fingerprint: cert.substring(0, 40)
947
+ };
948
+ } catch (error) {
949
+ console.warn("Failed to parse certificate:", error);
950
+ return {};
951
+ }
952
+ }
953
+ /**
954
+ * Clear all certificates
955
+ */
956
+ static async clearAllCertificates() {
957
+ const certificates = await this.listCertificates();
958
+ await Promise.all(certificates.map((cert) => this.removeMTLSCertificate(cert.uuid)));
959
+ }
960
+ };
961
+ __name(_CertificateStorage, "CertificateStorage");
962
+ var CertificateStorage = _CertificateStorage;
963
+
964
+ // src/constants/roles.ts
965
+ var UserRole = /* @__PURE__ */ function(UserRole2) {
966
+ UserRole2["PROVIDER"] = "provider";
967
+ UserRole2["MERCHANT"] = "merchant";
968
+ UserRole2["CASHIER"] = "cashier";
969
+ return UserRole2;
970
+ }({});
971
+ var ROLE_PERMISSIONS = {
972
+ ["provider"]: [
973
+ "create_merchant",
974
+ "manage_merchants",
975
+ "view_all_data"
976
+ ],
977
+ ["merchant"]: [
978
+ "create_cashier",
979
+ "manage_pos",
980
+ "create_cash_register",
981
+ "view_receipts",
982
+ "manage_business_data"
983
+ ],
984
+ ["cashier"]: [
985
+ "create_receipt",
986
+ "void_receipt",
987
+ "return_items",
988
+ "view_own_receipts"
989
+ ]
990
+ };
991
+ var hasPermission = /* @__PURE__ */ __name((userRole, permission) => {
992
+ const permissions = ROLE_PERMISSIONS[userRole];
993
+ return permissions.includes(permission);
994
+ }, "hasPermission");
995
+ var isProvider = /* @__PURE__ */ __name((role) => role === "provider", "isProvider");
996
+ var isMerchant = /* @__PURE__ */ __name((role) => role === "merchant", "isMerchant");
997
+ var isCashier = /* @__PURE__ */ __name((role) => role === "cashier", "isCashier");
998
+
999
+ // src/index.ts
1000
+ var SDK_VERSION = "1.0.0";
1001
+ var SDK_NAME = "a-cube-io/ereceipts-js-sdk";
1002
+ var initSDK = /* @__PURE__ */ __name(async (config) => {
1003
+ const { initializeAPIClient: initializeAPIClient2 } = await import('./client-Z2LXQJMF.js');
1004
+ return initializeAPIClient2(config);
1005
+ }, "initSDK");
1006
+ var quickLoginProvider = /* @__PURE__ */ __name(async (email, password) => {
1007
+ try {
1008
+ const { loginProvider: loginProvider2 } = await import('./auth-RZRIC4PK.js');
1009
+ const token = await loginProvider2(email, password);
1010
+ return {
1011
+ success: true,
1012
+ token
1013
+ };
1014
+ } catch (error) {
1015
+ return {
1016
+ success: false,
1017
+ error
1018
+ };
1019
+ }
1020
+ }, "quickLoginProvider");
1021
+ var quickLoginMerchant = /* @__PURE__ */ __name(async (email, password) => {
1022
+ try {
1023
+ const { loginMerchant: loginMerchant2 } = await import('./auth-RZRIC4PK.js');
1024
+ const token = await loginMerchant2(email, password);
1025
+ return {
1026
+ success: true,
1027
+ token
1028
+ };
1029
+ } catch (error) {
1030
+ return {
1031
+ success: false,
1032
+ error
1033
+ };
1034
+ }
1035
+ }, "quickLoginMerchant");
1036
+ var isSDKReady = /* @__PURE__ */ __name(async () => {
1037
+ try {
1038
+ const { getAPIClient: getAPIClient2 } = await import('./client-Z2LXQJMF.js');
1039
+ const client = getAPIClient2();
1040
+ return client !== null;
1041
+ } catch {
1042
+ return false;
1043
+ }
1044
+ }, "isSDKReady");
1045
+ {
1046
+ if (typeof globalThis !== "undefined") {
1047
+ globalThis.__ACUBE_SDK__ = {
1048
+ getAPIClient: /* @__PURE__ */ __name(async () => {
1049
+ const { getAPIClient: getAPIClient2 } = await import('./client-Z2LXQJMF.js');
1050
+ return getAPIClient2();
1051
+ }, "getAPIClient"),
1052
+ version: SDK_VERSION,
1053
+ clearAllData: /* @__PURE__ */ __name(async () => {
1054
+ const { SecureTokenStorage: SecureTokenStorage2 } = await import('./token-4OAGWTVG.js');
1055
+ const { RequestQueue: RequestQueue2 } = await import('./queue-D7PJ536B.js');
1056
+ await SecureTokenStorage2.clearAll();
1057
+ await RequestQueue2.clearQueue();
1058
+ }, "clearAllData")
1059
+ };
1060
+ }
1061
+ }
1062
+
1063
+ export { Button, CertificateStorage, FormInput, ROLE_PERMISSIONS, SDK_NAME, SDK_VERSION, UserRole, activatePointOfSale, closeJournal, createCashRegister, createCashier, createInactivityPeriod, createMerchant, createReceipt, deleteCashier, getCashRegisterById, getCashRegisters, getCashierById, getCashiers, getCurrentCashier, getMTLSCertificate, getMerchantById, getMerchants, getPointOfSaleBySerial, getPointOfSales, getReceiptById, getReceiptDetails, getReceipts, hasPermission, initSDK, isCashier, isMerchant, isProvider, isSDKReady, quickLoginMerchant, quickLoginProvider, returnReceiptItems, returnReceiptItemsWithProof, setPointOfSaleOffline, updateMerchant, useAuth, useProviderFlow, useRetryQueue, voidReceipt, voidReceiptWithProof };
1064
+ //# sourceMappingURL=index.js.map
1065
+ //# sourceMappingURL=index.js.map