Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
10c9b4e
feat(pricing): calculate parameterized economic scenarios
vitormattos Nov 5, 2026
e345feb
test(pricing): correct incremental candidate contribution expectation
vitormattos Nov 5, 2026
96b4418
feat(pricing): isolate private economic analysis and approved quote a…
vitormattos Nov 5, 2026
026205d
feat(pricing): distinguish one-time implementation from recurring prices
vitormattos Nov 5, 2026
f13b768
feat(pricing): return separately governed setup and service prices
vitormattos Nov 5, 2026
4ed6d8a
test(pricing): assert no-store with Symfony's private cache directive
vitormattos Nov 5, 2026
6f74bb7
fix(api): exclude private economic routes from public OpenAPI
vitormattos Nov 5, 2026
3055aa0
fix(pricing): bind quote approval date to deterministic result
vitormattos Nov 5, 2026
454cc4b
fix(pricing): reject mismatched matrix parameters without server errors
vitormattos Nov 5, 2026
c0e407a
test(pricing): validate private route wiring and fail closed on matri…
vitormattos Nov 5, 2026
11c7880
fix(api): repair private-route exclusion in OpenAPI configuration
vitormattos Nov 5, 2026
7df6365
Merge pull request #9 from LibreSign/feat/private-economic-authorization
vitormattos Nov 5, 2026
b3f7d25
feat(pricing): add guarded internal workbench and metadata routes
vitormattos Nov 5, 2026
8be3ca6
feat(pricing): add private browser simulation experience
vitormattos Nov 5, 2026
994740a
test(pricing): verify workbench privacy, metadata and versioning
vitormattos Nov 5, 2026
f8f128d
ci(pricing): validate internal workbench JavaScript syntax
vitormattos Nov 5, 2026
2385a8d
docs(pricing): add browser acceptance scenarios and readable margins
vitormattos Nov 5, 2026
ff30ad8
docs(pricing): explain private workbench and current maturity
vitormattos Nov 5, 2026
17b8b01
fix(pricing): exclude workbench assets from API rate limit
vitormattos Nov 5, 2026
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
33 changes: 33 additions & 0 deletions .github/workflows/ui.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# SPDX-FileCopyrightText: 2026 LibreSign contributors
# SPDX-License-Identifier: AGPL-3.0-or-later
name: Internal UI check

on:
pull_request:
push:
branches: [main]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
syntax:
name: Internal UI syntax
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Verify JavaScript syntax
run: node --check src/Ui/pricing-workbench.js
- name: Verify referenced local assets exist
run: |
test -s src/Ui/pricing-workbench.html
test -s src/Ui/pricing-workbench.css
test -s src/Ui/pricing-workbench.js
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,18 @@ The engine distinguishes costs that change with additional business from allocat

## Current maturity

This repository contains an **early technical increment with deliberately fictional test data only**. None of the numbers included in its fixtures represent LibreCode internal costs, approved market offers, or current Brazilian tax obligations. The engine refuses to load a catalog implicitly and cannot authorize commercialization.
This repository provides a parameterized economic calculator for the three LibreSign modalities, including an external economic matrix, deterministic result fingerprints, and separately calculated one-time setup costs. The public fixtures are **entirely fictional**: none of their values represent LibreCode expenses, approved prices, or applicable tax rates.

No customer-facing pricing integration is active. Access to sensitive calculations must remain restricted until roles, confidentiality controls, independently verified economics, and approval workflows have been implemented and reviewed.
A separate, disabled-by-default analyst API and private browser workbench support controlled economic validation. Real parameter files and analyst credentials are loaded **only from privately mounted host configuration**. The workbench never modifies configuration or enables WooCommerce billing, contract activation, or public price publication.

Economic results remain estimates pending governance and data homologation. No customer-facing pricing integration is active.

## Project documentation

