Ir al contenido

Base de datos

Keirost usa PostgreSQL con esquema multi-tenant:

  • public — usuarios, tenants, plugins, geografía
  • tenant_* — un schema por empresa con todo el negocio

Empresas registradas en el sistema.

Campo Tipo Descripción
id PK text UUID
name text unique Nombre visible
schemaName text unique Nombre del schema PostgreSQL
config text JSON de configuración
createdAt timestamp
updatedAt timestamp

Usuarios globales del sistema.

Campo Tipo Descripción
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

Relación usuario-empresa con rol.

Campo Tipo Descripción
id PK text
userId FK → GlobalUser
tenantId FK → Tenant
role text USER / ADMIN
permissions text JSON de permisos
UNIQUE (userId, tenantId)

Campos personalizados declarados por plugins o UI.

Campo Tipo Descripción
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

Tablas personalizadas declaradas por plugins.

Campo Tipo Descripción
id PK text
pluginId text __user__ para tablas UI
tenantId text null si es global
tableName text Nombre físico
definition text JSON con columnas
label text Etiqueta menu
kind text master / document
iconName text Icono lucide
menuModule text Modulo del menu

Activación de plugins por empresa.

Campo Tipo Descripción
id PK text
tenantId FK → Tenant
pluginId text
isActive boolean
config text JSON de config
UNIQUE (tenantId, pluginId)

Claves de desarrollo para plugins remotos.

Campo Tipo Descripción
id PK text
clientId text unique
clientSecret text
name text Descripción
createdBy FK → GlobalUser
tenantId FK → Tenant
permissions text Scopes del token
isActive boolean
lastUsedAt timestamp

Tokens server-to-server por tenant.

Campo Tipo Descripción
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

Paises. PK: code (ISO 3166-1 alpha-2).

Campo Tipo Descripción
code PK text ES, PT, etc.
name text
nameEn text Nombre en ingles
phonePrefix text +34
currency text EUR
taxIdRegex text Regex validación NIF
taxIdLabel text Etiqueta (NIF/CIF)
postalCodeRegex text

Regiones (comunidades autonomas).

Campo Tipo Descripción
id PK text
countryCode FK → Country
code text
name text
UNIQUE (countryCode, code)

Provincias.

Campo Tipo Descripción
id PK text
countryCode FK → Country
regionId FK → Region nullable
code text
name text
UNIQUE (countryCode, code)

Municipios.

Campo Tipo Descripción
id PK text
countryCode FK → Country
subRegionId FK → SubRegion
code text
name text
UNIQUE (countryCode, code)

Clave-valor de configuración por empresa.

Campo Tipo Descripción
id PK text
key text unique Ej: company_name
value text
description text

Modulos del menu creados desde la UI.

Campo Tipo Descripción
id PK text
tenantId text
label text Nombre visible
iconName text Icono lucide
moduleOrder integer Orden en el menu

Series documentales por tipo y periodo.

Campo Tipo Descripción
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

Plantillas PDF (HTML o canvas).

Campo Tipo Descripción
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 clásico

Tipos de impuesto (IVA, IRPF).

Campo Tipo Descripción
id PK text
code text unique IVA21, IVA10, IRPF19
rate decimal(5,2) Porcentaje

Monedas soportadas.

Campo Tipo Descripción
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

Tipos de documento fiscal configurables.

Campo Tipo Descripción
id PK text
code text
name text
docCategory text Categoría
isRectify boolean Es rectificativa
isActive boolean

Métodos de pago.

Campo Tipo Descripción
id PK text
code text unique transfer, cash, card
name text

Condiciones de pago (30 días, 60 días, etc.).

Campo Tipo Descripción
id PK text
name text
lines jsonb Array de plazos y porcentajes

Cobros y pagos registrados.

Campo Tipo Descripción
id PK text
salesInvoiceId FK → SalesInvoice o purchaseInvoiceId
date date
amount decimal(15,4)
currencyId FK → Currency
paymentMethodId FK → PaymentMethod
reference text Número de transferencia
source text manual, automation

Listas de precios.

Campo Tipo Descripción
id PK text
name text

Precio por artículo y lista.

Campo Tipo Descripción
id PK text
priceListId FK → PriceList
itemId FK → Item
price decimal(12,4)
UNIQUE (priceListId, itemId)

Periodos fiscales (ejercicios).

Campo Tipo Descripción
id PK text
code text unique
name text
startDate timestamp
endDate timestamp
status text O abierto / C cerrado

Plan contable.

Campo Tipo Descripción
id PK text
code text unique
name text
type text asset, liability, equity, income, expense
parentId text Jerarquía
isAnalytical boolean Requiere dimensión analítica
isActive boolean

