Update api.ts

This commit is contained in:
2025-12-10 23:34:56 +01:00
committed by GitHub
parent a8a4f5ed55
commit f5897ec8ac

View File

@@ -100,10 +100,20 @@ export const CondoService = {
getActiveCondo: async (): Promise<Condo | undefined> => {
const id = localStorage.getItem('active_condo_id');
const condos = await CondoService.getCondos();
let match;
if (id) {
return condos.find(c => c.id === id);
match = condos.find(c => c.id === id);
}
return condos.length > 0 ? condos[0] : undefined;
// Auto-repair: If the stored ID matches nothing in the new DB, but we have condos, default to the first one.
if (!match && condos.length > 0) {
const firstCondoId = condos[0].id;
localStorage.setItem('active_condo_id', firstCondoId);
return condos[0];
}
return match;
},
setActiveCondo: (id: string) => {
@@ -134,6 +144,9 @@ export const CondoService = {
// Families
getFamilies: async (condoId?: string): Promise<Family[]> => {
let url = '/families';
// Use explicit ID if provided, otherwise fetch active from storage
// WARNING: If storage is stale, this returns empty. The App Layout calls getActiveCondo() which fixes storage.
// But to be safe, we rely on the component passing the condoId usually.
const activeId = condoId || CondoService.getActiveCondoId();
if (activeId) url += `?condoId=${activeId}`;
return request<Family[]>(url);
@@ -143,7 +156,10 @@ export const CondoService = {
let activeId = CondoService.getActiveCondoId();
if (!activeId) {
const condos = await CondoService.getCondos();
if (condos.length > 0) activeId = condos[0].id;
if (condos.length > 0) {
activeId = condos[0].id;
localStorage.setItem('active_condo_id', activeId);
}
}
return request<Family>('/families', {
method: 'POST',
@@ -236,7 +252,7 @@ export const CondoService = {
// Notices
getNotices: async (condoId?: string): Promise<Notice[]> => {
let url = '/notices';
const activeId = CondoService.getActiveCondoId();
const activeId = condoId || CondoService.getActiveCondoId();
if (activeId) url += `?condoId=${activeId}`;
return request<Notice[]>(url);
},
@@ -270,13 +286,17 @@ export const CondoService = {
// Tickets
getTickets: async (): Promise<Ticket[]> => {
const activeId = CondoService.getActiveCondoId();
let activeId = CondoService.getActiveCondoId();
// If no active condo, try to self-heal first or let backend handle fallback
if (!activeId) {
const condos = await CondoService.getCondos();
if(condos.length > 0) activeId = condos[0].id;
}
return request<Ticket[]>(`/tickets?condoId=${activeId}`);
},
createTicket: async (data: any): Promise<void> => {
let activeId = CondoService.getActiveCondoId();
// Robustness: If no activeId (e.g. standard user), fetch condos and use the first one
if (!activeId) {
const condos = await CondoService.getCondos();
if (condos.length > 0) activeId = condos[0].id;