Skip to content
3 changes: 2 additions & 1 deletion config/packages/dev/nelmio_api_doc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ nelmio_api_doc:
- bearerAuth: []
areas:
path_patterns:
- '^/v1/'
# Private economic endpoints are intentionally outside the public synthetic OpenAPI.
- '^/v1/simulations$'
17 changes: 17 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
parameters:
env(PRICING_CATALOG_PATH): ''
env(PRICING_ECONOMIC_MATRIX_PATH): ''
env(PRICING_ECONOMIC_ANALYST_TOKEN_FILE): ''
env(PRICING_ECONOMIC_QUOTES_TOKEN_FILE): ''
env(PRICING_ECONOMIC_QUOTES_ENABLED): '0'

services:
_defaults:
Expand All @@ -15,3 +19,16 @@ services:
LibreSign\Pricing\Infrastructure\SyntheticCatalog:
arguments:
$filename: '%env(string:PRICING_CATALOG_PATH)%'

LibreSign\Pricing\Infrastructure\EconomicMatrixLoader:
arguments:
$filename: '%env(string:PRICING_ECONOMIC_MATRIX_PATH)%'

LibreSign\Pricing\Http\EconomicBearerAuthenticator:
arguments:
$analystTokenFile: '%env(string:PRICING_ECONOMIC_ANALYST_TOKEN_FILE)%'
$quotesTokenFile: '%env(string:PRICING_ECONOMIC_QUOTES_TOKEN_FILE)%'

LibreSign\Pricing\Controller\EconomicSimulationController:
arguments:
$quotesEnabled: '%env(string:PRICING_ECONOMIC_QUOTES_ENABLED)%'
14 changes: 14 additions & 0 deletions docker/nginx/pricing.conf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,20 @@ server {
fastcgi_pass $pricing_fpm;
}

# Role-specific private economic endpoints, never exposed through public ingress.
location ~ ^/v1/economic-(simulations|quotes)$ {
limit_except POST { deny all; }
limit_req zone=pricing_requests burst=4 nodelay;
limit_conn pricing_connections 2;

include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /app/public/index.php;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param HTTP_AUTHORIZATION $http_authorization;
fastcgi_read_timeout 15s;
fastcgi_pass $pricing_fpm;
}