Centros de coste.

Campo Tipo Descripción
id PK text
code text unique
name text
parentId text Jerarquía
managerEmployeeId FK → Employee
isActive boolean

Centros de beneficio.

Campo Tipo Descripción
id PK text
code text unique
name text
parentId text Jerarquía
managerEmployeeId FK → Employee
isActive boolean

Proyectos / ordenes internas / WBS.

Campo Tipo Descripción
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

Asientos contables (cabecera).

Campo Tipo Descripción
id PK text
number integer Número 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 reversión
postedAt timestamp

Líneas de asiento (debe/haber).

Campo Tipo Descripción
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

Mapeo de cuentas para asientos automáticos.

Campo Tipo Descripción
id PK text
kind text sales_revenue, customer_receivable, payroll_gross, etc.
key text default o override por partner/tax
accountId FK → ChartOfAccount

Reglas de dimensión por cuenta.

Campo Tipo Descripción
id PK text
accountId FK → ChartOfAccount UNIQUE
requiresCostCenter boolean
requiresProfitCenter boolean
requiresInternalOrder boolean

Grupos de socios (clientes, proveedores).

Campo Tipo Descripción
id PK text
code text unique CLI, PRV, MAY
name text
codePrefix text Prefijo de numeración
isCustomer boolean
isVendor boolean

Clientes y proveedores.

Campo Tipo Descripción
id PK text
code text unique Auto-generado
name text Razon social
nif text unique nullable Índice único 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

Direcciones de socios (facturación/envio).

Campo Tipo Descripción
id PK text
partnerId FK → BusinessPartner
name text
street text
city text
zipCode text
countryCode text
type text B facturación / S envío
isDefault boolean

Personas de contacto del socio.

Campo Tipo Descripción
id PK text
partnerId FK → BusinessPartner
name text
role text Cargo
email text
phone text
mobile text
isMain boolean Contacto principal

Categorías de artículos.

Campo Tipo Descripción
id PK text
name text
codePrefix text Prefijo de código
parentId FK → Category Jerarquía

Artículos / productos / servicios.

Campo Tipo Descripción
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 mínimo
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

Lotes de artículos.

Campo Tipo Descripción
id PK text
batchNum text Número de lote
itemId FK → Item
quantity double
expiryDate timestamp

Series de artículos.

Campo Tipo Descripción
id PK text
serialNum text unique Número de serie
itemId FK → Item
status text A activo / I inactivo

Unidades de medida.

Campo Tipo Descripción
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

Conversiones de unidad por artículo.

Campo Tipo Descripción
id PK text
itemId FK → Item
uomId FK → UnitOfMeasure
factor decimal(12,4) Ej: 12 (1 caja = 12 uds)

Almacenes.

Campo Tipo Descripción
id PK text
name text
location text
isDefault boolean
createdAt timestamp
updatedAt timestamp

Zonas dentro de un almacén.

Campo Tipo Descripción
id PK text
name text
description text
warehouseId FK → Warehouse

Stock por artículo y almacén.

Campo Tipo Descripción
itemId FK → Item PK (compuesto)
warehouseId FK → Warehouse PK (compuesto)
stock double
updatedAt timestamp

Stock por artículo, almacén y zona.

Campo Tipo Descripción
itemId FK → Item PK (compuesto)
warehouseId FK → Warehouse PK (compuesto)
zoneId FK → WarehouseZone PK (compuesto)
stock double
updatedAt timestamp

Campo Tipo Descripción
id PK text
seriesId FK → DocumentSeries
docNum integer Número 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
Campo Tipo Descripción
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) % retención
withholdingAmount decimal(15,4)
costCenterId FK → CostCenter
profitCenterId FK → ProfitCenter
internalOrderId FK → InternalOrder
pluginData jsonb

Igual estructura que SalesOrder mas: | orderId | FK → SalesOrder | Pedido origen |

Igual estructura que SalesOrderLine mas: | baseLine | integer | Línea del documento base |

Trazabilidad por lote en línea de albaran.

Campo Tipo Descripción
id PK text
deliveryLineId FK → SalesDeliveryNoteLine
batchNum text
quantity double

Extiende SalesOrder con campos fiscales:

Campo Tipo Descripción
isLocked boolean Bloqueada al asentar
lockedAt timestamp
documentTypeId text Tipo fiscal
dueDate date Vencimiento
supplyDate date Fecha de operación
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 rectificación
currencyId text Moneda
exchangeRate decimal(12,6)
totalCurrency decimal(15,4) Total en moneda extranjera
billingAddressId text Dirección de facturación
shippingAddressId text Dirección de envío
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 envío SII
costCenterId FK → CostCenter
profitCenterId FK → ProfitCenter
internalOrderId FK → InternalOrder

