优化训练计划相关服务,移除不必要的completed字段,简化DTO和模型结构。同时,增强训练会话删除逻辑,添加事务处理和错误日志记录,提升数据一致性和操作安全性。

This commit is contained in:
richarjiang
2025-08-15 17:15:17 +08:00
parent 4257449f76
commit d69cf9afbd
4 changed files with 42 additions and 32 deletions

View File

@@ -109,7 +109,11 @@ export class WorkoutsService {
});
if (!activeTrainingPlan) {
throw new NotFoundException('请先激活一个训练计划');
this.winstonLogger.info(`今日没有激活的训练计划`, {
context: 'WorkoutsService',
userId,
});
return null;
}
// 创建今日训练会话
@@ -352,28 +356,44 @@ export class WorkoutsService {
* 删除训练会话
*/
async deleteWorkoutSession(userId: string, sessionId: string) {
const [count] = await this.workoutSessionModel.update(
{ deleted: true },
{ where: { id: sessionId, userId, deleted: false } }
);
const transaction = await this.workoutSessionModel.sequelize?.transaction();
if (!transaction) throw new Error('Failed to start transaction');
if (count === 0) {
throw new NotFoundException('训练会话不存在');
try {
const [count] = await this.workoutSessionModel.update(
{ deleted: true },
{ where: { id: sessionId, userId, deleted: false }, transaction }
);
if (count === 0) {
throw new NotFoundException('训练会话不存在');
}
// 同时删除关联的训练动作
await this.workoutExerciseModel.update(
{ deleted: true },
{ where: { workoutSessionId: sessionId, userId, deleted: false }, transaction }
);
await transaction.commit();
this.winstonLogger.info(`删除训练会话 ${sessionId}`, {
context: 'WorkoutsService',
userId,
sessionId,
});
return { success: true };
} catch (error) {
await transaction.rollback();
this.winstonLogger.error(`删除训练会话失败 ${sessionId}`, {
context: 'WorkoutsService',
userId,
sessionId,
error,
});
throw error;
}
// 同时删除关联的训练动作
await this.workoutExerciseModel.update(
{ deleted: true },
{ where: { workoutSessionId: sessionId, userId, deleted: false } }
);
this.winstonLogger.info(`删除训练会话 ${sessionId}`, {
context: 'WorkoutsService',
userId,
sessionId,
});
return { success: true };
}
// ==================== 训练动作管理 ====================