All files / src/todos todo.service.ts

92.23% Statements 95/103
78.37% Branches 29/37
100% Functions 17/17
91.83% Lines 90/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 2872x         2x           2x 2x     2x   24x 24x           4x                           4x     4x       4x           4x                 4x 4x                       4x 1x         3x 1x       2x 1x         1x         4x 4x   4x 4x 4x         3x 3x 1x     2x 1x     1x       1x               5x 5x 1x     4x 1x     3x   3x 1x 3x   3x 2x 3x   3x                                   3x 1x   3x 3x       3x             3x 3x 1x     2x 1x     1x 1x       3x 3x 1x     2x 1x     1x 1x       1x       2x 4x 4x     2x 2x 2x     2x 2x 2x   2x   2x                   1x 1x 1x               1x                     1x   1x 2x                 2x             2x 2x 1x   2x     1x      
import {
  Injectable,
  NotFoundException,
  ForbiddenException,
} from "@nestjs/common";
import { TodoRepository } from "./todo.repository";
import { TodoEntity } from "./todo.entity";
import { CreateTodoDto } from "./dto/create-todo.dto";
import { UpdateTodoDto } from "./dto/update-todo.dto";
import { TodoCategoryDto } from "./dto/todo-category.dto";
import { TodoItem, TodoStats, TodoCategory } from "@calendar-todo/shared-types";
import { UserSettingsService } from "../user-settings/user-settings.service";
import { subDays } from "date-fns";
 
@Injectable()
export class TodoService {
  constructor(
    private readonly todoRepository: TodoRepository,
    private readonly userSettingsService: UserSettingsService,
  ) {}
 
  private convertCategoryDtoToCategory(
    categoryDto: TodoCategoryDto,
  ): TodoCategory {
    return {
      id: categoryDto.id,
      name: categoryDto.name,
      color: categoryDto.color,
      icon: categoryDto.icon,
      createdAt: new Date(categoryDto.createdAt),
      order: categoryDto.order,
    };
  }
 
  async create(
    createTodoDto: CreateTodoDto,
    userId: string,
  ): Promise<TodoItem> {
    const category = this.convertCategoryDtoToCategory(createTodoDto.category);
 
    // Verify category belongs to user
    const userCategory = await this.userSettingsService.getCategoryById(
      userId,
      category.id,
    );
    Iif (!userCategory) {
      throw new NotFoundException(
        "Category not found or does not belong to user",
      );
    }
 
    const todoData = {
      title: createTodoDto.title,
      description: createTodoDto.description,
      priority: createTodoDto.priority || "medium",
      categoryId: category.id,
      dueDate: new Date(createTodoDto.date),
      userId,
    };
 
    const todo = await this.todoRepository.create(todoData);
    return todo.toTodoItem(userCategory);
  }
 
  async findAll(
    userId: string,
    startDate?: string,
    endDate?: string,
    categoryId?: string,
    completed?: boolean,
  ): Promise<TodoItem[]> {
    let todos: TodoEntity[];
 
    if (startDate && endDate) {
      todos = await this.todoRepository.findByUserIdAndDateRange(
        userId,
        new Date(startDate),
        new Date(endDate),
      );
    } else if (categoryId) {
      todos = await this.todoRepository.findByUserIdAndCategory(
        userId,
        categoryId,
      );
    } else if (completed !== undefined) {
      todos = await this.todoRepository.findByUserIdAndCompleted(
        userId,
        completed,
      );
    } else {
      todos = await this.todoRepository.findByUserId(userId);
    }
 
    // Get user categories to resolve category information
    const userCategories =
      await this.userSettingsService.getUserCategories(userId);
    const categoryMap = new Map(userCategories.map((cat) => [cat.id, cat]));
 
    return todos.map((todo) => {
      const category = categoryMap.get(todo.categoryId);
      return todo.toTodoItem(category);
    });
  }
 
  async findOne(id: string, userId: string): Promise<TodoItem> {
    const todo = await this.todoRepository.findById(id);
    if (!todo) {
      throw new NotFoundException("할일을 찾을 수 없습니다");
    }
 
    if (todo.userId !== userId) {
      throw new ForbiddenException("해당 할일에 접근할 권한이 없습니다");
    }
 
    const category = await this.userSettingsService.getCategoryById(
      userId,
      todo.categoryId,
    );
    return todo.toTodoItem(category || undefined);
  }
 