Igual estructura que SalesOrderLine mas: | baseType | text | Tipo doc base | | baseId | text | ID doc base | | baseLine | integer | Línea doc base |

Trazabilidad por lote en línea de factura.

Campo Tipo Descripción
id PK text
invoiceLineId FK → SalesInvoiceLine
batchNum text
quantity double

Estructura idéntica a SalesOrder.

Estructura idéntica a SalesOrderLine.

Estructura idéntica a SalesDeliveryNote.

Estructura idéntica a SalesDeliveryNoteLine.

Estructura idéntica a SalesDeliveryNoteLineBatch.

Estructura idéntica a SalesInvoice.

Estructura idéntica a SalesInvoiceLine.

Estructura idéntica a SalesInvoiceLineBatch.

Nota: Los documentos de compra suman stock (albaranes) mientras que los de venta restan stock.


Departamentos.

Campo Tipo Descripción
id PK text
code text unique
name text
parentId text Jerarquía
managerEmployeeId FK → Employee
costCenterId FK → CostCenter
isActive boolean
createdAt timestamp
updatedAt timestamp

Puestos de trabajo.

Campo Tipo Descripción
id PK text
code text unique
name text
departmentId FK → Department
description text
isActive boolean

Empleados.

Campo Tipo Descripción
id PK text
code text unique Número de empleado
firstName text
lastName text
dni text
email text
phone text
birthDate date
hireDate date Fecha de contratación
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

Contratos por empleado.

Campo Tipo Descripción
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

Convenios colectivos.

Campo Tipo Descripción
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

Ausencias (vacaciones, baja médica).

Campo Tipo Descripción
id PK text
employeeId FK → Employee
type text Tipo de ausencia
startDate date
endDate date
days decimal(5,2) Días naturales
status text pending / approved

Nóminas.

Campo Tipo Descripción
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)

Catalogo de conceptos de nómina.

Campo Tipo Descripción
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

Líneas de nómina.

Campo Tipo Descripción
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

Plantillas de turno.

Campo Tipo Descripción
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

Patrones de rotación cíclica.

Campo Tipo Descripción
id PK text
name text
cycleWeeks integer Default 1
slots jsonb Matriz week x dayOfWeek
isActive boolean

Asignación de patron a empleado.

Campo Tipo Descripción
id PK text
patternId FK → ShiftPattern
employeeId FK → Employee
weekOffset integer Semana de inicio
validFrom date
validTo date

Asignación materializada (fila por empleado/dia).

Campo Tipo Descripción
id PK text
employeeId FK → Employee
date date
startAt timestamp
endAt timestamp
breakMinutes integer
shiftTemplateId FK → ShiftTemplate
patternId FK → ShiftPattern
status text scheduled / cancelled

Fichajes.

Campo Tipo Descripción
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

Kioskos fisicos compartidos.

Campo Tipo Descripción
id PK text
name text
location text
token text unique
isActive boolean

Tipos de incidencia laboral.

Campo Tipo Descripción
id PK text
code text unique
name text
requiresSubstitution boolean Requiere sustituto
affectsPayroll boolean Afecta a nómina
consumesLeaveBalance boolean Consume saldo vacaciones
paid boolean Pagada
color text
isActive boolean

Incidencia concreta de un empleado.

Campo Tipo Descripción
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

Sustitución de turno.

Campo Tipo Descripción
id PK text
incidentId FK → Incident
originalEmployeeId FK → Employee
substituteEmployeeId FK → Employee
status text proposed / accepted / rejected

Ciclo de evaluación (ej: Q1 2026).

Campo Tipo Descripción
id PK text
name text
startDate date
endDate date
status text draft / active / closed

Competencia evaluable.

Campo Tipo Descripción
id PK text
code text unique
name text
description text
weight decimal(5,2) Default 1
scaleMax integer Default 5
isActive boolean

Evaluación de un empleado en un ciclo.

Campo Tipo Descripción
id PK text
cycleId FK → EvaluationCycle
employeeId FK → Employee
managerId FK → Employee
status text pending / self_done / manager_done / closed
finalScore decimal(5,2)

Puntuación por competencia.

Campo Tipo Descripción
id PK text
evaluationId FK → EmployeeEvaluation
competencyId FK → EvaluationCompetency
scoreSelf decimal(5,2)
scoreManager decimal(5,2)
comments text

Objetivos SMART.

Campo Tipo Descripción
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

Reglas de comisión.

Campo Tipo Descripción
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

Acumulado de comisión por documento.

Campo Tipo Descripción
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

Tareas y planificación.

