feat(ops): show order redeem records including FIFO secondary coupons
CI / verify (pull_request) Has been cancelled
CI / verify (pull_request) Has been cancelled
Persist redeem allocations and surface them on HQ order detail with backfill for history. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1038,9 +1038,10 @@ model BenefitCoupon {
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
order Order? @relation(fields: [orderId], references: [id], onDelete: Restrict)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
order Order? @relation(fields: [orderId], references: [id], onDelete: Restrict)
|
||||
redeemRecords RedeemRecord[]
|
||||
redeemAllocations RedeemRecordAllocation[]
|
||||
|
||||
@@index([userId, status])
|
||||
@@map("user_benefit_coupon")
|
||||
@@ -1056,17 +1057,36 @@ model RedeemRecord {
|
||||
settleAmount Decimal @map("settle_amount") @db.Decimal(10, 2)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
|
||||
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
|
||||
rating StoreRating?
|
||||
payout StorePayout?
|
||||
pending RedeemPendingRecord?
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
|
||||
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
|
||||
store Store @relation(fields: [storeId], references: [id], onDelete: Restrict)
|
||||
rating StoreRating?
|
||||
payout StorePayout?
|
||||
pending RedeemPendingRecord?
|
||||
allocations RedeemRecordAllocation[]
|
||||
|
||||
@@index([storeId, createdAt])
|
||||
@@map("user_redeem_record")
|
||||
}
|
||||
|
||||
// 核销单跨券 FIFO 分摊明细(含次券可追溯)
|
||||
model RedeemRecordAllocation {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
redeemRecordId BigInt @map("redeem_record_id") @db.UnsignedBigInt
|
||||
couponId BigInt @map("coupon_id") @db.UnsignedBigInt
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
|
||||
redeemRecord RedeemRecord @relation(fields: [redeemRecordId], references: [id], onDelete: Cascade)
|
||||
coupon BenefitCoupon @relation(fields: [couponId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@unique([redeemRecordId, couponId])
|
||||
@@index([couponId])
|
||||
@@index([redeemRecordId])
|
||||
@@map("user_redeem_record_allocation")
|
||||
}
|
||||
|
||||
model RedeemPendingRecord {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
pendingNo String @unique @map("pending_no") @db.VarChar(32)
|
||||
|
||||
@@ -73,11 +73,18 @@ export class AdminOrdersService {
|
||||
},
|
||||
delivery: true,
|
||||
benefitCoupon: {
|
||||
select: { id: true, couponNo: true, balance: true, status: true },
|
||||
select: {
|
||||
id: true,
|
||||
couponNo: true,
|
||||
totalAmount: true,
|
||||
usedAmount: true,
|
||||
balance: true,
|
||||
status: true,
|
||||
},
|
||||
},
|
||||
city: { select: { id: true, name: true, code: true } },
|
||||
product: { select: { id: true, name: true, skuCode: true, barcode69: true } },
|
||||
imageResource: { select: { id: true, url: true } },
|
||||
imageResource: { select: { url: true } },
|
||||
fulfillmentWarehouse: {
|
||||
select: {
|
||||
id: true,
|
||||
@@ -97,11 +104,84 @@ export class AdminOrdersService {
|
||||
where: orderStatusLogWhere(id),
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return serializeBigInt(mapOrderCompat({
|
||||
...order,
|
||||
statusLogs: mapStatusLogCompat(statusLogs),
|
||||
benefitCoupons: order.benefitCoupon ? [order.benefitCoupon] : [],
|
||||
}));
|
||||
|
||||
const coupon = order.benefitCoupon;
|
||||
if (coupon) {
|
||||
await this.ensureRedeemAllocationsForCoupon(coupon.id);
|
||||
}
|
||||
|
||||
const redeemRows = coupon
|
||||
? await this.prisma.redeemRecord.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ couponId: coupon.id },
|
||||
{ allocations: { some: { couponId: coupon.id } } },
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
store: { select: { id: true, name: true, cityName: true } },
|
||||
allocations: {
|
||||
where: { couponId: coupon.id },
|
||||
select: { amount: true, sortOrder: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
: [];
|
||||
|
||||
const redeemRecords = redeemRows.map((r) => {
|
||||
const couponAmount =
|
||||
r.allocations[0] != null
|
||||
? Number(r.allocations[0].amount)
|
||||
: r.couponId === coupon!.id
|
||||
? Number(r.amount)
|
||||
: 0;
|
||||
const isPrimary = r.couponId === coupon!.id;
|
||||
return {
|
||||
id: r.id,
|
||||
redeemNo: r.redeemNo,
|
||||
amount: Number(r.amount),
|
||||
settleAmount: Number(r.settleAmount),
|
||||
couponAmount,
|
||||
role: isPrimary ? 'PRIMARY' : 'SECONDARY',
|
||||
createdAt: r.createdAt,
|
||||
store: r.store,
|
||||
};
|
||||
});
|
||||
const redeemRecordSum = redeemRecords.reduce((sum, r) => sum + r.couponAmount, 0);
|
||||
|
||||
const { benefitCoupon: _coupon, ...orderRest } = order;
|
||||
|
||||
return serializeBigInt(
|
||||
mapOrderCompat({
|
||||
...orderRest,
|
||||
statusLogs: mapStatusLogCompat(statusLogs),
|
||||
benefitCoupons: coupon
|
||||
? [
|
||||
{
|
||||
id: coupon.id,
|
||||
couponNo: coupon.couponNo,
|
||||
totalAmount: Number(coupon.totalAmount),
|
||||
usedAmount: Number(coupon.usedAmount),
|
||||
balance: Number(coupon.balance),
|
||||
status: coupon.status,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
redeemSummary: coupon
|
||||
? {
|
||||
couponNo: coupon.couponNo,
|
||||
totalAmount: Number(coupon.totalAmount),
|
||||
usedAmount: Number(coupon.usedAmount),
|
||||
balance: Number(coupon.balance),
|
||||
status: coupon.status,
|
||||
redeemCount: redeemRecords.length,
|
||||
redeemRecordSum,
|
||||
}
|
||||
: null,
|
||||
redeemRecords,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async updateStatusDebug(id: bigint, status: string) {
|
||||
@@ -309,7 +389,12 @@ export class AdminOrdersService {
|
||||
if (couponIds.length) {
|
||||
const redeemIds = (
|
||||
await tx.redeemRecord.findMany({
|
||||
where: { couponId: { in: couponIds } },
|
||||
where: {
|
||||
OR: [
|
||||
{ couponId: { in: couponIds } },
|
||||
{ allocations: { some: { couponId: { in: couponIds } } } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
).map((r) => r.id);
|
||||
@@ -317,6 +402,7 @@ export class AdminOrdersService {
|
||||
if (redeemIds.length) {
|
||||
await tx.storePayout.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
|
||||
await tx.storeRating.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
|
||||
await tx.redeemRecordAllocation.deleteMany({ where: { redeemRecordId: { in: redeemIds } } });
|
||||
await tx.redeemRecord.deleteMany({ where: { id: { in: redeemIds } } });
|
||||
}
|
||||
|
||||
@@ -332,4 +418,148 @@ export class AdminOrdersService {
|
||||
});
|
||||
await tx.order.deleteMany({ where: { id: { in: orderIds } } });
|
||||
}
|
||||
|
||||
/**
|
||||
* 补齐历史核销分摊:
|
||||
* 1) 待审核销 pending.allocationsJson → allocation 表
|
||||
* 2) 权益流水 REDEEM(次券)→ 按用户/门店/时间窗匹配核销单
|
||||
* 3) 仅主券、尚无分摊行的核销单 → 写入单行分摊(全额)
|
||||
*/
|
||||
private async ensureRedeemAllocationsForCoupon(couponId: bigint) {
|
||||
const coupon = await this.prisma.benefitCoupon.findUnique({
|
||||
where: { id: couponId },
|
||||
select: { id: true, userId: true },
|
||||
});
|
||||
if (!coupon) return;
|
||||
|
||||
const pendings = await this.prisma.redeemPendingRecord.findMany({
|
||||
where: { userId: coupon.userId, redeemRecordId: { not: null } },
|
||||
select: { redeemRecordId: true, allocationsJson: true },
|
||||
});
|
||||
|
||||
for (const pending of pendings) {
|
||||
if (!pending.redeemRecordId) continue;
|
||||
const allocs = this.parseAllocationsJson(pending.allocationsJson);
|
||||
if (!allocs.some((a) => a.couponId === couponId.toString())) continue;
|
||||
|
||||
const existing = await this.prisma.redeemRecordAllocation.count({
|
||||
where: { redeemRecordId: pending.redeemRecordId },
|
||||
});
|
||||
if (existing > 0) continue;
|
||||
|
||||
await this.prisma.redeemRecordAllocation.createMany({
|
||||
data: allocs.map((a, index) => ({
|
||||
redeemRecordId: pending.redeemRecordId!,
|
||||
couponId: BigInt(a.couponId),
|
||||
amount: a.amount,
|
||||
sortOrder: index,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
|
||||
const ledgers = await this.prisma.commonEvent.findMany({
|
||||
where: {
|
||||
eventType: 'BENEFIT_LEDGER',
|
||||
param1: 'REDEEM',
|
||||
param2: couponId.toString(),
|
||||
actorType: 'USER',
|
||||
actorId: coupon.userId,
|
||||
refType: 'STORE',
|
||||
},
|
||||
select: { id: true, refId: true, amount1: true, createdAt: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
|
||||
for (const ledger of ledgers) {
|
||||
if (ledger.refId == null || ledger.amount1 == null) continue;
|
||||
const allocAmount = Math.abs(Number(ledger.amount1));
|
||||
if (!(allocAmount > 0)) continue;
|
||||
|
||||
const already = await this.prisma.redeemRecordAllocation.findFirst({
|
||||
where: {
|
||||
couponId,
|
||||
amount: allocAmount,
|
||||
redeemRecord: {
|
||||
userId: coupon.userId,
|
||||
storeId: ledger.refId,
|
||||
createdAt: {
|
||||
gte: new Date(ledger.createdAt.getTime() - 8000),
|
||||
lte: new Date(ledger.createdAt.getTime() + 8000),
|
||||
},
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (already) continue;
|
||||
|
||||
const candidates = await this.prisma.redeemRecord.findMany({
|
||||
where: {
|
||||
userId: coupon.userId,
|
||||
storeId: ledger.refId,
|
||||
createdAt: {
|
||||
gte: new Date(ledger.createdAt.getTime() - 8000),
|
||||
lte: new Date(ledger.createdAt.getTime() + 8000),
|
||||
},
|
||||
amount: { gte: allocAmount },
|
||||
allocations: { none: { couponId } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 5,
|
||||
});
|
||||
if (!candidates.length) continue;
|
||||
|
||||
// 优先挂到主券不是本券的核销单(跨券 FIFO 次券场景)
|
||||
const target =
|
||||
candidates.find((r) => r.couponId !== couponId) ??
|
||||
(candidates.length === 1 ? candidates[0] : null);
|
||||
if (!target) continue;
|
||||
|
||||
await this.prisma.redeemRecordAllocation.create({
|
||||
data: {
|
||||
redeemRecordId: target.id,
|
||||
couponId,
|
||||
amount: allocAmount,
|
||||
sortOrder: target.couponId === couponId ? 0 : 1,
|
||||
},
|
||||
}).catch(() => {
|
||||
/* unique 冲突忽略 */
|
||||
});
|
||||
}
|
||||
|
||||
const primaryWithoutAlloc = await this.prisma.redeemRecord.findMany({
|
||||
where: {
|
||||
couponId,
|
||||
allocations: { none: {} },
|
||||
},
|
||||
select: { id: true, amount: true },
|
||||
});
|
||||
if (primaryWithoutAlloc.length) {
|
||||
await this.prisma.redeemRecordAllocation.createMany({
|
||||
data: primaryWithoutAlloc.map((r) => ({
|
||||
redeemRecordId: r.id,
|
||||
couponId,
|
||||
amount: r.amount,
|
||||
sortOrder: 0,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private parseAllocationsJson(
|
||||
value: Prisma.JsonValue,
|
||||
): Array<{ couponId: string; amount: number }> {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item) => {
|
||||
if (!item || typeof item !== 'object') return null;
|
||||
const row = item as { couponId?: unknown; amount?: unknown };
|
||||
const id = row.couponId != null ? String(row.couponId) : '';
|
||||
const amount = Number(row.amount);
|
||||
if (!id || !Number.isFinite(amount) || amount <= 0) return null;
|
||||
return { couponId: id, amount };
|
||||
})
|
||||
.filter((item): item is { couponId: string; amount: number } => !!item);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,14 +39,56 @@ export class AdminRedeemService {
|
||||
const record = await this.prisma.redeemRecord.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
user: true,
|
||||
store: { include: { partnerAccount: { select: { id: true, companyName: true } } } },
|
||||
coupon: true,
|
||||
user: { select: { id: true, userNo: true, phone: true, nickname: true } },
|
||||
store: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
cityName: true,
|
||||
address: true,
|
||||
partnerAccount: { select: { id: true, companyName: true } },
|
||||
},
|
||||
},
|
||||
coupon: {
|
||||
select: {
|
||||
id: true,
|
||||
couponNo: true,
|
||||
totalAmount: true,
|
||||
usedAmount: true,
|
||||
balance: true,
|
||||
status: true,
|
||||
orderId: true,
|
||||
order: { select: { id: true, orderNo: true } },
|
||||
},
|
||||
},
|
||||
allocations: {
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
include: {
|
||||
coupon: {
|
||||
select: {
|
||||
id: true,
|
||||
couponNo: true,
|
||||
order: { select: { id: true, orderNo: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
payout: true,
|
||||
rating: true,
|
||||
},
|
||||
});
|
||||
if (!record) throw new NotFoundException('核销记录不存在');
|
||||
return serializeBigInt(record);
|
||||
return serializeBigInt({
|
||||
...record,
|
||||
allocations: record.allocations.map((a) => ({
|
||||
couponId: a.couponId,
|
||||
amount: Number(a.amount),
|
||||
sortOrder: a.sortOrder,
|
||||
couponNo: a.coupon.couponNo,
|
||||
orderId: a.coupon.order?.id ?? null,
|
||||
orderNo: a.coupon.order?.orderNo ?? null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -181,6 +181,13 @@ export class RedeemService {
|
||||
storeId: account.storeId,
|
||||
amount,
|
||||
settleAmount,
|
||||
allocations: {
|
||||
create: normalizedAllocations.map((item, index) => ({
|
||||
couponId: BigInt(item.couponId),
|
||||
amount: item.amount,
|
||||
sortOrder: index,
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user