diff --git a/docs/economic-calculation.md b/docs/economic-calculation.md new file mode 100644 index 0000000..6a1de14 --- /dev/null +++ b/docs/economic-calculation.md @@ -0,0 +1,28 @@ + + +# 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`. +- 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)`. + +**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. 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/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..2a6dfae --- /dev/null +++ b/src/Domain/EconomicSimulationEngine.php @@ -0,0 +1,160 @@ + */ + 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.'.setup_hours' => 'hour/customer', + $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) { + 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 { + $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); + $setupHours = $values[$prefix.'.setup_hours']; + $setupCost = $setupHours->multipliedBy($collectiveHour); + $setupPrice = $setupCost->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), + '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, + '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..08c7563 --- /dev/null +++ b/tests/Unit/EconomicSimulationEngineTest.php @@ -0,0 +1,144 @@ + ['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 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'); + $result = self::engine()->simulate($input); + self::assertSame('200.00', $result['calculation']['candidate_price']); + 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']); + } + + 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 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)); + 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'; + } +}