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
|
import {
UserLedgerTransactionsResponse,
UserLedgerTransactionsResponseTransactionsInner,
WalletApi
} from "@/api_fsb";
import { useAppDispatch, useAppSelector } from "@/hooks";
import { bpid, formatCentsToUSD, } from "@/lib/utils";
import {
setTxPagination, setTxTotalItems, setTxTotalPages,
setUserLedgerSummary,
setUserLedgerTxs
} from "@/models/appSlice";
import {
RowData, createColumnHelper, flexRender, getCoreRowModel,
useReactTable
} from "@tanstack/react-table";
import moment from "moment";
import { useEffect, useState } from "react";
declare module '@tanstack/react-table' {
interface ColumnMeta<TData extends RowData, TValue> {
align?: 'left' | 'center' | 'right';
}
}
// Function to calculate background color based on balance
const getBackgroundColor = (balance: number | undefined): string => {
if (balance === undefined || balance === null) return 'bg-blue-600';
if (balance > 0) {
return 'bg-blue-600';
} else if (balance <= -100) {
return 'bg-red-600';
} else {
// Interpolate between blue and red for values between 0 and -100
// progress goes from 0 (at balance = 0) to 1 (at balance = -100)
const progress = Math.abs(balance) / 100;
// Blue RGB: (37, 99, 235) - Tailwind blue-600
// Red RGB: (220, 38, 38) - Tailwind red-600
const r = Math.round(37 + (220 - 37) * progress);
const g = Math.round(99 + (38 - 99) * progress);
const b = Math.round(235 + (38 - 235) * progress);
return `rgb(${r}, ${g}, ${b})`;
}
};
const WalletHeader = () => {
const amount = useAppSelector(state => state.app.userWalletBalance)?.amount ?? 0
const bgStyle = typeof getBackgroundColor(amount) === 'string' &&
getBackgroundColor(amount).startsWith('bg-')
? {}
: { backgroundColor: getBackgroundColor(amount) };
const bgClass = typeof getBackgroundColor(amount) === 'string' &&
getBackgroundColor(amount).startsWith('bg-')
? getBackgroundColor(amount)
: '';
return (
<div className={`w-full py-1 px-1 text-white rounded ${bgClass}`}
style={bgStyle}
>
<h2 className="text-xs font-semibold flex justify-between items-center">
<span className="text-left">User Wallet:</span>
{amount >= 0 ? (
<span className='text-emerald-50'>
{`${formatCentsToUSD(Math.abs(amount))}`}
</span>
) : (
<span className='text-rose-50'>
{`(${formatCentsToUSD(Math.abs(amount))})`}
</span>
)}
</h2>
</div>
)
};
const WalletSummary = () => {
const summary = useAppSelector(state => state.app.userLedgerSummary)
const survey_completes = summary?.bp_payment?.entry_count ?? 0
const survey_completes_f = (survey_completes ?? 0).toLocaleString('en-US')
const survey_adjustments = summary?.bp_adjustment?.entry_count ?? 0
const survey_adjustments_f = (survey_adjustments ?? 0).toLocaleString('en-US')
const min_payout: number = summary?.bp_payment?.min_amount ?? 0
const max_payout: number = summary?.bp_payment?.max_amount ?? 0
const adj_total: number = summary?.bp_adjustment?.total_amount ?? 0
const user_payments_total: number = (summary?.user_payout_request?.total_amount ?? 0) * -1
return (
<div className="grid grid-cols-[auto_1fr] text-xs">
<div className="label text-left">Completes:</div>
<div className="value text-right">{survey_completes_f} surveys</div>
<div className="label text-left">Avg Payouts:</div>
<div className="value text-right">{formatCentsToUSD(min_payout)} – {formatCentsToUSD(max_payout)}</div>
<div className="label text-left">Survey Adjustments:</div>
<div className="value text-right">{survey_adjustments_f}</div>
<div className="label text-left">Adjustment Amount:</div>
<div className="value text-right">
{adj_total >= 0 ? (
<span className='text-emerald-300'>
{`${formatCentsToUSD(adj_total)}`}
</span>
) : (
<span className='text-rose-300'>
{`(${formatCentsToUSD(Math.abs(adj_total))})`}
</span>
)}
</div>
<div className="label text-left">User Payments:</div>
<div className="value text-right">
{user_payments_total >= 0 ? (
<span className='text-emerald-300'>
{`${formatCentsToUSD(user_payments_total)}`}
</span>
) : (
<span className='text-rose-300'>
{`(${formatCentsToUSD(Math.abs(user_payments_total))})`}
</span>
)}
</div>
</div >
)
};
const WalletTransactionsHeader = () => {
const tx_cnt = useAppSelector(state => state.app.txTotalItems)
const txt_cnt_f = (tx_cnt ?? 0).toLocaleString('en-US')
const [showTx, setShowTx] = useState(false);
return (
<div className="w-full bg-blue-600 text-white rounded text-left">
<div className="hover:cursor-pointer hover:bg-blue-700 transition-colors duration-200"
onClick={() => setShowTx(!showTx)}>
<h2 className="text-xs font-semibold rounded flex justify-between
py-1 px-1"
onClick={() => setShowTx(!showTx)}
>
<span>Total Transactions:</span> <span>{txt_cnt_f}</span>
</h2>
<h4 className="text-[10px] text-center italic text-blue-300 py-1"
onClick={() => setShowTx(!showTx)}
>
(Click to {showTx ? 'hide' : 'show'})
</h4>
</div>
{showTx && (
<>
<WalletTransactions />
</>
)}
</div>
)
};
const WalletTransactions = () => {
const dispatch = useAppDispatch()
const bpuid = useAppSelector(state => state.app.bpuid)
const userLedgerTxs = useAppSelector(state => state.app.userLedgerTxs);
const txPagination = useAppSelector(state => state.app.txPagination);
const txTotalPages = useAppSelector(state => state.app.txTotalPages);
useEffect(() => {
if (!bpuid) return;
new WalletApi().getUserTransactionHistoryProductIdTransactionHistoryGet(
bpid, // productId
bpuid, // bpuid
undefined, // createdAfter
undefined, // createdBefore
"-created", // orderBy
txPagination.pageIndex + 1, // page
txPagination.pageSize // pageSize
).then(res => {
const response = res.data as UserLedgerTransactionsResponse;
console.log("Wallet: fetched user ledger", response);
dispatch(setUserLedgerSummary(response.summary));
dispatch(setUserLedgerTxs(response.transactions ?? []))
dispatch(setTxTotalItems(response.total!))
dispatch(setTxTotalPages(response.pages!))
});
}, [bpuid, txPagination.pageIndex, txPagination.pageSize]);
const columnHelper = createColumnHelper<UserLedgerTransactionsResponseTransactionsInner>()
const columns = [
columnHelper.accessor('created', {
header: () => 'Date',
cell: (info) => moment(info.getValue()).format('M/D/YY H:mm'),
size: 110,
meta: {
align: 'left'
}
}),
columnHelper.accessor('description', {
header: () => 'Type',
cell: props => {
const desc = props.getValue();
switch (desc) {
case 'Task Complete':
return 'Survey 🎉';
case 'Task Adjustment':
return 'Reject ⚠️';
case 'Compensation Bonus':
return 'Bonus 🎁';
case 'HIT Bonus':
return 'Bonus';
case 'HIT Reward':
return 'Assignment';
default:
return desc;
}
},
size: 80,
meta: {
align: 'left'
}
}),
columnHelper.accessor('amount', {
header: () => 'Amount',
cell: (props) => {
const val = props.renderValue() as number;
const isPositive = val >= 0;
const emoji = isPositive ? "⬆\uFE0E" : "⬇\uFE0E";
const colorClass = isPositive ? 'font-variant-emoji-text text-emerald-300' : 'font-variant-emoji-text text-rose-300';
return (
<span className={colorClass}>
{`${emoji} ${formatCentsToUSD(Math.abs(val))}`}
</span>
)
},
size: 70,
meta: {
align: 'center'
}
}),
columnHelper.accessor('balance_after', {
header: () => 'Balance',
cell: (props) => {
const val = props.renderValue() as number;
const isPositive = val >= 0;
const colorClass = isPositive ? 'text-emerald-300' : 'text-rose-300';
return (
<>
{isPositive ? (
<span className={colorClass}>
{`${formatCentsToUSD(Math.abs(val))}`}
</span>
) : (
<span className={colorClass}>
{`(${formatCentsToUSD(Math.abs(val))})`}
</span>
)}
</>
)
},
size: 70,
meta: {
align: 'center'
}
}),
]
const table = useReactTable({
'data': userLedgerTxs,
'columns': columns,
getCoreRowModel: getCoreRowModel(),
manualPagination: true,
pageCount: txTotalPages,
onPaginationChange: (updater) => {
dispatch(setTxPagination(
typeof updater === 'function' ? updater(txPagination) : updater
));
},
state: {
pagination: txPagination,
},
});
return (
<div className="w-full border-t-1 border-blue-800 p-2">
<table className="text-xs table-fixed border-collapse">
<thead className="font-bold">
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => {
const align = header.column.columnDef.meta?.align || 'left';
const alignClass = align === 'center' ? 'text-center' : align === 'right' ? 'text-right' : 'text-left';
return (
<th
key={header.id}
className={`p-0 m-0 ${alignClass}`}
style={{
width: `${header.column.getSize()}px`,
}}
>
{flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</th>
)
})}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => {
const align = cell.column.columnDef.meta?.align || 'left';
const alignClass = align === 'center' ? 'text-center' :
align === 'right' ? 'text-right' : 'text-left';
return (
<td key={cell.id}
className={`p-0 ${alignClass}`}
style={{
width: `${cell.column.getSize()}px`,
}}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
)
})}
</tr>
))}
</tbody>
<tfoot>
<tr>
<td colSpan={columns.length} className="p-2">
<div className="flex items-center justify-between text-xs">
{/* Page info */}
<div className="text-blue-50">
Page {table.getState().pagination.pageIndex + 1} of{' '}
{table.getPageCount()}
</div>
{/* Navigation buttons */}
<div className="flex gap-8 text-xs">
<button
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
className="px-3 py-1 border border-blue-200 rounded
font-variant-emoji-text
hover:cursor-pointer hover:bg-blue-700
disabled:opacity-50 disabled:cursor-not-allowed"
>
{'⬅\uFE0E'}
</button>
<button
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
className="px-3 py-1 border border-blue-200 rounded
font-variant-emoji-text
hover:cursor-pointer hover:bg-blue-700
disabled:opacity-50 disabled:cursor-not-allowed"
>
{'⮕\uFE0E'}
</button>
</div>
{/* Page size selector */}
<select
value={table.getState().pagination.pageSize}
onChange={e => table.setPageSize(Number(e.target.value))}
className="px-2 py-1 border border-blue-200 rounded
hover:cursor-pointer hover:bg-blue-700"
>
{[10, 20, 30, 40].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
)
};
const Wallet = () => {
const dispatch = useAppDispatch()
const bpuid = useAppSelector(state => state.app.bpuid)
const pagination = useAppSelector(state => state.app.txPagination);
useEffect(() => {
if (!bpuid) return;
new WalletApi().getUserTransactionHistoryProductIdTransactionHistoryGet(
bpid, // productId
bpuid, // bpuid
undefined, // createdAfter
undefined, // createdBefore
"-created", // orderBy
pagination.pageIndex + 1, // page
pagination.pageSize // pageSize
).then(res => {
const response = res.data as UserLedgerTransactionsResponse;
dispatch(setUserLedgerSummary(response.summary));
dispatch(setUserLedgerTxs(response.transactions ?? []))
dispatch(setTxPagination({
pageIndex: (response.page ?? 1) - 1,
pageSize: response.size ?? 10,
}))
dispatch(setTxTotalItems(response.total ?? 0))
dispatch(setTxTotalPages(response.pages ?? 9))
});
}, [bpuid])
if (!bpuid) return null;
return (
<div className="fixed top-2 left-2 p-2 rounded
bg-blue-500 text-white shadow-lg z-50
font-mono
max-h-[calc(100vh-2.5rem)] overflow-y-auto
max-w-[96vw]
">
<WalletHeader />
<WalletSummary />
<WalletTransactionsHeader />
</div>
)
};
export default Wallet;
|