GuestOps/web/src/api.ts

19 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export type User = { id: string; name: string; role: string; hotelId: string };
export type Session = { preview: boolean; csrfToken: string; user: User | null };
export type Hotel = { id: string; name: string; timezone: string; signature: string; replyMode: string; version: number; aiDraftsEnabled: boolean; staffSendingEnabled: boolean; paymentsEnabled: boolean; pmsUpdatesEnabled: boolean };
export type Conversation = { id: string; from: string; subject: string; body: string; receivedAt: string; status: string; draft: string; category: string; note: string; providerThreadId: string; version: number; mailboxId: string; replyAddress: string; draftSources: string[]; draftReviewNote: string; delivery: { state: string; recipient: string; body: string; detail: string; messageId: string; providerId: string } | null };
export type Knowledge = { id: string; title: string; category: string; answer: string; keywords: string; approved: boolean; version: number };
export type Activity = { id: string; at: string; userName: string; action: string };
export type Mailboxes = { configured: boolean; aiConfigured?: boolean; sendingConfigured?: boolean; items: { id: string; email: string; status: string; lastSyncAt: string | null; syncError: string; canSend: boolean }[] };
let csrf = '';
export async function api<T>(path: string, method = 'GET', body?: unknown): Promise<T> {
const response = await fetch('/api' + path, { method, credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf }, body: body === undefined ? undefined : JSON.stringify(body) });
const data = await response.json().catch(() => null);
if (!response.ok) {
if (response.status === 401 && path !== '/auth/login') window.dispatchEvent(new Event('session-expired'));
throw new Error(data?.error || (response.status === 429 ? 'Too many attempts. Please wait a minute.' : response.status === 403 ? 'Only the hotel owner can change this.' : 'We couldn’t complete that request. Please try again.'));
}
return data as T;
}
export async function session() { const value = await api<Session>('/session'); csrf = value.csrfToken; return value; }