forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitHistoryRepository.ts
More file actions
245 lines (212 loc) · 6.69 KB
/
Copy pathsplitHistoryRepository.ts
File metadata and controls
245 lines (212 loc) · 6.69 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
import { apiClient } from "../utils/api-client";
export type SplitStatus = "active" | "completed" | "cancelled";
export type SplitRole = "creator" | "participant";
export interface HistoryParticipant {
id: string;
name: string;
}
export interface HistorySplit {
id: string;
title: string;
totalAmount: number;
currency: string;
date: string;
status: SplitStatus;
participants: HistoryParticipant[];
role: SplitRole;
}
export type HistorySort =
| "date-desc"
| "date-asc"
| "amount-desc"
| "amount-asc"
| "status";
const API_PAGE_SIZE = 100;
const ALL_STATUSES: SplitStatus[] = ["active", "completed", "cancelled"];
export interface HistoryFilters {
statuses?: SplitStatus[];
role?: SplitRole | "all";
search?: string;
sort?: HistorySort;
page?: number;
limit?: number;
}
export interface HistoryResponse {
data: HistorySplit[];
source: "api";
meta: {
page: number;
limit: number;
totalItems: number;
totalPages: number;
hasMore: boolean;
};
summary: HistorySummaryData;
}
export interface HistorySummaryData {
totalAmount: number;
average: number;
counts: Record<SplitStatus, number>;
}
export interface SplitHistoryRepository {
fetchHistory(filters: HistoryFilters): Promise<HistoryResponse>;
}
class ApiSplitHistoryRepository implements SplitHistoryRepository {
async fetchHistory(filters: HistoryFilters): Promise<HistoryResponse> {
const page = positiveInteger(filters.page, 1);
const limit = positiveInteger(filters.limit, 20);
if (filters.statuses?.length === 0) {
return emptyResponse(page, limit);
}
const statusQueries = apiStatusQueries(filters.statuses);
const resultSets = await Promise.all(
statusQueries.map((status) => fetchAllApiPages(filters, status)),
);
const uniqueSplits = new Map<string, HistorySplit>();
resultSets.flat().map(mapApiHistoryItem).forEach((split) => {
uniqueSplits.set(split.id, split);
});
const filtered = sortHistory(
filterHistory(Array.from(uniqueSplits.values()), filters),
filters.sort,
);
const offset = (page - 1) * limit;
return {
data: filtered.slice(offset, offset + limit),
source: "api",
meta: {
page,
limit,
totalItems: filtered.length,
totalPages: Math.max(1, Math.ceil(filtered.length / limit)),
hasMore: offset + limit < filtered.length,
},
summary: summarizeHistory(filtered),
};
}
}
interface ApiHistoryItem {
id: string;
splitId: string;
role: SplitRole;
finalAmount: number;
status: string;
description?: string;
preferredCurrency?: string;
totalAmount: number;
completionTime: string;
isArchived: boolean;
}
interface ApiHistoryResponse {
data: ApiHistoryItem[];
total: number;
page: number;
limit: number;
hasMore: boolean;
}
function positiveInteger(value: number | undefined, fallback: number): number {
return Number.isInteger(value) && Number(value) > 0 ? Number(value) : fallback;
}
async function fetchAllApiPages(
filters: HistoryFilters,
status: string | undefined,
): Promise<ApiHistoryItem[]> {
const items: ApiHistoryItem[] = [];
let page = 1;
while (true) {
const response = await apiClient.get<ApiHistoryResponse>("/splits/history", {
params: buildApiParams(filters, page, API_PAGE_SIZE, status),
});
const payload = response.data;
items.push(...payload.data);
const responsePage = positiveInteger(payload.page, page);
const responseLimit = positiveInteger(payload.limit, API_PAGE_SIZE);
const totalPages = Math.max(1, Math.ceil(Math.max(0, payload.total) / responseLimit));
if (!payload.hasMore || responsePage >= totalPages) break;
page = responsePage + 1;
}
return items;
}
function buildApiParams(
filters: HistoryFilters,
page: number,
limit: number,
status: string | undefined,
) {
const params: Record<string, string | number> = { page, limit };
const search = filters.search?.trim();
if (filters.role && filters.role !== "all") params.role = filters.role;
if (search) params.search = search;
if (status) params.status = status;
return params;
}
function apiStatusQueries(statuses: SplitStatus[] | undefined): Array<string | undefined> {
if (!statuses || statuses.length === ALL_STATUSES.length) return [undefined];
return statuses.map((status) => (status === "cancelled" ? "archived" : status));
}
function mapApiHistoryItem(item: ApiHistoryItem): HistorySplit {
return {
id: item.id,
title: item.description?.trim() || `Split ${item.splitId}`,
totalAmount: Number(item.totalAmount) || Math.abs(Number(item.finalAmount)) || 0,
currency: item.preferredCurrency || "USD",
date: item.completionTime,
status: mapApiStatus(item.status, item.isArchived),
participants: [],
role: item.role,
};
}
function mapApiStatus(status: string, isArchived: boolean): SplitStatus {
if (isArchived || status === "archived" || status === "cancelled") return "cancelled";
if (status === "completed") return "completed";
return "active";
}
function filterHistory(splits: HistorySplit[], filters: HistoryFilters): HistorySplit[] {
if (!filters.statuses) return splits;
return splits.filter((split) => filters.statuses?.includes(split.status));
}
function sortHistory(splits: HistorySplit[], sort: HistorySort = "date-desc") {
return [...splits].sort((left, right) => {
switch (sort) {
case "date-asc":
return new Date(left.date).getTime() - new Date(right.date).getTime();
case "amount-desc":
return right.totalAmount - left.totalAmount;
case "amount-asc":
return left.totalAmount - right.totalAmount;
case "status":
return left.status.localeCompare(right.status);
case "date-desc":
default:
return new Date(right.date).getTime() - new Date(left.date).getTime();
}
});
}
function summarizeHistory(splits: HistorySplit[]): HistorySummaryData {
const totalAmount = splits.reduce((sum, split) => sum + split.totalAmount, 0);
const counts = splits.reduce(
(result, split) => {
result[split.status] += 1;
return result;
},
{ active: 0, completed: 0, cancelled: 0 } as Record<SplitStatus, number>,
);
return {
totalAmount,
average: splits.length ? totalAmount / splits.length : 0,
counts,
};
}
function emptyResponse(page: number, limit: number): HistoryResponse {
return {
data: [],
source: "api",
meta: { page, limit, totalItems: 0, totalPages: 1, hasMore: false },
summary: summarizeHistory([]),
};
}
let singleton: SplitHistoryRepository | null = null;
export function getSplitHistoryRepository(): SplitHistoryRepository {
if (!singleton) singleton = new ApiSplitHistoryRepository();
return singleton;
}