Skip to content

Contratos entre Módulos (MODULE_CONTRACTS.md) ​

Estado: Contrato arquitectónico normativo para ninaku-app-api.

Este documento define las reglas estrictas de colaboración entre módulos de negocio dentro del monolito modular de Ninaku. Complementa a ARCHITECTURE.md y consolida la especificación definitiva para las fronteras entre módulos en tiempo de compilación.

El objetivo es preservar una propiedad inmutable de los datos y hechos de negocio, manteniendo la colaboración de forma explícita, fuertemente tipada, comprobable y comprensible. Ninaku es una sola aplicación desplegable por defecto; los límites entre módulos no implican llamadas HTTP internas ni una base de datos independiente por módulo.


1. Regla Principal ​

Un módulo de negocio puede exponer sus capacidades funcionales únicamente a través de contratos públicos explícitos bajo su carpeta contracts/. Ningún módulo tiene permitido acceder a repositorios internos, consultas SQL, servicios de infraestructura o manejadores de aplicación de otro módulo.

Cada hecho de negocio tiene un solo módulo propietario. La colaboración entre módulos transfiere información o solicita acciones, pero nunca transfiere la propiedad del dato.

ts
// ❌ INCORRECTO: Violación de fronteras (acceso directo a repositorio ajeno)
class ConfirmSaleUseCase {
  constructor(
    private readonly inventoryRepository: InventoryRepository,
    private readonly paymentRepository: PaymentRepository,
  ) {}
}

// ✅ PREFERIDO: Colaboración explícita mediante Contratos Públicos
class ConfirmSaleUseCase {
  constructor(
    private readonly inventory: InventoryContract,
    private readonly payments: PaymentsContract,
  ) {}
}

En este ejemplo, Sales solicita a Inventory que ejecute una capacidad de reserva. Sales nunca escribe ni muta directamente el estado de Inventory.


2. Disposición Interna de un Módulo ​

Un módulo de negocio evoluciona hacia la siguiente estructura cuando sus responsabilidades realmente existen:

text
src/modules/inventory/
├── domain/                  <-- Reglas de negocio puras, agregados y eventos de dominio
├── application/             <-- Casos de uso, orquestación y puertos internos
├── infrastructure/          <-- Adaptadores de persistencia, proveedores y servicios
├── presentation/            <-- Controladores HTTP, DTOs y catálogo de fallos públicos
├── contracts/               <-- SUPERFICIE PÚBLICA IN-PROCESS DEL MÓDULO
└── inventory.module.ts      <-- Módulo NestJS que declara providers y exports

La carpeta contracts/ representa la superficie pública que otros módulos tienen permitido consumir. Todo lo demás (domain/, application/, infrastructure/, presentation/) es privado e interno del módulo.

  • Módulos pequeños: Pueden mantener un directorio de contratos plano:
    text
    contracts/
    ├── inventory.contract.ts
    └── inventory.contract.types.ts
  • Módulos grandes: Pueden categorizar sus archivos de contrato:
    text
    contracts/
    ├── commands/
    ├── queries/
    ├── results/
    ├── events/
    └── inventory.contract.ts

Nota sobre errores HTTP: El catálogo de fallos públicos (PublicFailure) no vive en contracts/. Los códigos de error públicos son consumidos por clientes HTTP externos, no por otros módulos de NestJS. Por ende, residen en presentation/failures/.

Un contrato publica decisiones y códigos de negocio (por ejemplo OperationDecision, el valor de la negativa y el error OperationRefusedError), nunca su traducción HTTP. El módulo que consume una decisión la traduce a PublicFailure en su propia capa presentation/, en su propio límite HTTP. La traducción de referencia de las negativas de autorización de operación (operationRefusalFailure y OPERATION_REFUSAL_FAILURE: 403 authorization.scope_unavailable, 403 platform.capability_not_entitled, 422 authorization.outlet_not_operational, 422 authorization.place_not_operational, 422 authorization.vertical_inactive) vive en src/modules/platform/presentation/failures/operation-refusal-failure.ts, y hoy solo la usa el fixture de prueba test/fixtures/operation-authorization/; catalog traduce la suya en src/modules/catalog/presentation/failures/to-public-catalog-failure.ts, donde scope_unavailable responde 403 authorization.scope_unavailable, capability_not_entitled responde 403 platform.capability_not_entitled y place_not_operational responde 422 authorization.place_not_operational; cualquier otra negativa responde igual que la denegación simple catalog.action_forbidden. place_not_operational se traduce desde la tajada K6 porque el catálogo ya tiene operaciones ancladas en una unidad de negocio (platform.authorize_operation_at): fijar el modo del surtido o listar artículos en una unidad inactiva es un rechazo de estado sobre un lugar que el llamador sí puede ver, no una falta de permiso, y se responde como en el resto de la plataforma.


3. Contrato vs. Puerto ​

Los términos Contrato (Contract) y Puerto (Port) no son intercambiables en la arquitectura de Ninaku Core.

A. Contrato Público de Módulo (Contract) ​

Un Contrato describe lo que un módulo ofrece a otros módulos de Ninaku.

text
Sales Application Use Case
    ↓ (consume)
PaymentsContract (Clase Abstracta bajo src/modules/payments/contracts/)
    ↓ (implementado por)
PaymentsApplicationService
ts
// src/modules/payments/contracts/payments.contract.ts
export abstract class PaymentsContract {
  abstract authorize(
    input: AuthorizePaymentInput,
  ): Promise<AuthorizePaymentResult>;
}

B. Puerto de Aplicación / Dominio (Port) ​

Un Puerto describe una dependencia que el propio módulo requiere de la infraestructura técnica o de un proveedor externo.

text
Payments Application
    ↓ (requiere)
PaymentGatewayPort (Interfaz bajo src/modules/payments/application/ports/)
    ↓ (implementado por)
DatafastAdapter (Servicio bajo src/modules/payments/infrastructure/)
ts
// src/modules/payments/application/ports/payment-gateway.port.ts
export interface PaymentGatewayPort {
  authorize(
    input: GatewayAuthorizationInput,
  ): Promise<GatewayAuthorizationResult>;
}

Regla nemotécnica:

  • Contrato = Lo que el módulo OFRECE hacia afuera (contracts/).
  • Puerto = Lo que el módulo NECESITA desde adentro (application/ports/).

4. Modos de Colaboración Permitidos ​

Ninaku utiliza tres modos principales de colaboración en proceso. Resuelven problemas distintos y no se deben colapsar en un bus genérico de mensajería.

4.1 Contrato Síncrono en Proceso ​

Se utiliza cuando el módulo llamador necesita el resultado inmediato para completar su caso de uso.

text
Confirm Sale Use Case
    ↓
InventoryContract.reserveStock(...)
    ↓
Inventory Application
  • La ejecución se realiza dentro del mismo proceso de NestJS (sin llamadas HTTP internas).
  • Cuando la invariante de negocio exige atomicidad entre varios propietarios, la llamada puede participar en la misma transacción de PostgreSQL compartiendo un objeto opaco TransactionContext provisto por Foundation.

4.2 Contrato de Lectura (Read Contract) ​

Se utiliza cuando un módulo o un compositor de consultas de pantalla necesita información perteneciente a otro módulo.

text
POS Workspace Query Composer
   ├── CatalogReadContract
   ├── PricingReadContract
   ├── InventoryReadContract
   └── CustomerReadContract
  • Los contratos de lectura retornan DTOs de proyección orientados a tareas.
  • No exponen entidades del ORM, firmas de repositorios ni SQL builders.

4.3 Evento Durable / Outbox ​

Se utiliza para consecuencias que no necesitan completarse en forma síncrona con el caso de uso iniciador, o que cruzan un límite externo/recuperable.

text
Sales Transaction
    ├── Actualiza estado propiedad de Sales
    └── Inserta evento de integración SaleConfirmed en la tabla outbox
             ↓ COMMIT (misma transacción de PostgreSQL)
      Worker de despacho (servicio Railway separado)
      reclama el lote con FOR UPDATE SKIP LOCKED + lease
             ↓
      Procesadores de eventos interesados (Notifications, Analytics, etc.)
  • Las llamadas a redes o servicios externos nunca se ejecutan dentro de la transacción SQL de PostgreSQL, ni dentro del proceso de la API. La fila de outbox se inserta en la misma transacción que el cambio de negocio; un worker separado (no BullMQ, no Redis) la reclama de PostgreSQL con FOR UPDATE SKIP LOCKED y un lease, reintenta con backoff acotado y deja dead letters cuando agota los reintentos — diseño completo en DECISIONS.md D26 y OUTBOX_USE_CASES.md.

4.4 Función SQL de Lectura Publicada (excepción normativa) ​

