fix: 非事务多写包裹 \$transaction(plan/elder-svc/record/abnormal/qc)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
liuyun 2026-10-21 11:49:33 +08:00
parent 6ea9ad097b
commit 292300c344
10 changed files with 265 additions and 221 deletions

View File

@ -30,16 +30,17 @@ function makeService(
const orderUpdate = overrides.orderUpdate ?? vi.fn().mockResolvedValue({ id: 'o1', orderStatus: 'not_met' });
const orderFindUnique = overrides.orderFindUnique ?? vi.fn().mockResolvedValue({ id: 'o1', orderStatus: 'assigned' });
const prisma = {
client: {
const client: Record<string, any> = {
recordAbnormal: {
create: recordAbnormalCreate,
findMany: recordAbnormalFindMany,
count: recordAbnormalCount,
},
order: { update: orderUpdate, findUnique: orderFindUnique },
},
};
// $transaction:交互式回调以 client 自身作为 tx(事务内写仍命中同一 mock)。
client.$transaction = vi.fn(async (arg: any) => (typeof arg === 'function' ? arg(client) : Promise.all(arg)));
const prisma = { client };
const service = new AbnormalService(prisma as unknown as PrismaService);
return { service, recordAbnormalCreate, recordAbnormalFindMany, recordAbnormalCount, orderUpdate, orderFindUnique };
}

View File

@ -39,7 +39,12 @@ export class AbnormalService {
this.assertNotMetEvidence(dto);
// 扑空:工单须存在,再转 not_met(原因 + 到访时间)。
await this.requireOrder(dto.orderId!);
await this.prisma.client.order.update({
}
// 扑空的「工单转 not_met + 写 record_abnormal」须原子落库,防止工单已转 not_met 而异常未写入。
const created = await this.prisma.client.$transaction(async (tx) => {
if (dto.abnormalType === NOT_MET) {
await tx.order.update({
where: { id: dto.orderId! },
data: {
orderStatus: 'not_met',
@ -49,8 +54,7 @@ export class AbnormalService {
},
});
}
const created = await this.prisma.client.recordAbnormal.create({
return tx.recordAbnormal.create({
data: {
tenantCode,
elderId: dto.elderId,
@ -69,6 +73,7 @@ export class AbnormalService {
handleStatus: 'open',
},
});
});
// Prisma Decimal(visit_lat/visit_lng)转字符串,避免经 TransformInterceptor 泄漏为 {s,e,d}。
return {
...created,

View File

@ -36,8 +36,7 @@ function makeService(
const elderSvcUpdateMany = overrides.elderSvcUpdateMany ?? vi.fn().mockResolvedValue({ count: 2 });
const elderSvcCreate = overrides.elderSvcCreate ?? vi.fn().mockResolvedValue({ id: 'es1' });
const prisma = {
client: {
const client: Record<string, any> = {
elder: { findFirst: elderFindFirst },
svcOrg: { findFirst: svcOrgFindFirst },
svcNational: { findFirst: svcNationalFindFirst },
@ -47,8 +46,10 @@ function makeService(
updateMany: elderSvcUpdateMany,
create: elderSvcCreate,
},
},
};
// $transaction:交互式回调以 client 自身作为 tx(事务内写仍命中同一 mock)。
client.$transaction = vi.fn(async (arg: any) => (typeof arg === 'function' ? arg(client) : Promise.all(arg)));
const prisma = { client };
const service = new ElderSvcService(prisma as unknown as PrismaService);
return {
service,

View File

@ -27,20 +27,21 @@ export class ElderSvcService {
return this.prisma.client.elderSvc.findMany({ where: { elderId } });
}
/** 整表覆盖保存个人项目库。 */
/** 整表覆盖保存个人项目库(软删旧行 + 写新行同一事务原子落库)。 */
async put(elderId: string, dto: PutElderSvcDto) {
await this.assertElderExists(elderId);
const resolved = await this.resolveSvcItems(dto.svcIds);
const ctx = getRequestContext()!;
return this.prisma.client.$transaction(async (tx) => {
// 软删旧行留档(care_mode 变更/重新保存均重制旧库)。
await this.prisma.client.elderSvc.updateMany({
await tx.elderSvc.updateMany({
where: { elderId },
data: { deletedAt: new Date() },
});
const ctx = getRequestContext()!;
const rows = [];
for (const item of resolved) {
rows.push(
await this.prisma.client.elderSvc.create({
await tx.elderSvc.create({
data: {
elderId,
tenantCode: ctx.tenantCode,
@ -54,6 +55,7 @@ export class ElderSvcService {
);
}
return rows;
});
}
/** 校验每个 svc_id 落本机构 L4,并解析名称/代码快照。 */

View File

@ -56,8 +56,7 @@ function makeService(
const planItemCreate = overrides.planItemCreate ?? vi.fn().mockResolvedValue({ id: 'pi1' });
const planItemFindMany = overrides.planItemFindMany ?? vi.fn().mockResolvedValue([]);
const prisma = {
client: {
const client: Record<string, any> = {
svcOrg: { findFirst: svcOrgFindFirst },
svcNational: { findFirst: svcNationalFindFirst },
svcLocal: { findFirst: svcLocalFindFirst },
@ -69,8 +68,10 @@ function makeService(
findMany: planFindMany,
},
planItem: { create: planItemCreate, findMany: planItemFindMany },
},
};
// $transaction:交互式回调以 client 自身作为 tx(事务内写仍命中同一 mock)。
client.$transaction = vi.fn(async (arg: any) => (typeof arg === 'function' ? arg(client) : Promise.all(arg)));
const prisma = { client };
const service = new PlanService(prisma as unknown as PrismaService);
return {
service,

View File

@ -27,18 +27,25 @@ export class PlanService {
/** 制定服务计划(active)。 */
create(dto: CreatePlanDto) {
return this.buildPlan(dto, { planStatus: 'active' });
return this.createPlan(dto, { planStatus: 'active' });
}
/** 变更服务计划:新建 active 计划并指向旧计划,旧计划转 changed。 */
/** 变更服务计划:新建 active 计划并指向旧计划,旧计划转 changed(同一事务原子落库)。 */
async change(dto: ChangePlanDto) {
const oldPlan = await this.requireExists(dto.changeFromPlanId);
if (oldPlan.elderId !== dto.elderId) {
throw new BusinessException(ErrorCodes.PLAN_NOT_FOUND, '被变更计划不属于该老人', HttpStatus.BAD_REQUEST);
}
const newPlan = await this.buildPlan(dto, { planStatus: 'active', changeFromPlanId: dto.changeFromPlanId });
await this.prisma.client.plan.update({ where: { id: dto.changeFromPlanId }, data: { planStatus: 'changed' } });
const { planData, resolved } = await this.preparePlan(dto, {
planStatus: 'active',
changeFromPlanId: dto.changeFromPlanId,
});
return this.prisma.client.$transaction(async (tx) => {
const newPlan = await this.createPlanHead(tx, planData);
await this.createPlanItems(tx, newPlan.id, resolved);
await tx.plan.update({ where: { id: dto.changeFromPlanId }, data: { planStatus: 'changed' } });
return newPlan;
});
}
/** 确认计划:仅写确认时间与老人/家属布尔(不改变 plan_status)。 */
@ -67,13 +74,23 @@ export class PlanService {
}
/** 制定/变更共用的建计划流程。 */
private async buildPlan(dto: CreatePlanDto, opts: { planStatus: string; changeFromPlanId?: string }) {
private async createPlan(dto: CreatePlanDto, opts: { planStatus: string; changeFromPlanId?: string }) {
const { planData, resolved } = await this.preparePlan(dto, opts);
return this.prisma.client.$transaction(async (tx) => {
const plan = await this.createPlanHead(tx, planData);
await this.createPlanItems(tx, plan.id, resolved);
return plan;
});
}
/** 制定/变更共用的前置校验与解析(读操作,事务外执行)。 */
private async preparePlan(dto: CreatePlanDto, opts: { planStatus: string; changeFromPlanId?: string }) {
await this.assertElderExists(dto.elderId);
const items = dto.items ?? [];
const extraCount = dto.extraItemCount ?? 0;
const resolved = await this.resolvePlanItems(items);
const { ok, hint } = checkItemCount(dto.careMode, dto.careLevel, items.length, extraCount);
const plan = await this.createPlanHead({
const planData: Record<string, any> = {
elderId: dto.elderId,
planPeriodStart: toDateOnly(dto.planPeriodStart),
planPeriodEnd: toDateOnly(dto.planPeriodEnd),
@ -88,26 +105,25 @@ export class PlanService {
planStatus: opts.planStatus,
planBasis: dto.planBasis,
changeFromPlanId: opts.changeFromPlanId,
});
await this.createPlanItems(plan.id, resolved);
return plan;
};
return { planData, resolved };
}
/** 写计划头,注入 tenantCode/createdBy(plan 为租户级模型)。 */
private createPlanHead(data: Record<string, any>) {
private createPlanHead(tx: any, data: Record<string, any>) {
const ctx = getRequestContext();
if (ctx) {
data.tenantCode = ctx.tenantCode;
data.createdBy = ctx.userId;
}
return this.prisma.client.plan.create({ data } as any);
return tx.plan.create({ data } as any);
}
/** 逐个写 plan_item(含 svc 名称/代码快照)。 */
private async createPlanItems(planId: string, items: ResolvedPlanItem[]) {
private async createPlanItems(tx: any, planId: string, items: ResolvedPlanItem[]) {
const ctx = getRequestContext()!;
for (const item of items) {
await this.prisma.client.planItem.create({
await tx.planItem.create({
data: {
planId,
tenantCode: ctx.tenantCode,

View File

@ -82,12 +82,7 @@ function makeService(
const planChange = overrides.planChange ?? vi.fn().mockResolvedValue({ id: 'p-new' });
const prisma = {
raw: {
record: { findMany: rawRecordFindMany },
qc: { findFirst: rawQcFindFirst, create: rawQcCreate },
},
client: {
const client: Record<string, any> = {
qc: {
findUnique: qcFindUnique,
findFirst: qcFindFirst,
@ -112,7 +107,16 @@ function makeService(
order: { findMany: orderFindMany, findFirst: orderFindFirst },
elder: { findMany: elderFindMany },
plan: { findFirst: planFindFirst },
};
// $transaction:交互式回调以 client 自身作为 tx(事务内写仍命中同一 mock)。
client.$transaction = vi.fn(async (arg: any) => (typeof arg === 'function' ? arg(client) : Promise.all(arg)));
const prisma = {
raw: {
record: { findMany: rawRecordFindMany },
qc: { findFirst: rawQcFindFirst, create: rawQcCreate },
},
client,
};
const service = new QcService(

View File

@ -170,7 +170,7 @@ export class QcService {
const qc = await this.requireQc(id);
const record = await this.requireRecord(qc.recordId);
await this.assertPassable(qc, record, ctx.userId);
return this.markPassed(id, ctx.userId);
return this.markPassed(this.prisma.client, id, ctx.userId);
}
/** 退回:幂等守卫 → qc_note 必填 → returned。 */
@ -260,7 +260,7 @@ export class QcService {
/** 批量放行:先全量预检(批量边界 + 逐条自检),全过才逐条落库(原子,不部分放行)。 */
async batchPass(dto: BatchPassDto) {
const ctx = getRequestContext()!;
const pendingQcs = [];
const pendingQcs: Array<Record<string, any>> = [];
// 阶段一:全量预检,任一不过整体抛错,不落任何 pass。
for (const recordId of dto.recordIds) {
const record = await this.requireRecord(recordId);
@ -289,18 +289,20 @@ export class QcService {
await this.assertPassable(qc, record, ctx.userId);
pendingQcs.push(qc);
}
// 阶段二:全部预检通过后逐条放行。
// 阶段二:全部预检通过后,同一事务内逐条放行(原子,不部分放行)。
await this.prisma.client.$transaction(async (tx) => {
for (const qc of pendingQcs) {
await this.markPassed(qc.id, ctx.userId);
await this.markPassed(tx, qc.id, ctx.userId);
}
});
return { passed: dto.recordIds.length };
}
// ---- 内部 ----
/** 放行落库:qc_result=passed + qc_staff_id + qc_time + pass_time。 */
private markPassed(id: string, userId: string) {
return this.prisma.client.qc.update({
private markPassed(tx: any, id: string, userId: string) {
return tx.qc.update({
where: { id },
data: { qcResult: 'passed', qcStaffId: userId, qcTime: new Date(), passTime: new Date() },
});

View File

@ -59,8 +59,7 @@ function makeService(
const svcNationalFindFirst = overrides.svcNationalFindFirst ?? vi.fn().mockResolvedValue(null);
const svcLocalFindFirst = overrides.svcLocalFindFirst ?? vi.fn().mockResolvedValue(null);
const prisma = {
client: {
const client: Record<string, any> = {
order: { findUnique: orderFindUnique },
staff: { findFirst: staffFindFirst },
elder: { findFirst: elderFindFirst, findUnique: elderFindUnique },
@ -77,8 +76,10 @@ function makeService(
svcOrg: { findFirst: svcOrgFindFirst },
svcNational: { findFirst: svcNationalFindFirst },
svcLocal: { findFirst: svcLocalFindFirst },
},
};
// $transaction:交互式回调以 client 自身作为 tx(事务内写仍命中同一 mock)。
client.$transaction = vi.fn(async (arg: any) => (typeof arg === 'function' ? arg(client) : Promise.all(arg)));
const prisma = { client };
const storage = {
buildKey: vi.fn().mockReturnValue('record/T001/1-a.jpg'),
upload: vi.fn().mockResolvedValue('record/T001/1-a.jpg'),

View File

@ -94,11 +94,12 @@ export class RecordService {
// 先全量校验(exec_result 枚举 + L4)并解析快照,任一失败不落库。
const resolved = await this.resolveItems(dto.items, order);
await this.prisma.client.recordItem.deleteMany({ where: { recordId: record.id } });
return this.prisma.client.$transaction(async (tx) => {
await tx.recordItem.deleteMany({ where: { recordId: record.id } });
const rows = [];
for (const item of resolved) {
rows.push(
await this.prisma.client.recordItem.create({
await tx.recordItem.create({
data: {
tenantCode: ctx.tenantCode,
recordId: record.id,
@ -115,6 +116,7 @@ export class RecordService {
);
}
return rows;
});
}
/** 上传照片:≤500KB → MinIO(record 前缀)→ record_photo。 */
@ -340,13 +342,21 @@ export class RecordService {
}
}
const created = [];
for (const rec of records) {
// 预读各垫付记录的 items/photos(读操作,事务外),再在同一事务内全量写入(原子,不部分结转)。
const snapshots = await Promise.all(
records.map(async (rec) => {
const [items, photos] = await Promise.all([
this.prisma.client.recordItem.findMany({ where: { recordId: rec.id } }),
this.prisma.client.recordPhoto.findMany({ where: { recordId: rec.id } }),
]);
const newRecord = await this.prisma.client.record.create({
return { rec, items, photos };
}),
);
return this.prisma.client.$transaction(async (tx) => {
const created = [];
for (const { rec, items, photos } of snapshots) {
const newRecord = await tx.record.create({
data: {
tenantCode: ctx.tenantCode,
createdBy: ctx.userId,
@ -366,7 +376,7 @@ export class RecordService {
},
});
for (const item of items) {
await this.prisma.client.recordItem.create({
await tx.recordItem.create({
data: {
tenantCode: ctx.tenantCode,
recordId: newRecord.id,
@ -382,7 +392,7 @@ export class RecordService {
});
}
for (const photo of photos) {
await this.prisma.client.recordPhoto.create({
await tx.recordPhoto.create({
data: {
tenantCode: ctx.tenantCode,
recordId: newRecord.id,
@ -397,6 +407,7 @@ export class RecordService {
created.push(this.serializeRecord(newRecord));
}
return created;
});
}
// ---- 内部校验 ----