@explorins/pers-sdk-react-native 1.3.2 → 1.5.2

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 (94) hide show
  1. package/README.md +276 -123
  2. package/dist/hooks/index.d.ts +10 -0
  3. package/dist/hooks/index.d.ts.map +1 -1
  4. package/dist/hooks/index.js +8 -0
  5. package/dist/hooks/useAnalytics.d.ts +96 -0
  6. package/dist/hooks/useAnalytics.d.ts.map +1 -0
  7. package/dist/hooks/useAnalytics.js +73 -0
  8. package/dist/hooks/useAuth.d.ts +52 -7
  9. package/dist/hooks/useAuth.d.ts.map +1 -1
  10. package/dist/hooks/useAuth.js +250 -3
  11. package/dist/hooks/useBusiness.d.ts +45 -3
  12. package/dist/hooks/useBusiness.d.ts.map +1 -1
  13. package/dist/hooks/useBusiness.js +182 -28
  14. package/dist/hooks/useCampaigns.d.ts +11 -4
  15. package/dist/hooks/useCampaigns.d.ts.map +1 -1
  16. package/dist/hooks/useCampaigns.js +101 -39
  17. package/dist/hooks/useDonations.d.ts +33 -0
  18. package/dist/hooks/useDonations.d.ts.map +1 -0
  19. package/dist/hooks/useDonations.js +62 -0
  20. package/dist/hooks/useFiles.d.ts +50 -0
  21. package/dist/hooks/useFiles.d.ts.map +1 -0
  22. package/dist/hooks/useFiles.js +140 -0
  23. package/dist/hooks/usePurchases.d.ts +9 -0
  24. package/dist/hooks/usePurchases.d.ts.map +1 -0
  25. package/dist/hooks/usePurchases.js +56 -0
  26. package/dist/hooks/useRedemptions.d.ts +10 -5
  27. package/dist/hooks/useRedemptions.d.ts.map +1 -1
  28. package/dist/hooks/useRedemptions.js +118 -66
  29. package/dist/hooks/useTenants.d.ts +10 -0
  30. package/dist/hooks/useTenants.d.ts.map +1 -0
  31. package/dist/hooks/useTenants.js +68 -0
  32. package/dist/hooks/useTokens.d.ts +36 -2
  33. package/dist/hooks/useTokens.d.ts.map +1 -1
  34. package/dist/hooks/useTokens.js +180 -19
  35. package/dist/hooks/useTransactionSigner.d.ts +73 -0
  36. package/dist/hooks/useTransactionSigner.d.ts.map +1 -0
  37. package/dist/hooks/useTransactionSigner.js +216 -0
  38. package/dist/hooks/useTransactions.d.ts +45 -3
  39. package/dist/hooks/useTransactions.d.ts.map +1 -1
  40. package/dist/hooks/useTransactions.js +149 -39
  41. package/dist/hooks/useUserStatus.d.ts +9 -0
  42. package/dist/hooks/useUserStatus.d.ts.map +1 -0
  43. package/dist/hooks/useUserStatus.js +57 -0
  44. package/dist/hooks/useUsers.d.ts +17 -0
  45. package/dist/hooks/useUsers.d.ts.map +1 -0
  46. package/dist/hooks/useUsers.js +120 -0
  47. package/dist/hooks/useWeb3.d.ts +69 -6
  48. package/dist/hooks/useWeb3.d.ts.map +1 -1
  49. package/dist/hooks/useWeb3.js +177 -17
  50. package/dist/index.d.ts +6 -4
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +31540 -794
  53. package/dist/index.js.map +1 -1
  54. package/dist/polyfills/index.d.ts +1 -1
  55. package/dist/polyfills/index.d.ts.map +1 -1
  56. package/dist/polyfills/index.js +155 -9
  57. package/dist/polyfills/web3-polyfills.d.ts +7 -0
  58. package/dist/polyfills/web3-polyfills.d.ts.map +1 -0
  59. package/dist/polyfills/web3-polyfills.js +85 -0
  60. package/dist/providers/PersSDKProvider.d.ts +28 -18
  61. package/dist/providers/PersSDKProvider.d.ts.map +1 -1
  62. package/dist/providers/PersSDKProvider.js +63 -129
  63. package/dist/providers/react-native-auth-provider.d.ts +19 -64
  64. package/dist/providers/react-native-auth-provider.d.ts.map +1 -1
  65. package/dist/providers/react-native-auth-provider.js +57 -175
  66. package/package.json +177 -157
  67. package/src/hooks/index.ts +13 -1
  68. package/src/hooks/useAnalytics.ts +150 -0
  69. package/src/hooks/useAuth.ts +286 -27
  70. package/src/hooks/useBusiness.ts +193 -30
  71. package/src/hooks/useCampaigns.ts +121 -43
  72. package/src/hooks/useDonations.ts +68 -0
  73. package/src/hooks/useFiles.ts +160 -0
  74. package/src/hooks/usePurchases.ts +69 -0
  75. package/src/hooks/useRedemptions.ts +135 -68
  76. package/src/hooks/useTenants.ts +77 -0
  77. package/src/hooks/useTokens.ts +189 -21
  78. package/src/hooks/useTransactionSigner.ts +287 -0
  79. package/src/hooks/useTransactions.ts +163 -41
  80. package/src/hooks/useUserStatus.ts +65 -0
  81. package/src/hooks/useUsers.ts +133 -0
  82. package/src/hooks/useWeb3.ts +201 -21
  83. package/src/index.ts +22 -17
  84. package/src/polyfills/index.ts +163 -10
  85. package/src/polyfills/web3-polyfills.ts +98 -0
  86. package/src/providers/PersSDKProvider.tsx +114 -178
  87. package/src/providers/react-native-auth-provider.ts +65 -208
  88. package/dist/index.esm.js +0 -1057
  89. package/dist/index.esm.js.map +0 -1
  90. package/dist/polyfills/index.simple.d.ts +0 -2
  91. package/dist/polyfills/index.simple.d.ts.map +0 -1
  92. package/dist/polyfills/index.simple.js +0 -17
  93. package/src/polyfills/index.simple.ts +0 -22
  94. package/src/types/external-modules.d.ts +0 -13