Una lectura caliente de una sola sentencia no puede partirse en una llamada a un contrato sin perder su única instantánea: el ETag y el cuerpo de la lectura del punto de venta, la búsqueda, el escaneo, resolve y admit de CatalogSellableContract salen de la misma sentencia. Solo esas lecturas pueden llamar desde su SQL a una función de lectura que el módulo propietario publica para eso, nunca a sus tablas; todo lo demás usa el contrato TypeScript.

  • La función la escribe el propietario en su propia migración, es STABLE y SECURITY INVOKER (la seguridad por fila de sus tablas se aplica a quien la llama), fija search_path, recibe la organización como primer argumento y filtra por ella, se revoca de PUBLIC y se concede solo a ninaku_runtime (también en database/access/runtime_grants.sql), y tiene su script de contratos. Las funciones de escritura de la ruta de suministro y de la venta son la única excepción a SECURITY INVOKER: siguen la frontera de escritura de más abajo.

  • Una fila de otra organización responde igual que una desconocida, también si se la nombra con su propia organización.

  • Funciones publicadas hoy (revisión 102, migración 0092): organization.outlet_operating_context(p_organization_id uuid, p_outlet_id uuid), que responde outlet_id, outlet_status, site_local_date (la fecha del sitio: now() en su zona horaria), business_unit_id (la unidad que opera el outlet en su fecha de negocio, organization.outlet_business_date, que es la fecha del sitio solo mientras el corte es 0 (since revision 179, migration 0154; before it was the unit of site_local_date), o NULL), structure_version y, desde la revisión 117 (migración 0107, rebanada S1), site_timezone (la zona horaria del sitio del outlet, al final de las columnas: las anteriores no cambian de nombre, tipo ni orden), o ninguna fila; y organization.business_unit_is_operable(p_organization_id uuid, p_business_unit_id uuid), verdadera solo para una unidad active de esa organización. organization.effective_business_unit ya seguía esta regla. Prueba: database/tests/contracts/organization-published-reads-contracts.ts. Desde la revisión 189 (migración 0164): organization.outlet_group_exists(p_organization_id uuid, p_outlet_group_id uuid) es verdadera solo para un grupo de esa organización (Settings la usa para responder 404 a lectura y escritura de un grupo desconocido o ajeno), y la estructura que un miembro con alcance puede leer la deciden organization.outlet_visible(p_permission_codes varchar[], p_outlet_id uuid), organization.site_visible(p_permission_codes varchar[], p_site_id uuid) y organization.visible_structure(p_permission_codes varchar[]) (filas kind, id de outlets, sitios, marcas, unidades y entidades legales dentro del alcance del miembro del contexto, por identity.effective_permission_history y identity.effective_permission_at; solo la usan las lecturas de organization). Prueba: database/tests/contracts/organization-structure-scope-contracts.ts.

  • Desde la rebanada K10b las usa catalog: la lista y la búsqueda del punto de venta, el escaneo, resolve y admit preguntan (SELECT organization.business_unit_is_operable(...)) como subconsulta escalar (PostgreSQL la resuelve una vez por sentencia cuando sus argumentos son parámetros) y leen el outlet, la unidad que lo opera hoy, la versión de la estructura y, desde la rebanada S1, la zona horaria del sitio (con ella evalúan las ventanas horarias de las cartas del outlet sin leer tablas de organization) de organization.outlet_operating_context, sin sentencias nuevas. El bloqueo compartido de la unidad en admit pasa por OrganizationContextContract.shareBusinessUnit, y las lecturas que no son calientes usan los contratos: businessUnitStates en las puertas de lectura, el surtido y el filtro listed de la lista de artículos, y activeBusinessUnits con BusinessUnitVerticalsContract.activeVerticals en el aviso de verticales del espacio de trabajo. npm run lint:sql-ownership vigila la regla (sección 10).

  • Rutas de suministro de stock (revisiones 159 a 170, migraciones 0133 a 0144): la misma excepción cubre las funciones que Inventory y Production publican para la ruta Ventas a stock. Las de lectura son SECURITY INVOKER y corren bajo el contexto de tenant de la transacción de quien llama; las de escritura son SECURITY DEFINER, propiedad de ninaku_domain_writer (frontera de escritura, más abajo); todas reciben la organización como primer argumento, devuelven tablas tipadas (nunca jsonb) y las que escriben son idempotentes por clave; las siete primeras y las dos últimas de este grupo (sales.take_order y organization.default_sales_channel, migración 0144) están registradas en tooling/repository/sql-ownership-rules.ts para que el SQL de src/ pueda llamarlas.

    FunciónPropietarioTipoFirma
    inventory.reserve_stockInventoryescritura(organización, clave, líneas inventory.stock_reservation_request_line[], needed_on, expires_at, motivo); la misma clave y las mismas líneas devuelven la misma reserva
    inventory.consume_reservationInventoryescritura(organización, reserva, clave, tipo de movimiento, fecha de negocio, líneas inventory.reservation_consumption_request[], motivo, referencia); un movimiento, una salida de libro por lote y un consumo igual a la salida completa
    inventory.release_reservationInventoryescritura(organización, reserva, estado, motivo); repetirla sobre una reserva terminada no cambia nada
    production.supply_order_sourceProductionescritura(organización, línea de pedido, clave, selección de combo, opción de modificador); resuelve la ruta, crea el plan directo y reserva; responde reserved, untracked, recipe_not_handled o unrouted (una variante sin ruta activa se vende sin descontar stock: no crea plan ni reserva y no lanza)
    production.settle_order_supplyProductionescritura(organización, pedido, clave, tipo de movimiento, fecha de negocio); consume las reservas de los planes directos del pedido; las líneas sin plan (unrouted, untracked) no hacen nada
    production.cancel_order_supplyProductionescritura(organización, pedido, línea, motivo); libera lo no consumido e informa lo consumido sin registrar nada; las líneas sin plan no hacen nada
    production.supply_feasible_unitsProductionlectura STABLE(organización, variante, outlet, unidad de negocio, canal, fecha, entidad legal); unidades enteras prometibles; untracked, recipe y unrouted informan su tipo sin límite (NULL)
    inventory.resolve_supply_routeInventorylectura STABLE(organización, variante, outlet, unidad de negocio, fecha); la ruta más específica gana: outlet, unidad de negocio y organización
    inventory.set_supply_routeInventoryescritura(organización, variante, tipo de lugar, lugar, tipo de ruta, desde, hasta, artículos[], cantidades[], receta); SECURITY DEFINER, requiere inventory.supply_routes.manage en el lugar y serializa por variante; reemplaza la ruta del mismo lugar y periodo (recorta la que empezó antes, cierra la que no había empezado, rechaza con 23P01 la que continúa después del fin pedido) y es idempotente: la misma ruta ya vigente responde changed = false; responde (route_id, changed, replaced_route_ids)
    inventory.end_supply_routeInventoryescritura(organización, variante, ruta, hasta); termina una ruta desde hasta (hoy en el outlet por omisión) o la cierra si no había empezado; una ruta cerrada o que ya termina antes no cambia nada; responde (changed, route_status, valid_until)
    inventory.list_supply_routesInventorylectura STABLE(organización, variante); las rutas vigentes y programadas de todos los lugares que el miembro puede ver (inventory.supply_routes.view o manage), con sus líneas de stock o su receta
    inventory.variant_supply_summaryInventorylectura STABLE(organización, outlet, variante); la ruta que resuelve una venta en el outlet, su disponibilidad (quantity, unlimited, recipe_not_handled o unrouted), production.supply_feasible_units y, por línea de stock, lo que hay y lo reservable en las ubicaciones que el outlet usa para vender
    inventory.supply_coverageInventorylectura STABLE(organización, outlet); cada variante activa del catálogo con la ruta que resuelve en el outlet (unrouted si ninguna), en un solo conjunto; la autorización la decide quien la llama
    inventory.resolve_issue_locationsInventorylectura STABLE(organización, outlet, unidad de negocio, canal, artículo, tipo de movimiento, fecha, entidad legal); ubicaciones candidatas ordenadas
    production.resolve_recipe_versionProductionlectura STABLE(organización, variante, unidad de negocio, outlet, fecha); firma nueva de la migración 0138: resuelve por la ruta de suministro (ya no por recipe_assignments) y falla con 23503 si una ruta de receta no tiene receta
    sales.take_orderSaleswrite(organization, outlet, idempotency key, currency, lines sales.take_order_line[], optional sales channel, service mode, menu, override approvals jsonb); a line is (variant, quantity, snapshots, options jsonb, bundle_choices jsonb) and carries no price: the function prices the whole cart once, set-based, with pricing.resolve_cart (an unknown or foreign variant, option, combo component, channel, menu or service mode, or price books that mix currencies or tax inclusions or differ from the currency of the outlet, are refused with 22023), freezes per line the list and resolved amounts, the price book entry, the price rule and the source (price_book or price_rule; a variant nobody prices is refused with 22023 and the constraint sales_line_unpriced), stores the chosen options and combo components as order_line_modifier_options and order_line_bundle_selections rows with their charges (the add-on amount of the line calculation is checked against them by the existing consistency trigger, and a combo choice that does not belong to the combo sold, or an option the item does not offer, is refused with 23514), draws the quota pools once with operations.take_capacity after its own order lock (order reference = the first 80 characters of the idempotency key, so a client can ask for the override approval of quota-override:<pool>:<idempotency key> before it sells; the pools that were only warned are kept in sales.orders.oversold_pool_ids; the service mode of the request is stored in sales.orders.service_mode_code, immutable, and an idempotent replay with another one is refused), derives the business date, business unit, legal entity and, when no channel is given, the default channel, numbers the order, supplies each line, closes the order and settles its stock in one transaction; returns one row per line with the order id, number, date, status, total, replayed, the supply outcome, the list, resolved, options, bundle and line amounts, the price source and the oversold pool ids; an exhausted blocking pool refuses with 23514 and the constraint capacity_exceeded (the application answers 409 sales.capacity_exceeded) and a missing or invalid override approval with 42501 and the constraints identity_approval_required or identity_approval_invalid; it requires the sales.orders.take permission of the current membership at the outlet (identity.effective_permission, so a role without it, a scope that does not cover the outlet or a suspended member is refused with 42501, a check the database makes itself because the sale path must not depend on the application layer alone); a closed order is guaranteed at commit by deferred triggers to have at least one line, a supply outcome for every line and no reservation left active on its direct plans, whatever the write path; the same key and request replay the order, a variant with no supply route sells with the outcome unrouted (nothing deducted), a changed request (including other options or combo choices) is refused with 23514 and the replay answers before any pricing or quota work, whatever changed in prices or quotas since, a quantity with more than six decimals is refused with 23514 instead of being rounded, a line priced from a tax-inclusive Price Book is refused with 23514 (the sale does not carve tax, so it sells tax-exclusive Price Books only), an order currency that is not the currency of its outlet is refused with 23514 and the constraint sales_order_currency_mismatch (the application answers 409 sales.currency_mismatch, as it does for price books that mix currencies), the business unit, the legal entity, the number of the order and the scope of the permission are all resolved on the one business date of the sale, so the night of a handover belongs to the assignment of the previous business day and a sale before the first business day of an assignment is refused with 23514 (sales_order_business_unit_context or sales_order_legal_entity_context), each line amount is round(quantity * (resolved price + options + combo adjustments), 6) and the order total is the exact sum of the stored six-decimal line amounts with no rounding amount (decision of the owner: the stored truth keeps six decimals and rounding to the minor unit of the currency belongs to presentation and payment), and insufficient stock aborts the whole sale with 23514 (message Order supply has insufficient stock)
    sales.find_order_replaySalesread inside the write boundary (STABLE, SECURITY DEFINER, owned by ninaku_domain_writer)(organization, outlet, idempotency key, variant ids, quantities); finds the stored order of the key when its lines are exactly the requested variants and quantities and returns its lines (price entry, unit price and snapshots) so sales.take_order can replay it; it requires the tenant and sales.orders.take at the outlet (42501), never sales.orders.read, so a member who may take but not read replays its own sale even after the price list changed
    inventory.receive_stockInventorywrite(organization, idempotency key, lines inventory.stock_receipt_line[], optional business date, reason, reference); it requires the permission inventory.stock.receive (owner, manager and stock keeper) at the outlet of every location of the receipt, or organization-wide for a location of no outlet (42501); the business date is derived on the server by inventory.location_business_date from the location: the business day of its outlet, else the business day of its site with the cutoff of its business unit (organization.site_business_date), and a location with neither a site nor an outlet has no time zone and is refused with 23514 and the constraint inventory_location_business_date_zone (the organization has no default time zone, and the UTC date is never used); a date sent by the client is accepted only within one day of it (23514); a key of more than 160 characters is refused with 23514; a lot-tracked or serialized line follows migrations 0149 and 0150
    organization.outlet_regional_profileOrganizationread STABLE (SECURITY INVOKER)(organization, outlet); the regional profile of an outlet: country_code and timezone of its site and currency_code and locale (the optional override of its site, else the default of the organization), or no row for an unknown outlet or one of another organization. It is the single source of the facts that depend on the country of an outlet: organization.outlet_business_date takes the time zone from the same site, sales.take_order refuses an order whose currency is not the one of its outlet (23514) and a line priced from a book of another currency, and SellItemsUseCase reads it through OrganizationContextContract.outletRegionalProfile
    organization.outlet_business_dateOrganizationread STABLE (SECURITY INVOKER)(organization, outlet, at) (at defaults to now()); the business date of the outlet: the wall clock of the site time zone at that instant minus the setting operations.business_day.cutoff_minutes resolved for the outlet (outlet, then business unit, then organization, then the default of 0), as a date, so a 01:30 sale at an outlet with a 02:00 cutoff belongs to the previous business day; the cutoff is read once, through the business unit that operates the outlet on the calendar date of the site of the instant (the anchor of the rule, so the cutoff never depends on the business date it is computing and the answer is the same whenever it is asked), and the business unit, the legal entity, the status of the outlet and the scope of the permissions (identity.access_scope_covers_outlet) are then resolved on the business date it returns, never on the calendar date; an assignment that starts on the calendar day D therefore serves a sale at 01:30 of D (business date D - 1) only if it also covered D - 1, and that sale is refused otherwise; the cutoff of a business unit that takes the outlet over at midnight governs the night of the handover; the anchor is deliberate and is the simplest deterministic choice: a handover of the outlet from business unit A to business unit B effective on day D with a cutoff of 180 minutes is cut by the setting of B, and the sale at 01:00 of D belongs to business date D - 1 and therefore to A (sales-business-day-handover-contracts.ts, case anchor); on that night organization.outlet_operating_context (so catalog.variant_is_listed_at_outlet, the sellable-items reads and the barcode lookup of Catalog), platform.authorize_operation (the operability of the business unit and its vertical), identity.effective_permission, identity.effective_permission_history, identity.permission_scope_unavailable, identity.role_offerable_at_scope and sales.take_order all answer for A (revision 179, migration 0154; business-day-handover-agreement-contracts.ts); the business date is computed by the caller, only for a business unit or legal entity scope row and never for the other scopes, and handed to identity.access_scope_covers_outlet and identity.access_scope_covers_outlet_history as their ninth parameter, so the scope function never resolves it again; outside the tenant context of the organization (a privileged caller with no context, or the context of another tenant) the cutoff setting cannot be read, because settings.resolve_setting refuses another organization with 42501, so identity.scope_business_date answers the calendar date of the site (read through organization.outlet_regional_profile) and identity.effective_permission ignores the cutoff there (same contracts, case foreign); the subtraction is on the local wall clock, so daylight saving changes never shift it; NULL for an unknown outlet. sales.take_order numbers and dates each order with it and inventory.receive_stock dates a receipt with the same rule. Absolute instants (approval expiry, price validity, occurred_at) stay in UTC and are never converted
    organization.site_business_dateOrganizationread STABLE (SECURITY INVOKER)(organization, site, outlet or NULL, business unit or NULL, at) (at defaults to now()); the one place of the business-date rule: the wall clock of the time zone of the site minus the setting operations.business_day.cutoff_minutes resolved for the outlet, the business unit (given, or the one that operates the outlet on the calendar date of the instant) and the organization, then the default of 0; NULL for an unknown site. organization.outlet_business_date is this function for the site of an outlet, and inventory.location_business_date uses it for a location of a site and without an outlet
    organization.default_sales_channelOrganizationread STABLE(organization); the active default sales channel, or NULL; the sale never takes its channel from the request; an organization that is not active may have none until it is reactivated, and reactivation ensures one (adopting an active pos channel or creating pos)
    operations.take_capacityOperationswrite (SECURITY DEFINER, owned by ninaku_domain_writer)(organization, outlet, order reference, lines operations.capacity_line[], idempotency key, optional approvals jsonb keyed by pool id, service instant); requires sales.orders.take at the outlet; draws the pools of the lines in pool units and answers one row per pool (taken, warned, overridden, unconstrained, replayed) with what remains; only pools with an active rule take the advisory lock of their counter, in a sorted order; a block rule that would be exceeded refuses with SQLSTATE 23514 and constraint capacity_exceeded unless the approval of quota-override:<pool>:<order reference> for operations.quotas.override is passed for that pool (one approval per blocked pool, in the jsonb map); the same key replays and a key of another order is refused with 23505; the caller (sales.take_order) calls it once per sale after its own lock with the sale idempotency key as key, flattens the options into extra lines (line quantity times one) and keeps the pools that only warned on the order; sales.cancel_order, which lives on unmerged branches, must call operations.release_capacity with the same order reference and key Review rules: the order reference is the whole idempotency key; a blocked variant, option or combo component is refused with item_blocked; release_capacity locks the counters like a take and refuses an order that drew at another outlet; quota rules and pool members are written under an idempotency key and an etag.
    operations.release_capacityOperationswrite (SECURITY DEFINER)(organization, outlet, order reference, idempotency key); reverses every draw of the order at the outlet that is not yet reversed and answers how many it reversed; repeating it reverses nothing more
    operations.check_capacityOperationsread STABLE(organization, outlet, lines, service instant); the dry run of take_capacity: per line and pool whether it is allowed, whether it only warns, the limiting rule and what would remain; it draws nothing
    operations.availability_forOperationsread STABLE(organization, selling outlet, fulfilling outlet, instant, variant ids, option ids); per subject state (limited, unlimited, sold_out, blocked), remaining (NULL is no limit), limited_by (quota, stock, block) and supply_kind (recipe and unrouted are unlimited and reported, never computed); a manual 86 wins over quota and stock
    production.recipe_routes_without_recipeProductionlectura STABLE(organización); rutas de receta activas sin receta
    production.direct_plan_requirementProductionlectura STABLE(organización, ruta, cantidad); artículo, cantidad exacta y línea de ruta de cada línea de stock

