feat: 删除心情打卡和目标子任务API测试文件

- 移除test-goal-tasks.http和test-mood-checkins.http文件,清理不再使用的测试文件。
- 更新GoalsService中的目标删除逻辑,增加事务处理以确保数据一致性。
- 优化GoalTaskService中的任务生成逻辑,增加日志记录以便于调试和监控。
This commit is contained in:
2025-08-23 14:31:15 +08:00
parent f6b4c99e75
commit cba56021de
5 changed files with 99 additions and 300 deletions

View File

@@ -1,6 +1,7 @@
import { Injectable, Logger, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op, WhereOptions, Order } from 'sequelize';
import { InjectModel, InjectConnection } from '@nestjs/sequelize';
import { Op, WhereOptions, Order, Transaction } from 'sequelize';
import { Sequelize } from 'sequelize-typescript';
import { Goal, GoalStatus, GoalRepeatType } from './models/goal.model';
import { GoalCompletion } from './models/goal-completion.model';
import { GoalTask } from './models/goal-task.model';
@@ -22,6 +23,8 @@ export class GoalsService {
private readonly goalCompletionModel: typeof GoalCompletion,
@InjectModel(GoalTask)
private readonly goalTaskModel: typeof GoalTask,
@InjectConnection()
private readonly sequelize: Sequelize,
private readonly goalTaskService: GoalTaskService,
) { }
@@ -180,27 +183,58 @@ export class GoalsService {
* 删除目标
*/
async deleteGoal(userId: string, goalId: string): Promise<boolean> {
const transaction = await this.sequelize.transaction();
try {
// 验证目标存在
const goal = await this.goalModel.findOne({
where: { id: goalId, userId, deleted: false },
transaction,
});
if (!goal) {
await transaction.rollback();
throw new NotFoundException('目标不存在');
}
// 软删除目标
await goal.update({ deleted: true });
// 使用事务删除目标及其相关数据
await Promise.all([
// 软删除目标本身
this.goalModel.update(
{ deleted: true },
{
where: { id: goalId, userId, deleted: false },
transaction
}
),
// 软删除目标完成记录
this.goalCompletionModel.update(
{ deleted: true },
{
where: { goalId, userId, deleted: false },
transaction
}
),
// 软删除与目标关联的任务
this.goalTaskModel.update(
{ deleted: true },
{
where: { goalId, userId, deleted: false },
transaction
}
),
]);
// 软删除相关的完成记录
await this.goalCompletionModel.update(
{ deleted: true },
{ where: { goalId, userId } }
);
// 提交事务
await transaction.commit();
this.logger.log(`用户 ${userId} 删除了目标: ${goal.title}`);
return true;
} catch (error) {
// 回滚事务
await transaction.rollback();
this.logger.error(`删除目标失败: ${error.message}`);
throw error;
}