@@ -0,0 +1,287 @@
1
+ import { useCallback, useState, useRef, useEffect } from 'react';
2
+ import { usePersSDK } from '../providers/PersSDKProvider';
3
+ import type { UserDTO, AdminDTO } from '@explorins/pers-shared';
4
+
5
+ // Dynamic import the signer SDK to avoid build issues with static dependencies
6
+ let createPersSignerSDK: ((config: any) => Promise<any>) | null = null;
7
+ try {
8
+ const signerModule = require('@explorins/pers-signer/react-native');
9
+ createPersSignerSDK = signerModule.createPersSignerSDK;
10
+ console.log('[useTransactionSigner] PERS Signer SDK loaded successfully');
11
+ } catch (error: unknown) {
12
+ console.warn('[useTransactionSigner] PERS Signer SDK not available:', (error as Error).message);
13
+ console.warn('[useTransactionSigner] Real blockchain signing will not be available');
14
+ }
15
+
16
+ interface PersSignerSDKInstance {
17
+ authenticateUser: (userInfo: SignerUserInfo) => Promise<SignerAuthenticatedUser>;
18
+ signPersTransaction: (user: SignerAuthenticatedUser, jwt: string) => Promise<SigningResult>;
19
+ }
20
+
21
+ interface SignerUserInfo {
22
+ identifier: string;
23
+ email?: string;
24
+ id?: string;
25
+ }
26
+
27
+ interface SignerAuthenticatedUser {
28
+ identifier: string;
29
+ signerAuthToken: string;
30
+ persAccessToken: string;
31
+ }
32
+
33
+ interface SigningResult {
34
+ success: boolean;
35
+ transactionHash?: string;
36
+ signature?: string;
37
+ error?: string;
38
+ }
39
+
40
+ /**
41
+ * Utility to decode JWT and extract user information
42
+ * This will be used to extract user data for the signer
43
+ */
44
+ const extractUserInfoFromJWT = async (jwt: string): Promise<{ userId?: string; email?: string; sub?: string }> => {
45
+ try {
46
+ // Dynamically import jwt-decode to avoid bundling issues
47
+ const { jwtDecode } = await import('jwt-decode');
48
+ const decoded = jwtDecode<{
49
+ sub?: string;
50
+ email?: string;
51
+ user_id?: string;
52
+ userId?: string;
53
+ uid?: string;
54
+ }>(jwt);
55
+
56
+ return {
57
+ userId: decoded.user_id || decoded.userId || decoded.uid || decoded.sub,
58
+ email: decoded.email,
59
+ sub: decoded.sub
60
+ };
61
+ } catch (error) {
62
+ console.warn('[useTransactionSigner] Failed to decode JWT:', error);
63
+ return {};
64
+ }
65
+ };
66
+
67
+ // Define our own result type that's compatible with both SDK and our usage
68
+ interface TransactionSigningResult {
69
+ success: boolean;
70
+ transactionHash?: string;
71
+ signature?: string;
72
+ error?: string;
73
+ }
74
+
75
+ // Constants - TODO: Move to environment config later
76
+ const DEFAULT_ETHERS_PROVIDER = "https://sepolia.infura.io/v3/2781b4b5242343d5b0954c98f287b29e";
77
+
78
+ /**
79
+ * React Native hook for blockchain transaction signing using PERS Signer SDK
80
+ *
81
+ * Provides WebAuthn-based transaction signing capabilities integrated with PERS ecosystem.
82
+ * Automatically handles user authentication and transaction signing workflows.
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * function TransactionComponent() {
87
+ * const { signTransaction, initializeSigner, isSignerAvailable } = useTransactionSigner();
88
+ *
89
+ * useEffect(() => {
90
+ * initializeSigner({
91
+ * tenantId: 'my-tenant',
92
+ * ethersProviderUrl: 'https://sepolia.infura.io/v3/...'
93
+ * });
94
+ * }, []);
95
+ *
96
+ * const handleSign = async () => {
97
+ * try {
98
+ * const result = await signTransaction('transaction-id-123');
99
+ * if (result.success) {
100
+ * console.log('Transaction signed:', result.transactionHash);
101
+ * }
102
+ * } catch (error) {
103
+ * console.error('Signing failed:', error);
104
+ * }
105
+ * };
106
+ *
107
+ * return (
108
+ * <button onClick={handleSign} disabled={!isSignerAvailable}>
109
+ * Sign Transaction
110
+ * </button>
111
+ * );
112
+ * }
113
+ * ```
114
+ */
115
+ export const useTransactionSigner = () => {
116
+ const { sdk, isInitialized, isAuthenticated, user } = usePersSDK();
117
+ const [isSignerInitialized, setIsSignerInitialized] = useState(false);
118
+ const signerSDKRef = useRef<PersSignerSDKInstance | null>(null);
119
+
120
+ // Auto-initialize signer when user is authenticated and real SDK is available
121
+ useEffect(() => {
122
+ if (isInitialized && isAuthenticated && user && !isSignerInitialized) {
123
+ console.log('[useTransactionSigner] Auto-initializing PERS transaction signer...');
124
+ initializeSigner({
125
+ tenantId: 'auto-tenant', // TODO: Get from SDK config or environment
126
+ ethersProviderUrl: DEFAULT_ETHERS_PROVIDER
127
+ }).catch((error) => {
128
+ console.error('[useTransactionSigner] Auto-initialization failed:', error);
129
+ });
130
+ }
131
+ }, [isInitialized, isAuthenticated, user, isSignerInitialized, createPersSignerSDK]);
132
+
133
+ /**
134
+ * Initialize the blockchain signer with configuration
135
+ *
136
+ * @param config - Signer configuration options
137
+ * @param config.tenantId - Multi-tenant identifier for the signer
138
+ * @param config.ethersProviderUrl - Custom blockchain provider URL
139
+ *
140
+ * @example
141
+ * ```typescript
142
+ * await initializeSigner({
143
+ * tenantId: 'my-tenant-id',
144
+ * ethersProviderUrl: 'https://sepolia.infura.io/v3/your-key'
145
+ * });
146
+ * ```
147
+ */
148
+ const initializeSigner = useCallback(async (config?: {
149
+ tenantId?: string;
150
+ ethersProviderUrl?: string;
151
+ }) => {
152
+ if (!createPersSignerSDK) {
153
+ throw new Error('PERS Signer SDK not available. Please ensure dependencies are properly installed.');
154
+ }
155
+
156
+ try {
157
+ console.log('[useTransactionSigner] Initializing PERS transaction signer...');
158
+
159
+ const signerSDK = await createPersSignerSDK({
160
+ tenantId: config?.tenantId,
161
+ ethersProviderUrl: config?.ethersProviderUrl || DEFAULT_ETHERS_PROVIDER
162
+ });
163
+
164
+ signerSDKRef.current = signerSDK;
165
+ setIsSignerInitialized(true);
166
+ console.log('[useTransactionSigner] PERS Signer SDK initialized successfully');
167
+
168
+ } catch (error) {
169
+ console.error('[useTransactionSigner] Failed to initialize transaction signer:', error);
170
+ throw new Error(`Signer initialization failed: ${error}`);
171
+ }
172
+ }, []);
173
+
174
+ /**
175
+ * Sign a blockchain transaction using WebAuthn authentication
176
+ *
177
+ * @param jwt - JWT token containing transaction information and user context
178
+ * @returns Promise resolving to signing result with transaction hash
179
+ *
180
+ * @throws {Error} When SDK not initialized, user not authenticated, or signer not initialized
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * try {
185
+ * const result = await signTransaction(jwtToken);
186
+ * if (result.success) {
187
+ * console.log('Signed transaction hash:', result.transactionHash);
188
+ * } else {
189
+ * console.error('Signing failed:', result.error);
190
+ * }
191
+ * } catch (error) {
192
+ * console.error('Signing error:', error);
193
+ * }
194
+ * ```
195
+ */
196
+ const signTransaction = useCallback(async (jwt: string): Promise<TransactionSigningResult> => {
197
+ if (!isInitialized || !sdk) {
198
+ throw new Error('SDK not initialized. Call initialize() first.');
199
+ }
200
+ if (!isAuthenticated || !user) {
201
+ throw new Error('User must be authenticated to sign transactions.');
202
+ }
203
+ if (!isSignerInitialized || !signerSDKRef.current) {
204
+ throw new Error('Transaction signer not initialized. Call initializeSigner() first.');
205
+ }
206
+ if (!createPersSignerSDK) {
207
+ throw new Error('PERS Signer SDK not available. Blockchain signing is not supported.');
208
+ }
209
+
210
+ try {
211
+ console.log('[useTransactionSigner] Extracting user info from JWT for transaction signing...');
212
+
213
+ // Extract user information from JWT
214
+ const jwtUserInfo = await extractUserInfoFromJWT(jwt);
215
+
216
+ // Create user info for signer, prioritizing current user data
217
+ const currentUser = user as UserDTO;
218
+ const signerUserInfo: SignerUserInfo = {
219
+ identifier: currentUser.email || currentUser.id || jwtUserInfo.userId || jwtUserInfo.sub || `user-${Date.now()}`,
220
+ email: currentUser.email || jwtUserInfo.email,
221
+ id: currentUser.id || jwtUserInfo.userId
222
+ };
223
+
224
+ // Authenticate user with blockchain signer
225
+ console.log('[useTransactionSigner] Authenticating user with signer:', signerUserInfo.identifier);
226
+ const signerUser = await signerSDKRef.current.authenticateUser(signerUserInfo);
227
+
228
+ // Sign the PERS transaction using JWT
229
+ console.log('[useTransactionSigner] Signing PERS transaction with JWT containing transaction data');
230
+ const result = await signerSDKRef.current.signPersTransaction(signerUser, jwt);
231
+
232
+ // Convert PERS SDK result to our format
233
+ const convertedResult: TransactionSigningResult = {
234
+ success: result.success || false,
235
+ transactionHash: result.transactionHash,
236
+ signature: result.signature,
237
+ error: result.error
238
+ };
239
+
240
+ if (convertedResult.success) {
241
+ console.log('[useTransactionSigner] Transaction signed successfully:', convertedResult.transactionHash);
242
+ } else {
243
+ console.warn('[useTransactionSigner] Transaction signing completed with warnings:', convertedResult.error);
244
+ }
245
+
246
+ return convertedResult;
247
+ } catch (error) {
248
+ console.error('[useTransactionSigner] Failed to sign transaction:', error);
249
+ return {
250
+ success: false,
251
+ error: `Transaction signing failed: ${error}`
252
+ };
253
+ }
254
+ }, [sdk, isInitialized, isAuthenticated, user, isSignerInitialized]);
255
+
256
+ return {
257
+ /**
258
+ * Sign a blockchain transaction with WebAuthn authentication
259
+ */
260
+ signTransaction,
261
+
262
+ /**
263
+ * Initialize the transaction signer with configuration
264
+ */
265
+ initializeSigner,
266
+
267
+ /**
268
+ * Whether the transaction signer has been initialized
269
+ */
270
+ isSignerInitialized,
271
+
272
+ /**
273
+ * Whether transaction signing is available (all requirements met)
274
+ */
275
+ isSignerAvailable: isInitialized && isAuthenticated && isSignerInitialized,
276
+ };
277
+ };
278
+
279
+ /**
280
+ * Type definition for the transaction signer hook
281
+ */
282
+ export type TransactionSignerHook = ReturnType<typeof useTransactionSigner>;
283
+
284
+ /**
285
+ * Export the transaction signing result type for external usage
286
+ */
287
+ export type { TransactionSigningResult };
@@ -1,85 +1,207 @@
1
1
  import { useCallback } from 'react';
