forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-client.ts
More file actions
644 lines (575 loc) · 14 KB
/
Copy pathapi-client.ts
File metadata and controls
644 lines (575 loc) · 14 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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
import axios, {
AxiosError,
type AxiosRequestConfig,
type InternalAxiosRequestConfig,
} from 'axios'
import {
API_TIMEOUT,
BASE_API_URL,
DEFAULT_API_REQUEST_ERROR,
DEFAULT_NETWORK_CONNECTIVITY_ERROR,
} from '../constants/api'
import {
getStoredActiveUserId,
getStoredAuthToken,
} from './session'
import { ApiRoutes } from '../services/apiRouteRegistry'
type RequestMethod = 'get' | 'post' | 'patch' | 'delete'
interface RequestOptions<TData = unknown> {
method: RequestMethod
endpoint: string
data?: TData
params?: Record<string, unknown>
headers?: Record<string, string>
signal?: AbortSignal
}
export interface ApiSplitParticipant {
id: string
userId: string
amountOwed: number | string
amountPaid: number | string
status: 'pending' | 'paid' | 'partial'
walletAddress?: string | null
}
export interface ApiSplitItem {
id: string
splitId: string
name: string
quantity: number
unitPrice: number | string
totalPrice: number | string
category?: string | null
assignedToIds: string[]
}
export interface ApiSplitRecord {
id: string
totalAmount: number | string
amountPaid: number | string
status: 'active' | 'completed' | 'partial'
description?: string | null
preferredCurrency?: string | null
creatorWalletAddress?: string | null
dueDate?: string | null
createdAt: string
updatedAt: string
participants: ApiSplitParticipant[]
items?: ApiSplitItem[]
}
export interface ApiPaymentRecord {
id: string
splitId: string
participantId: string
txHash: string
amount: number | string
asset: string
status: string
settlementStatus?: string
createdAt: string
updatedAt?: string
}
export interface ApiPaymentStats {
splitId: string
totalAmount: number | string
totalPaid: number | string
remainingAmount: number | string
paymentCount: number
status: string
}
export interface ApiReceiptOcrData {
items?: Array<{
name: string
quantity: number
price: number
}>
subtotal?: number
tax?: number
tip?: number
total?: number
confidence?: number
}
export interface ApiReceiptRecord {
id: string
splitId: string
uploadedBy: string
originalFilename: string
storagePath: string
fileSize: number
mimeType: string
thumbnailPath?: string
ocrProcessed: boolean
ocrConfidenceScore?: number | string | null
extractedData?: ApiReceiptOcrData | null
createdAt: string
}
export interface ApiReceiptOcrResponse {
processed: boolean
data?: ApiReceiptOcrData | null
}
export interface ApiProfile {
walletAddress: string
displayName: string | null
avatarUrl: string | null
preferredCurrency: string
}
export interface ApiActivityRecord {
id: string
userId?: string
activityType: string
splitId?: string
metadata: Record<string, unknown>
isRead: boolean
createdAt: string
}
export interface ApiDashboardSummary {
totalOwed: number | string
totalOwedToUser: number | string
activeSplits: number
splitsCreated: number
unreadNotifications: number
quickActions: Array<{
id: string
label: string
route: string
badge?: number
}>
}
export interface ApiDashboardActivityResponse {
data: ApiActivityRecord[]
total: number
page: number
limit: number
hasMore: boolean
unreadCount: number
}
export interface ApiCreateSplitPayload {
totalAmount: number
description: string
creatorWalletAddress: string
preferredCurrency?: string
dueDate?: string
participants: Array<{
userId: string
amountOwed: number
walletAddress?: string
}>
items?: Array<{
name: string
quantity: number
unitPrice: number
totalPrice: number
assignedToIds: string[]
}>
}
export interface ApiCreateActivityPayload {
userId: string
activityType: string
splitId?: string
metadata?: Record<string, unknown>
}
export interface ApiErrorLike {
statusCode?: number
message: string
details?: unknown
fieldErrors: Record<string, string>
isNetworkError: boolean
}
export class ApiError extends Error implements ApiErrorLike {
statusCode?: number
details?: unknown
fieldErrors: Record<string, string>
isNetworkError: boolean
constructor({
message,
statusCode,
details,
fieldErrors = {},
isNetworkError = false,
}: ApiErrorLike) {
super(message)
this.name = 'ApiError'
this.statusCode = statusCode
this.details = details
this.fieldErrors = fieldErrors
this.isNetworkError = isNetworkError
}
}
function createApiClient(baseURL: string) {
const apiInstance = axios.create({
baseURL,
timeout: API_TIMEOUT,
headers: {
'Content-Type': 'application/json',
},
})
apiInstance.interceptors.request.use(
async (config: InternalAxiosRequestConfig) => {
const authToken = getStoredAuthToken()
const activeUserId = getStoredActiveUserId()
if (authToken) {
config.headers.Authorization = `Bearer ${authToken}`
} else if (activeUserId) {
config.headers['x-user-id'] = activeUserId
}
if (config.data instanceof FormData) {
delete config.headers['Content-Type']
}
return config
},
)
return apiInstance
}
function extractMessages(input: unknown): string[] {
if (!input) {
return []
}
if (typeof input === 'string') {
return [input]
}
if (Array.isArray(input)) {
return input.flatMap((value) => extractMessages(value))
}
if (typeof input === 'object') {
return Object.values(input as Record<string, unknown>).flatMap((value) =>
extractMessages(value),
)
}
return []
}
function inferFieldKey(message: string): string | null {
const normalized = message.toLowerCase()
if (normalized.includes('title') || normalized.includes('description')) {
return 'title'
}
if (normalized.includes('currency')) {
return 'currency'
}
if (normalized.includes('total') || normalized.includes('amount')) {
return 'totalAmount'
}
if (normalized.includes('participant')) {
return 'participants'
}
if (normalized.includes('item')) {
return 'items'
}
if (normalized.includes('tax')) {
return 'taxAmount'
}
if (normalized.includes('tip')) {
return 'tipAmount'
}
if (normalized.includes('wallet')) {
return 'walletAddress'
}
return null
}
function createFieldErrorMap(messages: string[]): Record<string, string> {
return messages.reduce<Record<string, string>>((accumulator, message) => {
const fieldKey = inferFieldKey(message)
if (fieldKey && !accumulator[fieldKey]) {
accumulator[fieldKey] = message
}
return accumulator
}, {})
}
export function normalizeApiError(error: unknown): ApiError {
if (error instanceof ApiError) {
return error
}
if (!axios.isAxiosError(error)) {
return new ApiError({
message: DEFAULT_API_REQUEST_ERROR,
details: error,
fieldErrors: {},
isNetworkError: false,
})
}
const axiosError = error as AxiosError<{
message?: unknown
error?: unknown
statusCode?: number
}>
const responsePayload = axiosError.response?.data
const messages = extractMessages(
responsePayload?.message ?? responsePayload?.error ?? axiosError.message,
)
const message =
messages[0] ??
(axiosError.code === 'ECONNABORTED' || !axiosError.response
? DEFAULT_NETWORK_CONNECTIVITY_ERROR
: DEFAULT_API_REQUEST_ERROR)
return new ApiError({
message,
statusCode: axiosError.response?.status ?? responsePayload?.statusCode,
details: responsePayload ?? axiosError.toJSON(),
fieldErrors: createFieldErrorMap(messages),
isNetworkError: !axiosError.response,
})
}
async function request<TResponse, TData = unknown>({
method,
endpoint,
data,
params,
headers,
signal,
}: RequestOptions<TData>): Promise<TResponse> {
try {
const response = await apiClient.request<TResponse>({
method,
url: endpoint,
data,
params,
headers,
signal,
} as AxiosRequestConfig<TData>)
return response.data
} catch (requestError) {
throw normalizeApiError(requestError)
}
}
function normalizeSignedUrlResponse(response: unknown): string | null {
if (typeof response === 'string') {
return response
}
if (response && typeof response === 'object') {
const candidate = (response as { url?: unknown }).url
if (typeof candidate === 'string') {
return candidate
}
}
return null
}
export function normalizeDecimal(value: number | string | null | undefined): number {
if (typeof value === 'number') {
return value
}
if (typeof value === 'string') {
const parsed = Number.parseFloat(value)
return Number.isFinite(parsed) ? parsed : 0
}
return 0
}
export function getApiErrorMessage(error: unknown): string {
return normalizeApiError(error).message
}
export function getApiFieldErrors(error: unknown): Record<string, string> {
return normalizeApiError(error).fieldErrors
}
export const apiClient = createApiClient(BASE_API_URL)
export async function fetchSplitById(splitId: string, signal?: AbortSignal): Promise<ApiSplitRecord> {
return request<ApiSplitRecord>({
method: 'get',
endpoint: ApiRoutes.splits.byId(splitId),
signal,
})
}
export async function updateSplit(
splitId: string,
payload: Partial<Pick<ApiSplitRecord, 'totalAmount' | 'description' | 'preferredCurrency' | 'status'>>,
signal?: AbortSignal,
): Promise<ApiSplitRecord> {
return request<ApiSplitRecord, typeof payload>({
method: 'patch',
endpoint: ApiRoutes.splits.byId(splitId),
data: payload,
signal,
})
}
export async function createSplit(
payload: ApiCreateSplitPayload,
signal?: AbortSignal,
): Promise<ApiSplitRecord> {
return request<ApiSplitRecord, ApiCreateSplitPayload>({
method: 'post',
endpoint: ApiRoutes.splits.create(),
data: payload,
signal,
})
}
export async function fetchSplitPayments(
splitId: string,
signal?: AbortSignal,
): Promise<ApiPaymentRecord[]> {
return request<ApiPaymentRecord[]>({
method: 'get',
endpoint: ApiRoutes.payments.bySplit(splitId),
signal,
})
}
export async function fetchSplitPaymentStats(
splitId: string,
signal?: AbortSignal,
): Promise<ApiPaymentStats> {
return request<ApiPaymentStats>({
method: 'get',
endpoint: ApiRoutes.payments.stats(splitId),
signal,
})
}
export async function submitSplitPayment(
payload: {
splitId: string
participantId: string
stellarTxHash: string
idempotencyKey?: string
externalReference?: string
},
signal?: AbortSignal,
): Promise<{
success: boolean
message: string
paymentId?: string
isDuplicate?: boolean
idempotencyKey?: string
}> {
return request({
method: 'post',
endpoint: ApiRoutes.payments.submit(),
data: payload,
signal,
})
}
export async function fetchSplitReceipts(
splitId: string,
signal?: AbortSignal,
): Promise<ApiReceiptRecord[]> {
return request<ApiReceiptRecord[]>({
method: 'get',
endpoint: ApiRoutes.receipts.bySplit(splitId),
signal,
})
}
export async function uploadReceiptForSplit(
splitId: string,
file: File,
signal?: AbortSignal,
): Promise<ApiReceiptRecord> {
const formData = new FormData()
formData.append('file', file)
return request<ApiReceiptRecord, FormData>({
method: 'post',
endpoint: ApiRoutes.receipts.upload(splitId),
data: formData,
headers: {
Accept: 'application/json',
},
signal,
})
}
export async function fetchReceiptSignedUrl(receiptId: string, signal?: AbortSignal): Promise<string | null> {
const response = await request<unknown>({
method: 'get',
endpoint: ApiRoutes.receipts.signedUrl(receiptId),
signal,
})
return normalizeSignedUrlResponse(response)
}
export async function fetchReceiptOcrData(
receiptId: string,
signal?: AbortSignal,
): Promise<ApiReceiptOcrResponse> {
return request<ApiReceiptOcrResponse>({
method: 'get',
endpoint: ApiRoutes.receipts.ocrData(receiptId),
signal,
})
}
export async function createItem(
payload: {
splitId: string
name: string
quantity: number
unitPrice: number
totalPrice: number
assignedToIds: string[]
},
signal?: AbortSignal,
): Promise<ApiSplitItem> {
return request<ApiSplitItem, typeof payload>({
method: 'post',
endpoint: ApiRoutes.items.create(),
data: payload,
signal,
})
}
export async function deleteItem(itemId: string, signal?: AbortSignal): Promise<void> {
await request<void>({
method: 'delete',
endpoint: ApiRoutes.items.byId(itemId),
signal,
})
}
export async function fetchProfile(walletAddress: string, signal?: AbortSignal): Promise<ApiProfile | null> {
try {
return await request<ApiProfile>({
method: 'get',
endpoint: ApiRoutes.profile.byWallet(walletAddress),
signal,
})
} catch (error) {
const apiError = normalizeApiError(error)
if (apiError.statusCode === 404) {
return null
}
throw apiError
}
}
export async function fetchDashboardSummary(signal?: AbortSignal): Promise<ApiDashboardSummary> {
return request<ApiDashboardSummary>({
method: 'get',
endpoint: ApiRoutes.dashboard.summary(),
signal,
})
}
export async function fetchDashboardActivity(
page = 1,
limit = 10,
signal?: AbortSignal,
): Promise<ApiDashboardActivityResponse> {
return request<ApiDashboardActivityResponse>({
method: 'get',
endpoint: ApiRoutes.dashboard.activity(),
params: {
page,
limit,
},
signal,
})
}
export async function fetchUserActivities(
userId: string,
params?: {
splitId?: string
limit?: number
page?: number
isRead?: boolean
},
signal?: AbortSignal,
): Promise<{
data: ApiActivityRecord[]
total: number
page: number
limit: number
totalPages: number
hasMore: boolean
unreadCount: number
}> {
return request({
method: 'get',
endpoint: ApiRoutes.activities.byUser(userId),
params,
signal,
})
}
export async function createActivityRecord(
payload: ApiCreateActivityPayload,
signal?: AbortSignal,
): Promise<ApiActivityRecord> {
return request<ApiActivityRecord, ApiCreateActivityPayload>({
method: 'post',
endpoint: ApiRoutes.activities.create(),
data: payload,
signal,
})
}