| production.lock_order_supply_capacities | Production | escritura | (organización, pedido); toma, en orden canónico de (artículo, ubicación), los candados de capacidad de stock que el suministro de las líneas del pedido puede necesitar, para que dos ventas con las líneas en orden opuesto no se bloqueen entre sí; la llama sales.take_order antes de suministrar |

Las otras seis las llaman otras funciones SQL de Inventory y Production dentro de las migraciones y no son una API para otros módulos. Frontera de escritura (revisión 170, migración 0144; la prueba sales-write-boundary-contracts.ts y las matrices runtime-privilege-sale-path-expectations.ts y domain-writer-privilege-expectations.ts, vigiladas por runtime-sale-path-privilege-contracts.ts).

  • Una sola API de escritura. ninaku_runtime no tiene INSERT, UPDATE ni DELETE en ninguna tabla de sales, inventory, production ni pricing (ni INSERT en reference.quantity_unit_uses). Conserva USAGE de los schemas, SELECT donde la API lee y EXECUTE de los puntos de entrada publicados (las siete funciones de escritura de la tabla, inventory.resolve_supply_route, inventory.resolve_issue_locations y production.supply_feasible_units, más los cuatro ayudantes puros que esa lectura INVOKER invoca). Un error o una API comprometida no puede falsificar un movimiento de stock, una línea del libro, una reserva, un número de pedido ni un pedido mal armado: la única forma de escribir es una función que valida el tenant, el permiso y los invariantes de toda la operación.

  • Un solo rol de escritura. ninaku_domain_writer (NOLOGIN, sin BYPASSRLS, no es dueño de ninguna tabla ni pertenece a ningún rol) lo crea database/access/roles.sql; ninaku_migrator es miembro (INHERIT, SET) para poder traspasarle la propiedad de las funciones. Las funciones de escritura publicadas son SECURITY DEFINER, propiedad de ese rol, con SET search_path = pg_catalog, <sus schemas>, identity, pg_temp y SET row_security = on, revocadas de PUBLIC y concedidas solo a ninaku_runtime. Solo los puntos de entrada son DEFINER: los ayudantes que invocan siguen INVOKER y los ejecuta únicamente el escritor.

  • El tenant sigue protegido dentro del DEFINER. El escritor no es dueño de las tablas y no tiene BYPASSRLS, así que cada política le aplica igual que a ninaku_runtime (las políticas dependen del contexto de la transacción, no de current_user); y cada función empieza con identity.assert_tenant_context() y rechaza con 42501 una organización distinta de identity.current_organization_id(), de modo que no sirve para cruzar tenants. created_by_* y los permisos salen del contexto de la transacción (identity.current_identity_id(), identity.current_membership_id()), nunca de current_user. prepare-database.ts falla si el rol deja de ser seguro (NINAKU_DOMAIN_WRITER_UNSAFE).

  • Privilegios del escritor en database/access/domain_writer_grants.sql: los derivó ejecutar los contratos como escritor concediendo cada permission denied y revocando uno a uno para probar que cada concesión es necesaria. Costo asumido: los SELECT ... FOR SHARE de los ayudantes de bloqueo exigen UPDATE de una columna, así que el escritor tiene UPDATE (updated_at) (o la columna inocua que cada tabla ofrece) en las tablas que solo bloquea (organization.*, catalog.items, catalog.item_variants, catalog.catalogs); seguimiento: publicar esos bloqueos como funciones de la propiedad del módulo.

  • Cómo suma un módulo nuevo (pagos, devoluciones, ...) sus funciones a la frontera: (1) la función es SECURITY DEFINER SET search_path = pg_catalog, <schemas>, pg_temp SET row_security = on, su primera sentencia es identity.assert_tenant_context() y rechaza (42501) una organización distinta de la del contexto; (2) se revoca de PUBLIC; (3) en su migración y en el canónico ALTER FUNCTION ... OWNER TO ninaku_domain_writer (con GRANT CREATE ON SCHEMA al rol y REVOKE CREATE después, como en 0144); (4) los privilegios que le faltan al escritor se descubren ejecutando su contrato como escritor y se agregan a domain_writer_grants.sql, probando cada uno necesario; (5) EXECUTE del punto de entrada a ninaku_runtime y fuera del módulo cualquier INSERT, UPDATE o DELETE directo de runtime_grants.sql; (6) las dos matrices de expectativas y los casos de falsificación (42501 como runtime, otro tenant, search_path) en un contrato *-write-boundary-contracts.ts.

  • Lista de precios (revisión 172, migración 0146; pricing-price-list-contracts.ts, pricing-write-boundary-contracts.ts). pricing.replace_price_list(organización, pricing.price_list_entry[]) es la primera función de escritura de Pricing: SECURITY DEFINER, propiedad de ninaku_domain_writer, exige el contexto de tenant y pricing.prices.manage (42501), rechaza con 23514 una lista ausente, un monto ausente, negativo, de 10^13 o más o con más de seis decimales, una variante repetida o fuera del catálogo predeterminado, y reemplaza la lista como un conjunto en una transacción: crea la primera vez el libro default del catálogo predeterminado (moneda de la organización, sin impuestos incluidos), conserva la entrada de la variante cuyo monto no cambia, cierra la de la variante que cambia o sale de la lista (queda como historia) y inserta el precio nuevo con el mismo valid_from. ninaku_runtime solo tiene SELECT en las tablas de precios y EXECUTE de la función; pricing.prices.view es el permiso de lectura de la lista. sales.take_order acepta el price_book_entry_id de esa lista con su monto exacto. Una entrada está vigente en now() (el inicio de la transacción) cuando valid_from <= now() y valid_until es nulo o mayor que now(): la misma regla usan el resolvedor de precios, la lectura de la lista y la validación de take_order, de modo que una venta que empezó antes de un reemplazo sigue con el precio que vio; el resolvedor solo mira el libro default activo y en la moneda pedida (un libro con impuestos incluidos sigue rechazando la venta con 23514), y una variante sin precio vigente se vende a cero por diseño (decisión del dueño, cubierta por price-resolution-race.e2e-spec.ts). Un precio programado para el futuro (valid_from > now()) no lo cierra el reemplazo: el precio nuevo vale hasta esa fecha.

  • Visibilidad de lectura por permiso (revisión 171, migración 0145; sales-order-visibility-contracts.ts). Quien tiene sales.orders.read en un lugar ve los pedidos de los locales de ese lugar y quien no lo tiene no ve nada: identity.visible_outlet_ids(permission_code) (SECURITY INVOKER, STABLE) devuelve el arreglo de locales de la organización donde la membresía actual tiene el permiso con el mismo cálculo que identity.effective_permission (alcance de organización, unidad de negocio, entidad legal, marca, sitio o local), y cada tabla sales.order_* (salvo el contador order_number_sequences) lleva una política RESTRICTIVE FOR SELECT TO ninaku_runtime: sales.orders filtra outlet_id = ANY ((SELECT identity.visible_outlet_ids('sales.orders.read'))::uuid[]) y cada hija hereda la visibilidad de su padre con EXISTS (el plan la resuelve como un semi-join hash sobre un InitPlan). Las políticas por tenant existentes no cambian; la restrictiva solo se suma. Decisión explícita sobre el escritor: ninaku_domain_writer no está en la lista TO de la política, así que lee todo el tenant; es correcto porque cada función DEFINER ya exige el permiso de escritura (sales.orders.take) y el tenant antes de leer, y porque sales.take_order debe poder releer lo que escribió (reintento idempotente) aunque quien vende no tenga read: quien vende sin read obtiene su resultado de take_order y no puede volver a listar el pedido. Una tabla nueva sales.order_* entra con su política en el mismo cambio (el contrato lo vigila).

  • Permisos críticos solo con administración (revisión 171, migración 0145; roles-management-contracts.ts). Quien edita roles personalizados solo puede adjuntar permisos cuyo identity.permissions.risk_level no sea critical: identity.guard_role_change rechaza con 42501 (identity_critical_permission_requires_administration) agregar un permiso crítico a un rol, o reactivar un rol que ya lo contiene, salvo que el miembro del contexto tenga organization.account.manage en toda la organización (identity.effective_permission). Los roles de sistema siguen inmutables para un tenant. Archivar un rol solo lo frena un miembro activo que lo tenga, la guarda corre después del bloqueo de su organización y fuera de un contexto de tenant una edición de roles toma el bloqueo del catálogo en exclusivo desde el inicio. La migración 0145 concede sales.orders.read a todo rol que ya tenga sales.orders.take, sales.order_number_sequences sigue la misma visibilidad por local y identity.visible_outlet_ids conserva el historial de un local desactivado mediante identity.effective_permission_history (la autorización de escritura no cambia). organization.account.manage es el único permiso sembrado como critical (el catálogo de permisos no tiene códigos separados para roles, asignaciones, alcances ni aprobaciones, que lo reutilizan): la migración 0145 lo marca en las bases existentes y el sembrado de los roles de sistema no pasa por la guarda porque ocurre fuera de un contexto de tenant.

  • Aprobación opcional con PIN (revisión 171, migración 0145; identity-approval-contracts.ts e identity-approval-flow-contracts.ts). Una organización puede exigir que una acción de un miembro la apruebe otro miembro que tenga el mismo permiso en ese lugar. Es opcional y está apagada por defecto: identity.approval_settings (sin fila es apagada) es el interruptor de la organización, identity.approval_rules dice para qué permiso se exige y dónde (toda la organización, una unidad de negocio o un local) y identity.approval_required(organización, permiso, local) responde si una acción lo exige. El PIN de un miembro (de cuatro a ocho dígitos, que llega como parámetro de enlace) lo convierte identity.set_member_pin en un hash bcrypt con pgcrypto (crypt y gen_salt('bf')) dentro de la base y nunca sale de ella: el runtime no lee identity.membership_pins y no existe ninguna función que entregue el hash. identity.verify_approver_pin(organización, aprobador, permiso, local, clave de acción, pin) exige primero que approval_required sea verdadero, responde solo true o false (un aprobador sin PIN, sin el permiso en ese local, suspendido o bloqueado, y un PIN equivocado dan la misma respuesta), cuenta los intentos por pareja solicitante y aprobador en identity.approval_pin_checks (cinco fallos bloquean esa pareja quince minutos, así que nadie bloquea a un aprobador para todos) y deja la verificación atada al permiso, el local, la clave de la acción y el solicitante; identity.grant_approval consume esa verificación (una sola vez, en los últimos sesenta segundos) antes de escribir en identity.approvals quién pidió, quién aprobó, el permiso, el local y la clave de la acción. Una aprobación vence (máximo quince minutos), nunca se reescribe ni se borra y se gasta una sola vez: identity.require_approval(organización, permiso, local, clave de acción, aprobación) es el ayudante que llaman por dentro las funciones DEFINER de otros módulos (solo lo ejecuta el escritor; no hay concesión al runtime) y no hace nada si la acción no lo exige, rechaza con 42501 (identity_approval_required) si falta la aprobación y con 42501 (identity_approval_invalid) si no es del solicitante, de esa acción, de ese local, está vencida, ya se gastó o su aprobador perdió el permiso. Las funciones de escritura siguen la lista de la frontera de escritura (propiedad del escritor, search_path fijado, organización del contexto, sin INSERT, UPDATE ni DELETE para el runtime) y se auditan desde la aplicación con las acciones identity.approval.granted, identity.approval_rule.changed, identity.approval_switch.changed e identity.member_pin.set. El PIN llega a la base como parámetro de enlace de identity.set_member_pin y identity.verify_approver_pin: en producción y staging log_statement debe seguir en none y log_parameter_max_length y log_parameter_max_length_on_error en 0, y no se activa auto_explain con parámetros ni pg_stat_statements con valores, porque cualquiera de ellos escribiría el PIN en los logs de PostgreSQL; member-pin.e2e-spec.ts comprueba que el PIN tampoco llega a las respuestas ni a los logs de la aplicación.

  • SECURITY DEFINER sigue siendo la excepción para el resto del código: las puertas de staff, los disparadores de registro, el aprovisionamiento y events.append_tenant_event mantienen su convención; esta frontera solo agrega el rol ninaku_domain_writer para las escrituras de tenant de Sales, Inventory y Production.

  • Scoped settings (revision 173, migrations 0147 and 0148; settings-resolver-contracts.ts and settings-write-boundary-contracts.ts). settings.setting_definitions (global, seeded: code, boolean, integer or choice kind, typed default, integer bounds) and settings.setting_choices define a typed setting; settings.setting_assignments overrides it for an organization, a business unit or an outlet (one row per scope, typed value, tenant row level security). settings.resolve_setting(p_organization_id, p_code, p_outlet_id, p_business_unit_id) is a published STABLE SECURITY INVOKER read, like inventory.resolve_supply_route: it returns exactly one row (value_kind, value_boolean, value_integer, value_choice, scope_level in outlet, business_unit, organization or default, and scope_id), the most specific scope wins, an unknown code fails with 23503 and an organization other than the one of the tenant context with 42501. The caller passes the business unit that operates the outlet (organization.outlet_operating_context). Seeded settings: inventory.negative_stock_mode (prevent, allow; default prevent) and operations.business_day.cutoff_minutes (0 to 1439; default 0). The runtime only reads these tables: the writes are settings.assign_setting(p_organization_id, p_code, p_business_unit_id, p_outlet_id, p_value_boolean, p_value_integer, p_value_choice) (an upsert per scope that returns the assignment id) and settings.clear_setting(p_organization_id, p_code, p_business_unit_id, p_outlet_id) (true when an override existed), both SECURITY DEFINER and owned by ninaku_domain_writer under the write boundary below. They require the permission settings.assignments.manage (seeded for organization_owner and manager): at an outlet scope it is checked at that outlet, at a business unit or organization scope it is checked organization-wide; the table refuses a value of the wrong kind or outside the integer bounds (23514), a choice outside the allowed list (23503), a business unit together with an outlet (23514) and an outlet or business unit of another organization; an unknown code fails with 23503.

  • Regional profile (revision 178, migration 0153; sales-regional-profile-contracts.ts). Every restaurant or outlet can be in another country, so country-dependent facts are resolved per outlet through the regional profile, never per organization: organization.sites.currency_code and locale are nullable overrides (foreign keys to reference.currencies and reference.locales; NULL means the default of the organization, and the structure version moves with any change of a site) and organization.outlet_regional_profile answers them with the country and the time zone. A price list exists per currency: price books are unique per catalog, currency and code, pricing.replace_price_list(organization, entries, currency) replaces the default book of that currency (the default currency of the organization when the currency is omitted; an unknown currency is refused with 23514), GET and PUT /price-list take currency, and the resolver of a sale reads the book of the currency of the outlet. A sale at an outlet whose currency has no price list is refused as unpriced, as is a variant that is not listed. No currency conversion and no mixing of currencies in one order exist. What still depends on the country and is not built (follow-ups): the tax regime and its inheritance (W031), electronic invoicing (G24), number and date formats by locale, the country of the legal entity, an API to write the currency and locale of a site, and currency conversion (FX).

  • Price dimensions and the cart resolver (revisions 191 to 194, migrations 0166 to 0169; pricing-books-contracts.ts, pricing-assignments-contracts.ts, pricing-addon-prices-contracts.ts, pricing-addon-refusals-contracts.ts, pricing-rules-contracts.ts, pricing-rules-updates-contracts.ts, pricing-resolve-cart-contracts.ts, pricing-resolve-cart-addons-contracts.ts). Pricing owns one named price book per list (pricing.create_price_book, update_price_book) and says where it applies (pricing.replace_book_assignments: a place, which is the organization, one outlet group or one outlet, plus an optional sales channel, menu and service mode, a priority, a validity and whether the book is an overlay). Two active assignments cannot tie on place, qualifiers, priority and overlapping time (23P01, price_book_assignments_no_tie_excl). pricing.set_addon_prices sets the modifier option prices (fixed charge, linked variant price, or that price plus a delta) and the combo component adjustments of a book by value, closing what changes. pricing.create_price_rule and update_price_rule keep percentage and override rules over an item, variant or category, scoped by outlet or outlet group, channel, menu, service mode, organization schedule (organization.schedule_is_open, evaluated in the time zone of the outlet) and dates; one rule wins per line and rules never stack. All writers are SECURITY DEFINER, owned by ninaku_domain_writer, need the tenant context and pricing.prices.manage (42501), lock the book or rule (ninaku:pricing:book:v1, ninaku:pricing:rule:v1) and bump a version that REST serves as the strong etag for If-Match; creates are idempotent by code (23505 when the code is reused with other attributes) and a book or rule of another organization is P0002 like an unknown one. pricing.price_book_assignments_read and pricing.price_rules_read are the definer reads, because ninaku_runtime has no SELECT on those tables. pricing.resolve_cart(organization, outlet, channel, service mode, menu, at, lines jsonb) is the read-only (STABLE) function a sale will call: the books that match are ordered by place, qualifier count, priority, latest start and id; the chain runs from the first book down to the first non-overlay book (the default price list of the outlet currency when no base is assigned) and must share currency and tax inclusion (22023 otherwise); each variant takes the price of the first book of the chain that lists it, the winning rule is applied, options and combo components add their charges, and a variant no book prices answers unpriced with zero amounts. Unknown or foreign outlet, variant, option, component, channel, menu or service mode is 22023. It issues a constant number of statements for 1 or 100 lines. pricing.set_prices takes an optional price book (revision 195, migration 0170; pricing-book-prices-contracts.ts): with it the same delta writer prices that book in its own currency, under the lock of the book, and refuses an inactive book or another currency with 23514 and an unknown or foreign book with P0002; REST exposes it as bookId in PATCH /price-list. Business rules not built: fixed-amount deltas, rules stacking, business-unit scope, tax calculation (an external service).

  • Delta price edits (revision 190, migration 0165; pricing-set-prices-contracts.ts, pricing-item-price-matrix-contracts.ts, pricing-set-prices-race-contracts.ts). pricing.set_prices(organization, pricing.price_edit[], removals uuid[], currency) is the second writer of Pricing (SECURITY DEFINER, owned by ninaku_domain_writer; ninaku_runtime only executes it): it needs the tenant context and pricing.prices.manage (42501), takes at most 500 changes, and refuses with 23514 an absent list, a missing amount, an amount outside 0 to 9999999999999.999999 or with more than six decimals, a variant named twice (also as set and remove), a start that is not in the future, an unknown currency, and a variant that is unknown, of another organization or archived (all the same message); nothing is written on a refusal. An unchanged amount keeps its entry; a changed amount closes the effective entry now and opens the new one until the next pending start; a valid_from in the future schedules a price without closing the current one early (the current one ends when the scheduled one starts) and replaying the same schedule changes nothing, while another schedule for a variant that already has one is refused with 23P01; a removal closes the effective price and leaves pending ones alone. It shares the advisory lock of pricing.replace_price_list (organization and currency, taken by the helper pricing.default_price_book, which creates the default book of the currency like the replace does), so a delta and a replace of one currency never overlap. pricing.item_price_matrix(item, currency) is an invoker read that answers, per variant of the item that is not archived, the price in effect, the next scheduled price and its start in one statement; it answers no row for an unknown item or one of another organization. HTTP: PATCH /price-list (pricing.prices.manage; body {currency?, set: [{variantId, price, validFrom?}], remove: [variantId]}; it is idempotent by value, so it takes no Idempotency-Key and no If-Match, like the PUT), GET /price-list/variants/{variantId}/history (pricing.prices.view; keyset by start descending, scheduled versions included, changedBy and changedAt; a variant that is unknown or never priced answers an empty page) and GET /price-list/items/{itemId} (pricing.prices.view; the front composes it with the variants of the catalog, whose matrix does not change; an unknown or foreign item answers the same 403 as a missing permission). The audit action is pricing.price_list.edited, one record with the counts. Not built yet: price dimensions (outlet, channel, mode, schedule), option and combo prices, import and export, bulk percent edits, cancelling a scheduled price, and the health check for unpriced variants.

  • Outlet groups, service modes and the organization-wide helper (revision 180, migration 0155; organization-outlet-groups-contracts.ts, identity-group-scope-contracts.ts, identity-approval-pin-lockout-contracts.ts). reference.service_modes (code, name, status) is a global vocabulary seeded with dine_in, takeaway, pickup and delivery (runtime SELECT only); the order line will carry its mode in a later slice. organization.outlet_groups (id, organization_id, code, name, status) names a set of outlets (active, inactive or archived; the code is unique per organization ignoring case) and organization.outlet_group_members (outlet_group_id, outlet_id, valid_from, valid_until) dates each membership with [valid_from, valid_until): the same outlet cannot be in the same group twice at once (23P01, outlet_group_members_no_overlap_excl), may be in several groups, and a membership is ended by dating valid_until, never moved (23514, org_outlet_group_member_immutable). The runtime reads, inserts and updates both tables under the tenant policy and never deletes; every change bumps the structure version. identity.access_scopes.outlet_group_id is a sixth scope dimension (still one dimension per row, one dimension per assignment, a group named once per assignment): the scope covers an outlet that is a member of an active group on the business date of the outlet (organization.outlet_group_includes(organization, group, outlet, on, active_only), STABLE, SECURITY INVOKER). A group scope is never organization-wide: every "all dimensions empty means organization-wide" test (identity.effective_permission, effective_permission_at, effective_permission_history, has_organization_administrator, the administration transfer and the provisioning check) also requires outlet_group_id IS NULL, identity.access_scope_covers_outlet and access_scope_covers_outlet_history take the group as their ninth argument, and identity.permission_scope_unavailable reports an inactive group as an unavailable scope. A role cannot be given at an inactive group (23514, identity_role_assignment_scope_inactive). Invitations do not carry group scopes yet. identity.has_organization_wide_permission(permission_code) (STABLE, SECURITY INVOKER, runtime EXECUTE) answers for the membership of the tenant context whether it holds the permission through an organization-wide scope (false without a context): the single test a head-office-only operation uses. Approver pins gain membership_pins.failed_attempts and locked_until: identity.verify_approver_pin counts every wrong pin against the approver whoever asks, locks the pin for 15 minutes after 10 and answers false while it is locked (the per-requester lock of 5 stays); a right pin clears the count and identity.set_member_pin clears the count and the lock.

  • Schedules (revision 181, migration 0156; organization-schedules-contracts.ts). organization.schedules (id, organization_id, code, name, status) names a weekly opening pattern (code unique per organization ignoring case; active, inactive or archived) and organization.schedule_windows (schedule_id, window_kind, weekday or on_date, opens_at, closes_at) holds its rows: a recurring row names an ISO weekday (1 to 7), a dated row names a date (not before 2000) and replaces every recurring row of that date; window_kind is hours (both times, never equal; closes_at at or before opens_at crosses midnight and the window belongs to its opening date), all_day (the whole date) or closed (no window opens that date; it does not cut an overnight window that opened the day before). Times are wall-clock times: the schedule has no time zone and is evaluated in the time zone the caller passes (the site of an outlet), so the same schedule works for outlets in different zones. The generated columns day_key and span back two exclusion rules: windows of one schedule never overlap, including the overnight tail into the next day and the wrap from Sunday night to Monday (23P01, schedule_windows_span_excl), and a closed day has no other row (23P01 schedule_windows_closed_day_excl, 23505 schedule_windows_closed_day_uq). Shape violations answer 23514 (schedule_windows_day_chk, _weekday_chk, _date_chk, _kind_chk, _shape_chk). The runtime reads, inserts and updates both tables, deletes windows (a pattern is rewritten by deleting and inserting rows) and never deletes a schedule. Published reads, STABLE and SECURITY INVOKER, organization first, so another organization's schedule answers like an unknown one: organization.schedule_is_open(organization, schedule, at, time_zone) is true while an active schedule has a window open at the wall-clock time of at in time_zone, and organization.schedule_occurrence(organization, schedule, at, time_zone) returns the opening date, starts_at and ends_at of that window as instants (no row while closed). An unknown time zone answers 22023. On a daylight-saving night the wall clock rules: a window from 22:00 to 04:00 is five real hours long on the spring-forward night and seven on the fall-back night, both passes through the repeated hour are open, and a window that opens inside the skipped hour is open from the first instant the clock shows a later time; its starts_at follows the resolution PostgreSQL gives to that wall time.

  • Settings by outlet group, lock below and effective reads (revision 182, migration 0157; settings-group-scope-contracts.ts, settings-lock-below-contracts.ts, settings-effective-contracts.ts). settings.setting_assignments gains outlet_group_id (a third scope dimension: at most one of business unit, outlet and group, 23514 setting_assignments_scope_chk; one row per setting and scope, 23505 setting_assignments_scope_uq), value_location_id and locked_at. Precedence is outlet, then outlet group, then business unit, then organization, then the default. A group applies to an outlet that is a member of an active group on the calendar date of its site; when an outlet belongs to several groups that set the same setting the group whose code sorts first (ignoring case, then id) wins. A business unit or group row can be locked (locked_at is the date of the lock, 23514 setting_assignments_lock_scope_chk for any other scope): a locked row at a level wins over every row of a more specific level that covers the same outlet (a locked business unit row beats groups and outlets, a locked group row beats the outlets of the group) and, when two locks cover an outlet, the broader one wins; the ignored rows stay stored. Writing below a lock is refused at write time by the table trigger (23514, settings_locked_by_parent): an outlet row under a locked business unit of the outlet or a locked group that contains it, a group row whose member outlets sit in a locked business unit; a lock on one setting never affects another. locked_at is set when a lock is turned on and cleared when it is turned off. The setting kind location holds the id of an inventory.locations row (no default): it is assigned to an outlet only (23514 setting_assignments_location_scope) and the location must be active, of the same organization and either of that outlet or shared (no outlet) (23514 setting_assignments_location_unusable); the seeded inventory.default_receiving_location is its first use. Reads: settings.effective_settings(organization, outlet or NULL, business unit or NULL, code or NULL) (STABLE, SECURITY INVOKER, runtime EXECUTE; 42501 for an organization other than the context, 23503 for an unknown code) returns one row per setting (all of them when the code is NULL): definition_id, code, name, value_kind, the integer bounds, the typed value, scope_level (default, organization, business_unit, outlet_group or outlet), scope_id (the origin), assignment_id, locked (the winning row is locked) and overridden_assignment_ids (every row that covers the context and did not win, whether shadowed or ignored by a lock); the business unit of an outlet is derived on the calendar date of its site when it is not given. settings.resolve_setting is now a thin read over it. Writes (SECURITY DEFINER, owned by ninaku_domain_writer): settings.assign_setting(organization, code, business unit, outlet, outlet group, boolean, integer, choice, location, locked) (locked NULL keeps the current lock) and settings.clear_setting(organization, code, business unit, outlet, outlet group) return what they did (created, updated, unchanged, or cleared, absent) and the previous value and lock so the caller records the audit event settings.assignment.set or settings.assignment.cleared (resource kind settings.assignment, registered by this migration) only when something changed. An outlet row needs settings.assignments.manage at that outlet; every other scope (organization, business unit, outlet group) and every lock needs it organization-wide, which identity.has_organization_wide_permission answers (42501, settings_management_denied). The lone Settings entry points the runtime may execute are effective_settings, resolve_setting, assign_setting and clear_setting.

  • Approval thresholds, bound payloads and head office approvals (revision 183, migration 0158; identity-approval-thresholds-contracts.ts, identity-approval-binding-contracts.ts). An approval rule may carry one threshold, threshold_kind (amount, percent or units) with threshold_value (above zero, at most 100 for a percent; both or neither, 23514 approval_rules_threshold_chk, _kind_chk, _value_chk), and may be scoped to an outlet group (outlet_group_id; at most one of business unit, outlet and group, approval_rules_one_scope_chk; one rule per permission and scope, so setting a scope again replaces its threshold). identity.set_approval_rule(organization, permission, business unit, outlet, active, outlet group, threshold kind, threshold value) keeps its first five arguments and the last three default to none. identity.approval_required(organization, permission, outlet, metric kind, metric value) is true when some active rule applies to the outlet (organization-wide, its business unit, the outlet or an active group that contains it on the site date) and either has no threshold or is exceeded: the measure must be of the same kind and strictly above the value, and a missing measure or a measure of another kind fails closed (required). Only the gate passes a measure: identity.require_approval(organization, permission, outlet, action key, approval, payload hash, metric kind, metric value) returns without consuming anything when the action is below every threshold; identity.verify_approver_pin and identity.grant_approval do not know the measure and so treat a thresholded rule as applying. approvals.payload_hash and approval_pin_checks.verified_payload_hash (bytea, a 32 byte SHA-256 digest, 23514 approvals_payload_hash_chk) bind an approval to the payload of its action key: verify_approver_pin(..., payload hash) records it, grant_approval(..., ttl, payload hash) grants only the hash that was verified and stores it, and require_approval spends only an approval whose hash equals the one passed, both absent or both equal. A head office action has no outlet: approvals.outlet_id and the verified outlet may be NULL, only an organization-wide rule applies, and only a member who holds the permission organization-wide can approve it (identity.approver_eligibility), which an approval granted for an outlet never satisfies. identity.can_approve(organization, permission, outlet or NULL) (STABLE, SECURITY DEFINER, owned by ninaku_domain_writer, runtime EXECUTE; 42501 for another organization) tells the member of the context whether they can approve: an active member who holds the permission at the outlet (organization-wide for NULL), has a pin and whose pin is not locked; identity.holds_approval_authority is the shared test. No caller of require_approval exists yet: discounts, refunds, counts and purchase orders wire it in their own slices.

  • Foundation permissions (revision 184, migration 0159; identity-foundation-permissions-contracts.ts). Seven permissions, all standard risk (the rule that organization.account.manage is the only elevated one stays), split the administration that used to need the critical organization-wide organization.account.manage: settings.assignments.view, inventory.locations.view, inventory.locations.manage, organization.structure.view, organization.structure.manage (it also covers sales channels and schedules), identity.team.manage and audit.events.view. Seeds: organization_owner holds all seven; manager holds settings.assignments.view, inventory.locations.view and manage, organization.structure.view and identity.team.manage; stock_keeper holds inventory.locations.view; no other seeded role holds any of them, and organization.account.manage stays critical and owner-only. Like every permission they are checked per place with identity.effective_permission(membership, code, outlet) (organization-wide with a NULL outlet, identity.has_organization_wide_permission for the current member); the routes that still require organization.account.manage (members, roles, invitations, structure writes) move to them when their slice rewires the check.

  • Unlock permissions (revision 200, migration 0175; identity-unlock-permissions-contracts.ts). Seven permissions, all standard risk, seeded in one place for the quota, availability and supply route routes: operations.quotas.manage, operations.quotas.view, operations.quotas.override, operations.availability.block, operations.availability.view, inventory.supply_routes.view and inventory.supply_routes.manage. Seeds: organization_owner and manager hold all seven; stock_keeper holds inventory.supply_routes.view and operations.availability.view; cashier, waiter, bar and sales_associate hold operations.availability.view (the till reads availability); kitchen holds none, because the session context contract keeps it as the role that grants nothing. Selling needs sales.orders.take alone; a sale past an exhausted quota pool needs an approval of operations.quotas.override, which only the owner and the manager hold. Like every permission they are checked per place with identity.effective_permission(membership, code, outlet).

  • Foundation structure extras (revision 185, migration 0160; organization-plan-limits-contracts.ts, organization-plan-limit-concurrency.ts, organization-tax-identifiers-contracts.ts, organization-first-run-contracts.ts, organization-sales-channels-contracts.ts, identity-ownership-grant-contracts.ts). Regional profile of a site: organization.site_regional_profile(organization, site) (STABLE, SECURITY INVOKER) returns country_code, timezone, and the currency and locale of the site (its override, else the default of the organization); organization.outlet_regional_profile now reads it, so the two never drift; the site columns currency_code and locale keep their foreign keys as the only validation. Tax identifiers: organization.legal_entity_tax_identifiers (legal_entity_id, kind, value, country_code, valid_from, valid_until) is configuration only (the tax calculation and e-invoicing are an external service): a kind is lowercase snake case, a value is trimmed and not blank, a country is a reference.countries row, the dates are optional (valid_until after valid_from), one value per entity, kind and country at a time (23P01 legal_entity_tax_identifiers_no_overlap_excl; a row without dates is always in force) and a value is listed once per entity, kind and country ignoring case (23505 legal_entity_tax_identifiers_value_uq); the runtime reads, inserts, updates and deletes them and every change moves the structure version. Plan limits: organization.outlets, organization.sites and organization.business_units are limit definitions (integer counts, no plan value seeded: a plan without a row is unlimited, an override or a plan row sets the ceiling); a deferred constraint trigger on each table counts the active rows of the organization under an advisory lock at commit and refuses the one over the ceiling with 23514 and organization_outlets_plan_limit, organization_sites_plan_limit or organization_business_units_plan_limit; registering or reactivating counts, deactivating or archiving frees the place, and two registrations racing for the last place give one winner. First run: organization.provision_first_run(organization, request id, legal entity code, legal name, incorporation country, brand code, brand name, site code, site name, site country, time zone, currency, locale, outlet code, outlet name, business unit or NULL) (SECURITY DEFINER, owned by ninaku_migrator, runtime EXECUTE) creates in one transaction the legal entity, brand, site (with its regional fields), outlet, the outlet assignments to the legal entity and to the business unit from the day before today on the site (so the cutoff of the first night never leaves the outlet unassigned) and the default sales channel, and records one row in organization.first_run_provisions (legal_entity_id, brand_id, site_id, outlet_id, business_unit_id, replayed); the same request with the same values returns the same ids with replayed true, another request or other values are refused (23514 organization_first_run_done or organization_first_run_replay_mismatch), an organization that already has a legal entity, brand, site or outlet is refused (organization_first_run_not_empty), the business unit must be named when there are several (organization_first_run_business_unit), any failure (unknown country or currency 23503, time zone 22023, a plan limit) rolls everything back, and it needs organization.structure.manage organization-wide (42501, organization_structure_denied). organization.setup_progress(organization) (STABLE, SECURITY INVOKER; 42501 for another organization) counts the active legal entities, brands, sites, outlets, stock locations and catalog assignments. Sales channels: organization.register_sales_channel(organization, code, name, kind) returns the new id of an active channel that is not the default, and organization.update_sales_channel(organization, channel, name or NULL, status or NULL, make default or NULL) answers updated or unchanged, moves the default in one step (the previous default is cleared first) and refuses to deactivate or archive the default (23514 sales_channels_default_active_chk) or to make an inactive channel the default; unknown or foreign channels answer 23503 sales_channel_not_found; both need organization.structure.manage organization-wide and are SECURITY DEFINER owned by ninaku_migrator. Ownership grant: identity.grant_organization_ownership(request id, source assignment, target membership, reason) (runtime EXECUTE, SECURITY DEFINER owned by ninaku_migrator) lets the organization administrator who holds the organization-wide administrator assignment give the same role organization-wide to another active human member while keeping their own: the application checks step-up before calling it, a reason is required, the request id makes it idempotent (platform.identity_administration_requests records operation grant), and the last-administrator guard is untouched; it and identity.transfer_organization_administration are thin wrappers of the internal identity.apply_administration_command. The audit actions organization.first_run.provisioned, organization.sales_channel.registered, organization.sales_channel.updated and identity.ownership.granted are registered for the application layer to record.

  • R1 lane C: group scope readers and REST for the foundations (revision 186, migration 0161; roles-by-vertical-offering-contracts.ts, group-scope-readers.integration-spec.ts, outlet-groups*.e2e-spec.ts, schedules*.e2e-spec.ts, legal-entity-tax-identifiers.e2e-spec.ts, approvals.e2e-spec.ts, approval-settings-thresholds.e2e-spec.ts). Group scope is never organization-wide: every reader that decided "all dimensions empty means organization-wide" now sees the sixth dimension: identity.role_offerable_at_scope takes the group as a ninth argument (default NULL; the old eight-argument form is gone) and offers a vertical role at a group only when an active group holds an outlet whose business unit runs the vertical, the access scope vertical trigger passes outlet_group_id, the member directory and the role assignment reads answer the scope kind outlet_group, GET /memberships/{id}/access lists a group as a place with kind outlet_group, and GET /session/context shows the scope in access.scoped (scopeKind outlet_group, only while the group is active) and reaches the outlets of the group in the workspace on the site date of each outlet. Identity reads the group through the published function organization.outlet_group_is_active(organization, group) (STABLE, SECURITY INVOKER, runtime EXECUTE) and never names the group tables. Invitations still carry no group scope. Role scopes: POST /memberships/{id}/role-assignments and PATCH /role-assignments/{id}/scope accept { "kind": "outlet_group", "id": ... } (no includeDescendants); an unknown, foreign or inactive group is 422 identity.role_assignment_refused alike. Approvals: PUT /approvals/settings now carries outletGroupId and a threshold (kind amount, percent or units, value a decimal string with four decimals) per rule and calls identity.set_approval_rule with all eight arguments, so saving again never resets a threshold; a kept rule whose threshold changed is updated and audited (approval_rule.threshold). POST /approvals verifies the pin of an approver and grants an approval (identity.verify_approver_pin then identity.grant_approval; a wrong pin, an unknown or ineligible approver answer the same 403 identity.approval_denied, and the transaction is committed before the refusal so the count of tries and the lock persist; no active rule is 409 identity.approval_not_required), GET /approvals/can-approve?permission&outletId answers identity.can_approve. Structure routes (outlet groups, schedules, tax identifiers) need organization.structure.manage held organization-wide to write and organization.structure.view to read, and organization.account.manage counts for both; denials of a write are audited as denied with permission_missing, a permitted caller meets 404 organization.structure_not_found for an unknown or foreign id, and If-Match is checked against the structure version on outlet groups and tax identifiers (schedules do not move the structure version, so their writes are serialized by the structure version lock and have no If-Match). GET /outlet-groups (keyset, include=members), POST /outlet-groups, PATCH /outlet-groups/{id} (rename, active or inactive) and PUT /outlet-groups/{id}/members (a membership is an outlet and its validFrom; a membership left out is ended today, or the day after it starts when it starts today or later, never deleted; an overlap is 422 organization.structure_refused); GET /schedules (keyset, include=windows), POST /schedules, PUT /schedules/{id}/windows (replace, openTime and closeTime as wall-clock HH:MM) and GET /schedules/{id}/occurrences?from&to&timeZone (at most 31 days, evaluated with organization.schedule_occurrence at the opening instant of every window); GET /legal-entities/{id} (with taxIdentifiers) and PUT /legal-entities/{id}/tax-identifiers (configuration only, replaced as a set); GET /service-modes (the active shared vocabulary, any member). Migration 0260 registers the audit actions organization.outlet_group.created, .updated and .members_replaced, organization.schedule.created and .windows_replaced and organization.legal_entity.tax_identifiers_replaced.

