Skip to main content

Overview

The Orders API manages the complete order lifecycle from creation to completion. It supports three order types: pickup, delivery, and dine-in, with full status tracking and payment management.

Order Management

getOrdersFromCache

Retrieves orders from in-memory cache synchronously.
export const getOrdersFromCache = (): Order[]
orders
Order[]
Array of orders sorted by creation date (newest first)

fetchAndCacheOrders

Fetches orders from Firebase and updates caches.
export const fetchAndCacheOrders = async (): Promise<Order[]>
orders
Order[]
Array of all orders from Firebase
Behavior:
  • Syncs with Firebase Orders collection
  • Updates local caches
  • Seeds Firebase from local if Firebase is empty
  • Falls back to cache on errors

saveOrder

Creates a new order.
export const saveOrder = async (
  orderData: Omit<Order, 'id' | 'status' | 'createdAt' | 'statusHistory' | 'finishedAt' | 'isPaid'>
): Promise<Order>
orderData
object
required
Order data without auto-generated fields
order
Order
The created order with:
  • Generated ID (format: ORD-{timestamp}-{random})
  • Initial status: OrderStatus.PENDING
  • Created timestamp
  • Status history initialized
  • isPaid set based on payment proof URL
import { saveOrder, OrderType, PaymentMethod, CreatedBy } from './services/orderService';

const order = await saveOrder({
  customer: {
    name: "Juan Pérez",
    phone: "+5491123456789",
    address: "Av. Corrientes 1234, Buenos Aires"
  },
  items: [
    {
      name: "Pizza Muzzarella",
      quantity: 2,
      price: 9200,
      isPromotion: false,
      itemId: "PROD-123"
    }
  ],
  total: 18400,
  type: OrderType.DELIVERY,
  paymentMethod: PaymentMethod.TRANSFER,
  createdBy: CreatedBy.WEB_ASSISTANT
});

console.log('Order created:', order.id);

updateOrder

Updates order fields.
export const updateOrder = async (
  orderUpdates: Partial<Order> & { id: string }
): Promise<Order>
orderUpdates
object
required
Partial order object with required id field
order
Order
The updated order
import { updateOrder } from './services/orderService';

const updated = await updateOrder({
  id: "ORD-1709876543210-abc12",
  customer: {
    ...existingOrder.customer,
    address: "Nueva dirección 456"
  }
});

updateOrderStatus

Updates order status with validation and notifications.
export const updateOrderStatus = async (
  orderId: string,
  status: OrderStatus
): Promise<Order>
orderId
string
required
The order ID
status
OrderStatus
required
New status (see OrderStatus enum below)
order
Order
Updated order with new status added to history
Validation Rules:
  • Cannot update orders that are already finished
  • Cannot complete orders that are not paid (throws error)
  • Automatically sets isPaid: true and finishedAt timestamp for completed orders
  • Sends notification on status change
import { updateOrderStatus, OrderStatus } from './services/orderService';

try {
  const order = await updateOrderStatus(
    "ORD-1709876543210-abc12",
    OrderStatus.CONFIRMED
  );
  console.log('Order confirmed:', order.id);
} catch (error) {
  console.error('Status update failed:', error.message);
}
Error Cases:
// Throws: "No se puede completar un pedido cuyo pago no ha sido aprobado..."
await updateOrderStatus(unpaidOrderId, OrderStatus.COMPLETED_DELIVERY);

markOrderAsPaid

Marks an order as paid with payment method and optional proof.
export const markOrderAsPaid = async (
  orderId: string,
  paymentMethod: PaymentMethod,
  paymentProofUrl?: string | null
): Promise<Order>
orderId
string
required
The order ID
paymentMethod
PaymentMethod
required
Payment method used
paymentProofUrl
string | null
URL to payment proof image (optional)
order
Order
Updated order with payment information
Special Behavior:
  • For dine-in orders with status DINE_IN_PENDING_PAYMENT, automatically transitions to COMPLETED_DINE_IN
  • Sends payment approval notification
