@nehorai/credits 1.7.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +226 -2
- package/dist/adapters/index.cjs +298 -40
- package/dist/adapters/index.cjs.map +1 -1
- package/dist/adapters/index.d.cts +2 -2
- package/dist/adapters/index.d.ts +2 -2
- package/dist/adapters/index.js +298 -40
- package/dist/adapters/index.js.map +1 -1
- package/dist/core/index.cjs +696 -74
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +583 -5
- package/dist/core/index.d.ts +583 -5
- package/dist/core/index.js +648 -74
- package/dist/core/index.js.map +1 -1
- package/dist/index.cjs +1762 -365
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +41 -6
- package/dist/index.d.ts +41 -6
- package/dist/index.js +1706 -365
- package/dist/index.js.map +1 -1
- package/dist/repository/index.cjs +1399 -183
- package/dist/repository/index.cjs.map +1 -1
- package/dist/repository/index.d.cts +141 -15
- package/dist/repository/index.d.ts +141 -15
- package/dist/repository/index.js +1392 -183
- package/dist/repository/index.js.map +1 -1
- package/dist/sdk/index.cjs +23 -1
- package/dist/sdk/index.cjs.map +1 -1
- package/dist/sdk/index.d.cts +2 -2
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/index.js +23 -1
- package/dist/sdk/index.js.map +1 -1
- package/dist/service/index.cjs +480 -104
- package/dist/service/index.cjs.map +1 -1
- package/dist/service/index.d.cts +68 -10
- package/dist/service/index.d.ts +68 -10
- package/dist/service/index.js +480 -104
- package/dist/service/index.js.map +1 -1
- package/dist/types-BmG5Omzj.d.ts +646 -0
- package/dist/types-C8hZMe8a.d.cts +646 -0
- package/dist/{types-CjLj3GW5.d.cts → types-DJ8yqaVr.d.cts} +39 -1
- package/dist/{types-CjLj3GW5.d.ts → types-DJ8yqaVr.d.ts} +39 -1
- package/package.json +1 -1
- package/dist/types-DFe5BoJY.d.cts +0 -329
- package/dist/types-_bSybQnb.d.ts +0 -329
package/dist/service/index.js
CHANGED
|
@@ -1,3 +1,167 @@
|
|
|
1
|
+
// src/core/errors.ts
|
|
2
|
+
var CreditErrorCode = {
|
|
3
|
+
INSUFFICIENT_CREDITS: "INSUFFICIENT_CREDITS",
|
|
4
|
+
RESERVATION_NOT_FOUND: "RESERVATION_NOT_FOUND",
|
|
5
|
+
RESERVATION_EXPIRED: "RESERVATION_EXPIRED",
|
|
6
|
+
RESERVATION_ALREADY_PROCESSED: "RESERVATION_ALREADY_PROCESSED",
|
|
7
|
+
USER_NOT_FOUND: "USER_NOT_FOUND",
|
|
8
|
+
INVALID_OPERATION_TYPE: "INVALID_OPERATION_TYPE",
|
|
9
|
+
CONFIGURATION_ERROR: "CONFIGURATION_ERROR",
|
|
10
|
+
DATABASE_ERROR: "DATABASE_ERROR",
|
|
11
|
+
/** Caller reused an idempotency key with a different immutable payload. */
|
|
12
|
+
IDEMPOTENCY_CONFLICT: "IDEMPOTENCY_CONFLICT",
|
|
13
|
+
/**
|
|
14
|
+
* Retryable infrastructure failure — serialization/deadlock, lock timeout,
|
|
15
|
+
* connection loss, pool exhaustion. Distinct from `DATABASE_ERROR`, which is
|
|
16
|
+
* a deterministic failure that will fail again identically on retry.
|
|
17
|
+
*/
|
|
18
|
+
TRANSIENT_ERROR: "TRANSIENT_ERROR",
|
|
19
|
+
/** The configured repository adapter does not implement the requested V2 method. */
|
|
20
|
+
UNSUPPORTED_OPERATION: "UNSUPPORTED_OPERATION",
|
|
21
|
+
/** Amount was not a finite positive number. */
|
|
22
|
+
INVALID_AMOUNT: "INVALID_AMOUNT",
|
|
23
|
+
/** Idempotency key was supplied but empty or whitespace-only. */
|
|
24
|
+
INVALID_IDEMPOTENCY_KEY: "INVALID_IDEMPOTENCY_KEY",
|
|
25
|
+
/**
|
|
26
|
+
* A persisted reservation holds a status this library does not define, so no
|
|
27
|
+
* transition can reason about it. Quarantined rather than cast; nothing moved.
|
|
28
|
+
*/
|
|
29
|
+
CORRUPT_RESERVATION_STATUS: "CORRUPT_RESERVATION_STATUS",
|
|
30
|
+
/**
|
|
31
|
+
* A persisted reservation does not record that its hold was placed
|
|
32
|
+
* atomically, so the credits it claims are not known to be reserved. Moving
|
|
33
|
+
* it would spend another hold's coverage; nothing moved.
|
|
34
|
+
*/
|
|
35
|
+
UNBACKED_RESERVATION: "UNBACKED_RESERVATION"
|
|
36
|
+
};
|
|
37
|
+
var CreditError = class _CreditError extends Error {
|
|
38
|
+
code;
|
|
39
|
+
details;
|
|
40
|
+
constructor(message, code, details) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.name = "CreditError";
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.details = details;
|
|
45
|
+
if (Error.captureStackTrace) {
|
|
46
|
+
Error.captureStackTrace(this, _CreditError);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Convert to JSON-serializable object
|
|
51
|
+
*/
|
|
52
|
+
toJSON() {
|
|
53
|
+
return {
|
|
54
|
+
name: this.name,
|
|
55
|
+
code: this.code,
|
|
56
|
+
message: this.message,
|
|
57
|
+
...this.details && { details: this.details }
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
function isCreditError(error) {
|
|
62
|
+
return error instanceof CreditError;
|
|
63
|
+
}
|
|
64
|
+
function isInsufficientCreditsError(error) {
|
|
65
|
+
if (isCreditError(error)) {
|
|
66
|
+
return error.code === CreditErrorCode.INSUFFICIENT_CREDITS;
|
|
67
|
+
}
|
|
68
|
+
if (error instanceof Error) {
|
|
69
|
+
return error.message.toLowerCase().includes("insufficient credits");
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
function createInsufficientCreditsError(required, available) {
|
|
74
|
+
return new CreditError(
|
|
75
|
+
`Insufficient credits: available ${available}, required ${required}`,
|
|
76
|
+
CreditErrorCode.INSUFFICIENT_CREDITS,
|
|
77
|
+
{ required, available, shortfall: sumAmounts(required, -available) }
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
function createReservationNotFoundError(reservationId) {
|
|
81
|
+
return new CreditError(
|
|
82
|
+
`Reservation ${reservationId} not found`,
|
|
83
|
+
CreditErrorCode.RESERVATION_NOT_FOUND,
|
|
84
|
+
{ reservationId }
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
function createReservationAlreadyProcessedError(reservationId, status) {
|
|
88
|
+
return new CreditError(
|
|
89
|
+
`Reservation ${reservationId} has already been ${status}`,
|
|
90
|
+
CreditErrorCode.RESERVATION_ALREADY_PROCESSED,
|
|
91
|
+
{ reservationId, status }
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
function createIdempotencyConflictError(idempotencyKey, details) {
|
|
95
|
+
return new CreditError(
|
|
96
|
+
`Idempotency key ${idempotencyKey} was reused with a different payload`,
|
|
97
|
+
CreditErrorCode.IDEMPOTENCY_CONFLICT,
|
|
98
|
+
{ idempotencyKey, ...details }
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
function createUnsupportedOperationError(operation, hint) {
|
|
102
|
+
return new CreditError(
|
|
103
|
+
hint ? `Repository does not support ${operation}. ${hint}` : `Repository does not support ${operation}`,
|
|
104
|
+
CreditErrorCode.UNSUPPORTED_OPERATION,
|
|
105
|
+
{ operation, ...hint ? { hint } : {} }
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/core/amount.ts
|
|
110
|
+
var CREDIT_AMOUNT_SCALE = 2;
|
|
111
|
+
var CREDIT_AMOUNT_MAX = 999999999999e-2;
|
|
112
|
+
var MAX_CENTS = 999999999999;
|
|
113
|
+
function toCents(value) {
|
|
114
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return null;
|
|
115
|
+
const cents = Math.round(value * 100);
|
|
116
|
+
if (!Number.isSafeInteger(cents)) return null;
|
|
117
|
+
return value === cents / 100 ? cents : null;
|
|
118
|
+
}
|
|
119
|
+
function sumAmounts(...values) {
|
|
120
|
+
let cents = 0;
|
|
121
|
+
for (const value of values) {
|
|
122
|
+
const valueCents = toCents(value);
|
|
123
|
+
if (valueCents === null) return floatSum(values);
|
|
124
|
+
cents += valueCents;
|
|
125
|
+
}
|
|
126
|
+
return Number.isSafeInteger(cents) ? cents / 100 : floatSum(values);
|
|
127
|
+
}
|
|
128
|
+
function floatSum(values) {
|
|
129
|
+
let total = 0;
|
|
130
|
+
for (const value of values) total += value;
|
|
131
|
+
return total;
|
|
132
|
+
}
|
|
133
|
+
function isValidCreditAmount(value) {
|
|
134
|
+
if (typeof value !== "number") return false;
|
|
135
|
+
const cents = toCents(value);
|
|
136
|
+
return cents !== null && cents > 0 && cents <= MAX_CENTS;
|
|
137
|
+
}
|
|
138
|
+
function assertValidCreditAmount(value, context) {
|
|
139
|
+
if (isValidCreditAmount(value)) return;
|
|
140
|
+
throw new CreditError(
|
|
141
|
+
creditAmountReason(value),
|
|
142
|
+
CreditErrorCode.INVALID_AMOUNT,
|
|
143
|
+
{ amount: value, max: CREDIT_AMOUNT_MAX, scale: CREDIT_AMOUNT_SCALE, ...context }
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
function creditAmountReason(value) {
|
|
147
|
+
if (typeof value !== "number") {
|
|
148
|
+
return `Credit amount must be a number (got ${typeof value})`;
|
|
149
|
+
}
|
|
150
|
+
if (!Number.isFinite(value)) {
|
|
151
|
+
return `Credit amount must be finite (got ${String(value)})`;
|
|
152
|
+
}
|
|
153
|
+
if (value <= 0) {
|
|
154
|
+
return `Credit amount must be greater than zero (got ${value})`;
|
|
155
|
+
}
|
|
156
|
+
if (value > CREDIT_AMOUNT_MAX) {
|
|
157
|
+
return `Credit amount ${value} exceeds the maximum of ${CREDIT_AMOUNT_MAX}`;
|
|
158
|
+
}
|
|
159
|
+
return `Credit amount ${value} is not exact to ${CREDIT_AMOUNT_SCALE} decimal places`;
|
|
160
|
+
}
|
|
161
|
+
function storedMonthlyLimit(limit) {
|
|
162
|
+
return Number.isFinite(limit) ? limit : CREDIT_AMOUNT_MAX;
|
|
163
|
+
}
|
|
164
|
+
|
|
1
165
|
// src/core/types.ts
|
|
2
166
|
function toDate(value) {
|
|
3
167
|
if (value instanceof Date) {
|
|
@@ -12,32 +176,6 @@ function toDate(value) {
|
|
|
12
176
|
return /* @__PURE__ */ new Date();
|
|
13
177
|
}
|
|
14
178
|
|
|
15
|
-
// src/repository/types.ts
|
|
16
|
-
function toClientUserCredits(credits) {
|
|
17
|
-
return {
|
|
18
|
-
userId: credits.userId,
|
|
19
|
-
balance: credits.balance,
|
|
20
|
-
bonusCredits: credits.bonusCredits ?? 0,
|
|
21
|
-
reserved: credits.reserved,
|
|
22
|
-
tier: credits.tier,
|
|
23
|
-
monthlyLimit: credits.monthlyLimit,
|
|
24
|
-
monthlyUsed: credits.monthlyUsed,
|
|
25
|
-
monthlyResetAt: toISOString(credits.monthlyResetAt),
|
|
26
|
-
subscriptionExpiresAt: credits.subscriptionExpiresAt ? toISOString(credits.subscriptionExpiresAt) : null,
|
|
27
|
-
createdAt: toISOString(credits.createdAt),
|
|
28
|
-
updatedAt: toISOString(credits.updatedAt)
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
function toISOString(value) {
|
|
32
|
-
if (!value) return (/* @__PURE__ */ new Date()).toISOString();
|
|
33
|
-
if (typeof value === "string") return value;
|
|
34
|
-
if (value instanceof Date) return value.toISOString();
|
|
35
|
-
if (typeof value === "object" && "toDate" in value && typeof value.toDate === "function") {
|
|
36
|
-
return value.toDate().toISOString();
|
|
37
|
-
}
|
|
38
|
-
return (/* @__PURE__ */ new Date()).toISOString();
|
|
39
|
-
}
|
|
40
|
-
|
|
41
179
|
// src/config/index.ts
|
|
42
180
|
import { z } from "zod";
|
|
43
181
|
|
|
@@ -333,6 +471,178 @@ function getOperationLabel(operationType) {
|
|
|
333
471
|
}
|
|
334
472
|
initializeConfig();
|
|
335
473
|
|
|
474
|
+
// src/core/payment-ref.ts
|
|
475
|
+
function normalizePaymentRef(ref) {
|
|
476
|
+
if (typeof ref !== "string") return void 0;
|
|
477
|
+
const trimmed = ref.trim();
|
|
478
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// src/repository/types.ts
|
|
482
|
+
function supportsCreditsV2(repository) {
|
|
483
|
+
return typeof repository.reserveCreditsV2 === "function" && typeof repository.commitReservationV2 === "function" && typeof repository.releaseReservationV2 === "function" && typeof repository.expireReservationV2 === "function";
|
|
484
|
+
}
|
|
485
|
+
function supportsIdempotentCredit(repository) {
|
|
486
|
+
return typeof repository.addCreditsV2 === "function";
|
|
487
|
+
}
|
|
488
|
+
function toClientUserCredits(credits) {
|
|
489
|
+
return {
|
|
490
|
+
userId: credits.userId,
|
|
491
|
+
balance: credits.balance,
|
|
492
|
+
bonusCredits: credits.bonusCredits ?? 0,
|
|
493
|
+
reserved: credits.reserved,
|
|
494
|
+
tier: credits.tier,
|
|
495
|
+
monthlyLimit: credits.monthlyLimit,
|
|
496
|
+
monthlyUsed: credits.monthlyUsed,
|
|
497
|
+
monthlyResetAt: toISOString(credits.monthlyResetAt),
|
|
498
|
+
subscriptionExpiresAt: credits.subscriptionExpiresAt ? toISOString(credits.subscriptionExpiresAt) : null,
|
|
499
|
+
createdAt: toISOString(credits.createdAt),
|
|
500
|
+
updatedAt: toISOString(credits.updatedAt)
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
function toISOString(value) {
|
|
504
|
+
if (!value) return (/* @__PURE__ */ new Date()).toISOString();
|
|
505
|
+
if (typeof value === "string") return value;
|
|
506
|
+
if (value instanceof Date) return value.toISOString();
|
|
507
|
+
if (typeof value === "object" && "toDate" in value && typeof value.toDate === "function") {
|
|
508
|
+
return value.toDate().toISOString();
|
|
509
|
+
}
|
|
510
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// src/repository/flow.ts
|
|
514
|
+
async function reserveThroughRepository(repository, input) {
|
|
515
|
+
const v2 = supportsCreditsV2(repository);
|
|
516
|
+
if (!v2 && input.idempotencyKey !== void 0) {
|
|
517
|
+
throw createUnsupportedOperationError(
|
|
518
|
+
"reserveCredits with an idempotencyKey",
|
|
519
|
+
"This repository does not implement the V2 boundary, so it cannot enforce idempotency keys. Use a V2 repository (check with supportsCreditsV2) or omit the key and accept at-least-once holds."
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
assertValidCreditAmount(input.amount, { userId: input.userId });
|
|
523
|
+
if (v2) {
|
|
524
|
+
return repository.reserveCreditsV2(input);
|
|
525
|
+
}
|
|
526
|
+
try {
|
|
527
|
+
const reservation = await repository.reserveCreditsAtomic(
|
|
528
|
+
input.userId,
|
|
529
|
+
input.amount,
|
|
530
|
+
input.operationType,
|
|
531
|
+
input.expiresAt
|
|
532
|
+
);
|
|
533
|
+
return { outcome: "created", reservation };
|
|
534
|
+
} catch (error) {
|
|
535
|
+
if (!isInsufficientCreditsError(error)) throw error;
|
|
536
|
+
const credits = await repository.getUserCredits(input.userId);
|
|
537
|
+
const available = credits ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved) : 0;
|
|
538
|
+
return {
|
|
539
|
+
outcome: "insufficient",
|
|
540
|
+
available,
|
|
541
|
+
required: input.amount,
|
|
542
|
+
shortfall: Math.max(sumAmounts(input.amount, -available), 0)
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
async function commitThroughRepository(repository, userId, reservationId, options) {
|
|
547
|
+
if (supportsCreditsV2(repository)) {
|
|
548
|
+
return repository.commitReservationV2(userId, reservationId, options);
|
|
549
|
+
}
|
|
550
|
+
const reservation = await repository.getReservation(userId, reservationId);
|
|
551
|
+
if (!reservation) return { outcome: "not_found", reservationId };
|
|
552
|
+
if (reservation.status !== "reserved") {
|
|
553
|
+
return {
|
|
554
|
+
outcome: "already_terminal",
|
|
555
|
+
reservation,
|
|
556
|
+
terminalStatus: reservation.status
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
await repository.commitReservationAtomic(userId, reservationId);
|
|
560
|
+
const credits = await repository.getUserCredits(userId);
|
|
561
|
+
const balanceAfter = credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0;
|
|
562
|
+
const entry = await repository.createJournalEntry({
|
|
563
|
+
userId,
|
|
564
|
+
entryType: "debit",
|
|
565
|
+
amount: reservation.amount,
|
|
566
|
+
balanceAfter,
|
|
567
|
+
source: "operation_commit",
|
|
568
|
+
referenceId: reservationId,
|
|
569
|
+
referenceType: "reservation",
|
|
570
|
+
description: options?.description ?? `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,
|
|
571
|
+
// Deterministic fields last: they carry the identity of the event, and a
|
|
572
|
+
// caller who happens to send an `operationType` or an `amount` must not
|
|
573
|
+
// relabel what actually moved.
|
|
574
|
+
metadata: {
|
|
575
|
+
...options?.metadata,
|
|
576
|
+
operationType: reservation.operationType,
|
|
577
|
+
amount: reservation.amount
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
return {
|
|
581
|
+
outcome: "committed",
|
|
582
|
+
reservation: { ...reservation, status: "committed" },
|
|
583
|
+
amount: reservation.amount,
|
|
584
|
+
balanceAfter,
|
|
585
|
+
journalEntryId: entry.id
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
async function releaseThroughRepository(repository, userId, reservationId, options) {
|
|
589
|
+
if (supportsCreditsV2(repository)) {
|
|
590
|
+
return repository.releaseReservationV2(userId, reservationId, options);
|
|
591
|
+
}
|
|
592
|
+
const reservation = await repository.getReservation(userId, reservationId);
|
|
593
|
+
if (!reservation) {
|
|
594
|
+
await repository.releaseReservationAtomic(userId, reservationId);
|
|
595
|
+
return { outcome: "not_found", reservationId };
|
|
596
|
+
}
|
|
597
|
+
if (reservation.status !== "reserved") {
|
|
598
|
+
await repository.releaseReservationAtomic(userId, reservationId).catch(() => void 0);
|
|
599
|
+
return {
|
|
600
|
+
outcome: "already_terminal",
|
|
601
|
+
reservation,
|
|
602
|
+
terminalStatus: reservation.status
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
await repository.releaseReservationAtomic(userId, reservationId);
|
|
606
|
+
const credits = await repository.getUserCredits(userId);
|
|
607
|
+
const entry = await repository.createJournalEntry({
|
|
608
|
+
userId,
|
|
609
|
+
entryType: "credit",
|
|
610
|
+
// No credits changed hands — the hold just moved back into "available".
|
|
611
|
+
amount: 0,
|
|
612
|
+
balanceAfter: credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0,
|
|
613
|
+
source: "operation_release",
|
|
614
|
+
referenceId: reservationId,
|
|
615
|
+
referenceType: "reservation",
|
|
616
|
+
description: options?.description ?? `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,
|
|
617
|
+
metadata: {
|
|
618
|
+
...options?.metadata,
|
|
619
|
+
operationType: reservation.operationType,
|
|
620
|
+
amount: reservation.amount
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
return {
|
|
624
|
+
outcome: "released",
|
|
625
|
+
reservation: { ...reservation, status: "released" },
|
|
626
|
+
amount: reservation.amount,
|
|
627
|
+
journalEntryId: entry.id
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
async function addCreditsThroughRepository(repository, input) {
|
|
631
|
+
assertValidCreditAmount(input.amount, { userId: input.userId, operation: "addCredits" });
|
|
632
|
+
const paymentRef = normalizePaymentRef(input.paymentRef);
|
|
633
|
+
if (supportsIdempotentCredit(repository)) {
|
|
634
|
+
return repository.addCreditsV2({ ...input, paymentRef });
|
|
635
|
+
}
|
|
636
|
+
await repository.addCreditsAtomic(
|
|
637
|
+
input.userId,
|
|
638
|
+
input.amount,
|
|
639
|
+
input.description,
|
|
640
|
+
paymentRef,
|
|
641
|
+
input.options
|
|
642
|
+
);
|
|
643
|
+
return paymentRef ? { outcome: "created", paymentRef } : { outcome: "created" };
|
|
644
|
+
}
|
|
645
|
+
|
|
336
646
|
// src/service/credits-service.ts
|
|
337
647
|
function isPastMonthlyReset(resetAt) {
|
|
338
648
|
if (!resetAt) return false;
|
|
@@ -377,28 +687,38 @@ var CreditsService = class {
|
|
|
377
687
|
userId,
|
|
378
688
|
getConfig().subscriptionGracePeriodDays
|
|
379
689
|
);
|
|
380
|
-
if (expiryResult.wasDowngraded) {
|
|
690
|
+
if (expiryResult.wasDowngraded && !expiryResult.journaled) {
|
|
381
691
|
await this.repository.createJournalEntry({
|
|
382
692
|
userId,
|
|
383
693
|
entryType: "debit",
|
|
384
694
|
amount: 0,
|
|
385
695
|
// No credits deducted, just tier change
|
|
386
|
-
|
|
696
|
+
// The ledger balance, matching every other journal writer: the V2
|
|
697
|
+
// transitions and add/deduct all record `balance + bonusCredits`, so
|
|
698
|
+
// recording `balance` alone made the audit trail disagree with itself
|
|
699
|
+
// for any user holding bonus credits.
|
|
700
|
+
balanceAfter: sumAmounts(
|
|
701
|
+
expiryResult.credits.balance,
|
|
702
|
+
expiryResult.credits.bonusCredits
|
|
703
|
+
),
|
|
387
704
|
source: "subscription_downgrade",
|
|
388
705
|
referenceId: `downgrade-${Date.now()}`,
|
|
389
706
|
referenceType: "subscription",
|
|
390
|
-
|
|
707
|
+
// The tier actually landed on, not a hard-coded "free": the downgrade
|
|
708
|
+
// target is configurable, so naming `free` here could describe a
|
|
709
|
+
// transition that never happened.
|
|
710
|
+
description: `Subscription expired. Downgraded from ${data.tier} to ${expiryResult.credits.tier} tier.`,
|
|
391
711
|
metadata: {
|
|
392
712
|
previousTier: data.tier,
|
|
393
713
|
previousBalance: data.balance,
|
|
394
714
|
newBalance: expiryResult.credits.balance
|
|
395
715
|
}
|
|
396
716
|
});
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
}
|
|
717
|
+
}
|
|
718
|
+
if (expiryResult.wasDowngraded && this.subscriptionExpiredCallback) {
|
|
719
|
+
this.subscriptionExpiredCallback(userId, true).catch((error) => {
|
|
720
|
+
console.error("[Credits] Failed to send subscription expired notification:", error);
|
|
721
|
+
});
|
|
402
722
|
}
|
|
403
723
|
data = expiryResult.credits;
|
|
404
724
|
}
|
|
@@ -409,14 +729,17 @@ var CreditsService = class {
|
|
|
409
729
|
data.tier,
|
|
410
730
|
expectedResetAt
|
|
411
731
|
);
|
|
412
|
-
if (resetResult.wasReset) {
|
|
413
|
-
const balanceChange = resetResult.credits.balance -
|
|
732
|
+
if (resetResult.wasReset && !resetResult.journaled) {
|
|
733
|
+
const balanceChange = sumAmounts(resetResult.credits.balance, -data.balance);
|
|
414
734
|
if (balanceChange !== 0) {
|
|
415
735
|
await this.repository.createJournalEntry({
|
|
416
736
|
userId,
|
|
417
737
|
entryType: balanceChange > 0 ? "credit" : "debit",
|
|
418
738
|
amount: Math.abs(balanceChange),
|
|
419
|
-
balanceAfter:
|
|
739
|
+
balanceAfter: sumAmounts(
|
|
740
|
+
resetResult.credits.balance,
|
|
741
|
+
resetResult.credits.bonusCredits
|
|
742
|
+
),
|
|
420
743
|
source: "monthly_reset",
|
|
421
744
|
referenceId: `reset-${Date.now()}`,
|
|
422
745
|
referenceType: "reset",
|
|
@@ -467,14 +790,14 @@ var CreditsService = class {
|
|
|
467
790
|
*/
|
|
468
791
|
async checkCredits(userId, requiredCredits) {
|
|
469
792
|
const credits = await this.getOrCreateUserCredits(userId);
|
|
470
|
-
const totalBalance = credits.balance
|
|
471
|
-
const available = totalBalance -
|
|
793
|
+
const totalBalance = sumAmounts(credits.balance, credits.bonusCredits);
|
|
794
|
+
const available = sumAmounts(totalBalance, -credits.reserved);
|
|
472
795
|
const hasCredits = available >= requiredCredits;
|
|
473
796
|
return {
|
|
474
797
|
hasCredits,
|
|
475
798
|
balance: totalBalance,
|
|
476
799
|
required: requiredCredits,
|
|
477
|
-
shortfall: hasCredits ? 0 : requiredCredits -
|
|
800
|
+
shortfall: hasCredits ? 0 : sumAmounts(requiredCredits, -available)
|
|
478
801
|
};
|
|
479
802
|
}
|
|
480
803
|
/**
|
|
@@ -488,74 +811,110 @@ var CreditsService = class {
|
|
|
488
811
|
* @throws Error if insufficient credits
|
|
489
812
|
*/
|
|
490
813
|
async reserveCredits(userId, amount, operationType, options) {
|
|
814
|
+
const outcome = await this.reserveCreditsDetailed(userId, amount, operationType, options);
|
|
815
|
+
if (outcome.outcome === "created" || outcome.outcome === "replayed") {
|
|
816
|
+
return outcome.reservation;
|
|
817
|
+
}
|
|
818
|
+
if (outcome.outcome === "insufficient") {
|
|
819
|
+
throw createInsufficientCreditsError(outcome.required, outcome.available);
|
|
820
|
+
}
|
|
821
|
+
throw createIdempotencyConflictError(outcome.idempotencyKey, {
|
|
822
|
+
userId,
|
|
823
|
+
requested: { amount, operationType },
|
|
824
|
+
existing: {
|
|
825
|
+
amount: outcome.existing.amount,
|
|
826
|
+
operationType: outcome.existing.operationType
|
|
827
|
+
}
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Reserve credits and get the typed outcome instead of an exception.
|
|
832
|
+
*
|
|
833
|
+
* Prefer this over {@link reserveCredits} in async callers: it distinguishes
|
|
834
|
+
* a fresh hold from an idempotent replay, and reports insufficient funds as
|
|
835
|
+
* a value rather than as control flow.
|
|
836
|
+
*/
|
|
837
|
+
async reserveCreditsDetailed(userId, amount, operationType, options) {
|
|
491
838
|
const ttlMs = options?.ttlMs ?? getConfig().reservationExpiryMs;
|
|
492
839
|
const expiresAt = new Date(Date.now() + ttlMs);
|
|
493
|
-
return this.repository
|
|
840
|
+
return reserveThroughRepository(this.repository, {
|
|
841
|
+
userId,
|
|
842
|
+
amount,
|
|
843
|
+
operationType,
|
|
844
|
+
expiresAt,
|
|
845
|
+
idempotencyKey: options?.idempotencyKey
|
|
846
|
+
});
|
|
494
847
|
}
|
|
495
848
|
/**
|
|
496
|
-
* Commit a reservation (phase 2 of two-phase commit - success)
|
|
497
|
-
*
|
|
498
|
-
*
|
|
849
|
+
* Commit a reservation (phase 2 of two-phase commit - success).
|
|
850
|
+
*
|
|
851
|
+
* Idempotent: re-delivering a commit for an already-committed reservation is
|
|
852
|
+
* a no-op. Committing one that was released or expired throws, because the
|
|
853
|
+
* credits are no longer held and pretending otherwise would hide a real bug.
|
|
499
854
|
*/
|
|
500
|
-
async commitCredits(userId, reservationId) {
|
|
501
|
-
const
|
|
502
|
-
if (
|
|
503
|
-
throw
|
|
855
|
+
async commitCredits(userId, reservationId, options) {
|
|
856
|
+
const outcome = await this.commitCreditsDetailed(userId, reservationId, options);
|
|
857
|
+
if (outcome.outcome === "not_found") {
|
|
858
|
+
throw createReservationNotFoundError(reservationId);
|
|
504
859
|
}
|
|
505
|
-
if (
|
|
506
|
-
|
|
860
|
+
if (outcome.outcome === "already_terminal" && outcome.terminalStatus !== "committed") {
|
|
861
|
+
throw createReservationAlreadyProcessedError(reservationId, outcome.terminalStatus);
|
|
507
862
|
}
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Commit a reservation and get the typed outcome.
|
|
866
|
+
*
|
|
867
|
+
* Exactly one concurrent caller sees `committed`; that call moved the balance
|
|
868
|
+
* and wrote the single journal entry. On a V2 repository the journal is
|
|
869
|
+
* written inside the same transaction, so this method adds none of its own —
|
|
870
|
+
* the duplicate entry the previous implementation wrote is gone.
|
|
871
|
+
*
|
|
872
|
+
* The low-balance notification fires only for the winner, and only after the
|
|
873
|
+
* transaction has committed, so no callback runs inside a database
|
|
874
|
+
* transaction.
|
|
875
|
+
*/
|
|
876
|
+
async commitCreditsDetailed(userId, reservationId, options) {
|
|
877
|
+
const outcome = await commitThroughRepository(
|
|
878
|
+
this.repository,
|
|
879
|
+
userId,
|
|
880
|
+
reservationId,
|
|
881
|
+
options
|
|
882
|
+
);
|
|
883
|
+
if (outcome.outcome === "committed" && this.lowBalanceCallback) {
|
|
884
|
+
this.lowBalanceCallback(userId, outcome.balanceAfter).catch((error) => {
|
|
885
|
+
console.error("[Credits] Failed to send low balance notification:", error);
|
|
523
886
|
});
|
|
524
|
-
if (this.lowBalanceCallback) {
|
|
525
|
-
this.lowBalanceCallback(userId, credits.balance).catch((error) => {
|
|
526
|
-
console.error("[Credits] Failed to send low balance notification:", error);
|
|
527
|
-
});
|
|
528
|
-
}
|
|
529
887
|
}
|
|
888
|
+
return outcome;
|
|
530
889
|
}
|
|
531
890
|
/**
|
|
532
|
-
* Release a reservation (phase 2 of two-phase commit - failure)
|
|
533
|
-
*
|
|
891
|
+
* Release a reservation (phase 2 of two-phase commit - failure).
|
|
892
|
+
*
|
|
893
|
+
* Throws `RESERVATION_NOT_FOUND` for an unknown reservation, matching the
|
|
894
|
+
* pre-V2 behaviour — a release naming a reservation that does not exist is a
|
|
895
|
+
* caller bug, and swallowing it hides the bug while the credits stay held.
|
|
896
|
+
*
|
|
897
|
+
* Releasing one that is already terminal — `released`, `expired`, or
|
|
898
|
+
* `committed` — is a no-op, which is the behaviour this method has always
|
|
899
|
+
* had. A release that loses a race to a concurrent commit is the common
|
|
900
|
+
* case in a retry-heavy caller, and callers written against the pre-V2
|
|
901
|
+
* contract handle it by not handling it.
|
|
902
|
+
*
|
|
903
|
+
* That does mean this method cannot tell you that the credits were spent
|
|
904
|
+
* rather than returned. Use {@link releaseCreditsDetailed}, which reports
|
|
905
|
+
* `already_terminal` with `terminalStatus: 'committed'`, when you need to
|
|
906
|
+
* branch on it.
|
|
534
907
|
*/
|
|
535
|
-
async releaseCredits(userId, reservationId) {
|
|
536
|
-
const
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
const credits = await this.repository.getUserCredits(userId);
|
|
540
|
-
if (credits) {
|
|
541
|
-
await this.repository.createJournalEntry({
|
|
542
|
-
userId,
|
|
543
|
-
entryType: "credit",
|
|
544
|
-
amount: 0,
|
|
545
|
-
// No actual credits returned (they were reserved, not spent)
|
|
546
|
-
balanceAfter: credits.balance,
|
|
547
|
-
source: "operation_release",
|
|
548
|
-
referenceId: reservationId,
|
|
549
|
-
referenceType: "reservation",
|
|
550
|
-
description: `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,
|
|
551
|
-
metadata: {
|
|
552
|
-
operationType: reservation.operationType,
|
|
553
|
-
amount: reservation.amount
|
|
554
|
-
}
|
|
555
|
-
});
|
|
556
|
-
}
|
|
908
|
+
async releaseCredits(userId, reservationId, options) {
|
|
909
|
+
const outcome = await this.releaseCreditsDetailed(userId, reservationId, options);
|
|
910
|
+
if (outcome.outcome === "not_found") {
|
|
911
|
+
throw createReservationNotFoundError(reservationId);
|
|
557
912
|
}
|
|
558
913
|
}
|
|
914
|
+
/** Release a reservation and get the typed outcome. */
|
|
915
|
+
async releaseCreditsDetailed(userId, reservationId, options) {
|
|
916
|
+
return releaseThroughRepository(this.repository, userId, reservationId, options);
|
|
917
|
+
}
|
|
559
918
|
/**
|
|
560
919
|
* Log usage for audit trail
|
|
561
920
|
* @param log - Usage log data
|
|
@@ -571,9 +930,20 @@ var CreditsService = class {
|
|
|
571
930
|
* @param paymentRef - Optional payment reference
|
|
572
931
|
* @param options - Optional journal source / reference type / extra metadata
|
|
573
932
|
* for the credit journal entry (e.g. revenue-attribution fields).
|
|
933
|
+
* @returns Whether this delivery credited the account (`created`), repeated an
|
|
934
|
+
* earlier one (`replayed`), or reused the reference for a different credit
|
|
935
|
+
* event (`conflict`, which credited nothing). On a repository without
|
|
936
|
+
* `addCreditsV2` the result is always `created` and carries no
|
|
937
|
+
* deduplication guarantee — see {@link addCreditsThroughRepository}.
|
|
574
938
|
*/
|
|
575
939
|
async addCredits(userId, amount, description, paymentRef, options) {
|
|
576
|
-
return this.repository
|
|
940
|
+
return addCreditsThroughRepository(this.repository, {
|
|
941
|
+
userId,
|
|
942
|
+
amount,
|
|
943
|
+
description,
|
|
944
|
+
paymentRef,
|
|
945
|
+
options
|
|
946
|
+
});
|
|
577
947
|
}
|
|
578
948
|
/**
|
|
579
949
|
* One-shot atomic "deduct-if-sufficient" credit charge.
|
|
@@ -597,15 +967,14 @@ var CreditsService = class {
|
|
|
597
967
|
* @throws Error if amount is not a positive number
|
|
598
968
|
*/
|
|
599
969
|
async deductCredits(userId, amount, options) {
|
|
600
|
-
|
|
601
|
-
throw new Error(`deductCredits amount must be positive (got ${amount})`);
|
|
602
|
-
}
|
|
970
|
+
assertValidCreditAmount(amount, { userId, operation: "deductCredits" });
|
|
603
971
|
let deduction;
|
|
604
972
|
try {
|
|
605
973
|
deduction = await this.repository.deductCreditsAtomic(userId, amount);
|
|
606
974
|
} catch (error) {
|
|
975
|
+
if (isCreditError(error) && error.code === CreditErrorCode.INVALID_AMOUNT) throw error;
|
|
607
976
|
const credits = await this.repository.getUserCredits(userId);
|
|
608
|
-
const available = credits ? credits.balance
|
|
977
|
+
const available = credits ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved) : 0;
|
|
609
978
|
if (available >= amount) {
|
|
610
979
|
throw error;
|
|
611
980
|
}
|
|
@@ -614,7 +983,7 @@ var CreditsService = class {
|
|
|
614
983
|
reason: "insufficient",
|
|
615
984
|
available,
|
|
616
985
|
required: amount,
|
|
617
|
-
shortfall: amount -
|
|
986
|
+
shortfall: sumAmounts(amount, -available)
|
|
618
987
|
};
|
|
619
988
|
}
|
|
620
989
|
const operationType = options?.operationType;
|
|
@@ -628,8 +997,8 @@ var CreditsService = class {
|
|
|
628
997
|
referenceType: "adjustment",
|
|
629
998
|
description: operationType ? `Deducted ${amount} credits for ${getOperationLabel(operationType)}` : `Deducted ${amount} credits`,
|
|
630
999
|
metadata: {
|
|
631
|
-
...
|
|
632
|
-
...
|
|
1000
|
+
...options?.metadata,
|
|
1001
|
+
...operationType && { operationType }
|
|
633
1002
|
}
|
|
634
1003
|
});
|
|
635
1004
|
if (operationType) {
|
|
@@ -664,8 +1033,15 @@ var CreditsService = class {
|
|
|
664
1033
|
const free = isFreeTier(tier);
|
|
665
1034
|
await this.repository.updateUserTier(userId, {
|
|
666
1035
|
tier,
|
|
667
|
-
//
|
|
668
|
-
|
|
1036
|
+
// Through the shared contract, like every path that resolves the tier's
|
|
1037
|
+
// limit from configuration. (The repository's `updateUserCredits` and
|
|
1038
|
+
// `updateUserTier` still store a caller-supplied `monthlyLimit` verbatim;
|
|
1039
|
+
// they are given a value, not a tier, so there is no sentinel to map.)
|
|
1040
|
+
// This used to store 0 for an unlimited tier under a "0 means unlimited"
|
|
1041
|
+
// convention that nothing actually implemented — no read path anywhere in
|
|
1042
|
+
// the library branches on it — so upgrading a user to unlimited gave them
|
|
1043
|
+
// an allowance of zero.
|
|
1044
|
+
monthlyLimit: storedMonthlyLimit(monthlyLimit),
|
|
669
1045
|
// Reset balance to new tier limit if upgrading
|
|
670
1046
|
balance: !free ? unlimited ? getUnlimitedSentinelBalance() : monthlyLimit : void 0,
|
|
671
1047
|
monthlyUsed: !free ? 0 : void 0,
|