@classytic/loyalty 0.5.0 → 0.7.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/CHANGELOG.md +367 -231
- package/LICENSE +75 -21
- package/README.md +2 -2
- package/dist/{config-Dtun1duw.d.mts → config-CtkGj3xZ.d.mts} +41 -22
- package/dist/{constants-DkQYkOK1.mjs → constants-DOPBh6kt.mjs} +1 -3
- package/dist/domain/enums/index.d.mts +1 -1
- package/dist/domain/enums/index.mjs +1 -1
- package/dist/events/index.d.mts +2 -2
- package/dist/events/index.mjs +2 -2
- package/dist/{events-DN5_p6T0.mjs → events-BLjg3uLA.mjs} +22 -31
- package/dist/{index-Dngaj21_.d.mts → index-BIPHUsfR.d.mts} +92 -14
- package/dist/index-BIhVuwIZ.d.mts +692 -0
- package/dist/{index-YSsi4e_G.d.mts → index-Cp_sXNpG.d.mts} +35 -4
- package/dist/{index-D_5Ojc2c.d.mts → index-YUFamhDk.d.mts} +7 -17
- package/dist/index.d.mts +60 -29
- package/dist/index.mjs +103 -52
- package/dist/models/index.d.mts +3 -1273
- package/dist/models/index.mjs +2 -2
- package/dist/{models-Ddh62lgO.mjs → models-weWqS5Bc.mjs} +152 -70
- package/dist/notifications/index.d.mts +1 -2
- package/dist/repositories/index.d.mts +1 -1
- package/dist/repositories/index.mjs +1 -1
- package/dist/{repositories-CjWfUlrA.mjs → repositories-DErtHQou.mjs} +198 -69
- package/dist/types/index.d.mts +3 -3
- package/package.json +119 -116
- /package/dist/{index-DMK8a98J.d.mts → index-D_Oe3aDk.d.mts} +0 -0
- /package/dist/{loyalty-events-C38JA3cU.mjs → loyalty-events-DXirolM_.mjs} +0 -0
- /package/dist/{notification.port-CJ9nXj0k.d.mts → notification.port-wY4IKimz.d.mts} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as createEvent, t as LoyaltyEvents } from "./loyalty-events-
|
|
1
|
+
import { n as createEvent, t as LoyaltyEvents } from "./loyalty-events-DXirolM_.mjs";
|
|
2
2
|
import { Repository, appendOnlyPlugin, multiTenantPlugin } from "@classytic/mongokit";
|
|
3
3
|
import { localTimeParts } from "@classytic/primitives/timezone";
|
|
4
4
|
import { addDays, isoWeekday } from "@classytic/primitives/calendar";
|
|
@@ -152,6 +152,27 @@ var UnmanagedSessionError = class extends LoyaltyError {
|
|
|
152
152
|
}
|
|
153
153
|
};
|
|
154
154
|
/**
|
|
155
|
+
* A host passed `ctx.session`, but that session has no ACTIVE transaction.
|
|
156
|
+
*
|
|
157
|
+
* A bare `startSession()` provides NO atomicity — every write inside it
|
|
158
|
+
* commits independently. Accepting it as proof of a unit of work is the
|
|
159
|
+
* silent-permissiveness failure in its purest form: loyalty then saves the
|
|
160
|
+
* outbox row "in-session" and applies the balance `$inc` "in-session", and
|
|
161
|
+
* if the outbox save fails the balance mutation still stands with no ledger
|
|
162
|
+
* row behind it. Nothing throws; the points are simply wrong.
|
|
163
|
+
*
|
|
164
|
+
* `session.inTransaction()` is the driver's own answer, so this check cannot
|
|
165
|
+
* drift from what MongoDB actually thinks. `@classytic/access` refuses
|
|
166
|
+
* exactly this at `entitlement.repository.ts` — same rule, same reason.
|
|
167
|
+
*/
|
|
168
|
+
var SessionNotInTransactionError = class extends LoyaltyError {
|
|
169
|
+
code = "loyalty.transaction.session_not_in_transaction";
|
|
170
|
+
status = 409;
|
|
171
|
+
constructor() {
|
|
172
|
+
super("[loyalty] ctx.session was supplied but has no ACTIVE transaction — a bare session provides no atomicity (each write commits independently), so a failing outbox.save would leave the points mutation standing with the event lost. Drive it with session.withTransaction(...) / startTransaction(), or omit ctx.session and let loyalty open its own transaction.");
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
155
176
|
* The backend doesn't declare the runtime capabilities loyalty's
|
|
156
177
|
* transactional verbs require (earn / adjust / reserve / confirm / release /
|
|
157
178
|
* reverse all run inside `withTransaction`). MongoDB must run as a replica set
|
|
@@ -161,8 +182,18 @@ var UnmanagedSessionError = class extends LoyaltyError {
|
|
|
161
182
|
var LoyaltyCapabilityError = class extends LoyaltyError {
|
|
162
183
|
code = "loyalty.engine.missing_capabilities";
|
|
163
184
|
status = 500;
|
|
164
|
-
|
|
165
|
-
|
|
185
|
+
/**
|
|
186
|
+
* `true` when the backend never ANSWERED (bound before the connection
|
|
187
|
+
* opened, a driver exposing no topology) rather than answering "no". Both
|
|
188
|
+
* refuse — an unobserved outcome is never a positive one (AGENTS.md FAIL
|
|
189
|
+
* LOUD rule 3) — but the operator's fix differs, so the message must.
|
|
190
|
+
*/
|
|
191
|
+
indeterminate;
|
|
192
|
+
constructor(missing, opts = {}) {
|
|
193
|
+
const indeterminate = opts.indeterminate === true;
|
|
194
|
+
const backendMissing = missing.filter((flag) => !flag.startsWith("outbox."));
|
|
195
|
+
super(indeterminate ? `[loyalty] could NOT determine whether the backend supports: ${missing.join(", ")}. An unconfirmed answer is treated as unsupported — point earn / redemption / reversal paths are transactional. Bind AFTER \`await mongoose.connect(...)\`, or call \`await probeMongoCapabilities(connection)\` first, or set \`allowNonTransactional: true\`.` : `[loyalty] missing required capabilities: ${missing.join(", ")}.` + (backendMissing.length > 0 ? " Point earn / redemption / reversal paths are transactional — MongoDB must run as a replica set or sharded cluster, or set `allowNonTransactional: true`." : ""));
|
|
196
|
+
this.indeterminate = indeterminate;
|
|
166
197
|
}
|
|
167
198
|
};
|
|
168
199
|
//#endregion
|
|
@@ -234,8 +265,9 @@ function validatePositivePoints(points, label = "points") {
|
|
|
234
265
|
validatePoints(points, label);
|
|
235
266
|
if (points <= 0) throw new ValidationError(`${label} must be positive`);
|
|
236
267
|
}
|
|
268
|
+
/** `orderTotal` is an integer in the host's minor currency unit (paisa for BDT). */
|
|
237
269
|
function validateOrderTotal(total) {
|
|
238
|
-
if (!Number.
|
|
270
|
+
if (!Number.isSafeInteger(total) || total < 0) throw new ValidationError("orderTotal must be a non-negative safe integer (minor units)");
|
|
239
271
|
}
|
|
240
272
|
//#endregion
|
|
241
273
|
//#region src/repositories/earning-rule.repository.ts
|
|
@@ -251,7 +283,7 @@ var EarningRuleRepository = class extends Repository {
|
|
|
251
283
|
injectTenantIntoData(data, options, this.config.tenant);
|
|
252
284
|
}
|
|
253
285
|
/**
|
|
254
|
-
* Auto-injects `programId` from `
|
|
286
|
+
* Auto-injects `programId` from `LoyaltyShape.program.id` and the tenant id
|
|
255
287
|
* from repo options when omitted. This keeps custom-program engines aligned
|
|
256
288
|
* with `MemberRepository.enroll(...)`, which uses the same config default.
|
|
257
289
|
*/
|
|
@@ -264,6 +296,14 @@ var EarningRuleRepository = class extends Repository {
|
|
|
264
296
|
for (const doc of docs) this.applyCreateDefaults(doc, opts);
|
|
265
297
|
return super.createMany(docs, options);
|
|
266
298
|
}
|
|
299
|
+
/**
|
|
300
|
+
* Evaluates every active order/category/tier_bonus rule against an order.
|
|
301
|
+
*
|
|
302
|
+
* `orderTotal` and `items[].amount` are **integers in the host's minor
|
|
303
|
+
* currency unit** (paisa for BDT) — `50000` = ৳500. Rates on the rule
|
|
304
|
+
* (`amountPerPoint`, `pointsPerAmount` + `rateBasis`) are quoted in the
|
|
305
|
+
* same minor units.
|
|
306
|
+
*/
|
|
267
307
|
async evaluateOrder(input, ctx) {
|
|
268
308
|
validateOrderTotal(input.orderTotal);
|
|
269
309
|
assertTenantContext(ctx, this.config.tenant);
|
|
@@ -394,18 +434,34 @@ var EarningRuleRepository = class extends Repository {
|
|
|
394
434
|
weekday(instant) {
|
|
395
435
|
return (this.config.timezone ? localTimeParts(instant, this.config.timezone).isoWeekday : isoWeekday(instant)) % 7;
|
|
396
436
|
}
|
|
437
|
+
/**
|
|
438
|
+
* `orderTotal` is integer minor units. Two rate shapes:
|
|
439
|
+
* - `pointsPerAmount` + `rateBasis`: `points = pointsPerAmount × (orderTotal / rateBasis)`
|
|
440
|
+
* - `amountPerPoint` (minor units per point): `points = orderTotal / amountPerPoint`
|
|
441
|
+
* Rounding is applied ONCE at the end, per the rule's `roundingMode`.
|
|
442
|
+
*/
|
|
397
443
|
calculateOrderPoints(rule, orderTotal) {
|
|
398
444
|
const { reward } = rule;
|
|
399
445
|
let points = 0;
|
|
400
|
-
if (reward.pointsPerAmount) points =
|
|
446
|
+
if (reward.pointsPerAmount) points = reward.pointsPerAmount * (orderTotal / this.requireRateBasis(rule));
|
|
401
447
|
else if (reward.amountPerPoint && reward.amountPerPoint > 0) points = orderTotal / reward.amountPerPoint;
|
|
402
448
|
return this.applyRounding(points, reward.roundingMode);
|
|
403
449
|
}
|
|
450
|
+
/**
|
|
451
|
+
* `pointsPerAmount` has NO implicit basis — a rule that carries it without
|
|
452
|
+
* an explicit integer minor-unit `rateBasis` is malformed (the schema
|
|
453
|
+
* enforces the pairing on write; this guards legacy/hand-written docs).
|
|
454
|
+
*/
|
|
455
|
+
requireRateBasis(rule) {
|
|
456
|
+
const rateBasis = rule.reward.rateBasis;
|
|
457
|
+
if (typeof rateBasis !== "number" || !Number.isInteger(rateBasis) || rateBasis < 1) throw new ValidationError(`Earning rule '${rule.name}' (${rule._id}) sets reward.pointsPerAmount without a valid integer reward.rateBasis (minor units) — points = pointsPerAmount × (orderTotal / rateBasis)`);
|
|
458
|
+
return rateBasis;
|
|
459
|
+
}
|
|
404
460
|
calculateCategoryPoints(rule, items) {
|
|
405
461
|
const { conditions, reward } = rule;
|
|
406
462
|
let points = 0;
|
|
407
463
|
for (const item of items) if (conditions.categories && item.categoryId && conditions.categories.includes(item.categoryId)) {
|
|
408
|
-
if (reward.pointsPerAmount) points += item.amount
|
|
464
|
+
if (reward.pointsPerAmount) points += reward.pointsPerAmount * (item.amount / this.requireRateBasis(rule));
|
|
409
465
|
else if (reward.amountPerPoint) points += item.amount / reward.amountPerPoint;
|
|
410
466
|
}
|
|
411
467
|
return this.applyRounding(points, reward.roundingMode);
|
|
@@ -428,7 +484,35 @@ var EarningRuleRepository = class extends Repository {
|
|
|
428
484
|
* host-supplied context fields and never appears in the public type.
|
|
429
485
|
*/
|
|
430
486
|
const PENDING_EVENTS = Symbol.for("@classytic/loyalty:pendingEvents");
|
|
487
|
+
/**
|
|
488
|
+
* Set when the unit of work was PERMITTED to run without a transaction
|
|
489
|
+
* (`allowNonTransactional`), so the session-in-transaction guard knows the
|
|
490
|
+
* degradation was chosen rather than stumbled into.
|
|
491
|
+
*
|
|
492
|
+
* Carried on the context because the guard also runs from
|
|
493
|
+
* `dispatchLoyaltyEvent`, which never sees the unit of work. Internal and
|
|
494
|
+
* `Symbol.for`, so no host can set it by accident or on purpose.
|
|
495
|
+
*/
|
|
496
|
+
const NON_TRANSACTIONAL_CONSENTED = Symbol.for("@classytic/loyalty:nonTransactionalConsented");
|
|
497
|
+
/**
|
|
498
|
+
* A caller-supplied `ctx.session` is only evidence of a unit of work if it
|
|
499
|
+
* has an ACTIVE transaction. A bare `startSession()` commits every write
|
|
500
|
+
* independently, so treating it as atomic is how a balance `$inc` lands with
|
|
501
|
+
* no ledger row behind it when the outbox save fails — silently, because the
|
|
502
|
+
* business write already succeeded.
|
|
503
|
+
*
|
|
504
|
+
* `inTransaction()` is the driver's own answer, so this cannot drift from
|
|
505
|
+
* what Mongo actually thinks. Same guard, same rationale as
|
|
506
|
+
* `@classytic/access`'s `atomically()`.
|
|
507
|
+
*/
|
|
508
|
+
function assertSessionInTransaction(ctx) {
|
|
509
|
+
if (!ctx.session) return;
|
|
510
|
+
if (ctx[NON_TRANSACTIONAL_CONSENTED]) return;
|
|
511
|
+
const session = ctx.session;
|
|
512
|
+
if (typeof session.inTransaction !== "function" || !session.inTransaction()) throw new SessionNotInTransactionError();
|
|
513
|
+
}
|
|
431
514
|
async function dispatchLoyaltyEvent(deps, event, ctx) {
|
|
515
|
+
assertSessionInTransaction(ctx);
|
|
432
516
|
const pending = ctx[PENDING_EVENTS];
|
|
433
517
|
if (deps.outbox) try {
|
|
434
518
|
const saveOptions = {};
|
|
@@ -469,15 +553,21 @@ async function dispatchLoyaltyEvent(deps, event, ctx) {
|
|
|
469
553
|
*/
|
|
470
554
|
async function runLoyaltyUnit(unitOfWork, deps, ctx, body) {
|
|
471
555
|
const internalCtx = ctx;
|
|
472
|
-
if (ctx.session)
|
|
556
|
+
if (ctx.session) {
|
|
557
|
+
assertSessionInTransaction(ctx);
|
|
558
|
+
return body(internalCtx);
|
|
559
|
+
}
|
|
473
560
|
const pending = [];
|
|
474
561
|
const result = await unitOfWork.withTransaction(async (session) => {
|
|
475
562
|
pending.length = 0;
|
|
476
|
-
|
|
563
|
+
const innerCtx = {
|
|
477
564
|
...internalCtx,
|
|
478
565
|
session,
|
|
479
|
-
[PENDING_EVENTS]: pending
|
|
480
|
-
|
|
566
|
+
[PENDING_EVENTS]: pending,
|
|
567
|
+
...unitOfWork.allowsNonTransactional ? { [NON_TRANSACTIONAL_CONSENTED]: true } : {}
|
|
568
|
+
};
|
|
569
|
+
assertSessionInTransaction(innerCtx);
|
|
570
|
+
return body(innerCtx);
|
|
481
571
|
});
|
|
482
572
|
await flushPendingLoyaltyEvents(deps.events, pending, deps.logger);
|
|
483
573
|
return result;
|
|
@@ -984,43 +1074,56 @@ var PointTransactionRepository = class extends Repository {
|
|
|
984
1074
|
const affectedMemberIds = /* @__PURE__ */ new Set();
|
|
985
1075
|
for (const tx of expiredTxs) {
|
|
986
1076
|
throwIfAborted(ctx.signal);
|
|
987
|
-
await this.unitOfWork.withTransaction(async (session) => {
|
|
988
|
-
await this.
|
|
989
|
-
memberId: tx.memberId,
|
|
990
|
-
programId: tx.programId,
|
|
991
|
-
type: "expire",
|
|
992
|
-
points: -tx.points,
|
|
993
|
-
balanceAfter: 0,
|
|
994
|
-
description: `Points expired from transaction ${tx._id}`,
|
|
995
|
-
referenceType: "expiration",
|
|
996
|
-
referenceId: tx._id,
|
|
997
|
-
actorId: ctx.actorId
|
|
998
|
-
}, {
|
|
1077
|
+
const expiredAmount = await this.unitOfWork.withTransaction(async (session) => {
|
|
1078
|
+
const member = await this.memberRepo.requireMember(tx.memberId, {
|
|
999
1079
|
session,
|
|
1000
1080
|
...tc
|
|
1001
1081
|
});
|
|
1082
|
+
const available = Math.max(0, member.balance.current);
|
|
1083
|
+
const amount = Math.min(tx.points, available);
|
|
1002
1084
|
await this.update(tx._id, { expiredAt: now }, {
|
|
1003
1085
|
session,
|
|
1004
1086
|
...tc,
|
|
1005
1087
|
bypassAppendOnly: true
|
|
1006
1088
|
});
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1089
|
+
if (amount <= 0) return 0;
|
|
1090
|
+
const updatedMember = await this.memberRepo.updateBalance(tx.memberId, {
|
|
1091
|
+
current: -amount,
|
|
1092
|
+
expired: amount
|
|
1010
1093
|
}, {
|
|
1011
1094
|
session,
|
|
1012
1095
|
...tc
|
|
1013
1096
|
});
|
|
1097
|
+
if (updatedMember.balance.current < 0) throw new InsufficientPointsError(updatedMember.balance.current + amount, amount);
|
|
1098
|
+
await this.create({
|
|
1099
|
+
memberId: tx.memberId,
|
|
1100
|
+
programId: tx.programId,
|
|
1101
|
+
type: "expire",
|
|
1102
|
+
points: -amount,
|
|
1103
|
+
balanceAfter: updatedMember.balance.current,
|
|
1104
|
+
description: `Points expired from transaction ${tx._id}`,
|
|
1105
|
+
referenceType: "expiration",
|
|
1106
|
+
referenceId: tx._id,
|
|
1107
|
+
actorId: ctx.actorId
|
|
1108
|
+
}, {
|
|
1109
|
+
session,
|
|
1110
|
+
...tc
|
|
1111
|
+
});
|
|
1112
|
+
return amount;
|
|
1014
1113
|
});
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1114
|
+
if (expiredAmount > 0) {
|
|
1115
|
+
affectedMemberIds.add(tx.memberId);
|
|
1116
|
+
totalExpired += expiredAmount;
|
|
1117
|
+
transactionCount++;
|
|
1118
|
+
}
|
|
1018
1119
|
}
|
|
1019
|
-
if (totalExpired > 0) await this.
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1120
|
+
if (totalExpired > 0) await runLoyaltyUnit(this.unitOfWork, this._dispatchDeps, ctx, async (txCtx) => {
|
|
1121
|
+
await this._dispatch(createEvent(LoyaltyEvents.POINTS_EXPIRED, {
|
|
1122
|
+
membersAffected: affectedMemberIds.size,
|
|
1123
|
+
pointsExpired: totalExpired,
|
|
1124
|
+
transactionCount
|
|
1125
|
+
}, txCtx), txCtx);
|
|
1126
|
+
});
|
|
1024
1127
|
return {
|
|
1025
1128
|
membersAffected: affectedMemberIds.size,
|
|
1026
1129
|
pointsExpired: totalExpired,
|
|
@@ -1091,20 +1194,36 @@ var RedemptionRepository = class extends Repository {
|
|
|
1091
1194
|
}
|
|
1092
1195
|
/**
|
|
1093
1196
|
* Atomic compare-and-set status transition.
|
|
1094
|
-
*
|
|
1197
|
+
*
|
|
1198
|
+
* `null` means ONE thing and one thing only: the guarded update matched
|
|
1199
|
+
* no document, i.e. the status was not `expectedStatus`. `throwOnNotFound:
|
|
1200
|
+
* false` already produces that `null`, so there is nothing legitimate left
|
|
1201
|
+
* for a `catch` to convert.
|
|
1202
|
+
*
|
|
1203
|
+
* There used to be a bare `} catch { return null; }` here. It laundered
|
|
1204
|
+
* every real failure into a CAS miss, and callers map a CAS miss to
|
|
1205
|
+
* `ValidationError("Redemption status must be 'reserved', got '<status>'")`
|
|
1206
|
+
* — a NON-retryable 4xx built from the status read BEFORE the write. So a
|
|
1207
|
+
* routine Mongo `WriteConflict` (a retryable transient, the normal outcome
|
|
1208
|
+
* of two concurrent confirms) surfaced as a client error whose message
|
|
1209
|
+
* could literally read "must be 'reserved', got 'reserved'": an operator
|
|
1210
|
+
* chasing a contradiction while the actual fix was to retry.
|
|
1211
|
+
*
|
|
1212
|
+
* Anything that throws in here is a real error and must propagate.
|
|
1095
1213
|
*/
|
|
1096
1214
|
async atomicStatusTransition(id, expectedStatus, data, ctx) {
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
});
|
|
1104
|
-
} catch {
|
|
1105
|
-
return null;
|
|
1106
|
-
}
|
|
1215
|
+
return this.update(id, data, {
|
|
1216
|
+
lean: true,
|
|
1217
|
+
query: { status: expectedStatus },
|
|
1218
|
+
throwOnNotFound: false,
|
|
1219
|
+
...ctx
|
|
1220
|
+
});
|
|
1107
1221
|
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Validates a redemption request. `orderTotal` is an **integer in the
|
|
1224
|
+
* host's minor currency unit** (paisa for BDT); the returned
|
|
1225
|
+
* `discountAmount` is in the same minor units.
|
|
1226
|
+
*/
|
|
1108
1227
|
async validate(input, ctx) {
|
|
1109
1228
|
validatePositivePoints(input.pointsToRedeem, "pointsToRedeem");
|
|
1110
1229
|
validateOrderTotal(input.orderTotal);
|
|
@@ -1113,7 +1232,7 @@ var RedemptionRepository = class extends Repository {
|
|
|
1113
1232
|
const tc = tenantCtx(this.config.tenant, tenantId);
|
|
1114
1233
|
const member = await this.memberRepo.requireActiveMember(input.memberId, tc);
|
|
1115
1234
|
const { minPoints, minOrderAmount, maxRedeemPercent } = this.config.redemption;
|
|
1116
|
-
const {
|
|
1235
|
+
const { pointValueMinor } = this.config;
|
|
1117
1236
|
if (input.pointsToRedeem < minPoints) return {
|
|
1118
1237
|
valid: false,
|
|
1119
1238
|
error: `Minimum ${minPoints} points required`,
|
|
@@ -1135,17 +1254,24 @@ var RedemptionRepository = class extends Repository {
|
|
|
1135
1254
|
discountAmount: 0,
|
|
1136
1255
|
maxAllowedPoints: member.balance.current
|
|
1137
1256
|
};
|
|
1138
|
-
const
|
|
1139
|
-
const
|
|
1140
|
-
const
|
|
1141
|
-
const maxAllowedPoints = Math.floor(
|
|
1257
|
+
const maxDiscountMinor = Math.floor(input.orderTotal * maxRedeemPercent / 100);
|
|
1258
|
+
const requestedDiscountMinor = input.pointsToRedeem * pointValueMinor;
|
|
1259
|
+
const cappedDiscountMinor = Math.min(requestedDiscountMinor, maxDiscountMinor);
|
|
1260
|
+
const maxAllowedPoints = Math.floor(maxDiscountMinor / pointValueMinor);
|
|
1261
|
+
const actualPoints = cappedDiscountMinor < requestedDiscountMinor ? Math.floor(cappedDiscountMinor / pointValueMinor) : input.pointsToRedeem;
|
|
1142
1262
|
return {
|
|
1143
1263
|
valid: true,
|
|
1144
|
-
pointsToRedeem:
|
|
1145
|
-
discountAmount,
|
|
1264
|
+
pointsToRedeem: actualPoints,
|
|
1265
|
+
discountAmount: actualPoints * pointValueMinor,
|
|
1146
1266
|
maxAllowedPoints
|
|
1147
1267
|
};
|
|
1148
1268
|
}
|
|
1269
|
+
/**
|
|
1270
|
+
* Reserves points against an order. `orderTotal` is an **integer in the
|
|
1271
|
+
* host's minor currency unit** (paisa for BDT). The persisted
|
|
1272
|
+
* `discountAmount` is minor units and the reserve-time `pointValueMinor`
|
|
1273
|
+
* rate is snapshotted on the doc.
|
|
1274
|
+
*/
|
|
1149
1275
|
async reserve(input, ctx) {
|
|
1150
1276
|
assertTenantContext(ctx, this.config.tenant);
|
|
1151
1277
|
const tenantId = getTenantValue(ctx, this.config.tenant);
|
|
@@ -1172,7 +1298,7 @@ var RedemptionRepository = class extends Repository {
|
|
|
1172
1298
|
pointsReserved: validation.pointsToRedeem,
|
|
1173
1299
|
pointsConfirmed: 0,
|
|
1174
1300
|
discountAmount: validation.discountAmount,
|
|
1175
|
-
|
|
1301
|
+
pointValueMinor: this.config.pointValueMinor,
|
|
1176
1302
|
status: "reserved",
|
|
1177
1303
|
ownerType: input.ownerType,
|
|
1178
1304
|
ownerId: input.ownerId,
|
|
@@ -1482,19 +1608,24 @@ var ReferralRepository = class extends Repository {
|
|
|
1482
1608
|
}
|
|
1483
1609
|
/**
|
|
1484
1610
|
* Atomic compare-and-set status transition.
|
|
1485
|
-
*
|
|
1611
|
+
*
|
|
1612
|
+
* `null` means ONE thing: the guarded update matched no document, i.e.
|
|
1613
|
+
* the status was not `expectedStatus`. `throwOnNotFound: false` already
|
|
1614
|
+
* returns that `null`, so the bare `} catch { return null; }` that used
|
|
1615
|
+
* to sit here could only ever hide REAL errors — most damagingly a
|
|
1616
|
+
* retryable Mongo `WriteConflict`, which callers then re-threw as a
|
|
1617
|
+
* non-retryable `ValidationError` describing a status that had not
|
|
1618
|
+
* actually gone stale.
|
|
1619
|
+
*
|
|
1620
|
+
* Anything that throws in here is a real error and must propagate.
|
|
1486
1621
|
*/
|
|
1487
1622
|
async atomicStatusTransition(id, expectedStatus, data, ctx) {
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
});
|
|
1495
|
-
} catch {
|
|
1496
|
-
return null;
|
|
1497
|
-
}
|
|
1623
|
+
return this.update(id, data, {
|
|
1624
|
+
lean: true,
|
|
1625
|
+
query: { status: expectedStatus },
|
|
1626
|
+
throwOnNotFound: false,
|
|
1627
|
+
...ctx
|
|
1628
|
+
});
|
|
1498
1629
|
}
|
|
1499
1630
|
async generateCode(memberId, ctx) {
|
|
1500
1631
|
assertTenantContext(ctx, this.config.tenant);
|
|
@@ -1694,7 +1825,7 @@ var ReferralRepository = class extends Repository {
|
|
|
1694
1825
|
if (maxDepth > 1 && referrerRewardPoints > 0) {
|
|
1695
1826
|
const awards = [];
|
|
1696
1827
|
let currentId = referrer.referredBy;
|
|
1697
|
-
const visited = new Set([referrer._id, referee._id]);
|
|
1828
|
+
const visited = /* @__PURE__ */ new Set([referrer._id, referee._id]);
|
|
1698
1829
|
for (let depth = 2; depth <= maxDepth && currentId; depth++) {
|
|
1699
1830
|
if (visited.has(currentId)) break;
|
|
1700
1831
|
visited.add(currentId);
|
|
@@ -1829,9 +1960,7 @@ var TierDefinitionRepository = class extends Repository {
|
|
|
1829
1960
|
case "downgraded":
|
|
1830
1961
|
downgraded++;
|
|
1831
1962
|
break;
|
|
1832
|
-
default:
|
|
1833
|
-
unchanged++;
|
|
1834
|
-
break;
|
|
1963
|
+
default: unchanged++;
|
|
1835
1964
|
}
|
|
1836
1965
|
}
|
|
1837
1966
|
return {
|
|
@@ -2095,4 +2224,4 @@ function createRepositories(input) {
|
|
|
2095
2224
|
};
|
|
2096
2225
|
}
|
|
2097
2226
|
//#endregion
|
|
2098
|
-
export {
|
|
2227
|
+
export { SessionNotInTransactionError as C, ValidationError as D, UnmanagedSessionError as E, SelfReferralError as S, TierNotFoundError as T, RedemptionExpiredError as _, PointTransactionRepository as a, ReferralNotFoundError as b, flushPendingLoyaltyEvents as c, DuplicateReferralError as d, InsufficientPointsError as f, MemberNotFoundError as g, MemberInactiveError as h, RedemptionRepository as i, EarningRuleRepository as l, MemberAlreadyEnrolledError as m, TierDefinitionRepository as n, MemberRepository as o, LoyaltyCapabilityError as p, ReferralRepository as r, PENDING_EVENTS as s, createRepositories as t, CircularReferralError as u, RedemptionNotFoundError as v, TenantIsolationError as w, RuleNotFoundError as x, ReferralLimitExceededError as y };
|
package/dist/types/index.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { _ as TierEvaluationBatch, a as EnrollInput, c as UpdateTierInput, d as EarningResult, f as ExpirationResult, g as TierEvaluation, h as RedemptionValidation, i as EarnPointsInput, l as BalanceSummary, m as PaginatedResult, n as CreateEarningRuleInput, o as LoyaltyContext, p as ListQuery, r as CreateTierInput, s as UpdateEarningRuleInput, t as AdjustPointsInput, u as EarningBreakdown } from "../index-
|
|
2
|
-
import { a as
|
|
3
|
-
export { AdjustPointsInput, BalanceSummary, CreateEarningRuleInput, CreateTierInput, EarnPointsInput, EarningBreakdown, EarningResult, EnrollInput, ExpirationResult, IndexDefinition, ListQuery,
|
|
1
|
+
import { _ as TierEvaluationBatch, a as EnrollInput, c as UpdateTierInput, d as EarningResult, f as ExpirationResult, g as TierEvaluation, h as RedemptionValidation, i as EarnPointsInput, l as BalanceSummary, m as PaginatedResult, n as CreateEarningRuleInput, o as LoyaltyContext, p as ListQuery, r as CreateTierInput, s as UpdateEarningRuleInput, t as AdjustPointsInput, u as EarningBreakdown } from "../index-Cp_sXNpG.mjs";
|
|
2
|
+
import { a as ModelName, c as ResolvedConfig, i as LoyaltyShape, l as ResolvedTenant, o as PluginType, r as LoyaltyRuntime, s as RepositoryPlugins, t as IndexDefinition, u as TenantConfig } from "../config-CtkGj3xZ.mjs";
|
|
3
|
+
export { AdjustPointsInput, type BalanceSummary, CreateEarningRuleInput, CreateTierInput, EarnPointsInput, type EarningBreakdown, type EarningResult, EnrollInput, type ExpirationResult, type IndexDefinition, type ListQuery, LoyaltyContext, type LoyaltyRuntime, type LoyaltyShape, type ModelName, type PaginatedResult, type PluginType, type RedemptionValidation, type RepositoryPlugins, type ResolvedConfig, type ResolvedTenant, type TenantConfig, type TierEvaluation, type TierEvaluationBatch, UpdateEarningRuleInput, UpdateTierInput };
|