Base de datos
Keirost usa PostgreSQL con esquema multi-tenant:
- public — usuarios, tenants, plugins, geografia
- tenant_* — un schema por empresa con todo el negocio
Schema public
Tenant
Empresas registradas en el sistema.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | UUID |
name | text unique | Nombre visible |
schemaName | text unique | Nombre del schema PostgreSQL |
config | text | JSON de configuracion |
createdAt | timestamp | |
updatedAt | timestamp |
GlobalUser
Usuarios globales del sistema.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | UUID |
email | text unique | Login |
username | text unique | Alias |
password | text | Hash bcrypt |
role | text | USER / ADMIN / SUPERUSER |
signatureName | text | Firma para PDFs |
signatureRole | text | Cargo en firma |
signatureImageUrl | text | Imagen de firma |
createdAt | timestamp | |
updatedAt | timestamp |
UserTenantMembership
Relacion usuario-empresa con rol.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
userId | FK → GlobalUser | |
tenantId | FK → Tenant | |
role | text | USER / ADMIN |
permissions | text | JSON de permisos |
| UNIQUE | (userId, tenantId) |
PluginField
Campos personalizados declarados por plugins o UI.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
pluginId | text | __user__ para campos UI |
tenantId | text | null si es plugin global |
tableName | text | Tabla destino |
fieldName | text | Nombre del campo |
fieldType | text | TEXT, INTEGER, DECIMAL, BOOLEAN, DATE, JSONB, ENUM |
label | text | Etiqueta UI |
options | jsonb | Opciones para ENUM |
required | boolean | Obligatorio |
defaultValue | text | Valor por defecto |
showInList | boolean | Visible en listado |
refTable | text | Para campos REFERENCE |
validation | jsonb | {min, max, pattern} |
createdAt | timestamp |
PluginTable
Tablas personalizadas declaradas por plugins.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
pluginId | text | __user__ para tablas UI |
tenantId | text | null si es global |
tableName | text | Nombre fisico |
definition | text | JSON con columnas |
label | text | Etiqueta menu |
kind | text | master / document |
iconName | text | Icono lucide |
menuModule | text | Modulo del menu |
TenantPlugin
Activacion de plugins por empresa.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
tenantId | FK → Tenant | |
pluginId | text | |
isActive | boolean | |
config | text | JSON de config |
| UNIQUE | (tenantId, pluginId) |
DevApiKey
Claves de desarrollo para plugins remotos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
clientId | text unique | |
clientSecret | text | |
name | text | Descripcion |
createdBy | FK → GlobalUser | |
tenantId | FK → Tenant | |
permissions | text | Scopes del token |
isActive | boolean | |
lastUsedAt | timestamp |
ApiToken
Tokens server-to-server por tenant.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
tenantId | text | |
name | text | |
tokenHash | text unique | SHA-256 del token |
prefix | text | Primeros caracteres legibles |
scopes | text | CSV de permisos |
createdByUserId | text | |
revokedAt | timestamp |
Country
Paises. PK: code (ISO 3166-1 alpha-2).
| Campo | Tipo | Descripcion |
|---|---|---|
code | PK text | ES, PT, etc. |
name | text | |
nameEn | text | Nombre en ingles |
phonePrefix | text | +34 |
currency | text | EUR |
taxIdRegex | text | Regex validacion NIF |
taxIdLabel | text | Etiqueta (NIF/CIF) |
postalCodeRegex | text |
Region
Regiones (comunidades autonomas).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
countryCode | FK → Country | |
code | text | |
name | text | |
| UNIQUE | (countryCode, code) |
SubRegion
Provincias.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
countryCode | FK → Country | |
regionId | FK → Region | nullable |
code | text | |
name | text | |
| UNIQUE | (countryCode, code) |
Locality
Municipios.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
countryCode | FK → Country | |
subRegionId | FK → SubRegion | |
code | text | |
name | text | |
| UNIQUE | (countryCode, code) |
Configuracion
SystemConfig
Clave-valor de configuracion por empresa.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
key | text unique | Ej: company_name |
value | text | |
description | text |
UserModule
Modulos del menu creados desde la UI.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
tenantId | text | |
label | text | Nombre visible |
iconName | text | Icono lucide |
moduleOrder | integer | Orden en el menu |
DocumentSeries
Series documentales por tipo y periodo.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text unique | |
docType | text | SINV, PINV, SDN, PDN, SO, PO |
periodId | FK → AccountingPeriod | |
prefix | text | Ej: FA |
firstNumber | integer | |
nextNumber | integer | |
lastNumber | integer | |
isDefault | boolean |
DocumentTemplate
Plantillas PDF (HTML o canvas).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
docType | text | Tipo de documento |
name | text | |
html | text | HTML Handlebars |
canvasLayout | jsonb | Layout del editor visual |
isDefault | boolean | |
legacyHtml | boolean | true = HTML clasico |
Fiscalidad y pagos
TaxGroup
Tipos de impuesto (IVA, IRPF).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | IVA21, IVA10, IRPF19 |
rate | decimal(5,2) | Porcentaje |
Currency
Monedas soportadas.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | EUR, USD |
name | text | |
symbol | text | €, $ |
decimals | integer | Default 2 |
exchangeRate | decimal(12,6) | vs moneda base |
isBase | boolean | Moneda base del tenant |
DocumentType
Tipos de documento fiscal configurables.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text | |
name | text | |
docCategory | text | Categoria |
isRectify | boolean | Es rectificativa |
isActive | boolean |
PaymentMethod
Metodos de pago.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | transfer, cash, card |
name | text |
PaymentTerm
Condiciones de pago (30 dias, 60 dias, etc.).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
lines | jsonb | Array de plazos y porcentajes |
Payment
Cobros y pagos registrados.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
salesInvoiceId | FK → SalesInvoice | o purchaseInvoiceId |
date | date | |
amount | decimal(15,4) | |
currencyId | FK → Currency | |
paymentMethodId | FK → PaymentMethod | |
reference | text | Numero de transferencia |
source | text | manual, automation |
PriceList
Listas de precios.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text |
ItemPrice
Precio por articulo y lista.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
priceListId | FK → PriceList | |
itemId | FK → Item | |
price | decimal(12,4) | |
| UNIQUE | (priceListId, itemId) |
Contabilidad
AccountingPeriod
Periodos fiscales (ejercicios).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
startDate | timestamp | |
endDate | timestamp | |
status | text | O abierto / C cerrado |
ChartOfAccount
Plan contable.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
type | text | asset, liability, equity, income, expense |
parentId | text | Jerarquia |
isAnalytical | boolean | Requiere dimension analitica |
isActive | boolean |
CostCenter
Centros de coste.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
parentId | text | Jerarquia |
managerEmployeeId | FK → Employee | |
isActive | boolean |
ProfitCenter
Centros de beneficio.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
parentId | text | Jerarquia |
managerEmployeeId | FK → Employee | |
isActive | boolean |
InternalOrder
Proyectos / ordenes internas / WBS.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
type | text | project, internal_order, wbs |
startDate | date | |
endDate | date | |
budgetAmount | decimal(15,2) | |
status | text | open, closed |
costCenterId | FK → CostCenter |
JournalEntry
Asientos contables (cabecera).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
number | integer | Numero de asiento |
date | timestamp | |
periodId | FK → AccountingPeriod | |
description | text | |
source | text | manual, sales_invoice, payment, payroll |
sourceDocumentId | text | ID del documento origen |
status | text | draft, posted, reversed |
reversedById | text | ID del asiento de reversion |
postedAt | timestamp |
JournalEntryLine
Lineas de asiento (debe/haber).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
entryId | FK → JournalEntry | |
lineNumber | integer | |
accountId | FK → ChartOfAccount | |
debit | decimal(15,4) | Default 0 |
credit | decimal(15,4) | Default 0 |
costCenterId | FK → CostCenter | |
profitCenterId | FK → ProfitCenter | |
internalOrderId | FK → InternalOrder | |
partnerId | text | |
currency | text | Default EUR |
exchangeRate | decimal(15,6) | Default 1 |
AccountMapping
Mapeo de cuentas para asientos automaticos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
kind | text | sales_revenue, customer_receivable, payroll_gross, etc. |
key | text | default o override por partner/tax |
accountId | FK → ChartOfAccount |
DimensionRule
Reglas de dimension por cuenta.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
accountId | FK → ChartOfAccount | UNIQUE |
requiresCostCenter | boolean | |
requiresProfitCenter | boolean | |
requiresInternalOrder | boolean |
Socios de negocio
PartnerGroup
Grupos de socios (clientes, proveedores).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | CLI, PRV, MAY |
name | text | |
codePrefix | text | Prefijo de numeracion |
isCustomer | boolean | |
isVendor | boolean |
BusinessPartner
Clientes y proveedores.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | Auto-generado |
name | text | Razon social |
nif | text unique nullable | Indice unico parcial |
foreignName | text | Nombre extranjero |
phone | text | |
email | text | |
website | text | |
groupId | FK → PartnerGroup | |
priceListId | FK → PriceList | |
defaultDocumentTypeId | text | |
defaultPaymentMethodId | text | |
defaultPaymentTermId | text | |
defaultWithholdingRate | decimal(5,2) | IRPF por defecto |
iban | text | |
bankName | text | |
bankSwift | text |
PartnerAddress
Direcciones de socios (facturacion/envio).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
partnerId | FK → BusinessPartner | |
name | text | |
street | text | |
city | text | |
zipCode | text | |
countryCode | text | |
type | text | B facturacion / S envio |
isDefault | boolean |
Contact
Personas de contacto del socio.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
partnerId | FK → BusinessPartner | |
name | text | |
role | text | Cargo |
email | text | |
phone | text | |
mobile | text | |
isMain | boolean | Contacto principal |
Inventario
Category
Categorias de articulos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
codePrefix | text | Prefijo de codigo |
parentId | FK → Category | Jerarquia |
Item
Articulos / productos / servicios.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | Referencia interna |
barcode | text unique nullable | EAN-13, Code-128 |
name | text | |
description | text | |
uomId | FK → UnitOfMeasure | Unidad base |
categoryId | FK → Category | |
taxGroupId | FK → TaxGroup | |
manageBy | text | N nada / B lotes / S series |
basePrice | decimal(12,4) | Precio base |
stock | double | Stock total |
minStock | double | Stock minimo |
defaultWarehouseId | text | |
defaultZoneId | text | |
kind | text | product (default) / box caja |
boxLengthMm | integer | Para cajas |
boxWidthMm | integer | |
boxHeightMm | integer | |
boxMaxWeightKg | double | |
boxTareWeightKg | double | |
createdAt | timestamp | |
updatedAt | timestamp |
ItemBatch
Lotes de articulos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
batchNum | text | Numero de lote |
itemId | FK → Item | |
quantity | double | |
expiryDate | timestamp |
ItemSerial
Series de articulos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
serialNum | text unique | Numero de serie |
itemId | FK → Item | |
status | text | A activo / I inactivo |
UnitOfMeasure
Unidades de medida.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | UD, KG, L, M |
name | text | |
baseValue | decimal(12,4) | Factor base (default 1) |
baseUomId | FK → UnitOfMeasure | Para conversiones |
ItemAlternativeUom
Conversiones de unidad por articulo.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
itemId | FK → Item | |
uomId | FK → UnitOfMeasure | |
factor | decimal(12,4) | Ej: 12 (1 caja = 12 uds) |
Warehouse
Almacenes.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
location | text | |
isDefault | boolean | |
createdAt | timestamp | |
updatedAt | timestamp |
WarehouseZone
Zonas dentro de un almacen.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
description | text | |
warehouseId | FK → Warehouse |
ItemWarehouseStock
Stock por articulo y almacen.
| Campo | Tipo | Descripcion |
|---|---|---|
itemId | FK → Item | PK (compuesto) |
warehouseId | FK → Warehouse | PK (compuesto) |
stock | double | |
updatedAt | timestamp |
ItemZoneStock
Stock por articulo, almacen y zona.
| Campo | Tipo | Descripcion |
|---|---|---|
itemId | FK → Item | PK (compuesto) |
warehouseId | FK → Warehouse | PK (compuesto) |
zoneId | FK → WarehouseZone | PK (compuesto) |
stock | double | |
updatedAt | timestamp |
Documentos de venta
SalesOrder (Pedido de venta)
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
seriesId | FK → DocumentSeries | |
docNum | integer | Numero en la serie |
periodId | FK → AccountingPeriod | |
partnerId | FK → BusinessPartner | |
date | timestamp | |
deliveryDate | timestamp | Fecha de entrega |
status | text | O borrador / P pendiente / C cerrado / X anulado |
warehouseId | FK → Warehouse | |
internalOrderId | FK → InternalOrder | |
subtotal | decimal(15,4) | |
taxTotal | decimal(15,4) | |
total | decimal(15,4) | |
taxBreakdown | text | JSON desglose IVA |
salesAgentId | text | Comercial (para comisiones) |
createdBy | text | |
createdAt | timestamp |
SalesOrderLine
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
orderId | FK → SalesOrder | |
lineNum | integer | |
itemId | FK → Item | |
orderedQty | decimal(12,4) | Cantidad pedida |
deliveredQty | decimal(12,4) | Cantidad entregada |
price | decimal(15,4) | |
taxGroupId | FK → TaxGroup | |
lineTotal | decimal(15,4) | |
uomId | FK → UOM | |
uomFactor | decimal(12,4) | Default 1 |
discountRate | decimal(5,2) | % descuento |
discountAmount | decimal(15,4) | |
withholdingRate | decimal(5,2) | % retencion |
withholdingAmount | decimal(15,4) | |
costCenterId | FK → CostCenter | |
profitCenterId | FK → ProfitCenter | |
internalOrderId | FK → InternalOrder | |
pluginData | jsonb |
SalesDeliveryNote (Albaran de venta)
Igual estructura que SalesOrder mas:
| orderId | FK → SalesOrder | Pedido origen |
SalesDeliveryNoteLine
Igual estructura que SalesOrderLine mas:
| baseLine | integer | Linea del documento base |
SalesDeliveryNoteLineBatch
Trazabilidad por lote en linea de albaran.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
deliveryLineId | FK → SalesDeliveryNoteLine | |
batchNum | text | |
quantity | double |
SalesInvoice (Factura de venta)
Extiende SalesOrder con campos fiscales:
| Campo | Tipo | Descripcion |
|---|---|---|
isLocked | boolean | Bloqueada al asentar |
lockedAt | timestamp | |
documentTypeId | text | Tipo fiscal |
dueDate | date | Vencimiento |
supplyDate | date | Fecha de operacion |
paymentMethodId | text | |
paymentTermId | text | |
paymentStatus | text | pending / partial / paid |
amountPaid | decimal(15,4) | |
withholdingRate | decimal(5,2) | |
withholdingAmount | decimal(15,4) | |
rectifyRef | text | Referencia rectificada |
rectifyReason | text | Motivo rectificacion |
currencyId | text | Moneda |
exchangeRate | decimal(12,6) | |
totalCurrency | decimal(15,4) | Total en moneda extranjera |
billingAddressId | text | Direccion de facturacion |
shippingAddressId | text | Direccion de envio |
notes | text | Notas del cliente |
internalNotes | text | Notas internas |
fiscalHash | text | Hash de cadena de suministro |
fiscalHashPrev | text | Hash anterior |
fiscalStatus | text | Estado ante Hacienda |
fiscalSentAt | timestamp | Fecha envio SII |
costCenterId | FK → CostCenter | |
profitCenterId | FK → ProfitCenter | |
internalOrderId | FK → InternalOrder |
SalesInvoiceLine
Igual estructura que SalesOrderLine mas:
| baseType | text | Tipo doc base |
| baseId | text | ID doc base |
| baseLine | integer | Linea doc base |
SalesInvoiceLineBatch
Trazabilidad por lote en linea de factura.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
invoiceLineId | FK → SalesInvoiceLine | |
batchNum | text | |
quantity | double |
Documentos de compra
PurchaseOrder
Estructura identica a SalesOrder.
PurchaseOrderLine
Estructura identica a SalesOrderLine.
PurchaseDeliveryNote
Estructura identica a SalesDeliveryNote.
PurchaseDeliveryNoteLine
Estructura identica a SalesDeliveryNoteLine.
PurchaseDeliveryNoteLineBatch
Estructura identica a SalesDeliveryNoteLineBatch.
PurchaseInvoice
Estructura identica a SalesInvoice.
PurchaseInvoiceLine
Estructura identica a SalesInvoiceLine.
PurchaseInvoiceLineBatch
Estructura identica a SalesInvoiceLineBatch.
Nota: Los documentos de compra suman stock (albaranes) mientras que los de venta restan stock.
Recursos Humanos
Department
Departamentos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
parentId | text | Jerarquia |
managerEmployeeId | FK → Employee | |
costCenterId | FK → CostCenter | |
isActive | boolean | |
createdAt | timestamp | |
updatedAt | timestamp |
Position
Puestos de trabajo.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
departmentId | FK → Department | |
description | text | |
isActive | boolean |
Employee
Empleados.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | Numero de empleado |
firstName | text | |
lastName | text | |
dni | text | |
email | text | |
phone | text | |
birthDate | date | |
hireDate | date | Fecha de contratacion |
terminationDate | date | Fecha de baja |
address | jsonb | {street, city, zipCode} |
iban | text | Cuenta bancaria |
departmentId | FK → Department | |
costCenterId | FK → CostCenter | |
profitCenterId | FK → ProfitCenter | |
status | text | active / inactive / terminated |
userId | text | Vinculado a GlobalUser |
kioskPin | text | PIN para fichar (4-8 digitos) |
notes | text | |
createdAt | timestamp | |
updatedAt | timestamp |
Contract
Contratos por empleado.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
positionId | FK → Position | |
type | text | indefinite, temporary, training |
startDate | date | |
endDate | date | |
grossSalary | decimal(15,2) | Salario bruto anual |
paymentsPerYear | integer | Default 12 |
workHoursPerWeek | decimal(5,2) | |
collectiveAgreementId | text | Convenio colectivo |
probationDays | integer | |
noticeDays | integer | |
isPartTime | boolean | |
partTimeRatio | decimal(4,3) | |
documentUrl | text | PDF del contrato |
signedAt | timestamp | |
isActive | boolean |
CollectiveAgreement
Convenios colectivos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
sector | text | |
baseSalary | decimal(15,2) | Salario base de convenio |
vacationDays | integer | Default 22 |
weeklyHours | decimal(5,2) | Default 40 |
isActive | boolean |
Leave
Ausencias (vacaciones, baja medica).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
type | text | Tipo de ausencia |
startDate | date | |
endDate | date | |
days | decimal(5,2) | Dias naturales |
status | text | pending / approved |
Payroll
Nominas.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
contractId | FK → Contract | |
periodYear | integer | |
periodMonth | integer | |
gross | decimal(15,2) | |
irpfAmount | decimal(15,2) | |
ssEmployee | decimal(15,2) | Seguridad Social empleado |
ssEmployer | decimal(15,2) | Seguridad Social empresa |
netPay | decimal(15,2) | Neto a percibir |
status | text | draft / calculated / sent / paid |
approvedAt | timestamp | |
approvedBy | text | |
| UNIQUE | (employeeId, periodYear, periodMonth) |
PayrollConcept
Catalogo de conceptos de nomina.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
kind | text | devengo, deduccion, aportacion_empresa |
taxableIrpf | boolean | |
taxableSs | boolean | |
calculation | text | fixed, percent_of_base, per_hour |
defaultAmount | decimal(15,2) | |
defaultPercent | decimal(6,3) | |
accountId | FK → ChartOfAccount | |
isActive | boolean |
PayrollLine
Lineas de nomina.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
payrollId | FK → Payroll | |
conceptId | FK → PayrollConcept | |
concept | text | Nombre del concepto |
type | text | |
quantity | decimal(12,4) | |
rate | decimal(15,4) | |
baseAmount | decimal(15,2) | |
amount | decimal(15,2) | |
accountId | FK → ChartOfAccount |
ShiftTemplate
Plantillas de turno.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
startTime | text | HH:mm |
endTime | text | HH:mm |
breakMinutes | integer | |
secondStartTime | text | Turno partido |
secondEndTime | text | |
color | text | |
isActive | boolean |
ShiftPattern
Patrones de rotacion ciclica.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
cycleWeeks | integer | Default 1 |
slots | jsonb | Matriz week x dayOfWeek |
isActive | boolean |
ShiftPatternAssignment
Asignacion de patron a empleado.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
patternId | FK → ShiftPattern | |
employeeId | FK → Employee | |
weekOffset | integer | Semana de inicio |
validFrom | date | |
validTo | date |
ShiftAssignment
Asignacion materializada (fila por empleado/dia).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
date | date | |
startAt | timestamp | |
endAt | timestamp | |
breakMinutes | integer | |
shiftTemplateId | FK → ShiftTemplate | |
patternId | FK → ShiftPattern | |
status | text | scheduled / cancelled |
TimeclockEntry
Fichajes.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
kind | text | in / out / break_start / break_end |
at | timestamp | |
source | text | web / kiosk / admin |
latitude | decimal(9,6) | |
longitude | decimal(9,6) | |
taskId | text | Tarea imputada |
TimeclockKiosk
Kioskos fisicos compartidos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
location | text | |
token | text unique | |
isActive | boolean |
IncidentType
Tipos de incidencia laboral.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
requiresSubstitution | boolean | Requiere sustituto |
affectsPayroll | boolean | Afecta a nomina |
consumesLeaveBalance | boolean | Consume saldo vacaciones |
paid | boolean | Pagada |
color | text | |
isActive | boolean |
Incident
Incidencia concreta de un empleado.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
incidentTypeId | FK → IncidentType | |
startAt | timestamp | |
endAt | timestamp | |
status | text | pending / approved / rejected |
documentUrl | text | |
notes | text | |
approvedBy | text | |
approvedAt | timestamp |
Substitution
Sustitucion de turno.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
incidentId | FK → Incident | |
originalEmployeeId | FK → Employee | |
substituteEmployeeId | FK → Employee | |
status | text | proposed / accepted / rejected |
EvaluationCycle
Ciclo de evaluacion (ej: Q1 2026).
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
startDate | date | |
endDate | date | |
status | text | draft / active / closed |
EvaluationCompetency
Competencia evaluable.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
description | text | |
weight | decimal(5,2) | Default 1 |
scaleMax | integer | Default 5 |
isActive | boolean |
EmployeeEvaluation
Evaluacion de un empleado en un ciclo.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
cycleId | FK → EvaluationCycle | |
employeeId | FK → Employee | |
managerId | FK → Employee | |
status | text | pending / self_done / manager_done / closed |
finalScore | decimal(5,2) |
EmployeeEvaluationScore
Puntuacion por competencia.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
evaluationId | FK → EmployeeEvaluation | |
competencyId | FK → EvaluationCompetency | |
scoreSelf | decimal(5,2) | |
scoreManager | decimal(5,2) | |
comments | text |
EmployeeObjective
Objetivos SMART.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
cycleId | FK → EvaluationCycle | |
title | text | |
targetValue | decimal(15,2) | |
achievedValue | decimal(15,2) | |
weight | decimal(5,2) | Default 1 |
status | text | pending / in_progress / achieved / missed |
dueDate | date |
CommissionRule
Reglas de comision.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
scope | text | employee / department / all |
employeeId | FK → Employee | |
departmentId | FK → Department | |
basis | text | net_amount / gross_amount / margin |
kind | text | flat_pct / tiered |
pct | decimal(6,3) | |
tiers | jsonb | Tramos |
isActive | boolean |
CommissionAccrual
Acumulado de comision por documento.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
employeeId | FK → Employee | |
ruleId | FK → CommissionRule | |
periodYear / periodMonth | integer | |
sourceDocType | text | SINV, SO, SDN |
sourceDocId | text | |
base | decimal(15,2) | |
amount | decimal(15,2) | |
status | text | pending / paid / cancelled |
Task
Tareas y planificacion.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
title | text | |
description | text | |
status | text | todo / in_progress / done / cancelled |
priority | text | low / normal / high / urgent |
assigneeId | FK → Employee | |
startDate / dueDate | date | |
estimatedHours | decimal(8,2) | |
actualHours | decimal(8,2) | |
progress | integer | 0-100 |
parentTaskId | text |
TaskDependency
Dependencia entre tareas.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
predecessorId | FK → Task | |
successorId | FK → Task | |
kind | text | finish_to_start |
lagDays | integer |
TaskComment
Comentario en tarea.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
taskId | FK → Task | |
userId | text | |
body | text | |
at | timestamp |
Logistica
Carrier
Transportistas.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
code | text | |
logoUrl | text | |
adapterId | text | null = manual |
isActive | boolean |
CarrierAccount
Cuentas de integracion con transportistas.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
carrierId | FK → Carrier | |
name | text | |
sandbox | boolean | |
credentials | jsonb | Config del adapter |
Vehicle
Vehiculos de la flota.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
plate | text unique | Matricula |
brand | text | |
model | text | |
capacityKg | double | Carga maxima |
capacityM3 | double | Volumen |
status | text | active / maintenance / retired |
defaultDriverEmployeeId | FK → Employee | |
archivedAt | timestamp | Baja logica |
Shipment
Envios.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
deliveryNoteId | text | Albaran origen |
carrier | text | seur, correos, propio |
carrierAccountId | text | |
trackingNumber | text | |
status | text | pending / in_transit / delivered |
preparationStatus | text | draft / picking / packed / dispatched |
reportToken | text unique | Token publico tracking |
destinationAddress | text | |
destinationLat / destinationLng | double | |
recipientName / email / phone | text | |
lastLat / lastLng | double | Ultima posicion |
deliveredAt | timestamp | |
driverName | text | |
driverPhone | text | |
vehiclePlate | text |
ShipmentEvent
Eventos en el envio.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
shipmentId | FK → Shipment | |
kind | text | status_change / incident / note |
status | text | |
description | text |
ShipmentPosition
Posiciones GPS del envio.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
shipmentId | FK → Shipment | |
lat / lng | double | |
speedKmh | double | |
reportedAt | timestamp |
Route
Rutas de reparto.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
plannedDate | date | |
status | text | planned / in_progress / completed |
vehiclePlate | text | Snapshot historico |
vehicleId | text | |
driverEmployeeId | FK → Employee | |
startedAt / completedAt | timestamp |
RouteStop
Paradas de la ruta.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
routeId | FK → Route | |
sequence | integer | Orden |
shipmentId | FK → Shipment | |
address | text | |
lat / lng | double | |
arrivedAt / departedAt | timestamp | |
status | text | |
signatureImage | text | Firma POD |
podNotes | text |
ExternalPlatform
Plataformas logisticas externas.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
address | text | |
lat / lng | double | |
openingHours | text | Ej: “L-V 8-18” |
contactName / phone / email | text | |
archivedAt | timestamp |
StagingArea
Areas de staging/acopio.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
name | text | |
warehouseId | text | |
partnerId | text | Cliente dueño |
platformId | text | Plataforma ajena |
lat / lng | double |
StagingAreaItem
Articulos en un area de staging.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
stagingAreaId | FK → StagingArea | |
itemId | FK → Item | |
expectedQty | double | Nivel objetivo |
Package
Paquetes/cajas preparadas.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text unique | |
deliveryNoteId | text | Albaran origen |
shipmentId | text | |
boxItemId | FK → Item | Tipo de caja |
stagingAreaId | FK → StagingArea | |
status | text | open / sealed / shipped |
weightKg | double | |
pickedAt | timestamp | |
sealedAt | timestamp |
PackageLine
Contenido de un paquete.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
packageId | FK → Package | |
itemId | FK → Item | |
quantity | double | |
sourceLineId | text | Linea de albaran origen |
PickingTask
Tareas de picking.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
docType | text | SDN / PDN |
docId | text | ID del albaran |
docLineId | text | Linea del albaran |
itemId | text | |
warehouseId / zoneId | text | |
requestedQty | double | |
pickedQty | double | |
status | text | pending / partial / done / missing |
shipmentId | text | |
assignedUserId / pickedByUserId | text |
Stock avanzado
TransferNote
Traspasos entre almacenes.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text | |
fromWarehouseId | text | |
toWarehouseId | text | |
date | timestamp | |
status | text | draft / sent / received |
sentAt / receivedAt | timestamp |
TransferNoteLine
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
transferId | FK → TransferNote | |
lineNum | integer | |
itemId | text | |
quantity | double | |
fromZoneId / toZoneId | text | |
batchNum | text |
GoodsReceipt
Entradas de mercancia.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text | |
warehouseId | text | |
type | text | internal / return / adjustment |
status | text | draft / posted |
postedAt | timestamp |
GoodsReceiptLine
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
receiptId | FK → GoodsReceipt | |
lineNum | integer | |
itemId | text | |
quantity | double | |
zoneId | text | |
batchNum | text |
GoodsIssue
Salidas de mercancia.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
code | text | |
warehouseId | text | |
type | text | internal / scrap / adjustment |
status | text | draft / posted |
postedAt | timestamp |
GoodsIssueLine
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
issueId | FK → GoodsIssue | |
lineNum | integer | |
itemId | text | |
quantity | double | |
zoneId | text | |
batchNum | text |
Sistema
AuditLog
Registro inmutable de cambios.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
tenantId | FK → Tenant | |
entityType | text | Item, SalesInvoice, etc. |
entityId | text | |
action | text | CREATE / UPDATE / DELETE |
userId | FK → GlobalUser | |
oldValue | jsonb | Estado anterior |
newValue | jsonb | Estado nuevo |
createdAt | timestamp |
Attachment
Archivos adjuntos.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
entityType | text | sales_invoice, item |
entityId | text | ID del documento |
fileName | text | Nombre original |
mime | text | application/pdf, etc. |
size | bigint | Bytes |
provider | text | local, s3 |
externalId | text | Ruta en storage |
uploadedBy | text | |
deletedAt | timestamp | Soft delete |
Notification
Notificaciones in-app por usuario.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
userId | text | Destinatario |
title | text | |
body | text | |
level | text | info / warn / error / success |
link | text | URL de accion |
readAt | timestamp | null = no leida |
Automation
Automatizaciones.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
tenantId | text | |
name | text | |
enabled | boolean | |
triggerType | text | schedule / event / manual |
triggerConfig | jsonb | |
actionType | text | email / webhook / notification |
actionConfig | jsonb |
AutomationRun
Ejecucion de automatizacion.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
automationId | FK → Automation | |
tenantId | text | |
status | text | |
startedAt / finishedAt | timestamp | |
durationMs | integer | |
errorText | text |
WebhookSubscription
Webhooks salientes.
| Campo | Tipo | Descripcion |
|---|---|---|
id | PK text | |
name | text | |
url | text | Endpoint destino |
events | text[] | Array de eventos |
secret | text | Para firma HMAC |
isActive | boolean |
Relaciones entre tablas
Tenant├── UserTenantMembership → GlobalUser├── TenantPlugin│ └── PluginField / PluginTable├── SystemConfig├── UserModule│ └── PluginTable├── DocumentSeries → AccountingPeriod├── DocumentTemplate├── AccountingPeriod│ └── JournalEntry│ └── JournalEntryLine → ChartOfAccount, CostCenter, ProfitCenter, InternalOrder│ └── SalesInvoice, PurchaseInvoice, SalesOrder, PurchaseOrder│ └── SalesDeliveryNote, PurchaseDeliveryNote├── ChartOfAccount│ └── AccountMapping│ └── DimensionRule├── CostCenter / ProfitCenter / InternalOrder│ └── JournalEntryLine│ └── Employee, Department├── PartnerGroup│ └── BusinessPartner│ └── PartnerAddress│ └── Contact│ └── SalesOrder, PurchaseOrder, SalesInvoice, PurchaseInvoice├── PriceList│ └── ItemPrice → Item├── Category│ └── Item (parentId)├── Item│ ├── ItemBatch / ItemSerial│ ├── ItemAlternativeUom → UnitOfMeasure│ ├── ItemWarehouseStock → Warehouse│ ├── ItemZoneStock → WarehouseZone│ └── SalesOrderLine, PurchaseOrderLine, SalesInvoiceLine, PurchaseInvoiceLine├── Warehouse│ └── WarehouseZone│ └── ItemWarehouseStock, ItemZoneStock│ └── GoodsReceipt, GoodsIssue, TransferNote├── TaxGroup│ └── Item, SalesOrderLine, PurchaseOrderLine, SalesInvoiceLine, PurchaseInvoiceLine├── PaymentMethod│ └── Payment → SalesInvoice / PurchaseInvoice├── PaymentTerm│ └── SalesInvoice, PurchaseInvoice├── Currency│ └── SalesInvoice, PurchaseInvoice, Payment, JournalEntryLine├── DocumentType│ └── SalesInvoice, PurchaseInvoice├── Department│ ├── Employee│ └── Position├── Employee│ ├── Contract → Position, CollectiveAgreement│ ├── Payroll → PayrollLine → PayrollConcept│ ├── ShiftAssignment → ShiftTemplate, ShiftPattern│ ├── TimeclockEntry│ ├── Incident → IncidentType│ ├── Substitution → Incident│ ├── EmployeeEvaluation → EvaluationCycle, EvaluationCompetency│ ├── EmployeeObjective → EvaluationCycle│ ├── CommissionAccrual → CommissionRule│ └── Task├── Carrier│ └── CarrierAccount├── Vehicle│ └── Route (vehicleId, defaultDriverEmployeeId)├── Route│ └── RouteStop → Shipment├── Shipment│ ├── ShipmentEvent│ ├── ShipmentPosition│ └── Package├── StagingArea│ ├── StagingAreaItem → Item│ └── ExternalPlatform (platformId)├── Package│ └── PackageLine → Item│ └── PickingTask├── TransferNote│ └── TransferNoteLine → Item, WarehouseZone├── GoodsReceipt / GoodsIssue│ └── GoodsReceiptLine / GoodsIssueLine → Item, WarehouseZone├── Automation│ └── AutomationRun├── WebhookSubscription├── AuditLog → GlobalUser, Tenant├── Notification → GlobalUser└── Attachment (polimorfico: entityType + entityId)