Skip to main content

POS API

The POS_firebase.js module provides functions for managing products, processing sales, and handling customer loyalty points in the point of sale system.

Product Management

obtenerProductos

Retrieves all products from the database.
import { obtenerProductos } from './services/POS_firebase';

const productos = await obtenerProductos();

productos.forEach(producto => {
  console.log(`${producto.nombre}: $${producto.precio}`);
  console.log(`Stock: ${producto.stock}`);
});
result
array
Array of product objects, each containing id and all product data

crearProducto

Creates a new product in the database.
import { crearProducto } from './services/POS_firebase';

await crearProducto({
  nombre: 'Cable USB-C',
  precio: 150,
  stock: 50,
  categoria: 'Accesorios',
  descripcion: 'Cable USB-C 2m'
});
data
object
required
Product information
Note: The function automatically saves the document ID within the document itself for easier reference.

actualizarProducto

Updates an existing product.
import { actualizarProducto } from './services/POS_firebase';

await actualizarProducto('prod123', {
  precio: 175,
  stock: 45
});
id
string
required
The product document ID
data
object
required
Object containing fields to update (partial update supported)

eliminarProductoDB

Deletes a product from the database.
import { eliminarProductoDB } from './services/POS_firebase';

await eliminarProductoDB('prod123');
id
string
required
The product document ID to delete
Warning: This permanently deletes the product. Consider marking products as inactive instead of deleting them.

Customer Management

buscarClientePorTelefono

Searches for a customer by phone number.
import { buscarClientePorTelefono } from './services/POS_firebase';

const cliente = await buscarClientePorTelefono('5551234567');

if (cliente) {
  console.log(`Cliente encontrado: ${cliente.nombre}`);
  console.log(`Puntos: ${cliente.puntos || 0}`);
} else {
  console.log('Cliente no encontrado');
}
telefono
string
required
Customer phone number (will be trimmed)
result
object | null
Customer object with id and all customer data, or null if not found

sumarPuntosCliente

Adds loyalty points to a customer account.
import { sumarPuntosCliente } from './services/POS_firebase';

// Add 50 points to customer
await sumarPuntosCliente('cliente123', 50);

// Points can be negative to redeem
await sumarPuntosCliente('cliente123', -100);
clienteId
string
required
The customer document ID
puntosNuevos
number
required
Points to add (can be negative to subtract/redeem points)
Note: If the customer doesn’t have a puntos field, it initializes to 0 before adding.

Sales Management

registrarVenta

Records a new sale transaction.
import { registrarVenta } from './services/POS_firebase';

const ventaId = await registrarVenta({
  clienteId: 'cliente123',
  productos: [
    { id: 'prod1', nombre: 'Cable USB-C', cantidad: 2, precio: 150 },
    { id: 'prod2', nombre: 'Mouse', cantidad: 1, precio: 250 }
  ],
  total: 550,
  metodoPago: 'efectivo',
  puntosGanados: 55,
  fecha: new Date(),
  vendedor: 'Luis García'
});

console.log(`Venta registrada: ${ventaId}`);
data
object
required
Sale transaction data
result
string
The created sale document ID

descontarStock

Deducts stock quantity from a product after a sale.
import { descontarStock } from './services/POS_firebase';

// Deduct 3 units from product
await descontarStock('prod123', 47); // new stock level
productoId
string
required
The product document ID
nuevoStock
number
required
The new stock quantity (not the amount to deduct, but the final stock level)
Important: This function expects the final stock level, not the quantity to deduct. Calculate the new stock before calling:
const producto = await obtenerProducto(id);
const nuevoStock = producto.stock - cantidadVendida;
await descontarStock(id, nuevoStock);

Complete Sale Flow Example

import {
  obtenerProductos,
  buscarClientePorTelefono,
  registrarVenta,
  descontarStock,
  sumarPuntosCliente
} from './services/POS_firebase';

async function procesarVenta(telefono, itemsVenta) {
  // 1. Find or create customer
  const cliente = await buscarClientePorTelefono(telefono);
  
  if (!cliente) {
    throw new Error('Cliente no encontrado');
  }
  
  // 2. Calculate totals
  let total = 0;
  const productos = [];
  
  for (const item of itemsVenta) {
    const subtotal = item.precio * item.cantidad;
    total += subtotal;
    
    productos.push({
      id: item.id,
      nombre: item.nombre,
      cantidad: item.cantidad,
      precio: item.precio,
      subtotal
    });
  }
  
  // 3. Calculate loyalty points (10% of total)
  const puntosGanados = Math.floor(total * 0.10);
  
  // 4. Register sale
  const ventaId = await registrarVenta({
    clienteId: cliente.id,
    productos,
    total,
    metodoPago: 'efectivo',
    puntosGanados,
    fecha: new Date(),
    vendedor: 'Luis García'
  });
  
  // 5. Update stock for each product
  for (const item of itemsVenta) {
    const nuevoStock = item.stockActual - item.cantidad;
    await descontarStock(item.id, nuevoStock);
  }
  
  // 6. Add loyalty points
  await sumarPuntosCliente(cliente.id, puntosGanados);
  
  return {
    ventaId,
    total,
    puntosGanados,
    puntosNuevos: (cliente.puntos || 0) + puntosGanados
  };
}

Data Structures

Product Document

{
  id: 'prod123',
  nombre: 'Cable USB-C',
  precio: 150,
  stock: 50,
  categoria: 'Accesorios',
  descripcion: 'Cable USB-C 2m'
}

Sale Document

{
  id: 'venta123',
  clienteId: 'cliente123',
  productos: [
    {
      id: 'prod1',
      nombre: 'Cable USB-C',
      cantidad: 2,
      precio: 150,
      subtotal: 300
    }
  ],
  total: 550,
  metodoPago: 'efectivo',
  puntosGanados: 55,
  fecha: Timestamp,
  vendedor: 'Luis García'
}

Customer Document (with points)

{
  id: 'cliente123',
  nombre: 'Juan Pérez',
  telefono: '5551234567',
  direccion: 'Calle Principal 123',
  puntos: 250,
  createdAt: Timestamp,
  updatedAt: Timestamp
}

Build docs developers (and LLMs) love