From 10c9b4ea5122e0c9ff36c725ef401e41a604667b Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:25:38 +0000 Subject: [PATCH 01/11] feat(pricing): calculate parameterized economic scenarios Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- docs/economic-calculation.md | 27 +++ src/Domain/EconomicScenarioInput.php | 38 ++++ src/Domain/EconomicSimulationEngine.php | 149 +++++++++++++ .../economic-historical-synthetic.json | 197 ++++++++++++++++++ tests/Unit/EconomicSimulationEngineTest.php | 116 +++++++++++ 5 files changed, 527 insertions(+) create mode 100644 docs/economic-calculation.md create mode 100644 src/Domain/EconomicScenarioInput.php create mode 100644 src/Domain/EconomicSimulationEngine.php create mode 100644 tests/Fixtures/economic-historical-synthetic.json create mode 100644 tests/Unit/EconomicSimulationEngineTest.php diff --git a/docs/economic-calculation.md b/docs/economic-calculation.md new file mode 100644 index 0000000..58b9e2d --- /dev/null +++ b/docs/economic-calculation.md @@ -0,0 +1,27 @@ + + +# Economic simulation formulas + +The calculator is a side-effect-free domain service. It **does not** replace the cooperative production allocator, a tax opinion, the WooCommerce commercial catalog, or the signature metering ledger. + +All values are read from the external, versioned economic matrix as exact decimal strings. The `simulation.${model}.*` keys identify fixed period costs, variable per-paying-customer costs, incremental work hours and hourly economic benchmarks. No numerical economic assumptions are embedded in PHP. + +For `customers = N`, `fixed_pool = F`, `variable_unit = V`, `hours_unit = h`, `full_hour = C`, `collective_hour = Q`, `tax = t`, `default = d`, and `margin = m`: + +- Cash cost per customer: `F / N + V`. +- Full-cost basis: `cash_cost + h * C`. +- Cooperative preservation basis: `cash_cost + h * Q`. +- 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)`. + +**Interpretation:** the scenario's `collective_hour` is the fully loaded target return per weighted work hour, not an additional salary expense. It replaces `full_hour` for the preservation basis; it is not added to the full-cost basis. The actual collective return indicator (`D / H`) from cooperative accounting should inform the benchmark when appropriately reviewed. Contract scope, fixed-versus-incremental capacity, reserves and special production allocations can require different inputs. The formulas express a commercial sensitivity analysis, not the legal allocation of production. + +The margin `m` is defined here on gross revenue, net of taxes and expected default, by reducing the denominator. This convention must match the approved commercial policy before any real quoting. + +All outputs are rounded HALF_UP at two decimal places. Intermediate divisions retain twelve decimals. A zero or negative denominator, excess capacity, incompatible units or unknown input fails closed. Unknown economics produces `status=incomplete`, not a zero. + +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. diff --git a/src/Domain/EconomicScenarioInput.php b/src/Domain/EconomicScenarioInput.php new file mode 100644 index 0000000..3639439 --- /dev/null +++ b/src/Domain/EconomicScenarioInput.php @@ -0,0 +1,38 @@ +model, ['cloud', 'managed', 'customer_infrastructure'], true) + || preg_match('/^[a-z][a-z0-9-]{0,63}$/D', $this->parameterVersion) !== 1 + || $this->customers < 1 + || $this->customers > 1000000 + || ($this->candidatePrice !== null + && preg_match('/^(?:0|[1-9][0-9]{0,8})(?:\.[0-9]{1,2})?$/D', $this->candidatePrice) !== 1)) { + throw new InvalidSimulationInput('Invalid economic scenario input.'); + } + } + + /** @return array{model: string, parameter_version: string, customers: int, candidate_price: string|null} */ + public function normalized(): array + { + return [ + 'model' => $this->model, + 'parameter_version' => $this->parameterVersion, + 'customers' => $this->customers, + 'candidate_price' => $this->candidatePrice, + ]; + } +} diff --git a/src/Domain/EconomicSimulationEngine.php b/src/Domain/EconomicSimulationEngine.php new file mode 100644 index 0000000..a5bce64 --- /dev/null +++ b/src/Domain/EconomicSimulationEngine.php @@ -0,0 +1,149 @@ + */ + public function simulate(EconomicScenarioInput $input): array + { + $matrix = $this->loader->load(); + if ($matrix->version() !== $input->parameterVersion) { + throw new InvalidSimulationInput('Unknown economic parameter version.'); + } + $model = $matrix->model($input->model); + $prefix = $model['parameter_prefix']; + $needed = [ + $prefix.'.fixed_pool' => 'BRL/period', + $prefix.'.variable_unit' => 'BRL/customer_period', + $prefix.'.hours_unit' => 'hours/customer_period', + $prefix.'.full_hour' => 'BRL/hour', + $prefix.'.collective_hour' => 'BRL/hour', + $prefix.'.capacity' => 'customer', + 'simulation.tax' => 'fraction', + 'simulation.default' => 'fraction', + 'simulation.target_margin' => 'fraction', + ]; + $values = []; + $missing = []; + foreach ($needed as $id => $unit) { + $number = $matrix->decimal($id, $unit); + if ($number === null) { + $missing[] = $id; + } else { + $values[$id] = $number; + } + } + $metadata = $matrix->metadata(); + $fingerprint = hash('sha256', json_encode([ + 'engine' => self::VERSION, + 'matrix_sha256' => $matrix->fingerprint(), + 'input' => $input->normalized(), + ], JSON_THROW_ON_ERROR)); + $base = [ + 'engine_version' => self::VERSION, + 'simulation_fingerprint' => $fingerprint, + 'parameters' => $metadata, + 'input' => $input->normalized(), + 'currency' => 'BRL', + 'billing_basis' => $model['billing_basis'], + 'commercialization' => [ + 'quote_allowed' => false, + 'activation_allowed' => false, + 'reason_code' => 'EXPLICIT_APPROVAL_REQUIRED', + ], + ]; + + if ($missing !== []) { + return $base + [ + 'status' => 'incomplete', + 'missing_parameters' => $missing, + 'calculation' => null, + ]; + } + + $capacity = $values[$prefix.'.capacity']; + if ($capacity->compareTo(0) <= 0 || $capacity->compareTo($input->customers) < 0) { + throw new InvalidSimulationInput('Customers exceed configured capacity.'); + } + $tax = $this->rate($values['simulation.tax']); + $badDebt = $this->rate($values['simulation.default']); + $margin = $this->rate($values['simulation.target_margin']); + $denominator = BigDecimal::one()->minus($tax)->minus($badDebt); + $withMargin = $denominator->minus($margin); + if ($denominator->compareTo(0) <= 0 || $withMargin->compareTo(0) <= 0) { + throw new InvalidSimulationInput('Tax, risk and target margin exceed available revenue.'); + } + + // Calculate per-contract prices, not total portfolio revenue. + $fixed = $values[$prefix.'.fixed_pool']->dividedBy($input->customers, 12, RoundingMode::HalfUp); + $variable = $values[$prefix.'.variable_unit']; + $hours = $values[$prefix.'.hours_unit']; + $fullHour = $values[$prefix.'.full_hour']; + $collectiveHour = $values[$prefix.'.collective_hour']; + + $cashCost = $fixed->plus($variable); + $fullCost = $cashCost->plus($hours->multipliedBy($fullHour)); + $preservationCost = $cashCost->plus($hours->multipliedBy($collectiveHour)); + $incrementalFloor = $variable->dividedBy($denominator, 12, RoundingMode::HalfUp); + $fullPrice = $fullCost->dividedBy($withMargin, 12, RoundingMode::HalfUp); + $preservationPrice = $preservationCost->dividedBy($withMargin, 12, RoundingMode::HalfUp); + + $result = [ + 'status' => 'calculated', + 'missing_parameters' => [], + 'calculation' => [ + 'cash_cost' => $this->money($cashCost), + 'full_cost' => $this->money($fullCost), + 'preservation_cost' => $this->money($preservationCost), + 'incremental_floor' => $this->money($incrementalFloor), + 'full_price_with_margin' => $this->money($fullPrice), + 'preservation_price_with_margin' => $this->money($preservationPrice), + 'tax_rate' => (string) $tax, + 'default_rate' => (string) $badDebt, + 'margin_target' => (string) $margin, + 'customers' => $input->customers, + 'capacity' => (string) $capacity, + 'utilization_percent' => $this->money(BigDecimal::of($input->customers)->multipliedBy(100)->dividedBy($capacity, 12, RoundingMode::HalfUp)), + ], + ]; + if ($input->candidatePrice !== null) { + $candidate = BigDecimal::of($input->candidatePrice); + $net = $candidate->multipliedBy($denominator); + $result['calculation']['candidate_price'] = $input->candidatePrice; + $result['calculation']['candidate_incremental_contribution'] = $this->money($net->minus($variable)); + $result['calculation']['candidate_full_margin'] = $this->money($net->minus($fullCost)); + $result['calculation']['candidate_preservation_delta'] = $this->money($net->minus($preservationCost)); + } + + return $base + $result; + } + + private function rate(BigDecimal $value): BigDecimal + { + if ($value->compareTo(0) < 0 || $value->compareTo(1) > 0) { + throw new InvalidSimulationInput('Rate must be within [0,1].'); + } + return $value; + } + + private function money(BigDecimal $value): string + { + return (string) $value->toScale(2, RoundingMode::HalfUp); + } +} diff --git a/tests/Fixtures/economic-historical-synthetic.json b/tests/Fixtures/economic-historical-synthetic.json new file mode 100644 index 0000000..ff67f63 --- /dev/null +++ b/tests/Fixtures/economic-historical-synthetic.json @@ -0,0 +1,197 @@ +{ + "contract_id": "libresign.pricing.economic-parameters", + "schema_version": "2.0.0", + "parameter_set_id": "fictional-historical-2026", + "parameter_set_version": "fictional-v2", + "scope": "SYNTHETIC_ONLY", + "approval_status": "research_only", + "currency": "BRL", + "approved_by": null, + "approval_reference": null, + "effective_from": null, + "effective_until": null, + "models": { + "cloud": { + "billing_basis": "monthly", + "parameter_prefix": "simulation.cloud" + }, + "managed": { + "billing_basis": "monthly", + "parameter_prefix": "simulation.managed" + }, + "customer_infrastructure": { + "billing_basis": "project_with_optional_recurring", + "parameter_prefix": "simulation.customer_infrastructure" + } + }, + "parameters": [ + { + "id": "simulation.cloud.fixed_pool", + "value": "1600.00", + "unit": "BRL/period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.cloud.variable_unit", + "value": "26.00", + "unit": "BRL/customer_period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.cloud.hours_unit", + "value": "0.40", + "unit": "hours/customer_period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.cloud.full_hour", + "value": "45.00", + "unit": "BRL/hour", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.cloud.collective_hour", + "value": "90.00", + "unit": "BRL/hour", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.cloud.setup_hours", + "value": "2.00", + "unit": "hour/customer", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.cloud.capacity", + "value": "80", + "unit": "customer", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.managed.fixed_pool", + "value": "3300.00", + "unit": "BRL/period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.managed.variable_unit", + "value": "60.00", + "unit": "BRL/customer_period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.managed.hours_unit", + "value": "10.00", + "unit": "hours/customer_period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.managed.full_hour", + "value": "45.00", + "unit": "BRL/hour", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.managed.collective_hour", + "value": "90.00", + "unit": "BRL/hour", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.managed.setup_hours", + "value": "16.00", + "unit": "hour/customer", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.managed.capacity", + "value": "6", + "unit": "customer", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.customer_infrastructure.fixed_pool", + "value": "300.00", + "unit": "BRL/period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.customer_infrastructure.variable_unit", + "value": "40.00", + "unit": "BRL/customer_period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.customer_infrastructure.hours_unit", + "value": "6.00", + "unit": "hours/customer_period", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.customer_infrastructure.full_hour", + "value": "45.00", + "unit": "BRL/hour", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.customer_infrastructure.collective_hour", + "value": "90.00", + "unit": "BRL/hour", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.customer_infrastructure.setup_hours", + "value": "20.00", + "unit": "hour/customer", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.customer_infrastructure.capacity", + "value": "6", + "unit": "customer", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.tax", + "value": "0.06", + "unit": "fraction", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.default", + "value": "0.02", + "unit": "fraction", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + }, + { + "id": "simulation.target_margin", + "value": "0.15", + "unit": "fraction", + "source": "FICTIONAL_SCENARIO_REPRODUCTION", + "approval_status": "not_approved_for_commercial_use" + } + ] +} diff --git a/tests/Unit/EconomicSimulationEngineTest.php b/tests/Unit/EconomicSimulationEngineTest.php new file mode 100644 index 0000000..8f44b03 --- /dev/null +++ b/tests/Unit/EconomicSimulationEngineTest.php @@ -0,0 +1,116 @@ + ['cloud', 20, '124.00', '142.00', '161.04', '184.42']; + yield 'cloud medium' => ['cloud', 50, '76.00', '94.00', '98.70', '122.08']; + yield 'cloud high' => ['cloud', 75, '65.33', '83.33', '84.85', '108.23']; + yield 'managed low' => ['managed', 1, '3810.00', '4260.00', '4948.05', '5532.47']; + yield 'managed medium' => ['managed', 3, '1610.00', '2060.00', '2090.91', '2675.32']; + yield 'managed high' => ['managed', 6, '1060.00', '1510.00', '1376.62', '1961.04']; + yield 'infrastructure low' => ['customer_infrastructure', 1, '610.00', '880.00', '792.21', '1142.86']; + yield 'infrastructure medium' => ['customer_infrastructure', 3, '410.00', '680.00', '532.47', '883.12']; + yield 'infrastructure high' => ['customer_infrastructure', 6, '360.00', '630.00', '467.53', '818.18']; + } + + #[DataProvider('historicalScenarios')] + public function testReproducesNinePreviouslyDocumentedIllustrativeScenarios( + string $model, + int $customers, + string $fullCost, + string $preservationCost, + string $fullPrice, + string $preservationPrice, + ): void { + $engine = self::engine(); + $input = new EconomicScenarioInput($model, 'fictional-v2', $customers, null); + $first = $engine->simulate($input); + self::assertSame($first, $engine->simulate($input)); + self::assertSame('calculated', $first['status']); + self::assertSame($fullCost, $first['calculation']['full_cost']); + self::assertSame($preservationCost, $first['calculation']['preservation_cost']); + self::assertSame($fullPrice, $first['calculation']['full_price_with_margin']); + self::assertSame($preservationPrice, $first['calculation']['preservation_price_with_margin']); + self::assertFalse($first['commercialization']['quote_allowed']); + self::assertFalse($first['commercialization']['activation_allowed']); + } + + public function testCandidatePriceProducesExplainableComparisons(): void + { + $input = new EconomicScenarioInput('cloud', 'fictional-v2', 20, '200.00'); + $result = self::engine()->simulate($input); + self::assertSame('200.00', $result['calculation']['candidate_price']); + self::assertSame('58.00', $result['calculation']['candidate_incremental_contribution']); + self::assertSame('60.00', $result['calculation']['candidate_full_margin']); + self::assertSame('42.00', $result['calculation']['candidate_preservation_delta']); + } + + public function testExcessCapacityIsRejected(): void + { + $this->expectException(\InvalidArgumentException::class); + self::engine()->simulate(new EconomicScenarioInput('cloud', 'fictional-v2', 81, null)); + } + + public function testWrongMatrixVersionIsRejected(): void + { + $this->expectException(\InvalidArgumentException::class); + self::engine()->simulate(new EconomicScenarioInput('cloud', 'wrong-v1', 20, null)); + } + + public function testUnknownCostsBlockCalculationInsteadOfBecomingZero(): void + { + $data = json_decode( + (string) file_get_contents(self::fixturePath()), + true, + 32, + JSON_THROW_ON_ERROR, + ); + $data['parameters'][0]['value'] = null; + $path = tempnam(sys_get_temp_dir(), 'pricing-test-'); + self::assertNotFalse($path); + try { + file_put_contents($path, json_encode($data, JSON_THROW_ON_ERROR)); + $result = (new EconomicSimulationEngine(new EconomicMatrixLoader($path))) + ->simulate(new EconomicScenarioInput('cloud', 'fictional-v2', 20, null)); + self::assertSame('incomplete', $result['status']); + self::assertNull($result['calculation']); + self::assertContains('simulation.cloud.fixed_pool', $result['missing_parameters']); + self::assertFalse($result['commercialization']['quote_allowed']); + } finally { + unlink($path); + } + } + + public function testSyntheticApprovalNeverAuthorizesQuote(): void + { + $result = self::engine()->simulate(new EconomicScenarioInput('cloud', 'fictional-v2', 20, null)); + self::assertSame('SYNTHETIC_ONLY', $result['parameters']['scope']); + self::assertFalse($result['commercialization']['quote_allowed']); + } + + private static function engine(): EconomicSimulationEngine + { + return new EconomicSimulationEngine(new EconomicMatrixLoader(self::fixturePath())); + } + + private static function fixturePath(): string + { + return dirname(__DIR__, 2).'/tests/Fixtures/economic-historical-synthetic.json'; + } +} From e345febe1c881eca389cc071bb20adb17edb8e9d Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:26:11 +0000 Subject: [PATCH 02/11] test(pricing): correct incremental candidate contribution expectation Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Unit/EconomicSimulationEngineTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Unit/EconomicSimulationEngineTest.php b/tests/Unit/EconomicSimulationEngineTest.php index 8f44b03..316a69f 100644 --- a/tests/Unit/EconomicSimulationEngineTest.php +++ b/tests/Unit/EconomicSimulationEngineTest.php @@ -56,7 +56,7 @@ public function testCandidatePriceProducesExplainableComparisons(): void $input = new EconomicScenarioInput('cloud', 'fictional-v2', 20, '200.00'); $result = self::engine()->simulate($input); self::assertSame('200.00', $result['calculation']['candidate_price']); - self::assertSame('58.00', $result['calculation']['candidate_incremental_contribution']); + self::assertSame('158.00', $result['calculation']['candidate_incremental_contribution']); self::assertSame('60.00', $result['calculation']['candidate_full_margin']); self::assertSame('42.00', $result['calculation']['candidate_preservation_delta']); } From 96b4418be35bddf0dfe3257ed160f25dc93dbe2a Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:28:02 +0000 Subject: [PATCH 03/11] feat(pricing): isolate private economic analysis and approved quote access Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- config/services.yaml | 17 ++ docker/nginx/pricing.conf | 14 ++ docs/private-economic-configuration.md | 52 ++++++ .../EconomicSimulationController.php | 86 +++++++++ src/Domain/EconomicSimulationEngine.php | 5 + src/Http/EconomicBearerAuthenticator.php | 43 +++++ src/Http/EconomicRequestParser.php | 47 +++++ tests/Http/EconomicSimulationHttpTest.php | 166 ++++++++++++++++++ 8 files changed, 430 insertions(+) create mode 100644 docs/private-economic-configuration.md create mode 100644 src/Controller/EconomicSimulationController.php create mode 100644 src/Http/EconomicBearerAuthenticator.php create mode 100644 src/Http/EconomicRequestParser.php create mode 100644 tests/Http/EconomicSimulationHttpTest.php diff --git a/config/services.yaml b/config/services.yaml index c5d1e61..0996ead 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -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: @@ -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)%' diff --git a/docker/nginx/pricing.conf b/docker/nginx/pricing.conf index eedf525..cf2b249 100644 --- a/docker/nginx/pricing.conf +++ b/docker/nginx/pricing.conf @@ -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; diff --git a/docs/private-economic-configuration.md b/docs/private-economic-configuration.md new file mode 100644 index 0000000..b4c3b64 --- /dev/null +++ b/docs/private-economic-configuration.md @@ -0,0 +1,52 @@ + + +# 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 only a candidate quote amount, 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. +- `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. diff --git a/src/Controller/EconomicSimulationController.php b/src/Controller/EconomicSimulationController.php new file mode 100644 index 0000000..bfc8aac --- /dev/null +++ b/src/Controller/EconomicSimulationController.php @@ -0,0 +1,86 @@ + '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); + + 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'], + 'model' => $input->model, + 'billing_basis' => $result['billing_basis'], + 'currency' => $result['currency'], + 'candidate_quote_price' => $result['calculation']['preservation_price_with_margin'], + '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); + } + } +} diff --git a/src/Domain/EconomicSimulationEngine.php b/src/Domain/EconomicSimulationEngine.php index a5bce64..50d36f7 100644 --- a/src/Domain/EconomicSimulationEngine.php +++ b/src/Domain/EconomicSimulationEngine.php @@ -131,6 +131,11 @@ public function simulate(EconomicScenarioInput $input): array $result['calculation']['candidate_preservation_delta'] = $this->money($net->minus($preservationCost)); } + if ($matrix->quoteAllowed(array_keys($needed), gmdate('Y-m-d'))) { + $base['commercialization']['quote_allowed'] = true; + $base['commercialization']['reason_code'] = 'APPROVED_PARAMETER_SET'; + } + return $base + $result; } diff --git a/src/Http/EconomicBearerAuthenticator.php b/src/Http/EconomicBearerAuthenticator.php new file mode 100644 index 0000000..5c8aacc --- /dev/null +++ b/src/Http/EconomicBearerAuthenticator.php @@ -0,0 +1,43 @@ +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'); + } + } +} diff --git a/src/Http/EconomicRequestParser.php b/src/Http/EconomicRequestParser.php new file mode 100644 index 0000000..9e4b119 --- /dev/null +++ b/src/Http/EconomicRequestParser.php @@ -0,0 +1,47 @@ +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, + ); + } +} diff --git a/tests/Http/EconomicSimulationHttpTest.php b/tests/Http/EconomicSimulationHttpTest.php new file mode 100644 index 0000000..dd47d51 --- /dev/null +++ b/tests/Http/EconomicSimulationHttpTest.php @@ -0,0 +1,166 @@ + */ + private array $files = []; + + protected function tearDown(): void + { + foreach ($this->files as $file) { + @unlink($file); + } + } + + public function testAnalystReceivesDetailedSyntheticCalculation(): void + { + $controller = $this->controller('0'); + $response = $controller->simulate(self::request('/v1/economic-simulations', 'analyst-'.str_repeat('x', 33))); + self::assertSame(200, $response->getStatusCode()); + $data = json_decode((string) $response->getContent(), true, 32, JSON_THROW_ON_ERROR); + self::assertSame('3810.00', $data['calculation']['full_cost']); + self::assertFalse($data['commercialization']['quote_allowed']); + self::assertSame('no-store', $response->headers->get('Cache-Control')); + } + + public function testQuotesFailClosedForSyntheticParameters(): void + { + $controller = $this->controller('1'); + $response = $controller->quote(self::request('/v1/economic-quotes', 'quotes-'.str_repeat('y', 33))); + self::assertSame(409, $response->getStatusCode()); + self::assertStringNotContainsString('full_cost', (string) $response->getContent()); + self::assertStringNotContainsString('tax_rate', (string) $response->getContent()); + } + + public function testQuotesDisabledWithoutHostApproval(): void + { + $controller = $this->controller('0'); + $response = $controller->quote(self::request('/v1/economic-quotes', 'quotes-'.str_repeat('y', 33))); + self::assertSame(403, $response->getStatusCode()); + } + + public function testRolesAreNotInterchangeable(): void + { + $controller = $this->controller('1'); + self::assertSame(401, $controller->simulate(self::request('/v1/economic-simulations', 'quotes-'.str_repeat('y', 33)))->getStatusCode()); + self::assertSame(401, $controller->quote(self::request('/v1/economic-quotes', 'analyst-'.str_repeat('x', 33)))->getStatusCode()); + } + + public function testUnconfiguredAuthenticationDeniesAccess(): void + { + $controller = new EconomicSimulationController( + new EconomicSimulationEngine(new EconomicMatrixLoader(self::fixture())), + new EconomicBearerAuthenticator('', ''), + new EconomicRequestParser(), + '1', + ); + self::assertSame(401, $controller->simulate(self::request('/v1/economic-simulations', 'analyst-'.str_repeat('x', 33)))->getStatusCode()); + } + + public function testMissingMatrixIsSanitized(): void + { + $controller = $this->controller('1', '/nonexistent/private/economics.json'); + $response = $controller->simulate(self::request('/v1/economic-simulations', 'analyst-'.str_repeat('x', 33))); + self::assertSame(503, $response->getStatusCode()); + self::assertStringNotContainsString('/nonexistent', (string) $response->getContent()); + } + + public function testInvalidJsonIsRejected(): void + { + $controller = $this->controller('1'); + $request = Request::create( + '/v1/economic-simulations', + 'POST', + [], + [], + [], + ['HTTP_AUTHORIZATION' => 'Bearer analyst-'.str_repeat('x', 33), 'CONTENT_TYPE' => 'application/json'], + '{invalid', + ); + self::assertSame(400, $controller->simulate($request)->getStatusCode()); + } + + public function testApprovedPrivateQuotesAreRedacted(): void + { + $data = json_decode((string) file_get_contents(self::fixture()), true, 32, JSON_THROW_ON_ERROR); + $data['scope'] = 'PRIVATE_ECONOMICS'; + $data['approval_status'] = 'approved_for_quotes'; + $data['approved_by'] = 'fictional-reviewer'; + $data['approval_reference'] = 'synthetic-test-approval'; + $data['effective_from'] = '2020-01-01'; + $data['effective_until'] = '2099-12-31'; + foreach ($data['parameters'] as &$parameter) { + $parameter['approval_status'] = 'approved_for_commercial_use'; + } + unset($parameter); + $private = $this->secret(json_encode($data, JSON_THROW_ON_ERROR)); + $controller = $this->controller('1', $private); + $response = $controller->quote(self::request('/v1/economic-quotes', 'quotes-'.str_repeat('y', 33))); + self::assertSame(200, $response->getStatusCode()); + $payload = json_decode((string) $response->getContent(), true, 32, JSON_THROW_ON_ERROR); + self::assertSame('5532.47', $payload['candidate_quote_price']); + self::assertFalse($payload['activation_allowed']); + self::assertArrayNotHasKey('calculation', $payload); + self::assertArrayNotHasKey('parameters', $payload); + self::assertStringNotContainsString('full_cost', (string) $response->getContent()); + } + + private function controller(string $enabled, ?string $path = null): EconomicSimulationController + { + return new EconomicSimulationController( + new EconomicSimulationEngine(new EconomicMatrixLoader($path ?? self::fixture())), + new EconomicBearerAuthenticator( + $this->secret('analyst-'.str_repeat('x', 33)), + $this->secret('quotes-'.str_repeat('y', 33)), + ), + new EconomicRequestParser(), + $enabled, + ); + } + + private function secret(string $content): string + { + $file = tempnam(sys_get_temp_dir(), 'pricing-auth-'); + self::assertNotFalse($file); + $this->files[] = $file; + file_put_contents($file, $content); + return $file; + } + + private static function request(string $path, string $token): Request + { + return Request::create( + $path, + 'POST', + [], + [], + [], + ['HTTP_AUTHORIZATION' => 'Bearer '.$token, 'CONTENT_TYPE' => 'application/json'], + json_encode([ + 'model' => 'managed', + 'parameter_version' => 'fictional-v2', + 'customers' => 1, + ], JSON_THROW_ON_ERROR), + ); + } + + private static function fixture(): string + { + return dirname(__DIR__, 2).'/tests/Fixtures/economic-historical-synthetic.json'; + } +} From 026205d4eaeeeeaf370806960a0b3abfd5e138ef Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:29:27 +0000 Subject: [PATCH 04/11] feat(pricing): distinguish one-time implementation from recurring prices Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- docs/economic-calculation.md | 3 ++- src/Domain/EconomicSimulationEngine.php | 6 ++++++ tests/Unit/EconomicSimulationEngineTest.php | 8 ++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/docs/economic-calculation.md b/docs/economic-calculation.md index 58b9e2d..6a1de14 100644 --- a/docs/economic-calculation.md +++ b/docs/economic-calculation.md @@ -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)`. @@ -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. diff --git a/src/Domain/EconomicSimulationEngine.php b/src/Domain/EconomicSimulationEngine.php index a5bce64..68e558f 100644 --- a/src/Domain/EconomicSimulationEngine.php +++ b/src/Domain/EconomicSimulationEngine.php @@ -32,6 +32,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', @@ -103,6 +104,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', @@ -114,6 +118,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, diff --git a/tests/Unit/EconomicSimulationEngineTest.php b/tests/Unit/EconomicSimulationEngineTest.php index 316a69f..271d526 100644 --- a/tests/Unit/EconomicSimulationEngineTest.php +++ b/tests/Unit/EconomicSimulationEngineTest.php @@ -51,6 +51,14 @@ public function testReproducesNinePreviouslyDocumentedIllustrativeScenarios( self::assertFalse($first['commercialization']['activation_allowed']); } + public function testSetupPriceIsSeparateFromRecurringInfrastructureSupport(): void + { + $result = self::engine()->simulate(new EconomicScenarioInput('customer_infrastructure', 'fictional-v2', 1, null)); + self::assertSame('1142.86', $result['calculation']['preservation_price_with_margin']); + self::assertSame('1800.00', $result['calculation']['one_time_setup_cost']); + self::assertSame('2337.66', $result['calculation']['one_time_setup_preservation_price']); + } + public function testCandidatePriceProducesExplainableComparisons(): void { $input = new EconomicScenarioInput('cloud', 'fictional-v2', 20, '200.00'); From f13b768258e793139f7a64bb61b34d1f6a830f7e Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:29:50 +0000 Subject: [PATCH 05/11] feat(pricing): return separately governed setup and service prices Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- docs/economic-calculation.md | 3 ++- docs/private-economic-configuration.md | 2 +- src/Controller/EconomicSimulationController.php | 3 ++- src/Domain/EconomicSimulationEngine.php | 6 ++++++ tests/Http/EconomicSimulationHttpTest.php | 3 ++- tests/Unit/EconomicSimulationEngineTest.php | 8 ++++++++ 6 files changed, 21 insertions(+), 4 deletions(-) diff --git a/docs/economic-calculation.md b/docs/economic-calculation.md index 58b9e2d..6a1de14 100644 --- a/docs/economic-calculation.md +++ b/docs/economic-calculation.md @@ -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)`. @@ -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. diff --git a/docs/private-economic-configuration.md b/docs/private-economic-configuration.md index b4c3b64..b6dcf52 100644 --- a/docs/private-economic-configuration.md +++ b/docs/private-economic-configuration.md @@ -21,7 +21,7 @@ Rotating credentials or a parameter snapshot is an operator-controlled action. C ## 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 only a candidate quote amount, 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. +- `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. - `POST /v1/simulations`: legacy synthetic-only endpoint. Unchanged. Both economic routes accept the same JSON request shape: diff --git a/src/Controller/EconomicSimulationController.php b/src/Controller/EconomicSimulationController.php index bfc8aac..07f7881 100644 --- a/src/Controller/EconomicSimulationController.php +++ b/src/Controller/EconomicSimulationController.php @@ -72,7 +72,8 @@ public function quote(Request $request): JsonResponse 'model' => $input->model, 'billing_basis' => $result['billing_basis'], 'currency' => $result['currency'], - 'candidate_quote_price' => $result['calculation']['preservation_price_with_margin'], + '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) { diff --git a/src/Domain/EconomicSimulationEngine.php b/src/Domain/EconomicSimulationEngine.php index 50d36f7..ca35c1f 100644 --- a/src/Domain/EconomicSimulationEngine.php +++ b/src/Domain/EconomicSimulationEngine.php @@ -32,6 +32,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', @@ -103,6 +104,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', @@ -114,6 +118,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, diff --git a/tests/Http/EconomicSimulationHttpTest.php b/tests/Http/EconomicSimulationHttpTest.php index dd47d51..3ba6666 100644 --- a/tests/Http/EconomicSimulationHttpTest.php +++ b/tests/Http/EconomicSimulationHttpTest.php @@ -113,7 +113,8 @@ public function testApprovedPrivateQuotesAreRedacted(): void $response = $controller->quote(self::request('/v1/economic-quotes', 'quotes-'.str_repeat('y', 33))); self::assertSame(200, $response->getStatusCode()); $payload = json_decode((string) $response->getContent(), true, 32, JSON_THROW_ON_ERROR); - self::assertSame('5532.47', $payload['candidate_quote_price']); + self::assertSame('5532.47', $payload['service_period_reference_price']); + self::assertSame('1870.13', $payload['one_time_setup_reference_price']); self::assertFalse($payload['activation_allowed']); self::assertArrayNotHasKey('calculation', $payload); self::assertArrayNotHasKey('parameters', $payload); diff --git a/tests/Unit/EconomicSimulationEngineTest.php b/tests/Unit/EconomicSimulationEngineTest.php index 316a69f..271d526 100644 --- a/tests/Unit/EconomicSimulationEngineTest.php +++ b/tests/Unit/EconomicSimulationEngineTest.php @@ -51,6 +51,14 @@ public function testReproducesNinePreviouslyDocumentedIllustrativeScenarios( self::assertFalse($first['commercialization']['activation_allowed']); } + public function testSetupPriceIsSeparateFromRecurringInfrastructureSupport(): void + { + $result = self::engine()->simulate(new EconomicScenarioInput('customer_infrastructure', 'fictional-v2', 1, null)); + self::assertSame('1142.86', $result['calculation']['preservation_price_with_margin']); + self::assertSame('1800.00', $result['calculation']['one_time_setup_cost']); + self::assertSame('2337.66', $result['calculation']['one_time_setup_preservation_price']); + } + public function testCandidatePriceProducesExplainableComparisons(): void { $input = new EconomicScenarioInput('cloud', 'fictional-v2', 20, '200.00'); From 4ed6d8ad978f1a3533fff0063452027735805385 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:31:14 +0000 Subject: [PATCH 06/11] test(pricing): assert no-store with Symfony's private cache directive Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- tests/Http/EconomicSimulationHttpTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Http/EconomicSimulationHttpTest.php b/tests/Http/EconomicSimulationHttpTest.php index 3ba6666..4873a94 100644 --- a/tests/Http/EconomicSimulationHttpTest.php +++ b/tests/Http/EconomicSimulationHttpTest.php @@ -35,7 +35,7 @@ public function testAnalystReceivesDetailedSyntheticCalculation(): void $data = json_decode((string) $response->getContent(), true, 32, JSON_THROW_ON_ERROR); self::assertSame('3810.00', $data['calculation']['full_cost']); self::assertFalse($data['commercialization']['quote_allowed']); - self::assertSame('no-store', $response->headers->get('Cache-Control')); + self::assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control')); } public function testQuotesFailClosedForSyntheticParameters(): void From 6f74bb7db4640f495823cf9babf88199337aa69d Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:32:16 +0000 Subject: [PATCH 07/11] fix(api): exclude private economic routes from public OpenAPI Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- config/packages/dev/nelmio_api_doc.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/config/packages/dev/nelmio_api_doc.yaml b/config/packages/dev/nelmio_api_doc.yaml index 0a1e63c..8272acd 100644 --- a/config/packages/dev/nelmio_api_doc.yaml +++ b/config/packages/dev/nelmio_api_doc.yaml @@ -15,4 +15,6 @@ nelmio_api_doc: - bearerAuth: [] areas: path_patterns: - - '^/v1/' + # Private economic routes are deliberately excluded from the public synthetic API spec. + - '^/v1/simulations + From 3055aa0e5b630e2531b4056e72cdce323f010321 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:33:14 +0000 Subject: [PATCH 08/11] fix(pricing): bind quote approval date to deterministic result Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- docs/private-economic-configuration.md | 2 +- src/Controller/EconomicSimulationController.php | 3 ++- src/Domain/EconomicSimulationEngine.php | 7 +++++-- tests/Http/EconomicSimulationHttpTest.php | 1 + 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/private-economic-configuration.md b/docs/private-economic-configuration.md index b6dcf52..267805a 100644 --- a/docs/private-economic-configuration.md +++ b/docs/private-economic-configuration.md @@ -21,7 +21,7 @@ Rotating credentials or a parameter snapshot is an operator-controlled action. C ## 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. +- `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: diff --git a/src/Controller/EconomicSimulationController.php b/src/Controller/EconomicSimulationController.php index 07f7881..ad4ed09 100644 --- a/src/Controller/EconomicSimulationController.php +++ b/src/Controller/EconomicSimulationController.php @@ -59,7 +59,7 @@ public function quote(Request $request): JsonResponse return new JsonResponse(['error' => 'quotes_disabled'], 403, self::RESPONSE_HEADERS); } $input = $this->parser->parse($request); - $result = $this->engine->simulate($input); + $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); @@ -69,6 +69,7 @@ public function quote(Request $request): JsonResponse 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'], diff --git a/src/Domain/EconomicSimulationEngine.php b/src/Domain/EconomicSimulationEngine.php index ca35c1f..2e8b244 100644 --- a/src/Domain/EconomicSimulationEngine.php +++ b/src/Domain/EconomicSimulationEngine.php @@ -20,7 +20,7 @@ public function __construct(private EconomicMatrixLoader $loader) } /** @return array */ - public function simulate(EconomicScenarioInput $input): array + public function simulate(EconomicScenarioInput $input, ?string $approvalDate = null): array { $matrix = $this->loader->load(); if ($matrix->version() !== $input->parameterVersion) { @@ -55,12 +55,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' => [ @@ -137,7 +139,8 @@ public function simulate(EconomicScenarioInput $input): array $result['calculation']['candidate_preservation_delta'] = $this->money($net->minus($preservationCost)); } - if ($matrix->quoteAllowed(array_keys($needed), gmdate('Y-m-d'))) { + // 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'; } diff --git a/tests/Http/EconomicSimulationHttpTest.php b/tests/Http/EconomicSimulationHttpTest.php index 4873a94..0d1bdd0 100644 --- a/tests/Http/EconomicSimulationHttpTest.php +++ b/tests/Http/EconomicSimulationHttpTest.php @@ -115,6 +115,7 @@ public function testApprovedPrivateQuotesAreRedacted(): void $payload = json_decode((string) $response->getContent(), true, 32, JSON_THROW_ON_ERROR); self::assertSame('5532.47', $payload['service_period_reference_price']); self::assertSame('1870.13', $payload['one_time_setup_reference_price']); + self::assertSame(gmdate('Y-m-d'), $payload['approval_as_of']); self::assertFalse($payload['activation_allowed']); self::assertArrayNotHasKey('calculation', $payload); self::assertArrayNotHasKey('parameters', $payload); From 454cc4b0ab7c942a360365079785db9d65730361 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:33:53 +0000 Subject: [PATCH 09/11] fix(pricing): reject mismatched matrix parameters without server errors Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Domain/EconomicSimulationEngine.php | 7 ++++++- tests/Unit/EconomicSimulationEngineTest.php | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Domain/EconomicSimulationEngine.php b/src/Domain/EconomicSimulationEngine.php index 68e558f..2a6dfae 100644 --- a/src/Domain/EconomicSimulationEngine.php +++ b/src/Domain/EconomicSimulationEngine.php @@ -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 @@ -43,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 { diff --git a/tests/Unit/EconomicSimulationEngineTest.php b/tests/Unit/EconomicSimulationEngineTest.php index 271d526..08c7563 100644 --- a/tests/Unit/EconomicSimulationEngineTest.php +++ b/tests/Unit/EconomicSimulationEngineTest.php @@ -9,6 +9,7 @@ use LibreSign\Pricing\Domain\EconomicScenarioInput; use LibreSign\Pricing\Domain\EconomicSimulationEngine; +use LibreSign\Pricing\Infrastructure\CatalogUnavailable; use LibreSign\Pricing\Infrastructure\EconomicMatrixLoader; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -105,6 +106,25 @@ public function testUnknownCostsBlockCalculationInsteadOfBecomingZero(): void } } + public function testMissingRequiredParameterIsAConfigurationError(): void + { + $data = json_decode((string) file_get_contents(self::fixturePath()), true, 32, JSON_THROW_ON_ERROR); + $data['parameters'] = array_values(array_filter( + $data['parameters'], + static fn (array $item): bool => $item['id'] !== 'simulation.cloud.fixed_pool', + )); + $path = tempnam(sys_get_temp_dir(), 'pricing-test-'); + self::assertNotFalse($path); + try { + file_put_contents($path, json_encode($data, JSON_THROW_ON_ERROR)); + $this->expectException(CatalogUnavailable::class); + (new EconomicSimulationEngine(new EconomicMatrixLoader($path))) + ->simulate(new EconomicScenarioInput('cloud', 'fictional-v2', 20, null)); + } finally { + unlink($path); + } + } + public function testSyntheticApprovalNeverAuthorizesQuote(): void { $result = self::engine()->simulate(new EconomicScenarioInput('cloud', 'fictional-v2', 20, null)); From c0e407afbc7c3da3ad32b072f29e2efb574e25fb Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:34:17 +0000 Subject: [PATCH 10/11] test(pricing): validate private route wiring and fail closed on matrix mismatches Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- src/Domain/EconomicSimulationEngine.php | 7 ++++- tests/Http/EconomicRoutingHttpTest.php | 35 +++++++++++++++++++++ tests/Unit/EconomicSimulationEngineTest.php | 20 ++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 tests/Http/EconomicRoutingHttpTest.php diff --git a/src/Domain/EconomicSimulationEngine.php b/src/Domain/EconomicSimulationEngine.php index 2e8b244..c343013 100644 --- a/src/Domain/EconomicSimulationEngine.php +++ b/src/Domain/EconomicSimulationEngine.php @@ -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 @@ -43,7 +44,11 @@ public function simulate(EconomicScenarioInput $input, ?string $approvalDate = n $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 { diff --git a/tests/Http/EconomicRoutingHttpTest.php b/tests/Http/EconomicRoutingHttpTest.php new file mode 100644 index 0000000..0092ca6 --- /dev/null +++ b/tests/Http/EconomicRoutingHttpTest.php @@ -0,0 +1,35 @@ +request( + 'POST', + $path, + server: ['CONTENT_TYPE' => 'application/json'], + content: '{}', + ); + self::assertResponseStatusCodeSame(401); + self::assertStringContainsString('no-store', (string) $client->getResponse()->headers->get('Cache-Control')); + } + } +} diff --git a/tests/Unit/EconomicSimulationEngineTest.php b/tests/Unit/EconomicSimulationEngineTest.php index 271d526..08c7563 100644 --- a/tests/Unit/EconomicSimulationEngineTest.php +++ b/tests/Unit/EconomicSimulationEngineTest.php @@ -9,6 +9,7 @@ use LibreSign\Pricing\Domain\EconomicScenarioInput; use LibreSign\Pricing\Domain\EconomicSimulationEngine; +use LibreSign\Pricing\Infrastructure\CatalogUnavailable; use LibreSign\Pricing\Infrastructure\EconomicMatrixLoader; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -105,6 +106,25 @@ public function testUnknownCostsBlockCalculationInsteadOfBecomingZero(): void } } + public function testMissingRequiredParameterIsAConfigurationError(): void + { + $data = json_decode((string) file_get_contents(self::fixturePath()), true, 32, JSON_THROW_ON_ERROR); + $data['parameters'] = array_values(array_filter( + $data['parameters'], + static fn (array $item): bool => $item['id'] !== 'simulation.cloud.fixed_pool', + )); + $path = tempnam(sys_get_temp_dir(), 'pricing-test-'); + self::assertNotFalse($path); + try { + file_put_contents($path, json_encode($data, JSON_THROW_ON_ERROR)); + $this->expectException(CatalogUnavailable::class); + (new EconomicSimulationEngine(new EconomicMatrixLoader($path))) + ->simulate(new EconomicScenarioInput('cloud', 'fictional-v2', 20, null)); + } finally { + unlink($path); + } + } + public function testSyntheticApprovalNeverAuthorizesQuote(): void { $result = self::engine()->simulate(new EconomicScenarioInput('cloud', 'fictional-v2', 20, null)); From 11c78807458fef8ea5aaf2bcade38966a5c62848 Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:36:34 +0000 Subject: [PATCH 11/11] fix(api): repair private-route exclusion in OpenAPI configuration Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- config/packages/dev/nelmio_api_doc.yaml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/config/packages/dev/nelmio_api_doc.yaml b/config/packages/dev/nelmio_api_doc.yaml index 8272acd..d2236fb 100644 --- a/config/packages/dev/nelmio_api_doc.yaml +++ b/config/packages/dev/nelmio_api_doc.yaml @@ -15,6 +15,5 @@ nelmio_api_doc: - bearerAuth: [] areas: path_patterns: - # Private economic routes are deliberately excluded from the public synthetic API spec. - - '^/v1/simulations - + # Private economic endpoints are intentionally outside the public synthetic OpenAPI. + - '^/v1/simulations$'