Reglas de la ruta: la ruta más específica gana (D68), el libro de recetas es global y las recetas se asignan por ruta (D69), las ubicaciones se resuelven por reglas con precedencia documentada (D70), el piso de stock reservado se aplica al confirmar (D71), la ruta directa pasa por los planes de consumo (D72) y los escritores son idempotentes (D73).

4.5 Función SQL de Escritura de Eventos Publicada (excepción normativa) ​

Un módulo que debe anunciar un cambio en la misma transacción que lo hace no escribe las tablas de events: llama a la función que Events publica para eso.

  • events.append_tenant_event(p_producer_module_code, p_event_name, p_contract_version, p_idempotency_key, p_payload) (revisión 124, migración 0114) es SECURITY DEFINER con search_path fijado, exige contexto de tenant, toma la organización del contexto (nunca de un argumento), exige que el tipo de evento pertenezca al módulo productor y tenga una versión de contrato published o deprecated, y escribe el evento, su publicación y su fila de outbox en la transacción de quien llama. Se revoca de PUBLIC y no se concede a ninaku_runtime ni a ninaku_worker: la llama un disparador SECURITY DEFINER del propio productor, de modo que el rol de la API no tiene ningún privilegio sobre el esquema events.
  • El productor declara sus tipos en su propia migración (events.event_types con su owner_module_code y events.event_contract_versions), con el contrato ejecutable de la carga en su módulo.
  • La llama el código SQL del propio productor en su esquema (un disparador SECURITY DEFINER con search_path fijado, como catalog.record_change_feed()), no el TypeScript de src/: npm run lint:sql-ownership sigue vigilando el SQL de src/.
  • Orden de bloqueos: la función toma el contador de publicaciones de la organización. Un productor que ya tenga una fila de versión u otro bloqueo de dominio lo toma después de ellos (Catalog: la fila de versión, luego el contador); quien emita eventos desde otro módulo no puede tomar el contador antes de llamar a CatalogSellableContract.admit (D40).
  • Funciones publicadas hoy: events.append_tenant_event, usada por catalog.record_change_feed() para los nueve tipos catalog.*.changed.