import { markOrderAsPaid, PaymentMethod } from './services/orderService';

const order = await markOrderAsPaid(
  "ORD-1709876543210-abc12",
  PaymentMethod.TRANSFER,
  "https://storage.example.com/payment-proof.jpg"
);

console.log('Payment approved:', order.isPaid);

deleteOrder

Deletes an order by ID.
export const deleteOrder = async (orderId: string): Promise<void>
orderId
string
required
The order ID to delete

isOrderFinished

Checks if an order has a finished status.
export const isOrderFinished = (status: OrderStatus): boolean
status
OrderStatus
required
Order status to check
isFinished
boolean
Returns true if status is one of: COMPLETED_PICKUP, COMPLETED_DELIVERY, COMPLETED_DINE_IN, or CANCELLED
import { isOrderFinished, OrderStatus } from './services/orderService';

if (isOrderFinished(order.status)) {
  console.log('Order is complete');
}

TypeScript Types

OrderStatus Enum

enum OrderStatus {
  PENDING = 'Pendiente',
  CONFIRMED = 'Confirmado',
  PREPARING = 'En Preparación',
  READY = 'Listo para Retirar/Entregar',
  DELIVERING = 'En Camino',
  DINE_IN_PENDING_PAYMENT = 'En Mesa (Pendiente de Pago)',
  COMPLETED_PICKUP = 'Completado (Retirado)',
  COMPLETED_DELIVERY = 'Completado (Entregado)',
  COMPLETED_DINE_IN = 'Completado (En Mesa)',
  CANCELLED = 'Cancelado'
}

OrderType Enum

enum OrderType {
  PICKUP = 'pickup',
  DELIVERY = 'delivery',
  DINE_IN = 'dine-in'
}

PaymentMethod Enum

enum PaymentMethod {
  CASH = 'Efectivo',
  CREDIT = 'Credito',
  TRANSFER = 'Transferencia'
}

CreatedBy Enum

enum CreatedBy {
  ADMIN = 'Admin Panel',
  WEB_ASSISTANT = 'Web Assistant',
  WHATSAPP_ASSISTANT = 'WhatsApp Assistant'
}

Order Interface

interface Order {
  id: string;
  customer: {
    name: string;
    phone?: string;
    address?: string;
  };
  items: OrderItem[];
  total: number;
  status: OrderStatus;
  type: OrderType;
  createdAt: string;
  statusHistory: StatusHistory[];
  finishedAt: string | null;
  tableIds?: string[];
  guests?: number;
  paymentMethod: PaymentMethod;
  isPaid: boolean;
  paymentProofUrl?: string | null;
  reservationId?: string;
  createdBy: CreatedBy;
}

OrderItem Interface

interface OrderItem {
  name: string;
  quantity: number;
  price: number;
  isPromotion: boolean;
  itemId: string;
}

StatusHistory Interface

interface StatusHistory {
  status: OrderStatus | ReservationStatus;
  startedAt: string; // ISO timestamp
}

Status Workflow

Pickup Orders

  1. PENDING → Order created
  2. CONFIRMED → Order accepted
  3. PREPARING → Kitchen preparing
  4. READY → Ready for pickup
  5. COMPLETED_PICKUP → Customer picked up

Delivery Orders

  1. PENDING → Order created
  2. CONFIRMED → Order accepted
  3. PREPARING → Kitchen preparing
  4. READY → Ready for delivery
  5. DELIVERING → Out for delivery
  6. COMPLETED_DELIVERY → Delivered

Dine-In Orders

  1. PENDING → Order created
  2. CONFIRMED → Order accepted
  3. PREPARING → Kitchen preparing
  4. READY → Food ready
  5. DINE_IN_PENDING_PAYMENT → Waiting for payment
  6. COMPLETED_DINE_IN → Payment received
Orders must be marked as paid before transitioning to any COMPLETED_* status.

Build docs developers (and LLMs) love