Operations for commercial promotions (PostgreSQL command model + CouchDB projection).
/v1/backend/promotion/promotions
| Header | Type | Description |
|---|---|---|
Authorization |
string |
Bearer <token> |
x-app-stage |
string |
Tenant stage |
x-app-uid |
string |
User UUID |
Queries promotions matching the specified company, status, and calendar month or custom date range.
GET /v1/backend/promotion/promotions?companyId=8&month=2026-10&filterMode=month
| Parameter | Type | Required | Description |
|---|---|---|---|
companyId |
integer |
Yes | Target company ID. |
month |
string |
No | Calendar month formatted as YYYY-MM (e.g. 2026-10). |
filterMode |
string |
No | Filtering mode: month (default) or range. |
startDate |
string |
No | Range start date formatted as YYYY-MM-DD. |
endDate |
string |
No | Range end date formatted as YYYY-MM-DD. |
date |
string |
No | Reference date formatted as YYYY-MM-DD. |
view |
string |
No | Status filter: ALL, D, P, A, I, S, L (cancelado), C (cerrado), F, R. Default: A. |
skip |
integer |
No | Pagination offset. Default 0. |
limit |
integer |
No | Pagination limit. Default 1000. |
200 (ActionResult){
"success": true,
"message": "",
"data": [
{
"_id": "00e41707-d853-4209-a34f-f344626cd827",
"id": 102,
"promotion_number": "2610001-3",
"promotion_strategy": "PP",
"name": "Promo Octubre Danlac",
"description": "Promoción comercial de prueba",
"start_date": "2026-10-01",
"end_date": "2026-10-31",
"typeName": "Producto",
"bonificationTypeName": "Producto",
"status": "D",
"statusName": "Borrador",
"x_client": false,
"vendorLabel": "PM00000107",
"strategyLabel": "Producto + Producto",
"scopeSummary": "IC (CD), NZ · 2 canales",
"branchesLabel": "IC (CD), NZ",
"channelsLabel": "MINORISTA, MINIMAYORISTA",
"productsSummary": "2 compra · 1 bonif.",
"budgetLabel": "0 / 12 und.",
"budgetKind": "units",
"budgetCapTotal": 12,
"budgetConsumedTotal": 0,
"budgetRemainingTotal": 12,
"budgetUsedPercent": 0,
"limit": 12,
"assigned": 0,
"remaining": 12
}
]
}
List items are display-ready: scope, budget, vendor, and product counts are formatted server-side. The UI should bind these fields directly (no parsing of nested scope / budget / branches on the client).
| Field | Type | Description |
|---|---|---|
vendorLabel |
string |
Supplier name; Nombre (Código) when both vendor and vendorCode exist; code only if name missing. |
strategyLabel |
string |
Strategy display name from promotion_strategy catalog, or typeName + bonificationTypeName for legacy rows. |
scopeSummary |
string |
Short scope line (sites + channel count). |
branchesLabel |
string |
Comma-separated branch / CD codes. |
channelsLabel |
string |
Comma-separated channel names. |
productsSummary |
string |
e.g. 2 compra · 1 bonif. |
budgetLabel |
string |
Human-readable cap usage (0 / 12 und. or monetary). |
budgetKind |
string |
units, money, legacy, or none. |
budgetCapTotal |
integer |
Cap for KPI / progress (units or rounded money). |
budgetConsumedTotal |
integer |
Consumed amount for KPI / progress. |
budgetRemainingTotal |
integer |
Remaining cap. |
budgetUsedPercent |
integer |
0–100 utilization. |
limit / assigned / remaining |
integer |
Same totals as budget (backward compatible with legacy KPIs). |
Returns the full consolidated promotion read model plus a nested display object for UI overview screens.
GET /v1/backend/promotion/promotions/{promotionUuid}?companyId=8
200 (ActionResult)The data payload is the CouchDB document (scope, budget, limits, product groups, etc.) with an additional key:
{
"success": true,
"message": "Proceso realizado correctamente",
"data": {
"_id": "c6c046e9-c38f-41c0-a988-e5036e28d83a",
"promotion_number": "26100008-0",
"name": "SAM asdasd",
"scope": { "version": 2 },
"budget": { "version": 1 },
"display": {
"vendorLabel": "PM00000068",
"promotionNumberLabel": "26100008-0",
"strategyCode": "PP",
"strategyLabel": "Producto + Producto",
"validityLabel": "01/10/2026 – 31/10/2026",
"scopeSummary": "IC (CD), NZ · 2 canales",
"budgetLabel": "0 / 12 und.",
"productsSummary": "2 compra · 1 bonif.",
"customerGroupsLabel": "Todos",
"paymentTermsLabel": "—",
"businessTypesLabel": "Todos los tipos de negocio",
"limitsSummary": [{ "label": "Vigencia mensual", "detail": "Vence al final del mes en curso" }],
"activeControls": [],
"auditSummary": "Actualizado por gmelgarejo · 2026-10-27 22:28:19",
"scopeChips": [{ "type": "branchRoot", "label": "IC (CD)" }],
"sellGroupsSummary": [{ "name": "Grupo 1", "itemCount": 2, "limitLabel": "Mín. 45 und.", "selectionTypeLabel": "Manual / Simple" }]
}
}
}
All list display fields are included on detail. Additional detail-only fields:
| Field | Type | Description |
|---|---|---|
promotionNumberLabel |
string |
Formatted promotion number. |
strategyCode / strategyLabel |
string |
Wizard strategy code and name. |
validityLabel |
string |
Date range dd/mm/yyyy – dd/mm/yyyy. |
description |
string |
Promotion description (may be empty). |
customerGroupsLabel |
string |
Todos when group code is ALL, else truncated names. |
paymentTermsLabel |
string |
Same rule as customer groups. |
businessTypesLabel |
string |
Todos los tipos de negocio when many types selected, else truncated names. |
limitsSummary |
array |
{ label, detail } policy rows. |
activeControls |
array |
{ key, label } for enabled control flags only. |
auditSummary |
string |
Single workflow audit line for current status. |
sellGroupsSummary / bonificationGroupsSummary |
array |
Compact product group rows for overview UI. |
scopeChips |
array |
{ type, label } scope v2 nodes. |
mechanicsModeLabel |
string |
Mecánica simple vs escalonada. |
mechanicsSummary |
array |
{ label, value } rows for bonification type, factor, discount, price, base amount. |
promotionStepsSummary |
array |
When is_stepped: tramos with code, name, minimum label (sorted by sequence). |
minOrderLabel |
string |
Minimum ticket display value. |
Updates PostgreSQL + CouchDB projection. When the body includes scope (v2 nested branches), the backend re-syncs promotions_channels from channel nodes in the scope tree.
PUT /v1/backend/promotion/promotions/{promotionUuid}?companyId=8
promotions_channels sync rules| Rule | Detail |
|---|---|
| Resync | Existing rows for the promotion are hard-deleted before insert (avoids unique conflicts with soft-deleted rows). |
| Territory | Each channel node resolves an active territory by branch_id, then branch_code on the scope branch. |
| Uniqueness | One row per (promotion_id, territory_id, customer_channel_id). Duplicate scope paths that map to the same pair are skipped with a warning. |
| Master data | Operational branches (e.g. NZ) must have an active territory linked in Territorios (branch_id or branch_code). Otherwise sync returns 422. |
Example error (422):
{
"success": false,
"message": "No se pudieron sincronizar canales de promoción: La sucursal NZ no tiene un territorio activo vinculado (branch_id / branch_code)."
}
PostgreSQL stores core promotion attributes; ConsolidatePromotionAction rebuilds the Couch read model and merges explicit overrides from the request body. Include these keys when editing from the UI (wizard or overview dialogs):
| Key | Description |
|---|---|
scope, limits, budget |
Scope v2, audience limits, budget allocations |
is_stepped, promotion_steps |
Stepped tiers / volume ranges (required for Editar mecánica y escalas) |
minimum_quantity, proportional, proportional_factor |
Simple promo mechanics (factor Cada → proportional: true; per-tramo proportional_factor lives on each promotion_steps[] row when escalonada) |
scopeByStep, budgetByStep, limitsByStep |
Per-tramo bundles when is_stepped is true |
promotion_strategy, bees_export, wizard_completed, image_url, businessTypes |
Strategy, BEES hints, workflow |
bonificationTypeName, bonificationFactorName, bonificationDiscountTypeName, typeName |
Display labels not stored in PostgreSQL |
| promotion_strategy, bees_export, wizard_completed, image_url, businessTypes | Strategy, BEES hints, workflow |
| beesPromotionType, beesPromotionCategory, beesRangeTriggerType, rangeTriggerType | Optional on PUT for preview only; overwritten on consolidate when auto-resolution applies |
Couch fields used by BuildBeesPromotionsAction and ROMA export. Set by ResolveBeesPromotionTypeAction::applyToDocument() when the promotion has exactly one purchase group (sellGroup.length === 1). Otherwise existing Couch values are preserved.
| Field | Role |
|---|---|
beesPromotionType |
Internal primitive (matrix §1): GROUPED_FREE_GOOD_AMOUNT, INTERACTIVE_COMBO_QUANTITY, … |
beesPromotionCategory |
BEES category (FREE_GOOD, PERCENT_OFF, INTERACTIVE_COMBO, …) |
beesRangeTriggerType |
QUANTITY or AMOUNT |
promotionType |
Same as beesPromotionCategory |
rangeTriggerType |
Same as beesRangeTriggerType |
Full matrix mapping, inputs, and CLI: goal-backend/docs/promotions/BEES_PROMOTION_TYPE_RESOLUTION.md.
Implementation: ResolveBeesPromotionTypeAction::resolveDetails() / applyToDocument(). Unit tests: tests/Unit/Promotion/ResolveBeesPromotionTypeActionTest.php (11 contract rows).
Active SKU count ignores purchase lines with status === 'I'. Client PUT may include mirrored values from buildBeesIntegrationHints for preview; consolidation overwrites when resolution applies.
Related Couch hint: bees_export (BEES Promotions export node) is built by Domain\Promotion\BuildBeesPromotionExportAction::build() on consolidation. It synchronizes metadata (vendorPromotionId, type, title, description, image, startDate, endDate), beesPromotionType, beesPromotionCategory, beesRangeTriggerType, audience (scope, limits, renew), and mechanics (is_stepped, proportional, minimum_quantity, proportional_factor, gift_quantity, promotion_steps, ranges).
If is_stepped / promotion_steps are omitted on PUT, consolidation preserves the previous Couch values and scale edits will not persist after reload.
is_stepped)When is_stepped is true, send scopeByStep, budgetByStep, and limitsByStep keyed by each promotion_steps[].code. Every key in those maps must match a step code; orphan keys are stripped on normalize.
| Field | Shape |
|---|---|
scopeByStep[code] |
{ "version": 2, "branches": [ branchRoot → branches → channels ] } — same as non-stepped scope |
budgetByStep[code] |
Budget v1 (version: 1, promotionTotal, nodes[]) validated against that tramo’s scope |
limitsByStep[code] |
Same object shape as top-level limits |
scope, budget, limits |
Denormalized primary tramo (lowest sequence); server overwrites from stepped maps on PUT |
PostgreSQL: promotions_channels rows reflect the union of channels selected across all tramos (deduped). Channel limit_value on PG uses the primary tramo budget tree only. Full per-tramo budget caps stay in Couch budgetByStep.
Example (two tramos, different branch roots):
{
"is_stepped": true,
"promotion_steps": [
{ "code": "T1", "sequence": 1, "name": "Tramo 1" },
{ "code": "T2", "sequence": 2, "name": "Tramo 2" }
],
"scopeByStep": {
"T1": { "version": 2, "branches": [{ "nodeType": "branchRoot", "id": 1, "code": "IC", "status": "checked", "branches": [] }] },
"T2": { "version": 2, "branches": [{ "nodeType": "branchRoot", "id": 2, "code": "NZ", "status": "checked", "branches": [] }] }
},
"budgetByStep": {
"T1": { "version": 1, "promotionTotal": { "monetaryCap": 1000, "assignedUnitsCap": 0 }, "nodes": [] },
"T2": { "version": 1, "promotionTotal": { "monetaryCap": 2000, "assignedUnitsCap": 0 }, "nodes": [] }
},
"limitsByStep": {
"T1": { "dateConfig": {} },
"T2": { "dateConfig": {} }
},
"scope": { "version": 2, "branches": [{ "nodeType": "branchRoot", "id": 1, "code": "IC", "status": "checked", "branches": [] }] },
"budget": { "version": 1, "promotionTotal": { "monetaryCap": 1000, "assignedUnitsCap": 0 }, "nodes": [] },
"limits": { "dateConfig": {} }
}
Server actions: NormalizeSteppedPromotionBundlesAction, ValidateSteppedPromotionScopeBudgetAction, SyncPromotionChannelsFromSteppedScopeAction.
Server materialization: On every consolidate, materializeSteppedFieldsOnDocument() ensures stepped maps exist when is_stepped and promotion_steps are set but scopeByStep was never written. PUT normalization also merges stepped flags from the existing Couch document when the request body omits them.
Creates a new promotion in draft state. The backend automatically generates and assigns a unique promotion_number using App\Models\Core\Sequence::getNextNumber($companyId, Promotion::class).
POST /v1/backend/promotion/promotions?companyId=8
YYMMXXX-V)26 for 2026)10 for October)001, 002), automatically resets each month2610001-3{
"name": "Promo Octubre Danlac",
"supplier_id": 239,
"type": "P",
"promotion_strategy": "PP",
"start_date": "2026-10-01",
"end_date": "2026-10-31",
"limit": 100
}
200 (ActionResult)Returns the newly created and consolidated CouchDB document with assigned promotion_number.
Registers media image codes on the promotion (GOAL media service). Consolidates the CouchDB read document after save.
POST /v1/backend/promotion/promotions/{promotionUuid}/upload-image?companyId=1
{
"image_codes": ["GHh-vp", "E2w-ET"],
"image_code": ["GHh-vp"]
}
All lifecycle routes use GET and return standard ActionResult. Status codes follow PromotionStatusEnum (aligned with RecordStatusEnum + F Finalizado). See backend doc docs/promotions/PROMOTION_LIFECYCLE.md.
| Route | Target state |
|---|---|
GET .../promotions/{id}/validate |
Pendiente (P) |
GET .../promotions/{id}/activate |
Activo (A) |
GET .../promotions/{id}/reject |
Borrador (D) |
GET .../promotions/{id}/cancel |
Cancelado (L) — only if never used |
GET .../promotions/{id}/pause |
Suspendido (S) |
GET .../promotions/{id}/inactivate |
Inactivo (I) |
GET .../promotions/{id}/close |
Cerrado (C) |
GET .../promotions/{id}/archive |
Archivado (R) |
GET /v1/backend/promotion/promotions/00e41707-d853-4209-a34f-f344626cd827/inactivate?companyId=8
Authorization: Bearer <token>
x-app-stage: <stage>
x-app-uid: <user-uuid>
{
"success": true,
"message": "Promoción actualizada a Inactivo.",
"data": { "_id": "00e41707-d853-4209-a34f-f344626cd827", "status": "I", "statusName": "Inactivo" }
}
Operational CLI (same transitions + batch jobs):
php artisan goal:promotions migrate-status-codes --company=8 --dry-run
php artisan goal:promotions finalize-expired --company=8 --date=2026-10-29
Creates a new promotion (new UUID and promotion_number) by deep-cloning PostgreSQL relations and Couch workflow fields from the source. Result is always Borrador (D) with budget consumption reset (no ledger copy).
POST /v1/backend/promotion/promotions/{sourcePromotionUuid}/duplicate?companyId=8
Authorization: Bearer <token>
x-app-stage: <stage>
x-app-uid: <user-uuid>
Empty object {} or omit body.
200 (ActionResult){
"success": true,
"message": "Promoción duplicada correctamente. Se abrió como borrador.",
"data": {
"_id": "new-uuid-here",
"promotion_number": "2610002-1",
"status": "D",
"statusName": "Borrador",
"name": "Promo origen (copia)"
}
}
CLI: php artisan goal:promotions duplicate --company=8 --promotion=<source-uuid>
Deterministic 8-stage promotion evaluation engine (GBoni — 100% parity across PHP 8.2 Domain\Promotion\Engine\PromotionEngine, JS promotion-engine.js, and Dart promotion_engine.dart via shared promotion-engine-golden-tests.json).
| Method | Path | Action / Purpose |
|---|---|---|
POST |
/v1/backend/promotion/promotions/simulate |
Runs PromotionEngine::evaluate() against an order payload (used by Simulador de pedido (GBoni)). |
GET |
/v1/backend/promotion/reports/available-bonifications?companyId={id} |
AvailableBonificationsReportAction — crosses Cap - Assigned against warehouse stock by priority (#1 → #2 → #3) in PZA. |
GET |
/v1/backend/promotion/promotions/mobile-snapshot?companyId={id}&portfolioId={p}&salesTeamGroupId={g}&warehouseId={w} |
BuildMobilePromotionsSnapshotAction — compact precalculated catalog + SHIPPING address audience rules + priority PZA bonus stock for goal_me Isar (KPI-backed when ready). |
GET |
/v1/backend/promotion/promotions/mobile-enforcements?companyId={id}&portfolioId={p}&salesTeamGroupId={g} |
PublishMobilePromotionEnforcementsAction — lightweight delta feed of is_available, remaining_budget_units, by_step, eligible_shipping_address_ids, and by_shipping_address period balances. |
GET |
/v1/backend/promotion/promotions/sales-team-group-assortment?companyId={id}&salesTeamId={s}&salesTeamGroupId={g} |
ListSalesTeamGroupPromotionsSummaryAction — summary list of available promotions per Sales Team / Group for the web Promociones tab (KPI-backed with live CouchDB fallback). |
GET |
/v1/backend/promotion/promotions/{id}/sales-team-groups?companyId={id} |
ListPromotionSalesTeamGroupsAction — lists participating Sales Team Groups (with sales_team_name, territory/branch, SKUs count, and eligible customers count). |
GET |
/v1/backend/promotion/promotions/{id}/kpi-dashboard?companyId={id} |
GetPromotionKpiDashboardAction — consolidated KPI statistics dashboard (budget utilization/burn rate, fact_promotion_redemptions, fact_promotion_stock_fallbacks, agg_promotion_customer_period_usage, and kpi-db assortment coverage). |
POST |
/v1/backend/sales/orders/{id}/recalculate-promotions |
RecalculateOrderPromotionsAction — evaluates GBoni on a Sales Order (dry_run, preserve_manual_discounts, force_recalculate), respects promotions_preapplied = true from mobile (R13), replaces BONIFICATION lines (PZA), and updates PromotionBudgetGuard. |
minimum_type, uom_factor, combination_mode (CUMULATIVE | EXCLUSIVE_ALL | EXCLUSIVE_SELECTED), priority, exclusion_group, stack_order_rule (ADDITIVE | COMPOUND), audience_mode (ALL_IN_SCOPE | WHITELIST | BLACKLIST), whitelist_customer_ids, blacklist_customer_ids (business_partner_addresses.id where address_type = 'SHIPPING'), and audienceByStep.
R12)CancelOrderAction and ApplyPromotionBudgetToOrderAction automatically invoke PromotionBudgetGuard::releaseByOrderUid() on cancelled/voided orders, reversing both STATUS_RESERVED and STATUS_COMMITTED ledger entries idempotently.
Per-company KPI DB (kpi-db) stores precompiled promotion assortments and customer-level enforcements per sales_team_group_id:
sales_team_group_promotion_snapshots: master build state (pending|processing|ready|error), snapshot_version, source_fingerprint, enforcements_fingerprint.sales_team_group_promotion_assortments: promotion payloads intersected with SalesTeamGroupProduct & SalesTeamGroupProductMeasure, with bonification items strictly in PZA.sales_team_group_promotion_enforcements: availability and budget balances per promotion and group.sales_team_group_promotion_customer_eligibilities: pre-resolved customer (shipping_address_id) eligibility (can_obtain, period_cap, assigned_in_period, remaining_in_period).BuildMobilePromotionsSnapshotAction (/mobile-snapshot) and PublishMobilePromotionEnforcementsAction (/mobile-enforcements) read directly from kpi-db when salesTeamGroupId or portfolioId resolves to a ready snapshot (supporting sinceVersion → { "unchanged": true } fast-path), and fall back to live CouchDB compilation otherwise.
Scheduled Incremental CLI:
php artisan promotions:build-sales-team-assortment \
--company=8 \
[--sales-team=ID] [--group=ID] [--enforcements-only] [--force] [--dry-run]
Scheduled every 5 minutes in App\Console\Kernel; uses SHA-256 fingerprinting to skip unchanged groups, refresh only customer/budget enforcements when only balances changed, or rebuild full assortments when Promotions, Sales Team Catalogs, or Product Catalogs were modified.
| Code | When |
|---|---|
200 |
Successful operation |
201 |
Created successfully |
400 |
Validation error or invalid payload |
401 |
Unauthorized (invalid or missing token) |
404 |
Promotion not found |
422 |
Scope channel sync failed (territory master data or duplicate territory/channel after dedupe) |
500 |
Internal server or consolidation error |