5. Diseño de Contratos Públicos ​

Un contrato público debe:

  • Usar lenguaje e intenciones de negocio, no nombres de tablas SQL.
  • Exponer una cantidad acotada y significativa de operaciones.
  • Utilizar tipos explícitos para entradas (Input), comandos y resultados (Result).
  • Hacer explícito el contexto de tenant (organizationId, businessUnitId) cuando sea necesario.
  • Evitar la fuga de detalles de tecnología de persistencia o SDKs de terceros.
ts
// ✅ PREFERIDO
inventory.reserveStock(input);
payments.authorize(input);
pricing.resolvePrice(input);

// ❌ RECHAZADO
inventory.save(entity);
payments.execute('action', payload);
repository.findAll(table, filters);

6. Lo Que Los Contratos NUNCA Deben Exponer ​

Los siguientes elementos son detalles internos de implementación y tienen prohibido formar parte de la superficie de un contrato público:

  1. Instancias de pg.Pool o pg.PoolClient.
  2. Constructores de consultas SQL (Kysely, Knex) o fragmentos de SQL crudo.
  3. Repositorios de persistencia pertenecientes al módulo.
  4. Entidades o modelos del ORM/base de datos.
  5. Tipos de peticiones/respuestas directos de SDKs de terceros.
  6. Operaciones CRUD genéricas que permitan a otro módulo mutar libremente tablas ajenas.