  async update(
    id: string,
    updateTodoDto: UpdateTodoDto,
    userId: string,
  ): Promise<TodoItem> {
    const todo = await this.todoRepository.findById(id);
    if (!todo) {
      throw new NotFoundException("할일을 찾을 수 없습니다");
    }
 
    if (todo.userId !== userId) {
      throw new ForbiddenException("해당 할일을 수정할 권한이 없습니다");
    }
 
    const updateData: Partial<TodoEntity> = {};
 
    if (updateTodoDto.title !== undefined)
      updateData.title = updateTodoDto.title;
    Iif (updateTodoDto.description !== undefined)
      updateData.description = updateTodoDto.description;
    if (updateTodoDto.completed !== undefined)
      updateData.completed = updateTodoDto.completed;
    Iif (updateTodoDto.priority !== undefined)
      updateData.priority = updateTodoDto.priority;
    Iif (updateTodoDto.category !== undefined) {
      const category = this.convertCategoryDtoToCategory(
        updateTodoDto.category,
      );
 
      // Verify category belongs to user
      const userCategory = await this.userSettingsService.getCategoryById(
        userId,
        category.id,
      );
      Iif (!userCategory) {
        throw new NotFoundException(
          "Category not found or does not belong to user",
        );
      }
 
      updateData.categoryId = category.id;
    }
    if (updateTodoDto.date !== undefined)
      updateData.dueDate = new Date(updateTodoDto.date);
 
    const updatedTodo = await this.todoRepository.update(id, updateData);
    const category = await this.userSettingsService.getCategoryById(
      userId,
      updatedTodo!.categoryId,
    );
    return updatedTodo!.toTodoItem(category || undefined);
  }
 
  async remove(
    id: string,
    userId: string,
  ): Promise<{ success: boolean; deletedId: string }> {
    const todo = await this.todoRepository.findById(id);
    if (!todo) {
      throw new NotFoundException("할일을 찾을 수 없습니다");
    }
 
    if (todo.userId !== userId) {
      throw new ForbiddenException("해당 할일을 삭제할 권한이 없습니다");
    }
 
    const success = await this.todoRepository.delete(id);
    return { success, deletedId: id };
  }
 
  async toggle(id: string, userId: string): Promise<TodoItem> {
    const todo = await this.todoRepository.findById(id);
    if (!todo) {
      throw new NotFoundException("할일을 찾을 수 없습니다");
    }
 
    if (todo.userId !== userId) {
      throw new ForbiddenException("해당 할일을 수정할 권한이 없습니다");
    }
 
    const updatedTodo = await this.todoRepository.toggle(id);
    const category = await this.userSettingsService.getCategoryById(
      userId,
      updatedTodo!.categoryId,
    );
    return updatedTodo!.toTodoItem(category || undefined);
  }
 
  async getStats(userId: string): Promise<TodoStats> {
    const allTodos = await this.todoRepository.findByUserId(userId);
    const completedTodos = allTodos.filter((todo) => todo.completed);
    const incompleteTodos = allTodos.filter((todo) => !todo.completed);
 
    // 최근 7일 내 완료된 할일 수
    const sevenDaysAgo = subDays(new Date(), 7);
    const recentCompletions = completedTodos.filter(
      (todo) => todo.updatedAt >= sevenDaysAgo && todo.completed,
    ).length;
 
    const total = allTodos.length;
    const completed = completedTodos.length;
    const incomplete = incompleteTodos.length;
    const completionRate =
      total > 0 ? Math.round((completed / total) * 100) : 0;
 
    return {
      total,
      completed,
      incomplete,
      completionRate,
      recentCompletions,
    };
  }
 
  async removeAllByUserId(userId: string): Promise<number> {
    const todos = await this.todoRepository.findByUserId(userId);
    await this.todoRepository.deleteByUserId(userId);
    return todos.length;
  }
 
  async updateCategoryForUser(
    userId: string,
    oldCategoryId: string,
    newCategoryId: string,
  ): Promise<number> {
    return await this.todoRepository.updateCategoryForUser(
      userId,
      oldCategoryId,
      newCategoryId,
    );
  }
 
  async bulkCreate(
    todos: Omit<TodoItem, "id">[],
    userId: string,
  ): Promise<TodoItem[]> {
    const createdTodos: TodoItem[] = [];
 
    for (const todoData of todos) {
      const categoryDto: TodoCategoryDto = {
        id: todoData.category.id,
        name: todoData.category.name,
        color: todoData.category.color,
        icon: todoData.category.icon,
        createdAt: todoData.category.createdAt.toISOString(),
        order: todoData.category.order,
      };
 
      const createDto: CreateTodoDto = {
        title: todoData.title,
        category: categoryDto,
        date: todoData.date.toISOString(),
        priority: "medium",
      };
 
      const todo = await this.create(createDto, userId);
      if (todoData.completed) {
        await this.update(todo.id, { completed: true }, userId);
      }
      createdTodos.push(todo);
    }
 
    return createdTodos;
  }
}