2
2
  import { usePersSDK } from '../providers/PersSDKProvider';
3
+ import type {
4
+ TransactionRequestDTO,
5
+ TransactionRequestResponseDTO,
6
+ TransactionDTO
7
+ } from '@explorins/pers-shared';
8
+ import type { TransactionPaginationParams } from '@explorins/pers-sdk/transaction';
3
9
 
10
+ /**
11
+ * React hook for transaction operations in the PERS SDK
12
+ *
13
+ * Provides comprehensive transaction management including creation, retrieval, history,
14
+ * and administrative operations. Supports pagination and CSV export functionality.
15
+ *
16
+ * @returns Transaction hook with methods for transaction management
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * function TransactionsComponent() {
21
+ * const {
22
+ * createTransaction,
23
+ * getUserTransactionHistory
24
+ * } = useTransactions();
25
+ *
26
+ * const handleCreateTransaction = async (request) => {
27
+ * try {
28
+ * const result = await createTransaction(request);
29
+ * console.log('Transaction created:', result);
30
+ * // Handle signature URL if returned
31
+ * } catch (error) {
32
+ * console.error('Transaction failed:', error);
33
+ * }
34
+ * };
35
+ *
36
+ * return (
37
+ * <div>
38
+ * <button onClick={() => handleCreateTransaction(transactionRequest)}>
39
+ * Create Transaction
40
+ * </button>
41
+ * </div>
42
+ * );
43
+ * }
44
+ * ```
45
+ */
4
46
  export const useTransactions = () => {
5
- const { transactions, isInitialized, isAuthenticated } = usePersSDK();
47
+ const { sdk, isInitialized, isAuthenticated } = usePersSDK();
6
48
 
7
49
  if (!isAuthenticated && isInitialized) {
8
50
  console.warn('SDK not authenticated. Some transaction operations may fail.');
9
51
  }
10
52
 
11
- const createTransaction = useCallback(async (request: any) => {
12
- if (!isInitialized) {
53
+ /**
54
+ * Creates a new transaction in the system
55
+ *
56
+ * Automatically handles signature URLs by opening them in the device's browser.
57
+ * The transaction may require user approval through external wallet applications.
58
+ *
59
+ * @param request - Transaction request data including amount, recipient, etc.
60
+ * @returns Promise resolving to transaction response with potential actionable items
61
+ * @throws Error if SDK is not initialized
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * const { createTransaction } = useTransactions();
66
+ * const request = {
67
+ * amount: '100',
68
+ * recipient: '0x123...',
69
+ * tokenId: 'token-123'
70
+ * };
71
+ * const result = await createTransaction(request);
72
+ * console.log('Transaction created:', result);
73
+ * ```
74
+ */
75
+ const createTransaction = useCallback(async (request: TransactionRequestDTO): Promise<TransactionRequestResponseDTO> => {
76
+ if (!isInitialized || !sdk) {
13
77
  throw new Error('SDK not initialized. Call initialize() first.');
14
78
  }
15
- if (!transactions?.createTransaction) {
16
- throw new Error('createTransaction method not available');
17
- }
18
79
 
19
80
  try {
20
- console.log('🔄 Creating transaction with request:', request);
21
- const result = await transactions.createTransaction(request);
81
+ const result = await sdk.transactions.createTransaction(request);
22
82
 
23
- // React Native specific: Handle signature URLs
24
- if (result?.actionable?.actionUrl) {
25
- try {
26
- const { Linking } = require('react-native');
27
- console.log('🔗 Opening signature URL:', result.actionable.actionUrl);
28
- await Linking.openURL(result.actionable.actionUrl);
29
- } catch (linkingError) {
30
- console.error('❌ Failed to open signature URL:', linkingError);
31
- }
32
- }
83
+ // Cross-platform: Dont handle signature URLs here, leave to caller
33
84
 
34
- console.log('Transaction created successfully:', result);
85
+ console.log('Transaction created successfully:', result);
35
86
  return result;
36
87
  } catch (error) {
37
- console.error('Failed to create transaction:', error);
88
+ console.error('Failed to create transaction:', error);
38
89
  throw error;
39
90
  }
40
- }, [transactions]);
91
+ }, [sdk, isInitialized]);
41
92
 
42
- const getTransactionById = useCallback(async (transactionId: string) => {
43
- if (!isInitialized) {
93
+ /**
94
+ * Retrieves a specific transaction by its ID
95
+ *
96
+ * @param transactionId - Unique identifier of the transaction
97
+ * @returns Promise resolving to transaction data or null if not found
98
+ * @throws Error if SDK is not initialized
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * const { getTransactionById } = useTransactions();
103
+ * const transaction = await getTransactionById('txn-123');
104
+ * console.log('Transaction details:', transaction);
105
+ * ```
106
+ */
107
+ const getTransactionById = useCallback(async (transactionId: string): Promise<TransactionDTO | null> => {
108
+ if (!isInitialized || !sdk) {
44
109
  throw new Error('SDK not initialized. Call initialize() first.');
45
110
  }
46
- if (!transactions?.getTransactionById) {
47
- throw new Error('getTransactionById method not available');
111
+
112
+ try {
113
+ const result = await sdk.transactions.getTransactionById(transactionId);
114
+ console.log('Transaction fetched successfully:', result);
115
+ return result;
116
+ } catch (error) {
117
+ console.error('Failed to fetch transaction:', error);
118
+ throw error;
119
+ }
120
+ }, [sdk, isInitialized]);
121
+
122
+ /**
123
+ * Retrieves transaction history for the authenticated user, filtered by type
124
+ *
125
+ * @param type - Transaction type filter (defaults to 'all')
126
+ * @returns Promise resolving to array of user's transactions
127
+ * @throws Error if SDK is not initialized
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const { getUserTransactionHistory } = useTransactions();
132
+ * const transactions = await getUserTransactionHistory('credit');
133
+ * console.log('Credit transactions:', transactions);
134
+ * ```
135
+ */
136
+ const getUserTransactionHistory = useCallback(async (type: string = 'all'): Promise<TransactionDTO[]> => {
137
+ if (!isInitialized || !sdk) {
138
+ throw new Error('SDK not initialized. Call initialize() first.');
48
139
  }
49
140
 
50
141
  try {
51
- const result = await transactions.getTransactionById(transactionId);
52
- console.log('Transaction fetched successfully:', result);
142
+ const result = await sdk.transactions.getUserTransactionHistory(type);
143
+ console.log('Transaction history fetched successfully:', result);
53
144
  return result;
54
145
  } catch (error) {
55
- console.error('Failed to fetch transaction:', error);
146
+ console.error('Failed to fetch transaction history:', error);
56
147
  throw error;
57
148
  }
58
- }, [transactions]);
149
+ }, [sdk, isInitialized]);
59
150
 
60
- const getTransactionHistory = useCallback(async (filters?: any) => {
61
- if (!isInitialized) {
151
+ const getTenantTransactions = useCallback(async (): Promise<TransactionDTO[]> => {
152
+ if (!isInitialized || !sdk) {
62
153
  throw new Error('SDK not initialized. Call initialize() first.');
63
154
  }
64
- if (!transactions?.getTransactionHistory) {
65
- console.warn('getTransactionHistory method not available');
66
- return [];
155
+
156
+ try {
157
+ const result = await sdk.transactions.getTenantTransactions();
158
+ console.log('Tenant transactions fetched successfully:', result);
159
+ return result;
160
+ } catch (error) {
161
+ console.error('Failed to fetch tenant transactions:', error);
162
+ throw error;
163
+ }
164
+ }, [sdk, isInitialized]);
165
+
166
+ const getPaginatedTransactions = useCallback(async (params: TransactionPaginationParams): Promise<any> => {
167
+ if (!isInitialized || !sdk) {
168
+ throw new Error('SDK not initialized. Call initialize() first.');
67
169
  }
68
170
 
69
171
  try {
70
- const result = await transactions.getTransactionHistory(filters);
71
- console.log(' Transaction history fetched successfully:', result);
172
+ const result = await sdk.transactions.getPaginatedTransactions(params);
173
+ console.log('Paginated transactions fetched successfully:', result);
72
174
  return result;
73
175
  } catch (error) {
74
- console.error('Failed to fetch transaction history:', error);
176
+ console.error('Failed to fetch paginated transactions:', error);
75
177
  throw error;
76
178
  }
77
- }, [transactions]);
179
+ }, [sdk, isInitialized]);
180
+
181
+ const exportTransactionsCSV = useCallback(async (): Promise<Blob> => {
182
+ if (!isInitialized || !sdk) {
183
+ throw new Error('SDK not initialized. Call initialize() first.');
184
+ }
185
+
186
+ try {
187
+ const result = await sdk.transactions.exportTransactionsCSV();
188
+ console.log('Transactions CSV exported successfully');
189
+ return result;
190
+ } catch (error) {
191
+ console.error('Failed to export transactions CSV:', error);
192
+ throw error;
193
+ }
194
+ }, [sdk, isInitialized]);
78
195
 
79
196
  return {
80
197
  createTransaction,
81
198
  getTransactionById,
82
- getTransactionHistory,
83
- isAvailable: isInitialized && !!transactions,
199
+ getUserTransactionHistory,
200
+ getTenantTransactions,
201
+ getPaginatedTransactions,
202
+ exportTransactionsCSV,
203
+ isAvailable: isInitialized && !!sdk?.transactions,
84
204
  };
85
- };
205
+ };
206
+
207
+ export type TransactionHook = ReturnType<typeof useTransactions>;
@@ -0,0 +1,65 @@
1
+ import { useCallback } from 'react';
2
+ import { usePersSDK } from '../providers/PersSDKProvider';
3
+ import type { UserStatusTypeDTO } from '@explorins/pers-shared';
4
+
5
+ export const useUserStatus = () => {
6
+ const { sdk, isInitialized, isAuthenticated } = usePersSDK();
7
+
8
+ const getUserStatusTypes = useCallback(async (): Promise<UserStatusTypeDTO[]> => {
9
+ if (!isInitialized || !sdk) {
10
+ throw new Error('SDK not initialized. Call initialize() first.');
11
+ }
12
+
13
+ try {
14
+ const result = await sdk.userStatus.getUserStatusTypes();
15
+ console.log('User status types fetched successfully:', result);
16
+ return result;
17
+ } catch (error) {
18
+ console.error('Failed to fetch user status types:', error);
19
+ throw error;
20
+ }
21
+ }, [sdk, isInitialized]);
22
+
23
+ const getEarnedUserStatus = useCallback(async (): Promise<UserStatusTypeDTO[]> => {
24
+ if (!isInitialized || !sdk) {
25
+ throw new Error('SDK not initialized. Call initialize() first.');
26
+ }
27
+ if (!isAuthenticated) {
28
+ throw new Error('SDK not authenticated. getEarnedUserStatus requires authentication.');
29
+ }
30
+
31
+ try {
32
+ const result = await sdk.userStatus.getEarnedUserStatus();
33
+ console.log('Earned user status fetched successfully:', result);
34
+ return result;
35
+ } catch (error) {
36
+ console.error('Failed to fetch earned user status:', error);
37
+ throw error;
38
+ }
39
+ }, [sdk, isInitialized, isAuthenticated]);
40
+
41
+ // Admin methods
42
+ const createUserStatusType = useCallback(async (userStatusType: UserStatusTypeDTO): Promise<UserStatusTypeDTO> => {
43
+ if (!isInitialized || !sdk) {
44
+ throw new Error('SDK not initialized. Call initialize() first.');
45
+ }
46
+
47
+ try {
48
+ const result = await sdk.userStatus.createUserStatusType(userStatusType);
49
+ console.log('User status type created successfully:', result);
50
+ return result;
51
+ } catch (error) {
52
+ console.error('Failed to create user status type:', error);
53
+ throw error;
54
+ }
55
+ }, [sdk, isInitialized]);
56
+
57
+ return {
58
+ getUserStatusTypes,
59
+ getEarnedUserStatus,
60
+ createUserStatusType,
61
+ isAvailable: isInitialized && !!sdk?.userStatus,
62
+ };
63
+ };
64
+
65
+ export type UserStatusHook = ReturnType<typeof useUserStatus>;