7. Convención de Composición en NestJS ​

Dado que las interfaces de TypeScript no existen en tiempo de ejecución, un contrato inyectable requiere un token de runtime. Ninaku utiliza clases abstractas como tipo de contrato y token de inyección de dependencias (DI):

ts
// src/modules/inventory/contracts/inventory.contract.ts
export abstract class InventoryContract {
  abstract reserveStock(input: ReserveStockInput): Promise<ReserveStockResult>;
}

El módulo propietario vincula el contrato público con su servicio de aplicación interno:

ts
// src/modules/inventory/inventory.module.ts
@Module({
  providers: [
    InventoryApplicationService,
    {
      provide: InventoryContract,
      useExisting: InventoryApplicationService,
    },
  ],
  exports: [InventoryContract],
})
export class InventoryModule {}

Los módulos consumidores importan InventoryModule e inyectan únicamente la clase abstracta InventoryContract.


8. Regla de Transacciones Compartidas Entre Módulos ​

El caso de uso que inicia la operación es el dueño del límite de la transacción. Cuando la atomicidad exige que varios módulos participen:

text
Application Use Case (Sales)
    ↓
TenantTransactionRunnerService (Foundation)
    ├── SalesContract/Application escribe en tablas de Sales
    ├── InventoryContract/Application escribe en tablas de Inventory
    └── Outbox escribe el evento de integración
    ↓
COMMIT / ROLLBACK

Reglas obligatorias:

  • La transacción la abre y gestiona Foundation mediante TenantTransactionRunnerService.
  • Los módulos participantes reciben un contexto de transacción opaco (TransactionContext).
  • Un contrato público nunca recibe ni expone pg.PoolClient.
  • Un módulo convierte internamente el TransactionContext opaco en una sesión de consulta mediante la función guardián asDatabaseSession(context) dentro de sus propios repositorios en infrastructure/.
  • Los repositorios no crean transacciones anidadas ocultas.
  • Un contrato que responde una negativa como valor en vez de lanzar una excepción aísla la sentencia que puede fallar en un SAVEPOINT propio, vuelve a él (ROLLBACK TO SAVEPOINT y RELEASE SAVEPOINT) cuando atrapa el rechazo y lo libera cuando la sentencia termina bien. Sin el savepoint la transacción queda abortada y la siguiente sentencia del llamador falla con 25P02.
  • Atrapar un error de SQL y seguir sin savepoint no confirma nada: PostgreSQL responde al COMMIT de una transacción abortada con la etiqueta ROLLBACK. TransactionRunnerService lee esa etiqueta y, si no es COMMIT, rechaza la unidad de trabajo con TransactionAbortedError (sin reintentos; la API responde 500 foundation.internal_error, sin detalles de SQL), en lugar de devolver como confirmado un resultado cuyas escrituras se descartaron.

9. Eventos de Dominio vs. Eventos de Integración ​

  • Evento de Dominio: Mensaje interno del módulo que notifica un cambio de estado dentro del mismo límite del agregado. No se expone a otros módulos.
  • Evento de Integración: Mensaje público, durable e inmutable que se emite a través de la tabla outbox para ser consumido por otros módulos o procesos asíncronos.

Los eventos de integración deben ser minimalistas, versionados, serializables en JSON y libres de clases del dominio interno o tipos de drivers de base de datos.


10. Fronteras de Importación y Reglas de Linter R1–R9 ​

El script de verificación estática tooling/repository/check-module-boundaries.ts (ejecutado por npm run lint:module-boundaries y por npm run verify) evalúa y hace cumplir nueve reglas innegociables (R1–R9) en cada compilación:

