-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
532 lines (462 loc) · 14.8 KB
/
api.js
File metadata and controls
532 lines (462 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/**
* API Service for AX Merchant Portal
* Handles all backend API communication
*/
const API_BASE_URL = window.VITE_API_BASE_URL || 'https://www.orders.axpress.net/api';
const MASK_SECRET = "AX_SECURE_KEY_2026";
/**
* Unmask string using XOR with MASK_SECRET
* @param {string} maskedKey - Base64 encoded masked key
*/
function unmaskPaystackKey(maskedKey) {
try {
const maskedBytes = Uint8Array.from(atob(maskedKey), c => c.charCodeAt(0));
const secretBytes = new TextEncoder().encode(MASK_SECRET);
const unmasked = new Uint8Array(maskedBytes.length);
for (let i = 0; i < maskedBytes.length; i++) {
unmasked[i] = maskedBytes[i] ^ secretBytes[i % secretBytes.length];
}
return new TextDecoder().decode(unmasked);
} catch (e) {
console.error('Failed to unmask key:', e);
return null;
}
}
// Token management
const TokenManager = {
getAccessToken: () => localStorage.getItem('access_token'),
getRefreshToken: () => localStorage.getItem('refresh_token'),
setTokens: (access, refresh) => {
localStorage.setItem('access_token', access);
localStorage.setItem('refresh_token', refresh);
},
clearTokens: () => {
localStorage.clear();
sessionStorage.clear();
},
getUser: () => {
const user = localStorage.getItem('user');
return user ? JSON.parse(user) : null;
},
setUser: (user) => {
localStorage.setItem('user', JSON.stringify(user));
}
};
// Helper to extract error message from API response
function extractErrorMessage(data) {
// Check for errors object (Django REST Framework format)
if (data.errors) {
// Handle non_field_errors
if (data.errors.non_field_errors && Array.isArray(data.errors.non_field_errors)) {
return data.errors.non_field_errors[0];
}
// Handle field-specific errors
const firstErrorKey = Object.keys(data.errors)[0];
if (firstErrorKey) {
const errorValue = data.errors[firstErrorKey];
if (Array.isArray(errorValue)) {
return `${firstErrorKey}: ${errorValue[0]}`;
}
return `${firstErrorKey}: ${errorValue}`;
}
}
// Check for message field
if (data.message) {
return data.message;
}
// Check for detail field (DRF default)
if (data.detail) {
return data.detail;
}
// Fallback
return 'Request failed';
}
// ─── AUTO-REFRESH LOGIC ─────────────────────────────────────────
let isRefreshing = false;
let refreshSubscribers = [];
function onRefreshed(token) {
refreshSubscribers.forEach((callback) => callback(token));
refreshSubscribers = [];
}
function addRefreshSubscriber(callback) {
refreshSubscribers.push(callback);
}
// ────────────────────────────────────────────────────────────────
// API request helper
async function apiRequest(endpoint, options = {}) {
const token = TokenManager.getAccessToken();
const headers = {
'Content-Type': 'application/json',
...options.headers,
};
if (token && !options.skipAuth) {
headers['Authorization'] = `Bearer ${token}`;
}
const config = {
...options,
headers,
};
try {
let response = await fetch(`${API_BASE_URL}${endpoint}`, config);
let data = await response.json().catch(() => ({}));
// If unauthorized and we have a refresh token (and we're not already trying to fetch the refresh endpoint), try to refresh
if (!response.ok && response.status === 401 && !options.skipAuth && endpoint !== '/auth/refresh/') {
const refreshToken = TokenManager.getRefreshToken();
if (refreshToken) {
if (!isRefreshing) {
isRefreshing = true;
try {
const refreshRes = await fetch(`${API_BASE_URL}/auth/refresh/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh: refreshToken }),
});
const refreshData = await refreshRes.json();
if (refreshRes.ok && refreshData.access) {
TokenManager.setTokens(refreshData.access, refreshData.refresh || refreshToken);
isRefreshing = false;
onRefreshed(refreshData.access);
// Retry original request
config.headers['Authorization'] = `Bearer ${refreshData.access}`;
response = await fetch(`${API_BASE_URL}${endpoint}`, config);
data = await response.json().catch(() => ({}));
} else {
throw new Error('Refresh failed');
}
} catch (refreshErr) {
isRefreshing = false;
TokenManager.clearTokens();
// Optional: trigger a custom event or reload the page to kick the user out visually
window.dispatchEvent(new Event('auth:unauthorized'));
throw new Error('Session expired. Please log in again.');
}
} else {
// Wait for the ongoing refresh to complete, then retry
return new Promise((resolve, reject) => {
addRefreshSubscriber(async (newToken) => {
config.headers['Authorization'] = `Bearer ${newToken}`;
try {
const retryRes = await fetch(`${API_BASE_URL}${endpoint}`, config);
const retryData = await retryRes.json().catch(() => ({}));
if (!retryRes.ok) {
return reject(new Error(extractErrorMessage(retryData) || 'Request failed'));
}
resolve(retryData);
} catch (err) {
reject(err);
}
});
});
}
} else {
// 401 but no refresh token
TokenManager.clearTokens();
window.dispatchEvent(new Event('auth:unauthorized'));
}
}
if (!response.ok) {
const errorMessage = extractErrorMessage(data);
throw new Error(errorMessage);
}
return data;
} catch (error) {
console.error('API Error:', error);
throw error;
}
}
// Authentication API
const AuthAPI = {
signup: async (userData) => {
const response = await apiRequest('/auth/signup/', {
method: 'POST',
body: JSON.stringify(userData),
skipAuth: true,
});
if (response.success && response.tokens) {
TokenManager.setTokens(response.tokens.access, response.tokens.refresh);
TokenManager.setUser(response.user);
}
return response;
},
login: async (phone, password) => {
const response = await apiRequest('/auth/login/', {
method: 'POST',
body: JSON.stringify({ phone, password }),
skipAuth: true,
});
if (response.success && response.tokens) {
TokenManager.setTokens(response.tokens.access, response.tokens.refresh);
TokenManager.setUser(response.user);
}
return response;
},
logout: async () => {
// Blacklist the refresh token on the server (best-effort)
try {
const refreshToken = TokenManager.getRefreshToken();
if (refreshToken) {
await apiRequest('/auth/logout/', {
method: 'POST',
body: JSON.stringify({ refresh: refreshToken }),
});
}
} catch (_) { /* always clear locally even if server call fails */ }
// Wipe all local storage and session storage
TokenManager.clearTokens();
// Wipe all browser caches (service workers, fetch cache)
if ('caches' in window) {
try {
const keys = await caches.keys();
await Promise.all(keys.map(k => caches.delete(k)));
} catch (_) { }
}
},
getProfile: async () => {
return await apiRequest('/auth/me/', {
method: 'GET',
});
},
updateProfile: async (userData) => {
const response = await apiRequest('/auth/profile/', {
method: 'PUT',
body: JSON.stringify(userData),
});
// Update user in localStorage if successful
if (response.success && response.user) {
TokenManager.setUser(response.user);
}
return response;
},
// Address management
getAddresses: async () => {
return await apiRequest('/auth/addresses/', {
method: 'GET',
});
},
createAddress: async (addressData) => {
return await apiRequest('/auth/addresses/', {
method: 'POST',
body: JSON.stringify(addressData),
});
},
updateAddress: async (addressId, addressData) => {
return await apiRequest(`/auth/addresses/${addressId}/`, {
method: 'PUT',
body: JSON.stringify(addressData),
});
},
deleteAddress: async (addressId) => {
return await apiRequest(`/auth/addresses/${addressId}/`, {
method: 'DELETE',
});
},
setDefaultAddress: async (addressId) => {
return await apiRequest(`/auth/addresses/${addressId}/set-default/`, {
method: 'POST',
});
},
resendVerification: async () => {
return await apiRequest('/auth/resend-verification/', {
method: 'POST',
});
},
requestPasswordReset: async (email) => {
return await apiRequest('/auth/request-password-reset/', {
method: 'POST',
body: JSON.stringify({ email }),
skipAuth: true,
});
},
resetPassword: async (token, newPassword) => {
return await apiRequest('/auth/reset-password/', {
method: 'POST',
body: JSON.stringify({ token, new_password: newPassword, confirm_password: newPassword }),
skipAuth: true,
});
},
resendOTP: async (phone) => {
return await apiRequest("/auth/resend-otp/", {
method: "POST",
body: JSON.stringify({ phone }),
skipAuth: true,
});
},
verifyOTP: async (phone, otp) => {
return await apiRequest("/auth/verify-otp/", {
method: "POST",
body: JSON.stringify({ phone, otp }),
skipAuth: true,
});
},
verifyEmail: async (token) => {
return await apiRequest(`/auth/verify-email/?token=${token}`, {
method: 'GET',
skipAuth: true,
});
},
};
// Orders API
const OrdersAPI = {
getVehicles: async () => {
return await apiRequest('/orders/vehicles/', {
method: 'GET',
});
},
createQuickSend: async (orderData) => {
return await apiRequest('/orders/quick-send/', {
method: 'POST',
body: JSON.stringify(orderData),
});
},
createMultiDrop: async (orderData) => {
return await apiRequest('/orders/multi-drop/', {
method: 'POST',
body: JSON.stringify(orderData),
});
},
createBulkImport: async (orderData) => {
return await apiRequest('/orders/bulk-import/', {
method: 'POST',
body: JSON.stringify(orderData),
});
},
getOrders: async (filters = {}) => {
const params = new URLSearchParams();
if (filters.status) params.append('status', filters.status);
if (filters.mode) params.append('mode', filters.mode);
if (filters.limit) params.append('limit', filters.limit);
const queryString = params.toString();
const endpoint = queryString ? `/orders/?${queryString}` : '/orders/';
return await apiRequest(endpoint, {
method: 'GET',
});
},
getOrderDetails: async (orderNumber) => {
return await apiRequest(`/orders/${orderNumber}/`, {
method: 'GET',
});
},
getOrderStats: async () => {
return await apiRequest('/orders/stats/', {
method: 'GET',
});
},
cancelOrder: async (orderNumber, reason = 'Canceled by merchant') => {
return await apiRequest(`/orders/cancel/${orderNumber}/`, {
method: 'POST',
body: JSON.stringify({ reason }),
});
},
};
// Wallet API
const WalletAPI = {
/**
* Get Paystack public key
*/
getPaystackKey: async () => {
const response = await apiRequest('/wallet/paystack-key/', {
method: 'GET',
});
if (response.success && response.data && response.data.public_key) {
response.data.public_key = unmaskPaystackKey(response.data.public_key);
}
return response;
},
/**
* Get wallet balance
*/
getBalance: async () => {
return await apiRequest('/wallet/balance/', {
method: 'GET',
});
},
/**
* Get transaction history
* @param {Object} params - Query parameters (type, status, page)
*/
getTransactions: async (params = {}) => {
const queryString = new URLSearchParams(params).toString();
const url = queryString ? `/wallet/transactions/?${queryString}` : '/wallet/transactions/';
return await apiRequest(url, {
method: 'GET',
});
},
/**
* Initialize Paystack payment for wallet funding
* @param {number} amount - Amount to fund in Naira
*/
initializePayment: async (amount) => {
return await apiRequest('/wallet/fund/initialize/', {
method: 'POST',
body: JSON.stringify({ amount: amount.toString() }),
});
},
/**
* Verify Paystack payment
* @param {string} reference - Paystack payment reference
*/
verifyPayment: async (reference) => {
return await apiRequest('/wallet/fund/verify/', {
method: 'POST',
body: JSON.stringify({ reference }),
});
},
/**
* Get (or create) the merchant's CoreBanking virtual account.
* Returns account_number, account_name, bank_name, bank_code.
*/
getVirtualAccount: async () => {
return await apiRequest('/wallet/virtual-account/', {
method: 'GET',
});
},
/**
* Record that the merchant has claimed to have made a bank transfer.
* Creates a pending transaction so the claim is audited.
* The actual wallet credit happens when the bank webhook confirms the transfer.
* @param {number} amount - Amount in Naira
*/
claimTransfer: async (amount) => {
return await apiRequest('/wallet/fund/transfer-claim/', {
method: 'POST',
body: JSON.stringify({ amount: amount.toString() }),
});
},
};
// Activity / Ably API
const ActivityAPI = {
/**
* Request an Ably token from the backend.
* The returned object contains { token, token_request } and can be
* passed directly to Ably's authCallback.
*/
getAblyToken: async () => {
return await apiRequest('/dispatch/ably-token/', { method: 'GET' });
},
};
const SubscriptionAPI = {
getPlans: async () => apiRequest('/subscriptions/plans/', { method: 'GET' }),
subscribe: async (planId) =>
apiRequest(`/subscriptions/plans/${planId}/subscribe/`, {
method: 'POST',
body: JSON.stringify({})
}),
getActiveSubscription: async () => apiRequest('/subscriptions/active/', { method: 'GET' }),
// Postpaid plans
getPostpaidPlans: async () => apiRequest('/subscriptions/postpaid/plans/', { method: 'GET' }),
activatePostpaidPlan: async (planId) =>
apiRequest(`/subscriptions/postpaid/plans/${planId}/activate/`, {
method: 'POST',
body: JSON.stringify({})
}),
getActivePostpaidSubscription: async () => apiRequest('/subscriptions/postpaid/active/', { method: 'GET' }),
};
// Export API modules
window.API = {
Auth: AuthAPI,
Orders: OrdersAPI,
Wallet: WalletAPI,
Activity: ActivityAPI,
Token: TokenManager,
Subscription: SubscriptionAPI,
};