- [Architecture and development](docs/development.md)
- [Economic matrix contract](docs/economic-matrix.md)
- [Economic simulation formulas](docs/economic-calculation.md)
- [Private economic configuration and browser workbench](docs/private-economic-configuration.md)
- [Private Docker homologation and controlled deployment](docs/homologation.md)
- [Simulation API](docs/api.md)
- [Generated OpenAPI specification](docs/openapi.yaml)
Expand Down
3 changes: 2 additions & 1 deletion config/packages/dev/nelmio_api_doc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ nelmio_api_doc:
- bearerAuth: []
areas:
path_patterns:
- '^/v1/'
# Private economic endpoints are intentionally outside the public synthetic OpenAPI.
- '^/v1/simulations$'
22 changes: 22 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
# 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'
env(PRICING_WORKBENCH_ENABLED): '0'

services:
_defaults:
Expand All @@ -15,3 +20,20 @@ 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)%'

LibreSign\Pricing\Controller\EconomicWorkbenchController:
arguments:
$enabled: '%env(string:PRICING_WORKBENCH_ENABLED)%'
41 changes: 41 additions & 0 deletions docker/nginx/pricing.conf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,47 @@ 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;
}

# Static workbench assets do not consume the analyst API's request quota.
# Access remains loopback-only in the local preview and disabled by default in PHP.
location ~ ^/internal/pricing-workbench(?:\.(?:css|js))?$ {
limit_except GET { deny all; }
limit_conn pricing_connections 2;

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

# Analyst-only configuration metadata, never a financial export.
location = /v1/economic-metadata {
limit_except GET { deny all; }
limit_req zone=pricing_requests burst=4 nodelay;
limit_conn pricing_connections 2;

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

# Liveness reveals no catalog, price, identity, process or configuration data.
location = /healthz {
include fastcgi_params;
Expand Down
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.
83 changes: 83 additions & 0 deletions docs/private-economic-configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<!-- SPDX-FileCopyrightText: 2026 LibreSign contributors
SPDX-License-Identifier: AGPL-3.0-or-later -->

# Private economic configuration and commercial authorization

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

## Installation boundary

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

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

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

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

## Endpoints

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

Both economic routes accept the same JSON request shape:

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

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

## Approval and limits

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

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

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

## Private migration from previous research

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

No real parameter set, accountant working paper, confidential file path, or approval receipt must be committed. Economic homologation is a human-governed operation distinct from merging PHP code.

## Browser-based validation workbench

An optional, **internal-only** read-only interface is served by Symfony at `GET /internal/pricing-workbench`. The default `PRICING_WORKBENCH_ENABLED=0` returns HTTP 404 for the page and both local assets. An authorized infrastructure operator must deliberately set `PRICING_WORKBENCH_ENABLED=1` in the **private** deployment configuration and make the route reachable only on an authorized HTTPS/internal network.

The screen uses the same `POST /v1/economic-simulations` endpoint as programmatic consumers. `GET /v1/economic-metadata` accepts only the **analyst token** and returns the catalog version, SHA-256, scope, approval status and three model identifiers, not the underlying financial values. The browser sends the analyst token in an Authorization header, keeps it only in the password field during the open tab, and does not use browser storage or third-party scripts. Close/clear the tab after testing.

### Private setup (no real economic values in Git)

1. Integrate and review the calculator PR and this UI PR; validate their CI on the final `main` revision.
2. Use the existing isolated private Docker Compose override. Make sure no host ports are published and no public proxy network is attached. Mount the private economic matrix read-only at a path such as `/run/secrets/pricing_economic_matrix`, and an **independent** analyst token file at a path such as `/run/secrets/pricing_economic_analyst_token`. The token must be at least 32 characters. Never place its bytes or the matrix contents into Compose YAML, environment strings, the repository, container images, CI logs or support tickets.
3. Set `PRICING_ECONOMIC_MATRIX_PATH` and `PRICING_ECONOMIC_ANALYST_TOKEN_FILE` to those in-container secret paths. Set `PRICING_WORKBENCH_ENABLED=1` **only** in the host-private override. Keep `PRICING_ECONOMIC_QUOTES_ENABLED=0` and do not enable any WooCommerce activation or billing integration.
4. Open the internal workbench via the approved private HTTPS endpoint at `/internal/pricing-workbench`. Enter the analyst token and select **Carregar configuração**. The server responds with the current parameter version and scope. If the page is 404, verify the private enable flag and network route.
5. Select Cloud, Managed or infrastructure do cliente; enter the number of paying customers and optionally a candidate price; select **Calcular cenário**. Compare the full-cost, incremental and preservation results, plus one-time setup. Check the matrix SHA-256 and simulation fingerprint when editing the private JSON.
6. Validate unknown parameters (`null`), negative/invalid inputs, mismatched units, capacity limits and behavior with an expired/not approved snapshot. All quotes/activation must remain blocked when parameters or approvals are missing. To change costs, update only the private JSON, create a new catalog version and repeat the simulation.

Use `tests/Fixtures/economic-historical-synthetic.json` when demonstrating the workbench **without any actual economic data**. This file is intentionally fictional, reproducing three volume scenarios per modality in unit tests. The production image excludes test fixtures, so mount a private copy explicitly when testing with them.

The workbench has no parameter editor, import of confidential spreadsheets, history database or price publication action. Its session comparison table exists only in memory. In a private real-economics trial, each analyst is responsible for handling and clearing results; avoid browser extensions or screen sharing that could disclose those values. Never use an internet-facing endpoint as a substitute for internal authentication.

### Quick fictional acceptance values

With `tests/Fixtures/economic-historical-synthetic.json` explicitly mounted **in a private test installation** (parameter version `fictional-v2`), the browser must reproduce these non-commercial fixtures:

| Model | Paying customers | Preservation price per contract/period | One-time setup |
| --- | ---: | ---: | ---: |
| Cloud | 20 | BRL 184.42 | BRL 233.77 |
| Managed | 3 | BRL 2,675.32 | BRL 1,870.13 |
| Customer infrastructure | 1 | BRL 1,142.86 | BRL 2,337.66 |

The margin indicator should display `15%`; every result must have `activation_allowed=false`. A test that changes a JSON cost while retaining the same version should change the SHA-256/fingerprint and display a warning to reload the matrix. Bump the private version after any reviewed change. These numbers are fictional examples, not LibreSign sale prices.
53 changes: 53 additions & 0 deletions src/Controller/EconomicMetadataController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

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

declare(strict_types=1);

namespace LibreSign\Pricing\Controller;

use LibreSign\Pricing\Http\ApiProblem;
use LibreSign\Pricing\Http\EconomicBearerAuthenticator;
use LibreSign\Pricing\Infrastructure\CatalogUnavailable;
use LibreSign\Pricing\Infrastructure\EconomicMatrixLoader;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

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

public function __construct(
private EconomicMatrixLoader $loader,
private EconomicBearerAuthenticator $authenticator,
) {
}

#[Route('/v1/economic-metadata', methods: ['GET'])]
public function __invoke(Request $request): JsonResponse
{
try {
$this->authenticator->assertAnalyst($request);
$matrix = $this->loader->load();

return new JsonResponse([
'parameters' => $matrix->metadata(),
'currency' => 'BRL',
'models' => [
'cloud' => $matrix->model('cloud')['billing_basis'],
'managed' => $matrix->model('managed')['billing_basis'],
'customer_infrastructure' => $matrix->model('customer_infrastructure')['billing_basis'],
],
], 200, self::HEADERS);
} catch (ApiProblem $problem) {
return new JsonResponse($problem->toArray(), $problem->status, self::HEADERS);
} catch (CatalogUnavailable) {
return new JsonResponse(['error' => 'economic_matrix_unavailable'], 503, self::HEADERS);
}
}
}
Loading
Loading