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 1/4] 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 2/4] 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 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 3/4] 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 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 4/4] 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));