-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcredits.ts
More file actions
260 lines (227 loc) · 8.2 KB
/
Copy pathcredits.ts
File metadata and controls
260 lines (227 loc) · 8.2 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
import { Router } from 'express'
import { asyncSafeHandler } from '../../shared/utils/express.js'
import { handleAuth } from '../../infrastructure/services/auth/express.js'
import { CreditsUseCases } from '../../core/users/credits.js'
import {
handleInternalError,
handleInternalErrorResult,
} from '../../shared/utils/neverthrow.js'
import { handleError } from '../../errors/index.js'
import { PurchasedCredit } from '@auto-drive/models'
export const creditsController = Router()
// ---------------------------------------------------------------------------
// Serialisation helpers
// ---------------------------------------------------------------------------
// PurchasedCredit rows contain bigint fields that cannot be JSON-serialised
// directly. We convert each bigint to a string so the wire format is stable
// and the frontend can parse them with BigInt() or a numeric library.
const serializeCredit = (credit: PurchasedCredit) => ({
...credit,
uploadBytesOriginal: credit.uploadBytesOriginal.toString(),
uploadBytesRemaining: credit.uploadBytesRemaining.toString(),
downloadBytesOriginal: credit.downloadBytesOriginal.toString(),
downloadBytesRemaining: credit.downloadBytesRemaining.toString(),
})
// ---------------------------------------------------------------------------
// GET /credits/summary
// Returns the authenticated user's credit totals, next expiry, and whether
// they can still make a purchase without hitting the per-user cap.
// ---------------------------------------------------------------------------
creditsController.get(
'/summary',
asyncSafeHandler(async (req, res) => {
const user = await handleAuth(req, res)
if (!user) {
return
}
const result = await handleInternalError(
CreditsUseCases.getSummary(user),
'Failed to get credit summary',
)
if (result.isErr()) {
handleError(result.error, res)
return
}
const summary = result.value
res.status(200).json({
uploadBytesRemaining: summary.uploadBytesRemaining.toString(),
downloadBytesRemaining: summary.downloadBytesRemaining.toString(),
nextExpiryDate: summary.nextExpiryDate ?? null,
batchCount: summary.batchCount,
canPurchase: summary.canPurchase,
maxPurchasableBytes: summary.maxPurchasableBytes.toString(),
googleVerified: summary.googleVerified,
expiryDays: summary.expiryDays,
})
}),
)
// ---------------------------------------------------------------------------
// GET /credits/batches
// Returns the full purchase history for the authenticated user, including
// already-expired rows, ordered newest-first.
// ---------------------------------------------------------------------------
creditsController.get(
'/batches',
asyncSafeHandler(async (req, res) => {
const user = await handleAuth(req, res)
if (!user) {
return
}
const result = await handleInternalError(
CreditsUseCases.getBatches(user),
'Failed to get credit batches',
)
if (result.isErr()) {
handleError(result.error, res)
return
}
res.status(200).json(result.value.map(serializeCredit))
}),
)
// ---------------------------------------------------------------------------
// GET /credits/batches/expiring
// Returns active rows expiring within 30 days for the authenticated user.
// Useful for frontend expiry-warning banners.
// ---------------------------------------------------------------------------
creditsController.get(
'/batches/expiring',
asyncSafeHandler(async (req, res) => {
const user = await handleAuth(req, res)
if (!user) {
return
}
const result = await handleInternalError(
CreditsUseCases.getExpiringBatches(user),
'Failed to get expiring credit batches',
)
if (result.isErr()) {
handleError(result.error, res)
return
}
res.status(200).json(result.value.map(serializeCredit))
}),
)
// ---------------------------------------------------------------------------
// GET /credits/batches/all
// Admin-only: all credit batches across every user, newest-first.
// Each row includes the owner's userPublicId for easy cross-referencing
// with the admin user table. Returns 403 for non-admin callers.
//
// NOTE: registered BEFORE GET /credits/batches so Express does not attempt
// to match the literal string "all" against the existing /batches route
// (they are separate paths and Express won't confuse them, but ordering
// here keeps the admin routes grouped together).
// ---------------------------------------------------------------------------
creditsController.get(
'/batches/all',
asyncSafeHandler(async (req, res) => {
const user = await handleAuth(req, res)
if (!user) {
return
}
const result = await handleInternalErrorResult(
CreditsUseCases.getAllBatches(user),
'Failed to get all credit batches',
)
if (result.isErr()) {
handleError(result.error, res)
return
}
res.status(200).json(
result.value.map((batch) => ({
...serializeCredit(batch),
userPublicId: batch.userPublicId,
})),
)
}),
)
// ---------------------------------------------------------------------------
// GET /credits/batches/user/:userPublicId
// Admin-only: all credit batches for a specific user, newest-first.
// Each row includes intent fields (paymentAmount, shannonsPerByte, txHash,
// fromAddress) so the admin can calculate the AI3 price paid and identify
// the wallet used for the on-chain payment.
// Returns 403 for non-admin callers.
// ---------------------------------------------------------------------------
creditsController.get(
'/batches/user/:userPublicId',
asyncSafeHandler(async (req, res) => {
const user = await handleAuth(req, res)
if (!user) {
return
}
const { userPublicId } = req.params
const result = await handleInternalErrorResult(
CreditsUseCases.getUserBatches(user, userPublicId),
'Failed to get user credit batches',
)
if (result.isErr()) {
handleError(result.error, res)
return
}
res.status(200).json(
result.value.map((batch) => ({
...serializeCredit(batch),
userPublicId: batch.userPublicId,
paymentAmount: batch.paymentAmount?.toString() ?? null,
shannonsPerByte: batch.shannonsPerByte.toString(),
txHash: batch.txHash ?? null,
fromAddress: batch.fromAddress ?? null,
})),
)
}),
)
// ---------------------------------------------------------------------------
// POST /credits/batches/:id/refund
// Admin-only: marks a credit batch as refunded (zeros remaining bytes,
// sets refunded = true). Idempotent — safe to call multiple times.
// Returns 403 for non-admin callers, 404 if the batch is not found.
// ---------------------------------------------------------------------------
creditsController.post(
'/batches/:id/refund',
asyncSafeHandler(async (req, res) => {
const user = await handleAuth(req, res)
if (!user) {
return
}
const { id } = req.params
const result = await handleInternalErrorResult(
CreditsUseCases.refundBatch(user, id),
'Failed to refund credit batch',
)
if (result.isErr()) {
handleError(result.error, res)
return
}
res.status(200).json({ ok: true })
}),
)
// ---------------------------------------------------------------------------
// GET /credits/economics
// Admin-only: system-wide credit stats (expiring totals, byte volumes).
// Returns 403 for non-admin users.
// ---------------------------------------------------------------------------
creditsController.get(
'/economics',
asyncSafeHandler(async (req, res) => {
const user = await handleAuth(req, res)
if (!user) {
return
}
const result = await handleInternalErrorResult(
CreditsUseCases.getEconomics(user),
'Failed to get credit economics',
)
if (result.isErr()) {
handleError(result.error, res)
return
}
const economics = result.value
res.status(200).json({
totalExpiringWithin30Days: economics.totalExpiringWithin30Days,
totalExpiringUploadBytes: economics.totalExpiringUploadBytes.toString(),
totalExpiringDownloadBytes:
economics.totalExpiringDownloadBytes.toString(),
})
}),
)