import { Injectable } from '@angular/core'; import { collection, getDocs, doc, getDoc, setDoc, deleteDoc, updateDoc } from 'firebase/firestore'; import { db } from '../firebase'; import { Danka } from '../models/danka'; @Injectable({ providedIn: 'root', }) export class DankaService { private path = 'danka'; private readonly recentDankaStorageKey = 'kaimyo-management.recent-danka'; // 一覧 async getDankaList(): Promise { const snap = await getDocs(collection(db, this.path)); return snap.docs.map(d => ({ id: d.id, ...(d.data() as Omit) })); } // 1件 async getDankaById(id: string): Promise { const ref = doc(db, this.path, id); const snap = await getDoc(ref); if (!snap.exists()) return undefined; return { id: snap.id, ...(snap.data() as Omit) }; } // 作成・更新 async saveDanka(danka: Danka): Promise { const ref = doc(db, this.path, danka.id); await setDoc(ref, danka); } // 部分更新 async updateDanka(id: string, data: Partial): Promise { const ref = doc(db, this.path, id); await updateDoc(ref, data as any); } // 削除 async deleteDanka(id: string): Promise { const ref = doc(db, this.path, id); await deleteDoc(ref); } // ----------------------------- // 最近開いた檀家 // ----------------------------- private getRecentDankaIds(): string[] { if (!this.canUseLocalStorage()) return []; const value = localStorage.getItem(this.recentDankaStorageKey); if (!value) return []; try { const parsed = JSON.parse(value); return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : []; } catch { return []; } } private saveRecentDankaIds(ids: string[]): void { if (!this.canUseLocalStorage()) return; localStorage.setItem(this.recentDankaStorageKey, JSON.stringify(ids)); } private canUseLocalStorage(): boolean { return typeof localStorage !== 'undefined'; } // ★ここが重要:async化 async recordDankaOpened(id: string): Promise { const danka = await this.getDankaById(id); if (!danka) return; const recentIds = [ id, ...this.getRecentDankaIds().filter(rid => rid !== id), ].slice(0, 5); this.saveRecentDankaIds(recentIds); } // ★ここも async 必須 async getRecentDankaList(limit = 5): Promise { const ids = this.getRecentDankaIds().slice(0, limit); const list = await Promise.all( ids.map(id => this.getDankaById(id)) ); const filtered = list.filter((d): d is Danka => d !== undefined); if (filtered.length > 0) { return filtered; } // fallback(updatedAtがある前提なら) const all = await this.getDankaList(); return [...all] .sort((a: any, b: any) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '') ) .slice(0, limit); } }