All files / app/services shopping-list.service.ts

100% Statements 107/107
89.28% Branches 50/56
100% Functions 51/51
100% Lines 88/88

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 287 288 289 290                      1x         1x   1x 1x 1x 1x 1x     1x 1x 1x 1x 1x     1x     1x 1x           1x         1x 1x 1x 1x   1x         1x 1x 1x 1x 1x       1x   1x         1x 1x   1x         1x   1x 1x     1x 1x     1x 1x 1x 1x             1x             1x             1x 1x 1x                     1x 1x 1x                     1x 1x 1x                     1x 1x 1x                     1x 1x 1x                     1x               1x         1x 1x       1x 1x       1x 1x 1x 1x     1x             1x             1x             1x 1x                 1x 1x   1x   1x 1x   1x         1x             1x       1x       1x 1x               1x 1x 1x       1x       1x      
import { Injectable, signal, computed, effect } from '@angular/core';
import { ShoppingItem, FilterType, FavouriteItem, Unit } from '../models';
import Fuse from 'fuse.js';
 
interface StoredListData {
  items: ShoppingItem[];
  listName: string;
  listDescription: string;
  favourites?: FavouriteItem[];
}
 
const STORAGE_KEY = 'nimmit-shopping-list';
 
@Injectable({
  providedIn: 'root'
})
export class ShoppingListService {
  // Haupt-Daten
  private readonly _items = signal<ShoppingItem[]>([]);
  private readonly _listName = signal('Meine Einkaufsliste');
  private readonly _listDescription = signal('Tippe auf +, um Produkte hinzuzufügen');
  private readonly _favourites = signal<FavouriteItem[]>([]);
  private readonly _loaded = signal(false);
 
  // Public readonly signals
  readonly items = this._items.asReadonly();
  readonly listName = this._listName.asReadonly();
  readonly listDescription = this._listDescription.asReadonly();
  readonly favourites = this._favourites.asReadonly();
  readonly loaded = this._loaded.asReadonly();
 
  constructor() {
    this.loadFromStorage();
 
    // Auto-save bei Änderungen
    effect(() => {
      const data: StoredListData = {
        items: this._items(),
        listName: this._listName(),
        listDescription: this._listDescription(),
        favourites: this._favourites()
      };
      this.saveToStorage(data);
    });
  }
 
