ERP module Server Actions live inDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/ency07/B2B/llms.txt
Use this file to discover all available pages before exploring further.
src/erp/actions/. All require an authenticated session. They use supabaseAdmin (service role) but enforce tenant isolation and RBAC at the application layer before every query.
Leads
src/erp/actions/leads-erp.ts
getLeads
clients), contact (client_contacts), and diagnostic (diagnostic_reports). Supabase array-form 1:many FK relationships are normalized to single objects.
Tenant subdomain code. Resolved to UUID via
getTenantId.Promise<LeadRow[]>:
updateLeadStatus
leads RBAC action permission.
UUID of the lead to update.
Target status. Also updates
updated_at to the current timestamp.Promise<void>. Throws on Supabase error.
Required permission: leads
Quotes
src/erp/actions/quotes.ts
getQuotes
legal_name.
[] on Supabase error rather than throwing.
createQuote
BORRADOR status. The assigned_user_id is automatically set to the tenant owner.
UUID of the client this quote is for.
UUID of the associated requirement, if any.
Expiry date in
YYYY-MM-DD format.quotes.create
getQuoteItems
item_order ascending. Returns an empty array on error.
UUID of the quote.
addQuoteItem
unit field is hardcoded to "UNIDAD".
UUID of the parent quote.
Line item description.
Classification (e.g.
"Producto", "Servicio").Quantity of units.
Price per unit in COP.
Discount amount in COP for this line.
Tax percentage (e.g.
19 for 19% IVA).Display order of the line item within the quote.
updateQuoteStatus
UUID of the quote.
Target status string (e.g.
"ENVIADA", "APROBADA", "RECHAZADA").Requirements
src/erp/actions/requirements.ts
getRequirements
legal_name and city.
[] on Supabase error rather than throwing.
createRequirement
"BORRADOR". The created_by is set to the tenant owner’s user ID.
Requirement title / short description.
UUID of the client this requirement is associated with.
Requirement category (free text, e.g.
"Mantenimiento", "Instalación").Priority level:
"LOW", "MEDIUM", or "HIGH".requirements
updateRequirementStatus
UPDATE.
UUID of the requirement to update.
Target lifecycle status (e.g.
"EN_REVISION", "COTIZACION", "COMPLETADO").Additional column/value pairs to merge into the update payload (e.g.
{ engineering_user_id: "uuid" }).Promise<Requirement> — the updated row.
Dashboard
src/erp/actions/dashboard.ts
getDashboardCommandCenter
Promise.all to fire 7 concurrent Supabase queries to minimize latency:
| Query # | Table | Purpose |
|---|---|---|
| 1 | tenants | Fetch tenant display name |
| 2 | invoices | Outstanding balance, sparkline, collection rate |
| 3 | business_events | Recent pulse feed (last 10, excludes KPI events) |
| 4 | audit_log | Security audit trail (last 20, excludes KPI events) |
| 5 | leads | CRM health score and new leads count |
| 6 | inventory_stock | Inventory health score (items ≤ 10 available trigger alerts) |
| 7 | requirements | Purchases health score (BORRADOR/NUEVO count) |
- High-priority requirements in
BORRADOR,NUEVO, orEN_REVISIONstatus (up to 2). - High-priority jobs in
PENDIENTEorEN_EJECUCIONstatus (up to 2). - Leads with status
NUEVO(up to 2).
TOTAL_INVOICED, TOTAL_PAYMENTS, LEAD_SLA_BREACH_RATE) are computed server-side via the calculate_kpi Supabase RPC and read from kpi_history. If the RPC fails, JS-side aggregation is used as a fallback.
Audit log entries are enriched with user full names via a manual users join.
Returns Promise<DashboardCommandCenterData>:
KPIs
src/erp/actions/kpis.ts
getKpisForRole
Promise.all before branching into role-specific aggregation.
Role resolution — resolveCategory(role)
The authenticated user’s role code is mapped to one of eight dashboard categories:
| Category | Matched Role Codes |
|---|---|
admin | SUPER_ADMIN, ADMIN_EMPRESA, ADMIN_DEV |
director | GERENTE_GENERAL, DIRECTOR_FINANCIERO, JEFE_FINANZAS, AUXILIAR_FINANZAS |
comercial | DIRECTOR_COMERCIAL, EJECUTIVO_COMERCIAL, INGENIERO_COMERCIAL |
operaciones | DIRECTOR_OPERACIONES, JEFE_PROYECTOS |
tecnico | TECNICO_CAMPO, JEFE_MANTENIMIENTO |
almacenista | ALMACENISTA, JEFE_INVENTARIO |
auditor | AUDITOR |
default | Any unmapped role |
| Table | Fields fetched |
|---|---|
invoices | id, invoice_code, total_amount, paid_amount, balance_amount, status, invoice_date, due_date, client_id |
leads | id, lead_code, status, risk_level, created_at, client_id, company_name |
jobs | id, job_code, title, description, status, priority, planned_end_date, assigned_user_id, created_at, client_id |
inventory_stock | id, available_quantity, reserved_quantity, item_id, warehouse_id, inventory_items(name, item_code) |
audit_log | id, event_code, entity_type, action, created_at, user_id (last 7 days) |
quotes | id, quote_code, status, total_amount |
requirements | id, requirement_code, title, priority, status, client_id |
| Category | KPI 1 | KPI 2 | KPI 3 | KPI 4 |
|---|---|---|---|---|
admin / director | Facturación Emitida | Recaudo Cartera | Capacidad Activa (OTs) | Conversión Leads |
comercial | Leads Activos | Leads Calientes | Leads Nuevos (mes) | Tasa de Conversión |
operaciones | OTs Activas | OTs Vencidas | Vencen esta semana | OTs Completadas |
tecnico | OTs Activas | OTs Vencidas | Vencen Hoy | Prioridad Alta |
almacenista | Items Stock Bajo | Items en Stock | Unidades Reservadas | Items OK |
auditor | Eventos (7d) | Eventos Críticos (DELETE) | Eventos Hoy | Usuarios Únicos |
default | Sin rol asignado | Rol actual | Tenant (UUID prefix) | Acceso limitado |
- Overdue invoices →
isDanger: true - Low-stock items (available ≤ 10) →
isDanger: truewhenavailable_quantity <= 0 - Critical / overdue jobs →
isDanger: truewhenplanned_end_date < todayorpriority = HIGH - High-priority requirements →
isDanger: true - Hot leads (
risk_level = CALIENTE) →isDanger: false
Promise<RoleDashboardData>:
"No autenticado" if no session is present; throws on tenant access violation.
Users
src/erp/actions/users.ts
All user management actions are restricted to administrators. See the Users & Roles admin reference for complete documentation. Brief summaries:
listUsers
users → user_roles → roles.
listRoles
createUser
users row, and optionally assigns a role — all in one atomic flow with Auth rollback on failure. Required permission: users.create
updateUser
users.edit
assignRole
user_roles row. Idempotent — duplicate constraint violations (23505) are treated as success. Required permission: users.permissions
removeRole
user_roles row scoped to the tenant. Required permission: users.permissions