ReglaRegla EnforzadaQué Prohíbe ConcretamentePor Qué ExisteError Concreto que Evita
R1Un archivo bajo src/modules/<a>/** solo puede importar de src/modules/<b>/** a través de src/modules/<b>/contracts/**.Importar repositorios, entidades, servicios de aplicación o controladores internos de otro módulo.Preserva el aislamiento modular dentro del monolito.Evita que refactorizaciones internas en el módulo B rompan la compilación o lógica del módulo A.
R2Los archivos bajo src/modules/*/{domain,application,contracts,presentation}/** solo pueden importar el TIPO TransactionContext desde foundation/database/transaction-context.ts; no pueden importar pg, database-session.ts, ni los nombres DatabaseSession, asDatabaseSession o TRANSACTION_CONTEXT_BRAND.Importar el driver de PostgreSQL (pg) o funciones de ejecución SQL directa en capas que no sean infrastructure/.Mantiene la abstracción transaccional opaca en el dominio y la aplicación.Evita que casos de uso o controladores ejecuten consultas SQL crudas o administren transacciones directamente.
R3Los archivos bajo src/modules/*/domain/** no pueden importar @nestjs/*, zod, pg, foundation/http/**, foundation/database/** ni foundation/transactions/**.Importar frameworks web, ORMs, librerías de validación o infraestructura dentro del Dominio.Preserva la pureza y portabilidad del Dominio en Clean Architecture / DDD.Evita que las reglas puras de negocio queden acopladas a NestJS o PostgreSQL, imposibilitando tests unitarios puros.
R4Los archivos bajo src/foundation/** no pueden importar src/modules/** ni src/verticals/**.Importar cualquier código de negocio o vertical desde la capa base de infraestructura.foundation/ provee capacidades genéricas y debe ser completamente agnóstico al dominio.Evita acoplamientos circulares donde la infraestructura base depende de módulos comerciales.
R5Un archivo bajo src/verticals/<v>/** solo puede importar de otro dueño (src/modules/<m>/** o src/verticals/<other>/**) únicamente a través de su contracts/**.Que una vertical acceda a capas internas de un módulo o de otra vertical.Garantiza que los productos verticales compongan capacidades públicas estándar.Evita mutaciones directas en tablas de módulos compartidos sin pasar por las validaciones del módulo.
R6TenantTransactionRunnerService, SystemTransactionRunnerService y SystemStatementRunnerService solo se importan desde src/modules/*/application/** y src/verticals/*/application/**.Importar los ejecutores de transacciones desde domain/, presentation/ o infrastructure/.La capa de aplicación es la única responsable de coordinar la unidad de trabajo transaccional.Evita transacciones abiertas desde controladores HTTP o repositorios administrando su propio ciclo de vida.
R7Los archivos bajo src/modules/<m>/{domain,application,contracts,presentation}/** no pueden importar src/modules/<m>/infrastructure/**.Importaciones apuntando hacia capas exteriores de infraestructura dentro del mismo módulo.Aplica el principio de Inversión de Dependencias (Inward Dependency Rule).Evita el acoplamiento rígido de casos de uso a implementaciones técnicas concretas o adaptadores de base de datos.
R8Los archivos bajo src/modules/** no pueden importar src/verticals/**, ni siquiera su contracts/**.Que un módulo de negocio compartido conozca o importe una vertical específica.Los módulos del Core son agnósticos y reutilizables por cualquier vertical.Evita contaminar el Core con condicionales por vertical (ej. if (vertical === 'restaurant')).
R9SystemTransactionRunnerService y SystemStatementRunnerService (una sola sentencia en autocommit, también sin contexto de tenant) solo se importan desde los directorios permitidos explícitamente (SYSTEM_TRANSACTION_RUNNER_ALLOWED_DIRECTORIES).Usar transacciones sin contexto de tenant en flujos ordinarios de la aplicación.Obliga al uso de TenantTransactionRunnerService para proteger el aislamiento RLS por defecto.Evita fugas de aislamiento tenant donde una operación de negocio olvida aplicar el contexto de la organización.

Excepción Permitida en R9 (SYSTEM_TRANSACTION_RUNNER_ALLOWED_DIRECTORIES) ​

SystemTransactionRunnerService y SystemStatementRunnerService ejecutan consultas sin aplicar contexto de tenant (organization_id), por lo que su uso está restringido mediante una lista blanca explícita:

  • src/modules/identity/application: Permitido porque las operaciones de registro inicial de usuario, autenticación de credenciales y búsqueda global de identidades ocurren antes de que exista o se seleccione un contexto de organización activo.
  • src/modules/platform/application: Permitido porque el catálogo público de Planes (SP14) se lee sin sesión ni organización alguna, y porque el super admin de plataforma (SP13, platform.staff_members) administra planes, precios, mercados, suscripciones y el ciclo de vida de organizaciones ajenas sin pertenecer nunca a la organización sobre la que actúa; ninguna de las dos rutas tiene un organization_id propio del que leer contexto de tenant.
  • src/modules/organization/application: Permitido porque el aprovisionamiento autoservicio de una organización (O1, POST /organizations) crea el propio tenant, por lo que ningún contexto de tenant puede existir todavía cuando se ejecuta.

Propiedad del SQL (lint:sql-ownership) ​

tooling/repository/check-sql-ownership.ts (ejecutado por npm run lint:sql-ownership y por npm run verify, centinela NINAKU_SQL_OWNERSHIP_OK) revisa el código de producción de src/modules/<m>/** (nunca *.spec.ts, *.integration-spec.ts ni *.e2e-spec.ts) y falla con archivo:línea, el módulo y el nombre cuando un texto SQL nombra una tabla, vista, función o secuencia de un schema de otro módulo. El dueño de un schema es el módulo del mismo nombre, y solo cuentan los objetos que database/canonical/*.sql crea, así que un código de permiso o de problema con forma schema.nombre no es una referencia. Un texto cuenta como SQL cuando tiene SELECT, INSERT, UPDATE, DELETE, FROM o JOIN, cuando el nombre se llama como función o cuando el texto entero es el nombre; los literales SQL entre comillas simples y el código interpolado con ${...} no se miran.

  • Permitidos para todos (tooling/repository/sql-ownership-rules.ts, cada uno con su razón): el schema compartido reference; las funciones de contexto de tenant identity.current_organization_id e identity.has_active_tenant_context; y las funciones publicadas de la sección 4.4 (organization.outlet_operating_context, organization.business_unit_is_operable, organization.outlet_group_exists). Una función nueva entra a esa lista en el mismo cambio que la publica.
  • Qué cuenta como SQL y cuándo falla en vez de pasar: un texto cuenta como SQL cuando tiene select, insert, update, delete, from o join (en cualquier caso), cuando el nombre sigue a FROM/JOIN/INTO/UPDATE/TABLE, cuando se llama como función o cuando el texto entero es el nombre; los nombres se comparan sin distinguir mayúsculas, entre comillas dobles se toman tal cual, y schema.tabla.columna cuenta por schema.tabla. Si falta database/canonical, src/modules o la línea base, o el SQL canónico no crea ningún objeto, la regla falla con NINAKU_SQL_OWNERSHIP_SETUP_INVALID (código 2) en lugar de pasar. Un código de tres partes cuya última parte es una palabra clave (por ejemplo un código de permiso) o una frase en minúsculas que menciona una tabla puede dar un falso positivo; se corrige con el nombre o con una excepción justificada en sql-ownership-rules.ts, no desactivando la regla.
  • Línea base que solo encoge (tooling/repository/sql-ownership-baseline.json, JSON sin comentarios: archivo → nombre → cuántas veces): las referencias que existían cuando nació la regla. Un nombre nuevo o una vez más falla como referencia no listada; un archivo que nombra menos de lo que la línea base permite también falla, hasta que se baja la entrada, igual que la lista de comentarios SQL.

11. Compatibilidad y Cambios Rompedores ​

Los contratos in-process residen en la misma unidad de despliegue. Si un contrato público necesita un cambio incompatible:

  1. Se refactorizan todas las llamadas en los módulos consumidores dentro de la misma Pull Request.
  2. Se ejecutan las pruebas de integración del sistema.
  3. No se dejan capas de compatibilidad intermedias ni código deprecado dentro del repositorio.

12. Colaboración en Verticales ​

Las verticales (restaurant, retail, hospitality) son consumidoras de módulos del Core compartidos y deben respetar exactamente las mismas reglas de fronteras:

text
src/verticals/restaurant/
    ├── CatalogContract    (de src/modules/catalog/contracts/)
    ├── SalesContract      (de src/modules/sales/contracts/)
    ├── PaymentsContract   (de src/modules/payments/contracts/)
    └── PrintingContract   (de src/modules/printing/contracts/)

Código específico de restaurante (ej. comandas de cocina o asignación de mesas) nunca modifica directamente las tablas SQL de sales o catalog.


13. Antipatrones Rechazados Explícitamente ​

  1. Llamadas HTTP internas: Prohibido realizar peticiones HTTP entre módulos del mismo monolito.
  2. Importar repositorios ajenos: Un módulo nunca inyecta un repositorio de otro módulo.
  3. Exponer clientes SQL: Prohibido exportar pg.PoolClient o instancias de base de datos en contratos.
  4. Bus genérico no tipado: Prohibido usar patrones como eventBus.publish('any_string', payload) para colaboración síncrona ordinaria.
  5. Condicionales por vertical en el Core: Prohibido escribir bifurcaciones de código basadas en la vertical dentro de módulos compartidos.

14. Definición de Hecho (Definition of Done) para una Colaboración entre Módulos ​

Antes de dar por completada una integración entre módulos, se debe verificar:

  1. ¿Se identifica claramente cuál módulo es el propietario único del dato?
  2. ¿La llamada síncrona utiliza un contrato abstracto bajo contracts/?
  3. ¿El contrato expone únicamente DTOs y tipos de negocio sin fugas de persistencia?
  4. Si la operación requiere atomicidad, ¿se utiliza TenantTransactionRunnerService con un TransactionContext opaco?
  5. Si la operación es asíncrona, ¿se utiliza la tabla outbox y un procesador idempotente?
  6. ¿El comando npm run verify (y en particular npm run lint:module-boundaries y npm run lint:sql-ownership) pasa en verde sin violaciones de R1–R9 y sin SQL que nombre objetos de otro módulo?

15. Índice de Contratos Publicados ​

Cada contrato real, una vez implementado, se agrega a esta tabla en el mismo cambio que lo publica.

ContratoMódulo propietarioArchivoConsumidores actuales
PlatformAuditContractauditsrc/modules/audit/contracts/platform-audit.contract.tsidentity (diez transiciones de seguridad de plataforma: cambio y recuperación de contraseña, alta/baja de método de inicio de sesión, bloqueo de cuenta, cierre de sesión y cierre de sesión en todas partes, alta/baja de segundo factor, emisión de códigos de recuperación) y platform (cada comando de staff de platform-admin, ejecutado o rechazado: planes, ofertas, mercados, suscripciones, pagos, capacidades, estado de organizaciones y reemisión del outbox de seguridad)
TenantAuditContractauditsrc/modules/audit/contracts/tenant-audit.contract.tssales (SellItemsUseCase registra sales.order.taken sobre sales.order una vez por pedido tomado, nunca en el replay de la misma clave de idempotencia), organization (perfil, entidades legales, marcas, unidades de negocio, sitios, outlets y cambios de estado de la estructura), identity (invitaciones, asignaciones de roles y control de miembros) y catalog (creación, edición y ciclo de vida de los artículos, y sus negativas, desde la rebanada K2): cada comando de tenant auditado lo consume dentro de su propia transacción de tenant, de modo que el Audit Record (audit.records) es atómico con el cambio. Toma el actor, el recurso objetivo, el resultado y una lista plana de cambios (code, before, after) que se guardan como atributos before/after; un código con aspecto de secreto, hash o token se rechaza
PermissionCheckContractidentitysrc/modules/identity/contracts/permission-check.contract.tsorganization (los comandos y lecturas con permiso exigido, casos O5 al O33), catalog (desde la rebanada K2: la lectura de un artículo con catalog.items.view en toda la organización o con el ancla de una unidad de negocio, y la desactivación y el archivo de un artículo con catalog.items.manage, que nunca dependen del plan) e identity internamente (directorio de miembros, invitaciones, asignaciones de roles y control de miembros); platform reutiliza su tipo PermissionAnchor en OperationAuthorizationContract. Lo consumen dentro de su propia transacción de tenant, de modo que la verificación es atómica con el comando. isGranted responde si una membresía activa tiene un permiso activo mediante un rol activo; sin outletId ni anchor solo lo satisface un alcance de toda la organización. Desde el lote G acepta un ancla (anchor: business_unit, legal_entity, brand, site u outlet) y decide responde granted, denied o scope_unavailable en ese lugar. Un identificador mal formado o un código de permiso vacío o mayor de 120 caracteres responde false sin llegar a SQL
IdentitySessionContractidentitysrc/modules/identity/contracts/identity-session.contract.tsplatform: PlatformElevationGuard (src/modules/platform/presentation/guards/platform-elevation.guard.ts) llama verifyElevation con el token de elevación que presenta el llamador y la sesión autenticada, y responde la negativa de elevación de platform si no se confirma. PlatformModule importa IdentityModule desde src/modules/identity/contracts/identity.module.ts. Solo responde un booleano; no expone la sesión ni el token
SecurityOutboxOperationsContractidentitysrc/modules/identity/contracts/security-outbox-operations.contract.tsplatform: los casos de uso de src/modules/platform/application/security-outbox/ que sirven platform-admin/security-outbox (readBacklog para el atraso por estado, listDeadLetters paginado por keyset con el destino enmascarado y reissueDeadLetter para reemitir un mensaje muerto), cada uno con el callerIdentityId del staff dentro de la transacción del llamador, y la reemisión auditada con PlatformAuditContract. Los errores publicados (security-outbox-message-not-found.error.ts, security-outbox-reissue-refused.error.ts, security-outbox-staff-required.error.ts) viven junto al contrato; platform los traduce a sus Problem Details
OperationAuthorizationContractplatformsrc/modules/platform/contracts/operation-authorization.contract.tscatalog desde la rebanada K2: crear, editar, reactivar y restaurar un artículo exigen catalog.items.manage en toda la organización y la capacidad catalog.items, y catalog traduce la negativa en su propia capa presentation/failures/ (D15: ningún comando de organization exige una capacidad); también lo consume una ruta de prueba. Decide en una sola sentencia (platform.authorize_operation), sin lanzar error dentro de la transacción de tenant, si el miembro del contexto puede hacer una operación: tenant_context_missing, permission_missing, scope_unavailable, capability_not_entitled, outlet_not_operational, vertical_inactive o allowed, en ese orden. Con un ancla (anchor, autorización en un lugar) decide con platform.authorize_operation_at: un ancla de outlet responde igual que platform.authorize_operation; en una unidad de negocio, entidad legal, marca o sitio se omite el paso del outlet y responde place_not_operational si el lugar no está activo. src/modules/platform/contracts/operation-refusal.ts solo publica OperationRefusedError; la traducción HTTP de la negativa es del módulo consumidor, y la de referencia (operationRefusalFailure, que usa la denegación simple del consumidor para permission_missing y tenant_context_missing) vive en src/modules/platform/presentation/failures/operation-refusal-failure.ts. PlatformModule se importa desde src/modules/platform/contracts/platform.module.ts
CatalogSellableContractcatalogsrc/modules/catalog/contracts/catalog-sellable.contract.tssales (SellItemsUseCase de POST /outlets/{outletId}/sales llama admit al final de su transacción, después de comprobar sales.orders.take, y con su instantánea arma las líneas de sales.take_order); lo consumirá además pricing (configuración sobre lo vendible). También lo consume el módulo de prueba test/fixtures/catalog-sellable/, que ve únicamente el contrato. CatalogModule se importa desde src/modules/catalog/contracts/catalog.module.ts. resolve responde, sin bloquear nada, un veredicto por variante pedida (como máximo 100, sin repetidas) en el orden pedido, con la versión del catálogo leída en la misma sentencia y una instantánea de la variante (nombres y códigos del artículo y la variante, SKU, unidad y política de cantidad, y sus ofertas efectivas con sus opciones disponibles, la unidad de venta de la variante destino de cada opción y sus opciones preseleccionadas). admit recibe líneas (como máximo 100), cada una con su variante, su cantidad y sus selecciones { optionId, quantity } (como máximo 100 por línea, una opción una sola vez, cantidad entera de 1 a 999); juzga la cantidad de la línea contra la política de venta de la variante, la cantidad de cada opción contra su máximo efectivo y el mínimo y el máximo de cada grupo sobre la suma de las unidades, igual que el esquema de ventas. resolve y admit responden las ofertas efectivas de cada variante (itemModifierGroupId, modifierGroupId, source item o variant, mínimo y máximo), resueltas con una sola regla: la oferta activa de la variante reemplaza a la del artículo, la inactiva de la variante excluye el grupo y la ausencia hereda; la venta guarda la oferta que admit devolvió. Una opción de tipo text (K14c) lleva textMaxLength y puede llevar prefix, printsOnReceipt: false y printsOnKitchenTicket: false (campos opcionales que solo aparecen cuando difieren del valor por defecto); la selección de una opción text lleva text, que admit normaliza a NFC y juzga (no vacío, sin NUL ni caracteres de control, de 1 a textMaxLength caracteres y 500 como máximo, con cantidad 1; como máximo 10 selecciones con texto por línea, contando las de los componentes de un combo) y devuelve normalizado en la selección admitida, o rechaza con text_required, text_not_allowed, text_invalid o text_too_long (y too_many_texts antes de cualquier bloqueo); Ventas debe agregar la rama text a su comprobación de tipos y una columna para el valor antes de consumir opciones de texto. La oferta retirada de la variante también hereda, y una oferta retirada del artículo no se ofrece; una oferta del artículo suspendida (inactive) que la variante hereda y que exige un mínimo deja a esa variante sin poder configurarse. La vendibilidad es por variante: un grupo exigido sin opciones disponibles, o cuyas opciones disponibles no alcanzan su mínimo en unidades (la suma de sus cantidades máximas, la misma aritmética del esquema de ventas), deja fuera solo a esa variante (required_modifier_unsatisfiable), y las demás variantes del artículo siguen vendibles. Cuando aplica la oferta de la variante, source es variant e itemModifierGroupId es el de esa oferta. El punto de venta, la búsqueda, el escaneo, resolve y admit usan el mismo fragmento SQL. Ambos métodos aceptan además un outletId opcional (K16): con él, un artículo que ese punto de venta oculta (catalog.outlet_hidden_items) se juzga igual que uno que la unidad no lista (not_listed, también para el componente de un combo), y un outletId que no existe en la organización, que está mal formado o que la unidad de negocio dada no opera hoy (en la fecha local de su sitio, organization.outlet_operating_context) se refiere en la misma sentencia con outlet_not_operated_by_unit (una unidad inexistente si está mal formado), así que nunca se juzga el surtido de la unidad a ciegas; sin outletId el contrato juzga a nivel de unidad, un modo documentado para quien aún no conoce el punto de venta, y los consumidores existentes no cambian. X13 cerrada por la migración 0090: el esquema de ventas trata la oferta inactiva de la variante como exclusión del grupo, igual que admit, así que una línea de una variante excluida no exige el mínimo del artículo. Las ofertas de variante las escribe PUT /catalog/items/{itemId}/variants/{variantId}/modifier-groups (K9g): optedOut escribe la oferta inactiva de la variante, y la ruta del artículo suspende su oferta con suspended. admit responde por línea su posición (lineIndex), la instantánea, la cantidad y cada oferta efectiva con el nombre del grupo, las selecciones que la línea le hizo (modifierOptionId, nombre, tipo, cantidad, variante destino y su unidad de venta, lo que guarda una línea de venta), las preseleccionadas disponibles que la línea quitó (removedDefaults) y las que eligió con menos cantidad (reducedDefaults). Desde la rebanada B2 una línea puede llevar además bundleSelections (opcional): por grupo de un combo { bundleGroupId, choices }, y cada elección { choiceId, quantity, selections?, bundleSelections? } con la cantidad de veces que el cliente la tomó (entero de 1 a 999, el selection_count de ventas), los modificadores de ese componente y los grupos de un combo dentro del combo (hasta 3 niveles y 100 componentes por línea). admit juzga que el grupo y la elección existan y estén activos en ese combo, el mínimo y el máximo del grupo sobre la suma de las cantidades, el tope propio de cada elección, cada componente con la misma regla de lo vendible que una línea y sus modificadores contra sus propias ofertas efectivas; un grupo que la línea omite recibe sus preseleccionadas disponibles (appliedByDefault) y uno enviado sin una preseleccionada la nombra en removedDefaults. La línea admitida responde bundleGroups (solo si el artículo tiene un grupo activo: una línea sin combo responde exactamente lo mismo que antes) con cada grupo activo, sus elecciones con su instantánea, quantity, quantityPerSelection y sus ofertas admitidas, lo que guarda sales.order_line_bundle_selections, sin precio. Cada nivel de componentes suma una sentencia, sea cual sea el número de grupos. Las ofertas nunca se borran ni cambian de identidad: editar sus reglas u orden conserva el UUID, quitar un grupo la retira (retired) y volver a ofrecerlo la revive con el mismo UUID; conservar el UUID no congela las reglas históricas, que cada consumidor guarda en su propia instantánea. Comparte primero la fila catalog.catalog_versions de la organización y luego la fila de la unidad de negocio (FOR SHARE), antes de leer: un bloqueo compartido no hace fila detrás de un FOR UPDATE en espera, así que una venta nunca espera a un comando del catálogo; al revés, un comando del catálogo de la organización espera hasta que no quede ninguna admisión abierta y, si las ventas se solapan sin pausa, falla al vencer DATABASE_STATEMENT_TIMEOUT_MS; toda actualización de la fila de esa unidad (desactivarla, renombrarla) también espera, y dos admisiones no se esperan entre sí. Por eso el consumidor llama a admit al final de su transacción y confirma de inmediato. Rechaza todo o nada con CatalogNotSellableError (contracts/catalog-sellable.errors.ts), que lleva cada negativa por línea en un dominio cerrado (unknown, business_unit_unavailable, outlet_not_operated_by_unit, item_archived, item_inactive, variant_archived, variant_inactive, assortment_none, not_listed, required_modifier_unsatisfiable, bundle_group_unsatisfiable (también como motivo de resolve: un combo con un grupo obligatorio suspendido o cuyas elecciones disponibles no alcanzan su mínimo; admit lo explica por grupo con su path), quantity_out_of_policy, option_not_offered, option_unavailable, option_quantity_above_maximum, selection_below_minimum, selection_above_maximum y, dentro de un combo, bundle_group_not_offered, bundle_group_unavailable, bundle_group_unsatisfiable, bundle_choice_not_offered, bundle_choice_unavailable, bundle_choice_above_maximum, bundle_selection_below_minimum, bundle_selection_above_maximum, bundle_too_deep, bundle_components_above_limit); una negativa dentro de un combo es un BundleAdmissionRefusal que agrega path (por ejemplo lines[0].bundleSelections[1].choices[0]), bundleGroupId, choiceId y detail, un texto que dice cómo corregirla. Una entrada vacía, excesiva, repetida, con una cantidad inválida (invalid_quantity), con demasiados componentes (too_many_components) o demasiado anidada (too_deep) lanza CatalogSellableRequestInvalidError antes de cualquier SQL. Ambos métodos corren en la transacción de tenant del llamador, con la misma regla de lo vendible que las lecturas del punto de venta, no verifican ningún permiso (el comando consumidor autoriza el suyo), no escriben nada y no registran auditoría; una variante o una unidad de otra organización responde igual que una desconocida. El consumidor traduce CatalogNotSellableError a su propio código público en su capa presentation/failures/. El consumidor no muestra la instantánea de un veredicto rechazado (artículo archivado, inactivo o no listado: nombres, SKU, opciones) a un usuario que no tenga un permiso de lectura del catálogo
PriceResolutionContractpricingsrc/modules/pricing/contracts/price-resolution.contract.tspricing (POST /pricing/resolve). Sales no longer calls it: sales.take_order prices the sale inside the database with pricing.resolve_cart, and the sales repository asks pricing.resolve_cart which bundle group each chosen component belongs to before the catalog admits a combo. resolveCart(context, organizationId, input) expone pricing.resolve_cart en TypeScript: por línea devuelve lineNo, variantId, quantity, unpriced, currency, taxInclusion, listAmount, resolvedAmount, priceBookId, priceBookCode, priceBookEntryId, priceRuleId, priceRuleCode, priceSource (price_book, price_rule o unpriced), optionsAmount, bundleAmount, unitAmount, lineAmount, options y bundleChoices (cada componente con su bundleGroupId), todo en cadenas decimales.
OrganizationContextContractorganizationsrc/modules/organization/contracts/organization-context.contract.tscatalog desde la rebanada K10b, a través de CatalogBusinessUnits (src/modules/catalog/application/catalog-business-units.ts): businessUnitStates responde si una unidad existe en las puertas de lectura del catálogo, el estado de la unidad que entra al ETag del surtido y si la unidad del filtro listed de la lista de artículos opera; activeBusinessUnits lista las unidades activas para el aviso de verticales del espacio de trabajo (WorkspaceVerticals); shareBusinessUnit toma la fila de la unidad en admit. También lo consume el módulo de prueba test/support/published-reads-consumer.ts; los dos importan OrganizationModule desde src/modules/organization/contracts/organization.module.ts. activeBusinessUnits (desde K10b) responde id, nombre y estado de las unidades activas de la organización del contexto, ordenadas por id; businessUnitStates responde id, nombre y estado de las unidades nombradas de la organización del contexto, ordenadas por id, sin las desconocidas ni las de otra organización; outletOperatingContext responde el outlet, su estado, la fecha de su sitio, la unidad que lo opera en esa fecha (o null) y la versión de la estructura, leídos con organization.outlet_operating_context, o null; shareBusinessUnit toma la fila de la unidad con FOR SHARE hasta el fin de la transacción y responde si existe en la organización. Un id mal formado responde como uno desconocido sin llegar a SQL. Corre en la transacción de tenant del llamador, no verifica permisos, no escribe nada y no audita
BusinessUnitVerticalsContractplatformsrc/modules/platform/contracts/business-unit-verticals.contract.tscatalog desde la rebanada K10b: WorkspaceVerticals (src/modules/catalog/application/reads/workspace-verticals.ts) le pasa las unidades activas que responde OrganizationContextContract.activeBusinessUnits para decidir el aviso units_with_different_verticals del espacio de trabajo; organization desde la rebanada K10c: ChangeBusinessUnitVerticalUseCase llama activate y deactivate dentro de su transacción de tenant, junto al Audit Record, y ya no nombra tablas de platform; desde la revisión 109 (D1) también RegisterBusinessUnitUseCase llama activate por cada código de verticalCodes de POST /business-units, después de bloquear la unidad recién insertada y en la misma transacción del alta, y traduce unavailable al mismo 422 · organization.vertical_unavailable. activate y deactivate responden { outcome, previousStatus }: outcome es changed, unchanged, unavailable (vertical desconocida, no activa en el catálogo o rechazada por la base) o last_active_vertical (la última vertical activa de la organización entre sus unidades operables), y previousStatus es el estado anterior (null si no había fila); un rechazo viaja como resultado, no como excepción, y organization lo traduce a sus Problem Details. Cuando la base rechaza la escritura (la vertical se retiró o la unidad dejó de estar activa después de la lectura del catálogo), el repositorio aísla el INSERT o el UPDATE en el savepoint platform_business_unit_vertical_write y vuelve a él, así que la transacción del llamador sigue usable después de unavailable y confirma lo que escribió antes; cada activación que escribe suma dos sentencias (SAVEPOINT y RELEASE SAVEPOINT, más ROLLBACK TO SAVEPOINT cuando hay rechazo) y desactivar no suma ninguna. Precondición del llamador: activate y deactivate no serializan por sí solos dos cambios simultáneos del mismo par; el llamador tiene que sostener el lock de la fila de la unidad de negocio (en organization, BusinessUnitRepositoryPort.lock) en la misma transacción antes de llamarlos, y por eso la lectura del estado previo y la decisión de insertar o actualizar no se pisan. Toda sentencia nombra la organización del contexto de forma explícita. activeVerticals responde los pares unidad y vertical activos de las unidades nombradas de la organización del contexto, ordenados por unidad y código; una unidad sin verticales activas, desconocida o de otra organización no aparece, y un id mal formado no llega a SQL
AssetUsageContractassetssrc/modules/assets/contracts/asset-usage.contract.tscatalog desde las rebanadas A5b y A5c: SetItemImagesUseCase y SetManyItemImagesUseCase (src/modules/catalog/application/items/, a través de attachable-images.ts) lo llaman solo con los ids que la lista agrega, después de bloquear catalog_versions y el artículo (o los artículos en orden de id), y traducen AssetNotAttachableError a 422 · catalog.image_not_attachable con un meta.errors[] por artículo y asset; CatalogModule importa AssetsModule. AssetsModule se importa desde src/modules/assets/contracts/assets-contracts.module.ts. assertAttachable corre en la transacción de tenant del llamador y bloquea FOR SHARE, en orden de id y en una sola sentencia, los assets pedidos, así que un archivo concurrente (que toma el asset FOR UPDATE) y la vinculación se serializan; el consumidor lo llama después de bloquear sus propias filas (catalog_versions y el artículo). Los ids repetidos cuentan una sola vez, en su primera posición. Responde { assetId, imageRef } de cada asset vinculable en el orden de los ids pedidos (no en el orden del bloqueo) o rechaza todo con AssetNotAttachableError (contracts/asset-contract.errors.ts), que lleva una negativa por id pedido: not_found (desconocido o de otra organización, que RLS vuelve idénticos), purging, archived, not_ready, wrong_media_kind, wrong_access_class. No verifica permisos, no escribe ni audita; el consumidor traduce el error a su propio código público. No expone llaves, buckets, proveedores ni ids de variantes
AssetDeliveryContractassetssrc/modules/assets/contracts/asset-delivery.contract.tscatalog desde la rebanada A5b: ItemRepository (src/modules/catalog/infrastructure/items/item-reads.ts) describe en una sola llamada (en tandas de 2.000 ids si hiciera falta) las imágenes de los artículos que lee o bloquea, para las URLs de C3 y de cada respuesta de artículo; desde la rebanada A6, ReadWhatAnOutletSellsUseCase (src/modules/catalog/application/till/, a través de sellable-images.ts) lo llama una sola vez por respuesta de C17 y por página de C19, solo cuando algún artículo o variante listado tiene imagen principal, para el imageRef y aiGenerated del punto de venta, y suma fingerprint() a la ETag de C17 y tileUrlTemplate() a meta.media (ambas sin SQL, así que el 304 no lee assets). describe lee, en la transacción del llamador, en una sola sentencia por clave primaria y como máximo 2.000 ids (más lanza AssetDeliveryRequestTooLargeError antes de cualquier SQL), un mapa por asset encontrado con status, imageRef (<token>/p<perfil>), aiGenerated y las URLs públicas de las renditions pedidas; solo un asset ready y public tiene imageRef y URLs, los demás las tienen en null, y un asset archivado sigue resolviendo. tileUrlTemplate() da la plantilla https://<medios>/a/{imageRef}/tile.webp y fingerprint() la huella de entrega (8 hex de SHA-256 de ASSETS_PUBLIC_BASE_URL y la lista de perfiles) que el consumidor agrega a sus ETags. Sin ASSETS_PUBLIC_BASE_URL configurada, las URLs y la plantilla son null. No expone llaves, buckets, proveedores ni ids de variantes

Dos puertos técnicos transversales viven en src/foundation/ y no son contratos de módulo: SessionAuthenticator (src/foundation/auth/session-authenticator.ts) y TenantContextResolver (src/foundation/tenancy/tenant-context-resolver.ts). Los implementa identity (AuthenticateCallerUseCase y ResolveTenantContextUseCase) y los exporta desde IdentityModule; los consumen los guards SessionGuard y TenantContextGuard de foundation, que usan identity, platform y organization en lugar de definir cada uno el suyo. TenantContextResolver resuelve la membresía activa de una identidad en una organización o rechaza con TenantContextRejectedError.

16. Modelo Mental Práctico ​

text
Lo que mi módulo OFRECE a otros        → src/modules/<m>/contracts/
Lo que mi módulo NECESITA externamente  → src/modules/<m>/application/ports/
Cómo lo implemento técnicamente        → src/modules/<m>/infrastructure/
Cómo la API HTTP me alcanza            → src/modules/<m>/presentation/
Cómo protejo las reglas de negocio     → src/modules/<m>/domain/ + application/

Application Foundation in progress. Tracked in issue #13.