All files / src/user-settings user-settings.service.ts

100% Statements 72/72
95.23% Branches 20/21
100% Functions 15/15
100% Lines 68/68

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 2204x         4x         4x   25x         1x 1x               1x 1x   1x 1x         1x     1x 1x     1x     1x 1x     1x                 4x     4x 18x 1x           3x 1x         2x 2x   2x 2x                             5x     5x 5x 1x       4x 2x 2x   6x     1x           3x 3x 1x     2x   2x 2x                           4x   4x 4x 1x     3x 3x 2x         1x   1x         1x 1x               2x 2x   2x   1x                             1x 1x 1x             1x 1x               4x   4x 4x 3x     1x     1x      
import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from "@nestjs/common";
import { UserSettingsRepository } from "./user-settings.repository";
import { UserSettingsData } from "./user-settings.entity";
import { TodoCategory } from "@calendar-todo/shared-types";
 
@Injectable()
export class UserSettingsService {
  constructor(
    private readonly userSettingsRepository: UserSettingsRepository,
  ) {}
 
  // Get user settings (creates default if not exists)
  async getUserSettings(userId: string): Promise<UserSettingsData> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
    return settings.settings;
  }
 
  // Update user settings
  async updateUserSettings(
    userId: string,
    updates: Partial<UserSettingsData>,
  ): Promise<UserSettingsData> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
    settings.updateSettings(updates);
 
    await this.userSettingsRepository.update(userId, settings);
    return settings.settings;
  }
 
  // Get user categories
  async getUserCategories(userId: string): Promise<TodoCategory[]> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
 
    // Check if migration is needed before getting categories
    const needsMigration = settings.settings.categories.some(
      (cat) => typeof cat.order === "undefined",
    );
 
    const categories = settings.getCategories();
 
    // Save migration if it was applied
    if (needsMigration) {
      await this.userSettingsRepository.update(userId, settings);
    }
 
    return categories;
  }
 
  // Add new category
  async addCategory(
    userId: string,
    name: string,
    color: string,
  ): Promise<TodoCategory> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
 
    // Check if category name already exists
    const existingCategories = settings.getCategories();
    if (existingCategories.some((cat) => cat.name === name)) {
      throw new BadRequestException("Category name already exists");
    }
 
    // Allow duplicate colors - removed color uniqueness check
 
    // Check category limit (max 11: 3 default + 8 custom)
    if (existingCategories.length >= 11) {
      throw new BadRequestException(
        "Maximum number of categories reached (11)",
      );
    }
 
    const newCategoryId = settings.addCategory(name, color);
    await this.userSettingsRepository.update(userId, settings);
 
    const newCategory = settings.getCategoryById(newCategoryId);
    return {
      id: newCategory!.id,
      name: newCategory!.name,
      color: newCategory!.color,
      createdAt: newCategory!.createdAt,
      order: newCategory!.order || 0,
    };
  }
 
  // Update category
  async updateCategory(
    userId: string,
    categoryId: string,
    updates: Partial<Pick<TodoCategory, "name" | "color">>,
  ): Promise<TodoCategory> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
 
    // Check if category exists
    const category = settings.getCategoryById(categoryId);
    if (!category) {
      throw new NotFoundException("Category not found");
    }
 
    // Check if new name already exists (if updating name)
    if (updates.name && updates.name !== category.name) {
      const existingCategories = settings.getCategories();
      if (
        existingCategories.some(
          (cat) => cat.name === updates.name && cat.id !== categoryId,
        )
      ) {
        throw new BadRequestException("Category name already exists");
      }
    }
 
    // Allow duplicate colors - removed color uniqueness check for updates
 
    const success = settings.updateCategory(categoryId, updates);
    if (!success) {
      throw new BadRequestException("Failed to update category");
    }
 
    await this.userSettingsRepository.update(userId, settings);
 
    const updatedCategory = settings.getCategoryById(categoryId);
    return {
      id: updatedCategory!.id,
      name: updatedCategory!.name,
      color: updatedCategory!.color,
      createdAt: updatedCategory!.createdAt,
      order: updatedCategory!.order || 0,
    };
  }
 
  // Delete category
  async deleteCategory(
    userId: string,
    categoryId: string,
  ): Promise<{ success: boolean; deletedId: string }> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
 
    const category = settings.getCategoryById(categoryId);
    if (!category) {
      throw new NotFoundException("Category not found");
    }
 
    const success = settings.deleteCategory(categoryId);
    if (!success) {
      throw new BadRequestException(
        "Cannot delete the last category. At least one category must remain.",
      );
    }
 
    await this.userSettingsRepository.update(userId, settings);
 
    return { success: true, deletedId: categoryId };
  }
 
  // Get available colors
  async getAvailableColors(userId: string): Promise<string[]> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
    return settings.getAvailableColors();
  }
 
  // Get category by ID
  async getCategoryById(
    userId: string,
    categoryId: string,
  ): Promise<TodoCategory | null> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
    const category = settings.getCategoryById(categoryId);
 
    if (!category) return null;
 
    return {
      id: category.id,
      name: category.name,
      color: category.color,
      createdAt: category.createdAt,
      order: category.order || 0,
    };
  }
 
  // Update category filter
  async updateCategoryFilter(
    userId: string,
    categoryId: string,
    enabled: boolean,
  ): Promise<void> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
    settings.updateCategoryFilter(categoryId, enabled);
    await this.userSettingsRepository.update(userId, settings);
  }
 
  // Get category filter
  async getCategoryFilter(
    userId: string,
  ): Promise<{ [categoryId: string]: boolean }> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
    return settings.settings.categoryFilter;
  }
 
  // Reorder categories
  async reorderCategories(
    userId: string,
    categoryIds: string[],
  ): Promise<TodoCategory[]> {
    const settings = await this.userSettingsRepository.findOrCreate(userId);
 
    const success = settings.reorderCategories(categoryIds);
    if (!success) {
      throw new BadRequestException("Invalid category order provided");
    }
 
    await this.userSettingsRepository.update(userId, settings);
 
    // 업데이트된 카테고리 목록 반환
    return settings.getCategories();
  }
}