# Liveness reveals no catalog, price, identity, process or configuration data.
location = /healthz {
include fastcgi_params;
Expand Down
3 changes: 2 additions & 1 deletion docs/economic-calculation.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ For `customers = N`, `fixed_pool = F`, `variable_unit = V`, `hours_unit = h`, `f
- Cash cost per customer: `F / N + V`.
- Full-cost basis: `cash_cost + h * C`.
- Cooperative preservation basis: `cash_cost + h * Q`.
- One-time setup/implementation price (separate from maintenance): `setup_hours * Q / (1 - t - d - m)`.
- Incremental floor: `V / (1 - t - d)`. This is not an approved minimum selling price.
- Full-cost price at target margin: `full_cost / (1 - t - d - m)`.
- Cooperative preservation price at target margin: `preservation_cost / (1 - t - d - m)`.
Expand All @@ -24,4 +25,4 @@ All outputs are rounded HALF_UP at two decimal places. Intermediate divisions re

The nine historical research scenarios (three customer volumes for each modality) are reproduced with a **synthetic-only fixture**. Their values were illustrative, not observed LibreCode economics.

The `customer_infrastructure` scenario has a project-plus-optional-recurring contract basis. A later approved quote must separately express one-time setup and recurring support rather than mislabeling a project fee as a monthly subscription.
The `customer_infrastructure` scenario has a project-plus-optional-recurring contract basis. Its setup price is **always calculated and reported separately** from optional recurring support; do not mislabel either amount as the other.
52 changes: 52 additions & 0 deletions docs/private-economic-configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!-- SPDX-FileCopyrightText: 2026 LibreSign contributors
SPDX-License-Identifier: AGPL-3.0-or-later -->

# Private economic configuration and commercial authorization

The public Git repository and published Docker images **never include LibreCode's actual economic parameters**. Only fictional fixtures, schema documentation and the PHP formulas are versioned here.

## Installation boundary

The service starts with no configured economic matrix and no analyst/quote credentials: economic endpoints fail closed. To enable internal research, an authorized operator may supply the following paths in a **host-private Docker Compose override**, stored outside the repository:

- `PRICING_ECONOMIC_MATRIX_PATH`: read-only path inside the application container to a private, approved-for-access JSON configuration.
- `PRICING_ECONOMIC_ANALYST_TOKEN_FILE`: read-only credential file for internal analysis, distinct from the synthetic API token.
- `PRICING_ECONOMIC_QUOTES_TOKEN_FILE`: separate, read-only credential file for commercial quote consumers.
- `PRICING_ECONOMIC_QUOTES_ENABLED`: defaults to `0`. Deliberately setting `1` in the **private host configuration** enables a second gate, but never overrides unapproved parameters.

The host-private override must mount the economic matrix and credentials as **separate read-only secrets**; do not modify the published Compose file with real paths or add actual economic data to an image layer. Keep the pricing service on an isolated, non-public Docker network and do not expose new routes publicly without a separate security review.

Rotating credentials or a parameter snapshot is an operator-controlled action. Check the effective mounted file, source and SHA-256 before and after a change, and roll back by restoring the previous private snapshot. Do not log source paths, tokens, request bodies, cost results, or customer-identifying data.

## Endpoints

- `POST /v1/economic-simulations` (analyst token): calculates the full scenario, including economic costs, return targets and parameters' version/hash. This endpoint is **confidential**.
- `POST /v1/economic-quotes` (separate quotes token): returns separate one-time setup and service-period reference amounts, model, billing basis, parameter version and simulation fingerprint. It never returns costs, tax rates, return per hour or parameter values. An unapproved or incomplete matrix produces HTTP 409; an unset host enable flag produces HTTP 403. The explicit UTC approval date is included in the quote response and in the simulation fingerprint; analytical simulations do not silently depend on wall-clock time.
- `POST /v1/simulations`: legacy synthetic-only endpoint. Unchanged.

Both economic routes accept the same JSON request shape:

```json
{
"model": "cloud",
"parameter_version": "fictional-v2",
"customers": 20,
"candidate_price": "100.00"
}
```

The above is a **fictional example**. The `candidate_price` key is optional. No route provisions users, bills customers, or alters WooCommerce.

## Approval and limits

The private matrix records `approval_status`, `approved_by`, `approval_reference`, `effective_from`, `effective_until` and each parameter's approval status. The domain engine requires all inputs relevant to the selected scenario to be present, within validity and approved. The synthetic scope **cannot** authorize quotes.

These approval fields express **business evidence**, not a cryptographic signature. The private file must therefore be writable only by authorized financial governance and mounted read-only into the service; anyone allowed to edit it can change those assertions. Stronger approval attestation, per-client quotas and durable request audit may be added before internet-facing exposure. Until then, keep quote consumption private, per-role, explicitly enabled and independently reviewed.

A quote price is not a binding contract: `activation_allowed` is always `false`. Prices for project delivery and optional recurring support must be separated by the commercial adapter before sale.

## Private migration from previous research

Review the older `economic-parameters.private.review.json` **outside the public repository**. Convert its 39 `parameters` into one versioned matrix and normalize `customer_infra` to `customer_infrastructure`. Remove the duplicated `simulation_assumptions` and `scenario_results` source structures. Keep nulls for unverified quantities and update evidence and units explicitly. The nine fictional scenarios now have their own public test fixture.

No real parameter set, accountant working paper, confidential file path, or approval receipt must be committed. Economic homologation is a human-governed operation distinct from merging PHP code.
88 changes: 88 additions & 0 deletions src/Controller/EconomicSimulationController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

// SPDX-FileCopyrightText: 2026 LibreSign contributors
// SPDX-License-Identifier: AGPL-3.0-or-later

declare(strict_types=1);

namespace LibreSign\Pricing\Controller;

use LibreSign\Pricing\Domain\EconomicSimulationEngine;
use LibreSign\Pricing\Domain\InvalidSimulationInput;
use LibreSign\Pricing\Http\ApiProblem;
use LibreSign\Pricing\Http\EconomicBearerAuthenticator;
use LibreSign\Pricing\Http\EconomicRequestParser;
use LibreSign\Pricing\Infrastructure\CatalogUnavailable;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

final readonly class EconomicSimulationController
{
private const RESPONSE_HEADERS = [
'Cache-Control' => 'no-store',
'X-Content-Type-Options' => 'nosniff',
];

public function __construct(
private EconomicSimulationEngine $engine,
private EconomicBearerAuthenticator $authenticator,
private EconomicRequestParser $parser,
private string $quotesEnabled,
) {
}

#[Route('/v1/economic-simulations', methods: ['POST'])]
public function simulate(Request $request): JsonResponse
{
try {
$this->authenticator->assertAnalyst($request);
$input = $this->parser->parse($request);
$result = $this->engine->simulate($input);

return new JsonResponse($result, 200, self::RESPONSE_HEADERS);
} catch (ApiProblem $problem) {
return new JsonResponse($problem->toArray(), $problem->status, self::RESPONSE_HEADERS);
} catch (InvalidSimulationInput) {
return new JsonResponse(['error' => 'invalid_economic_input'], 422, self::RESPONSE_HEADERS);
} catch (CatalogUnavailable) {
return new JsonResponse(['error' => 'economic_matrix_unavailable'], 503, self::RESPONSE_HEADERS);
}
}

#[Route('/v1/economic-quotes', methods: ['POST'])]
public function quote(Request $request): JsonResponse
{
try {
$this->authenticator->assertQuotes($request);
if ($this->quotesEnabled !== '1') {
return new JsonResponse(['error' => 'quotes_disabled'], 403, self::RESPONSE_HEADERS);
}
$input = $this->parser->parse($request);
$result = $this->engine->simulate($input, gmdate('Y-m-d'));

if ($result['status'] !== 'calculated' || !$result['commercialization']['quote_allowed']) {
return new JsonResponse(['error' => 'quote_not_approved'], 409, self::RESPONSE_HEADERS);
}

// Sales consumers never receive costs, hourly return, tax rates or raw matrix data.
return new JsonResponse([
'simulation_fingerprint' => $result['simulation_fingerprint'],
'parameter_version' => $result['parameters']['version'],
'approval_as_of' => $result['approval_as_of'],
'model' => $input->model,
'billing_basis' => $result['billing_basis'],
'currency' => $result['currency'],
'service_period_reference_price' => $result['calculation']['preservation_price_with_margin'],
'one_time_setup_reference_price' => $result['calculation']['one_time_setup_preservation_price'],
'activation_allowed' => false,
], 200, self::RESPONSE_HEADERS);
} catch (ApiProblem $problem) {
return new JsonResponse($problem->toArray(), $problem->status, self::RESPONSE_HEADERS);
} catch (InvalidSimulationInput) {
return new JsonResponse(['error' => 'invalid_economic_input'], 422, self::RESPONSE_HEADERS);
} catch (CatalogUnavailable) {
return new JsonResponse(['error' => 'economic_matrix_unavailable'], 503, self::RESPONSE_HEADERS);
}
}
}
23 changes: 21 additions & 2 deletions src/Domain/EconomicSimulationEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Brick\Math\BigDecimal;
use Brick\Math\RoundingMode;
use LibreSign\Pricing\Infrastructure\CatalogUnavailable;
use LibreSign\Pricing\Infrastructure\EconomicMatrixLoader;

final readonly class EconomicSimulationEngine
Expand All @@ -20,7 +21,7 @@ public function __construct(private EconomicMatrixLoader $loader)
}

/** @return array<string, mixed> */
public function simulate(EconomicScenarioInput $input): array
public function simulate(EconomicScenarioInput $input, ?string $approvalDate = null): array
{
$matrix = $this->loader->load();
if ($matrix->version() !== $input->parameterVersion) {
Expand All @@ -32,6 +33,7 @@ public function simulate(EconomicScenarioInput $input): array
$prefix.'.fixed_pool' => 'BRL/period',
$prefix.'.variable_unit' => 'BRL/customer_period',
$prefix.'.hours_unit' => 'hours/customer_period',
$prefix.'.setup_hours' => 'hour/customer',
$prefix.'.full_hour' => 'BRL/hour',
$prefix.'.collective_hour' => 'BRL/hour',
$prefix.'.capacity' => 'customer',
Expand All @@ -42,7 +44,11 @@ public function simulate(EconomicScenarioInput $input): array
$values = [];
$missing = [];
foreach ($needed as $id => $unit) {
$number = $matrix->decimal($id, $unit);
try {
$number = $matrix->decimal($id, $unit);
} catch (\InvalidArgumentException $exception) {
throw new CatalogUnavailable('Economic matrix parameter contract mismatch.', 0, $exception);
}
if ($number === null) {
$missing[] = $id;
} else {
Expand All @@ -54,12 +60,14 @@ public function simulate(EconomicScenarioInput $input): array
'engine' => self::VERSION,
'matrix_sha256' => $matrix->fingerprint(),
'input' => $input->normalized(),
'approval_date' => $approvalDate,
], JSON_THROW_ON_ERROR));
$base = [
'engine_version' => self::VERSION,
'simulation_fingerprint' => $fingerprint,
'parameters' => $metadata,
'input' => $input->normalized(),
'approval_as_of' => $approvalDate,
'currency' => 'BRL',
'billing_basis' => $model['billing_basis'],
'commercialization' => [
Expand Down Expand Up @@ -103,6 +111,9 @@ public function simulate(EconomicScenarioInput $input): array
$incrementalFloor = $variable->dividedBy($denominator, 12, RoundingMode::HalfUp);
$fullPrice = $fullCost->dividedBy($withMargin, 12, RoundingMode::HalfUp);
$preservationPrice = $preservationCost->dividedBy($withMargin, 12, RoundingMode::HalfUp);
$setupHours = $values[$prefix.'.setup_hours'];
$setupCost = $setupHours->multipliedBy($collectiveHour);
$setupPrice = $setupCost->dividedBy($withMargin, 12, RoundingMode::HalfUp);

$result = [
'status' => 'calculated',
Expand All @@ -114,6 +125,8 @@ public function simulate(EconomicScenarioInput $input): array
'incremental_floor' => $this->money($incrementalFloor),
'full_price_with_margin' => $this->money($fullPrice),
'preservation_price_with_margin' => $this->money($preservationPrice),
'one_time_setup_cost' => $this->money($setupCost),
'one_time_setup_preservation_price' => $this->money($setupPrice),
'tax_rate' => (string) $tax,
'default_rate' => (string) $badDebt,
'margin_target' => (string) $margin,
Expand All @@ -131,6 +144,12 @@ public function simulate(EconomicScenarioInput $input): array
$result['calculation']['candidate_preservation_delta'] = $this->money($net->minus($preservationCost));
}

// Date-sensitive authorization is opt-in; ordinary simulations stay deterministic.
if ($approvalDate !== null && $matrix->quoteAllowed(array_keys($needed), $approvalDate)) {
$base['commercialization']['quote_allowed'] = true;
$base['commercialization']['reason_code'] = 'APPROVED_PARAMETER_SET';
}

return $base + $result;
}

Expand Down
43 changes: 43 additions & 0 deletions src/Http/EconomicBearerAuthenticator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

// SPDX-FileCopyrightText: 2026 LibreSign contributors
// SPDX-License-Identifier: AGPL-3.0-or-later

declare(strict_types=1);

namespace LibreSign\Pricing\Http;

use Symfony\Component\HttpFoundation\Request;

final readonly class EconomicBearerAuthenticator
{
public function __construct(
private string $analystTokenFile,
private string $quotesTokenFile,
) {
}

public function assertAnalyst(Request $request): void
{
$this->assertRole($request, $this->analystTokenFile);
}

public function assertQuotes(Request $request): void
{
$this->assertRole($request, $this->quotesTokenFile);
}

private function assertRole(Request $request, string $path): void
{
// File-only credentials; there is no environment token fallback.
if ($path === '') {
throw new ApiProblem(401, 'unauthorized');
}
$configured = @file_get_contents($path);
$configured = is_string($configured) ? rtrim($configured, "\r\n") : '';
if (strlen($configured) < 32
|| !hash_equals('Bearer '.$configured, (string) $request->headers->get('Authorization'))) {
throw new ApiProblem(401, 'unauthorized');
}
}
}
47 changes: 47 additions & 0 deletions src/Http/EconomicRequestParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

// SPDX-FileCopyrightText: 2026 LibreSign contributors
// SPDX-License-Identifier: AGPL-3.0-or-later

declare(strict_types=1);

namespace LibreSign\Pricing\Http;

use LibreSign\Pricing\Domain\EconomicScenarioInput;
use Symfony\Component\HttpFoundation\Request;

final readonly class EconomicRequestParser
{
public function parse(Request $request): EconomicScenarioInput
{
$type = strtolower((string) $request->headers->get('Content-Type'));
if (!preg_match('~^application/json(?:\s*;|$)~', $type)) {
throw new ApiProblem(415, 'content_type_not_supported');
}
$body = $request->getContent();
if (strlen($body) > 16384) {
throw new ApiProblem(413, 'request_too_large');
}
try {
$decoded = json_decode($body, true, 16, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
throw new ApiProblem(400, 'invalid_json');
}
if (!is_array($decoded) || array_is_list($decoded)
|| array_diff(array_keys($decoded), ['model', 'parameter_version', 'customers', 'candidate_price']) !== []) {
throw new ApiProblem(422, 'invalid_input');
}
if (!is_string($decoded['model'] ?? null)
|| !is_string($decoded['parameter_version'] ?? null)
|| !is_int($decoded['customers'] ?? null)
|| (isset($decoded['candidate_price']) && !is_string($decoded['candidate_price']))) {
throw new ApiProblem(422, 'invalid_input');
}
return new EconomicScenarioInput(
$decoded['model'],
$decoded['parameter_version'],
$decoded['customers'],
$decoded['candidate_price'] ?? null,
);
}
}
Loading
Loading