Skip to main content

Architecture Overview

AI Studio is built on a robust service layer architecture that manages all core business logic for a restaurant management system. The application uses Firebase as the backend database with a local caching strategy for optimal performance.

Service Layer Structure

The API is organized into several specialized service modules:
  • Product & Category Services - Menu item and category management
  • Order Service - Order processing and lifecycle management
  • Reservation Service - Table reservation system with availability checking
  • Table Service - Table management and occupancy tracking
  • Customer Services - Customer and customer category management
  • Gemini AI Service - AI-powered chat assistant and audio transcription

Core Design Patterns

Cache-First Architecture

All services implement a dual-layer caching strategy:
  1. In-Memory Cache - Fast synchronous access via getXFromCache() functions
  2. LocalStorage Cache - Persistent client-side storage
  3. Firebase Sync - Cloud database as source of truth
// Example: Product Service Cache Pattern
let productsCache: Product[] | null = null;

export const getProductsFromCache = (): Product[] => {
  return productsCache || [];
};

export const fetchAndCacheProducts = async (): Promise<Product[]> => {
  // Fetch from Firebase, update both caches
};

Optimistic Updates

Services update local caches immediately for responsive UI, then sync with Firebase:
export const addProduct = async (productData: Omit<Product, 'id'>): Promise<Product> => {
  const newProduct = { ...productData, id: generateId() };
  await setDoc(doc(db, 'Products', newProduct.id), newProduct);
  updateCaches([...getProductsFromCache(), newProduct]);
  return newProduct;
};

Firebase Integration

All services use Firebase Firestore with these collections:
CollectionPurposeDocument ID Format
ProductsMenu itemsPROD-{timestamp}-{random}
CategoriesProduct categoriesCAT-{timestamp}-{random}
OrdersCustomer ordersORD-{timestamp}-{random}
ReservationsTable reservationsRES-{timestamp}-{random}
TablesRestaurant tablesTBL-{timestamp}-{random} or custom
CustomersCustomer recordsCUST-{timestamp}-{random}
CustomerCategoriesCustomer categoriesCUSTCAT-{timestamp}-{random}
ReservationSettingsReservation configurationmain (singleton)

Common Patterns

Error Handling

All async operations follow this pattern:
try {
  await setDoc(doc(db, SHEET_NAME, id), data);
  updateCaches(newData);
  return data;
} catch (e) {
  const errorMessage = e instanceof Error ? e.message : String(e);
  console.error('Error details:', errorMessage);
  throw new Error(`User-friendly message: ${errorMessage}`);
}

Data Cleaning

All services remove undefined values before Firebase writes:
const cleanUndefined = (obj: any) => {
  const newObj = { ...obj };
  Object.keys(newObj).forEach(key => {
    if (newObj[key] === undefined) {
      delete newObj[key];
    }
  });
  return newObj;
};

Batch Operations

Bulk operations use Firebase batch writes for atomicity:
const batch = writeBatch(db);
itemsToUpdate.forEach(item => {
  const docRef = doc(db, SHEET_NAME, item.id);
  batch.set(docRef, item);
});
await batch.commit();

TypeScript Types

All services are fully typed using interfaces defined in types.ts. See individual service pages for detailed type definitions.

Authentication & Security

The services layer assumes Firebase authentication and security rules are configured. All operations respect Firebase security rules.

Next Steps

Explore specific service APIs:

Products API

Product and category management

Orders API

Order processing and tracking

Reservations API

Table reservation system

Tables API

Table management and status

Customers API

Customer management

Gemini AI API

AI assistant and transcription

Build docs developers (and LLMs) love