  private loadFromStorage(): void {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      Eif (stored) {
        const data: StoredListData = JSON.parse(stored);
        // Dates wiederherstellen
        const items = data.items.map(item => ({
          ...item,
          createdAt: new Date(item.createdAt),
          updatedAt: new Date(item.updatedAt)
        }));
        this._items.set(items);
        this._listName.set(data.listName || 'Meine Einkaufsliste');
        this._listDescription.set(data.listDescription || 'Tippe auf +, um Produkte hinzuzufügen');
        Eif (data.favourites) {
          this._favourites.set(data.favourites);
        }
      }
    } catch (e) {
      console.error('Fehler beim Laden der Daten:', e);
    } finally {
      this._loaded.set(true);
    }
  }
 
  private saveToStorage(data: StoredListData): void {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    } catch (e) {
      console.error('Fehler beim Speichern der Daten:', e);
    }
  }
 
  // Computed values
  readonly allCount = computed(() => this._items().length);
 
  readonly notPurchasedCount = computed(
    () => this._items().filter((item) => item.purchasedQuantity < item.totalQuantity).length
  );
 
  readonly purchasedCount = computed(
    () => this._items().filter((item) => item.purchasedQuantity >= item.totalQuantity).length
  );
 
  readonly progressPercentage = computed(() => {
    const total = this.allCount();
    Eif (total === 0) return 0;
    return (this.purchasedCount() / total) * 100;
  });
 
  /**
   * Fügt ein neues Item zur Liste hinzu
   */
  addItem(item: Omit<ShoppingItem, 'id' | 'createdAt' | 'updatedAt' | 'purchasedQuantity'>): void {
    const newItem: ShoppingItem = {
      ...item,
      id: crypto.randomUUID(),
      purchasedQuantity: 0,
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    this._items.update(items => [...items, newItem]);
  }
 
  /**
   * Markiert ein Item als gekauft
   */
  markAsPurchased(itemId: string): void {
    this._items.update(items =>
      items.map(item =>
        item.id === itemId
          ? { ...item, purchasedQuantity: item.totalQuantity, updatedAt: new Date() }
          : item
      )
    );
  }
 
  /**
   * Markiert ein Item als nicht gekauft
   */
  markAsNotPurchased(itemId: string): void {
    this._items.update(items =>
      items.map(item =>
        item.id === itemId
          ? { ...item, purchasedQuantity: 0, updatedAt: new Date() }
          : item
      )
    );
  }
 
  /**
   * Erhöht die eingekaufte Menge um 1
   */
  incrementPurchasedQuantity(itemId: string): void {
    this._items.update(items =>
      items.map(item =>
        item.id === itemId && item.purchasedQuantity < item.totalQuantity
          ? { ...item, purchasedQuantity: item.purchasedQuantity + 1, updatedAt: new Date() }
          : item
      )
    );
  }
 
  /**
   * Verringert die eingekaufte Menge um 1
   */
  decrementPurchasedQuantity(itemId: string): void {
    this._items.update(items =>
      items.map(item =>
        item.id === itemId && item.purchasedQuantity > 0
          ? { ...item, purchasedQuantity: item.purchasedQuantity - 1, updatedAt: new Date() }
          : item
      )
    );
  }
 
  /**
   * Aktualisiert ein Item
   */
  updateItem(itemId: string, updates: Partial<ShoppingItem>): void {
    this._items.update(items =>
      items.map(item =>
        item.id === itemId
          ? { ...item, ...updates, updatedAt: new Date() }
          : item
      )
    );
  }
 
  /**
   * Löscht ein Item
   */
  deleteItem(itemId: string): void {
    this._items.update(items => items.filter(item => item.id !== itemId));
  }
 
  /**
   * Filtert Items basierend auf Filter-Typ, Suchbegriff und Kategorien
   */
 
  getFilteredItems(filter: FilterType, searchQuery: string, selectedCategories: string[] = []): ShoppingItem[] {
    const fuse = new Fuse<ShoppingItem>(this._items(), {
      keys: ['name', 'category'],
      threshold: 0.4,
    });
 
    let result: ShoppingItem[] = searchQuery
      ? fuse.search(searchQuery).map(r => r.item)
      : this._items();
 
    // Kategorie-Filter
    Eif (selectedCategories.length > 0) {
      result = result.filter((item: ShoppingItem) => selectedCategories.includes(item.category));
    }
 
    // Tab-Filter
    if (filter === 'notPurchased') {
      result = result.filter((item: ShoppingItem) => item.purchasedQuantity < item.totalQuantity);
    E} else if (filter === 'purchased') {
      result = result.filter((item: ShoppingItem) => item.purchasedQuantity >= item.totalQuantity);
    }
 
    return result;
  }
 
  /**
   * Prüft ob ein Item gekauft ist
   */
  isPurchased(item: ShoppingItem): boolean {
    return item.purchasedQuantity >= item.totalQuantity;
  }
 
  /**
   * Generiert den Status-Text
   */
  getStatusText(item: ShoppingItem): string {
    return `${item.purchasedQuantity} von ${item.totalQuantity} gekauft`;
  }
 
  /**
   * Aktualisiert Listennamen und Beschreibung
   */
  updateListInfo(name: string, description: string): void {
    this._listName.set(name);
    this._listDescription.set(description);
  }
 
  // --- Favourites ---
 
  /**
   * Toggles a favourite item. If it exists, removes it. If it doesn't, adds it.
   */
  toggleFavourite(name: string, category: string, unit: Unit, size?: number): void {
    const trimmedName = name.trim();
    Eif (!trimmedName) return;
 
    const existingId = this.findFavouriteId(trimmedName, unit, size);
 
    if (existingId) {
      this.removeFavourite(existingId);
    } else {
      this.addFavourite(trimmedName, category, unit, size);
    }
  }
 
  addFavourite(name: string, category: string, unit: Unit, size?: number): void {
    const newFav: FavouriteItem = {
      id: crypto.randomUUID(),
      name,
      category,
      unit,
      size
    };
    this._favourites.update(favs => [...favs, newFav]);
  }
 
  removeFavourite(id: string): void {
    this._favourites.update(favs => favs.filter(f => f.id !== id));
  }
 
  updateFavourite(id: string, updates: Partial<FavouriteItem>): void {
    this._favourites.update(favs =>
      favs.map(fav => (fav.id === id ? { ...fav, ...updates } : fav))
    );
  }
 
  /**
   * Helper to find if a specific combination of name/unit/size is already a favourite
   */
  findFavouriteId(name: string, unit: Unit, size?: number): string | undefined {
    const trimmedName = name.trim().toLowerCase();
    const existing = this._favourites().find(f =>
      f.name.toLowerCase() === trimmedName &&
      f.unit === unit &&
      f.size === size
    );
    return existing?.id;
  }
 
  isCurrentFavourite(name: string, unit: Unit, size?: number): boolean {
    return !!this.findFavouriteId(name, unit, size);
  }
}