The Sales module (Documentation Index
Fetch the complete documentation index at: https://mintlify.com/ProyectoFerretek/FerreMarket/llms.txt
Use this file to discover all available pages before exploring further.
/ventas) is the transaction hub of FerreMarket. It provides a full-featured interface for creating new sales, browsing and filtering existing transactions, tracking daily and weekly revenue KPIs, generating per-sale PDF invoices via jsPDF, sending invoice emails, and bulk-exporting selected records. The page refreshes its data every time the browser tab regains focus so that figures stay current across multiple sessions.
Sales KPI Dashboard
Four metric cards appear above the transaction list, laid out in a2 → 4 column responsive grid:
| Card | Metric | Extra detail |
|---|---|---|
| Ventas Hoy | CLP total for the current calendar day | Day-over-day % change vs. yesterday with a green/red TrendingUp/TrendingDown icon |
| Esta Semana | CLP total for the rolling 7-day window | Count of individual transactions in that window |
| Promedio/Venta | Mean transaction value across all records | Labelled “Últimas 30 ventas” |
| Pendientes | Count of sales with estado === 'pendiente' | Labelled “Requieren atención” |
useMemo every time the ventas array or the refreshKey counter changes.
Statistics Charts
Below the KPI cards, two side-by-side distribution panels give a visual breakdown of the current transaction data. Both panels are rendered by theGraficosEstadisticas component and are recalculated via useMemo whenever the ventas array changes.
Estados de Ventas
Lists each
estado value with a coloured dot, transaction count, and percentage share. Colours follow the same badge scheme used throughout the module: green for completada, yellow for pendiente, and red for cancelada.Métodos de Pago
Lists each
metodoPago value with transaction count and percentage share. Values are taken directly from the ventas array and shown with an orange dot, so any payment method actually stored in the database will appear here automatically.Sale Fields
Each transaction is modelled by theVenta TypeScript interface from src/types/index.ts:
| Field | Type | Description |
|---|---|---|
id | string | Unique numeric identifier assigned by Supabase |
fecha | string | ISO 8601 timestamp in the America/Santiago timezone (set at creation) |
cliente | string | Numeric client ID referencing the clientes table |
productos | { id: string; cantidad: number; precioUnitario: number }[] | Line items; each references a product ID from productos |
total | number | Pre-calculated sale total in CLP (sum of cantidad × precioUnitario for all line items) |
metodoPago | string | One of the four accepted payment methods |
estado | string | Current status of the transaction — values in practice are 'completada', 'pendiente', or 'cancelada' (constrained by VentaFormulario) |
Creating a Sale
Open Nueva Venta
Click the orange Nueva Venta button in the top-right header. This opens
VentaModal with all fields blank.Select a client
Choose an active client from the dropdown. The list is populated from
obtenerClientes() and only active clients are selectable.Add line items
Search for and add products one by one. Set the quantity for each item; the unit price is pre-filled from the product’s
precio field and is editable. Each line item also has a per-product Desc. % field (percentage discount on that line). The running total updates in real time. A stock-availability check is performed per line — if the requested quantity exceeds available stock, an inline error appears.Set payment method, status, and taxes
Both
metodoPago and estado are required fields. Select from the dropdowns. Optionally set a Descuento General (percentage discount applied to the cart subtotal after per-line discounts) and adjust the IVA percentage (defaults to 19%). The summary panel shows Subtotal → Descuento → IVA → Total Final.Save the sale
On confirmation,
agregarVenta(venta) performs four sequential Supabase writes:- Inserts a row into
ventasand retrieves the newventaId. - Inserts one row per line item into
ventas_productos(withventa_id,producto_id,cantidad,precio_unitario). - Decrements
stockin theproductostable for each line item. - Updates
ultimacompraon the client record to the current Santiago timestamp.
Payment Methods
The following payment methods are supported and stored verbatim in themetodo_pago column:
| Stored value | Dropdown label |
|---|---|
Efectivo | Efectivo |
Tarjeta de crédito | Tarjeta de crédito |
Tarjeta de débito | Tarjeta de débito |
Transferencia | Transferencia bancaria |
Views
The transaction list supports three rendering modes, automatically adjusted on resize:| Mode | Trigger | Layout |
|---|---|---|
| Grid | Default on ≥ 1024 px | 1 → 2 → 3 → 4 columns of VentaCard components |
| Table | Manual toggle on ≥ 1024 px | Sortable table with columns: ID, Fecha, Cliente, Productos, Total, Método Pago, Estado, Acciones |
| Lista | Automatic on < 768 px | Single-column card list |
Filtering and Searching
The filter panel is always visible on desktop and toggles via a Filtros button on mobile:| Filter | Field filtered |
|---|---|
| Search box | cliente name (resolved via getNombreCliente) |
| Estado | estado — Completada / Pendiente / Cancelada |
| Método de pago | metodoPago — the four payment options above |
| Cliente | Exact client ID match |
| Fecha desde / hasta | Compares fecha.split('T')[0] against the date input values |
| Monto mínimo / máximo | Compares total against the numeric bounds |
PDF Invoices
Single invoice
Click the PDF button on any sale card or the download icon in the table actions row. This calls
generarFactura(venta), which uses jsPDF to build a formatted invoice document.Bulk export
Select one or more sales using the checkboxes on the cards or in the table header. A blue action banner appears showing the count of selected sales and two export buttons — PDF (via
FileText) and Excel (via FileSpreadsheet). Click either to call exportarSeleccion('pdf') or exportarSeleccion('excel').Send / Mail) on a sale card or in the table actions to call enviarFacturaPorEmail(venta). The function resolves the client’s email field from the clientes state array and dispatches the invoice.
Sale Status
Status values are displayed as coloured pill badges throughout the module:| Estado | Badge colour | Meaning |
|---|---|---|
completada | Green | Transaction fully processed and paid |
pendiente | Yellow | Transaction recorded but not yet finalised |
cancelada | Red | Transaction voided; stock is not automatically restocked |