Campo Tipo Descripción
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

Dependencia entre tareas.

Campo Tipo Descripción
id PK text
predecessorId FK → Task
successorId FK → Task
kind text finish_to_start
lagDays integer

Comentario en tarea.

Campo Tipo Descripción
id PK text
taskId FK → Task
userId text
body text
at timestamp

Transportistas.

Campo Tipo Descripción
id PK text
name text
code text
logoUrl text
adapterId text null = manual
isActive boolean

Cuentas de integración con transportistas.

Campo Tipo Descripción
id PK text
carrierId FK → Carrier
name text
sandbox boolean
credentials jsonb Config del adapter

Vehículos de la flota.

Campo Tipo Descripción
id PK text
code text unique
plate text unique Matricula
brand text
model text
capacityKg double Carga máxima
capacityM3 double Volumen
status text active / maintenance / retired
defaultDriverEmployeeId FK → Employee
archivedAt timestamp Baja lógica

Envíos.

Campo Tipo Descripción
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 Última posición
deliveredAt timestamp
driverName text
driverPhone text
vehiclePlate text

Eventos en el envío.

Campo Tipo Descripción
id PK text
shipmentId FK → Shipment
kind text status_change / incident / note
status text
description text

Posiciones GPS del envío.

Campo Tipo Descripción
id PK text
shipmentId FK → Shipment
lat / lng double
speedKmh double
reportedAt timestamp

Rutas de reparto.

Campo Tipo Descripción
id PK text
code text unique
name text
plannedDate date
status text planned / in_progress / completed
vehiclePlate text Snapshot histórico
vehicleId text
driverEmployeeId FK → Employee
startedAt / completedAt timestamp

Paradas de la ruta.

Campo Tipo Descripción
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

Plataformas logísticas externas.

Campo Tipo Descripción
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

Áreas de staging/acopio.

Campo Tipo Descripción
id PK text
code text unique
name text
warehouseId text
partnerId text Cliente dueño
platformId text Plataforma ajena
lat / lng double

Artículos en un área de staging.

Campo Tipo Descripción
id PK text
stagingAreaId FK → StagingArea
itemId FK → Item
expectedQty double Nivel objetivo

Paquetes/cajas preparadas.

Campo Tipo Descripción
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

Contenido de un paquete.

Campo Tipo Descripción
id PK text
packageId FK → Package
itemId FK → Item
quantity double
sourceLineId text Línea de albaran origen

Tareas de picking.

Campo Tipo Descripción
id PK text
docType text SDN / PDN
docId text ID del albaran
docLineId text Línea del albaran
itemId text
warehouseId / zoneId text
requestedQty double
pickedQty double
status text pending / partial / done / missing
shipmentId text
assignedUserId / pickedByUserId text

Traspasos entre almacenes.

Campo Tipo Descripción
id PK text
code text
fromWarehouseId text
toWarehouseId text
date timestamp
status text draft / sent / received
sentAt / receivedAt timestamp
Campo Tipo Descripción
id PK text
transferId FK → TransferNote
lineNum integer
itemId text
quantity double
fromZoneId / toZoneId text
batchNum text

Entradas de mercancía.

Campo Tipo Descripción
id PK text
code text
warehouseId text
type text internal / return / adjustment
status text draft / posted
postedAt timestamp
Campo Tipo Descripción
id PK text
receiptId FK → GoodsReceipt
lineNum integer
itemId text
quantity double
zoneId text
batchNum text

Salidas de mercancía.

Campo Tipo Descripción
id PK text
code text
warehouseId text
type text internal / scrap / adjustment
status text draft / posted
postedAt timestamp
Campo Tipo Descripción
id PK text
issueId FK → GoodsIssue
lineNum integer
itemId text
quantity double
zoneId text
batchNum text

Registro inmutable de cambios.

Campo Tipo Descripción
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

Archivos adjuntos.

Campo Tipo Descripción
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

Notificaciones in-app por usuario.

Campo Tipo Descripción
id PK text
userId text Destinatario
title text
body text
level text info / warn / error / success
link text URL de acción
readAt timestamp null = no leida

Automatizaciones.

Campo Tipo Descripción
id PK text
tenantId text
name text
enabled boolean
triggerType text schedule / event / manual
triggerConfig jsonb
actionType text email / webhook / notification
actionConfig jsonb

Ejecución de automatización.

Campo Tipo Descripción
id PK text
automationId FK → Automation
tenantId text
status text
startedAt / finishedAt timestamp
durationMs integer
errorText text

Webhooks salientes.

Campo Tipo Descripción
id PK text
name text
url text Endpoint destino
events text[] Array de eventos
secret text Para firma HMAC
isActive boolean

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)