Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/economic-calculation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!-- SPDX-FileCopyrightText: 2026 LibreSign contributors
SPDX-License-Identifier: AGPL-3.0-or-later -->

# 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.
38 changes: 38 additions & 0 deletions src/Domain/EconomicScenarioInput.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

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

declare(strict_types=1);

namespace LibreSign\Pricing\Domain;

final readonly class EconomicScenarioInput
{
public function __construct(
public string $model,
public string $parameterVersion,
public int $customers,
public ?string $candidatePrice,
) {
if (!in_array($this->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,
];
}
}
160 changes: 160 additions & 0 deletions src/Domain/EconomicSimulationEngine.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php

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

declare(strict_types=1);

namespace LibreSign\Pricing\Domain;

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

final readonly class EconomicSimulationEngine
{
public const VERSION = '1.0.0';

public function __construct(private EconomicMatrixLoader $loader)
{
}

/** @return array<string, mixed> */
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);
}
}
Loading
Loading