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

100% Statements 79/79
90.62% Branches 29/32
100% Functions 26/26
100% Lines 73/73

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 2466x                                     6x               48x 48x 48x 48x 48x       35x 35x     70x                       35x                                         25x   25x 45x 70x                     58x   58x 171x 19x 19x       58x 6x               17x 35x     17x               17x 17x 17x   17x               8x 16x   8x   7x   7x 7x   7x 7x         8x 20x   8x     7x 2x     5x 5x 5x   5x         28x 28x 65x           3x 3x           3x                     3x           5x   5x     5x 2x       3x 3x 1x     2x 5x     2x 1x       1x 3x 2x           1x 1x   1x         3x 3x         5x      
import { v4 as uuidv4 } from "uuid";
import { TodoCategory } from "@calendar-todo/shared-types";
 
export interface UserCategoryData {
  id: string;
  name: string;
  color: string;
  createdAt: Date;
  order?: number; // optional for backward compatibility
}
 
export interface UserSettingsData {
  categories: UserCategoryData[];
  categoryFilter: { [categoryId: string]: boolean };
  theme: "light" | "dark" | "system";
  language: string;
  // 필요시 다른 설정들 추가 가능
}
 
export class UserSettingsEntity {
  id: string;
  userId: string;
  settings: UserSettingsData;
  createdAt: Date;
  updatedAt: Date;
 
  constructor(data: Partial<UserSettingsEntity>) {
    this.id = data.id || uuidv4();
    this.userId = data.userId || "";
    this.settings = data.settings || this.getDefaultSettings();
    this.createdAt = data.createdAt || new Date();
    this.updatedAt = data.updatedAt || new Date();
  }
 
  private getDefaultSettings(): UserSettingsData {
    const defaultCategories = this.createDefaultCategories();
    return {
      categories: defaultCategories,
      categoryFilter: defaultCategories.reduce(
        (acc, cat) => ({
          ...acc,
          [cat.id]: true,
        }),
        {},
      ),
      theme: "system",
      language: "ko",
    };
  }
 
  private createDefaultCategories(): UserCategoryData[] {
    return [
      {
        id: uuidv4(),
        name: "개인",
        color: "#3b82f6",
        createdAt: new Date(),
        order: 0,
      },
      {
        id: uuidv4(),
        name: "회사",
        color: "#10b981",
        createdAt: new Date(),
        order: 1,
      },
    ];
  }
 
  // Get categories as TodoCategory array for frontend
  getCategories(): TodoCategory[] {
    // 기존 카테고리들의 order 필드 migration
    this.ensureCategoryOrder();
 
    return this.settings.categories
      .sort((a, b) => (a.order || 0) - (b.order || 0)) // 순서대로 정렬 (order가 없을 경우 0으로 처리)
      .map((cat) => ({
        id: cat.id,
        name: cat.name,
        color: cat.color,
        createdAt: cat.createdAt,
        order: cat.order || 0,
      }));
  }
 
  // 기존 카테고리들에 order 필드가 없는 경우 추가
  private ensureCategoryOrder(): void {
    let hasChanges = false;
 
    this.settings.categories.forEach((cat, index) => {
      if (typeof cat.order === "undefined") {
        cat.order = index;
        hasChanges = true;
      }
    });
 
    if (hasChanges) {
      this.updatedAt = new Date();
    }
  }
 
  // Add new category
  addCategory(name: string, color: string): string {
    // 새 카테고리의 순서는 기존 카테고리 수
    const maxOrder =
      this.settings.categories.length > 0
        ? Math.max(...this.settings.categories.map((cat) => cat.order || 0))
        : -1;
 
    const newCategory: UserCategoryData = {
      id: uuidv4(),
      name,
      color,
      createdAt: new Date(),
      order: maxOrder + 1,
    };
 
    this.settings.categories.push(newCategory);
    this.settings.categoryFilter[newCategory.id] = true;
    this.updatedAt = new Date();
 
    return newCategory.id;
  }
 
  // Update category
  updateCategory(
    categoryId: string,
    updates: Partial<Pick<UserCategoryData, "name" | "color">>,
  ): boolean {
    const categoryIndex = this.settings.categories.findIndex(
      (cat) => cat.id === categoryId,
    );
    if (categoryIndex === -1) return false;
 
    const category = this.settings.categories[categoryIndex];
 
    if (updates.name !== undefined) category.name = updates.name;
    if (updates.color !== undefined) category.color = updates.color;
 
    this.updatedAt = new Date();
    return true;
  }
 
  // Delete category (minimum 1 category must remain)
  deleteCategory(categoryId: string): boolean {
    const categoryIndex = this.settings.categories.findIndex(
      (cat) => cat.id === categoryId,
    );
    if (categoryIndex === -1) return false;
 
    // 최소 1개 카테고리는 유지해야 함
    if (this.settings.categories.length <= 1) {
      return false;
    }
 
    this.settings.categories.splice(categoryIndex, 1);
    delete this.settings.categoryFilter[categoryId];
    this.updatedAt = new Date();
 
    return true;
  }
 
  // Get category by ID
  getCategoryById(categoryId: string): UserCategoryData | null {
    this.ensureCategoryOrder(); // order 필드 migration
    return (
      this.settings.categories.find((cat) => cat.id === categoryId) || null
    );
  }
 
  // Update category filter
  updateCategoryFilter(categoryId: string, enabled: boolean): void {
    this.settings.categoryFilter[categoryId] = enabled;
    this.updatedAt = new Date();
  }
 
  // Get all available colors (allowing duplicates)
  getAvailableColors(): string[] {
    // Colors sorted by HSL hue for better visual organization
    const allColors = [
      "#ef4444", // Red (H: 0°)
      "#f97316", // Orange (H: 25°)
      "#eab308", // Yellow (H: 45°)
      "#22c55e", // Light Green (H: 142°)
      "#14b8a6", // Teal (H: 174°)
      "#0ea5e9", // Sky (H: 199°)
      "#3b82f6", // Blue (H: 221°)
      "#6366f1", // Indigo (H: 239°)
      "#8b5cf6", // Purple (H: 262°)
    ];
    return allColors; // Return all colors without filtering
  }
 
  // Reorder categories
  reorderCategories(categoryIds: string[]): boolean {
    // 먼저 order 필드 migration 수행
    this.ensureCategoryOrder();
 
    const currentCategories = this.settings.categories;
 
    // 전달된 ID 배열이 현재 카테고리와 일치하는지 확인
    if (categoryIds.length !== currentCategories.length) {
      return false;
    }
 
    // 중복 ID 검증
    const uniqueIds = new Set(categoryIds);
    if (uniqueIds.size !== categoryIds.length) {
      return false;
    }
 
    const hasAllIds = categoryIds.every((id) =>
      currentCategories.some((cat) => cat.id === id),
    );
 
    if (!hasAllIds) {
      return false;
    }
 
    // 새로운 순서로 카테고리 배열 재정렬
    const reorderedCategories = categoryIds.map((id, index) => {
      const category = currentCategories.find((cat) => cat.id === id)!;
      return {
        ...category,
        order: index,
      };
    });
 
    this.settings.categories = reorderedCategories;
    this.updatedAt = new Date();
 
    return true;
  }
 
  // Update entire settings
  updateSettings(newSettings: Partial<UserSettingsData>): void {
    this.settings = { ...this.settings, ...newSettings };
    this.updatedAt = new Date();
  }
 
  // Static method to create default settings for new user
  static createDefault(userId: string): UserSettingsEntity {
    return new UserSettingsEntity({ userId });
  }
}