diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml
new file mode 100644
index 0000000..b9aa23b
--- /dev/null
+++ b/.github/workflows/ui.yml
@@ -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
diff --git a/README.md b/README.md
index 0111a6c..cb7614c 100644
--- a/README.md
+++ b/README.md
@@ -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)
diff --git a/config/packages/dev/nelmio_api_doc.yaml b/config/packages/dev/nelmio_api_doc.yaml
index 0a1e63c..d2236fb 100644
--- a/config/packages/dev/nelmio_api_doc.yaml
+++ b/config/packages/dev/nelmio_api_doc.yaml
@@ -15,4 +15,5 @@ nelmio_api_doc:
- bearerAuth: []
areas:
path_patterns:
- - '^/v1/'
+ # Private economic endpoints are intentionally outside the public synthetic OpenAPI.
+ - '^/v1/simulations$'
diff --git a/config/services.yaml b/config/services.yaml
index c5d1e61..a61c7bf 100644
--- a/config/services.yaml
+++ b/config/services.yaml
@@ -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:
@@ -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)%'
diff --git a/docker/nginx/pricing.conf b/docker/nginx/pricing.conf
index eedf525..edcab65 100644
--- a/docker/nginx/pricing.conf
+++ b/docker/nginx/pricing.conf
@@ -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;
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/docs/private-economic-configuration.md b/docs/private-economic-configuration.md
new file mode 100644
index 0000000..97e32d3
--- /dev/null
+++ b/docs/private-economic-configuration.md
@@ -0,0 +1,83 @@
+
+
+# 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.
diff --git a/src/Controller/EconomicMetadataController.php b/src/Controller/EconomicMetadataController.php
new file mode 100644
index 0000000..189c181
--- /dev/null
+++ b/src/Controller/EconomicMetadataController.php
@@ -0,0 +1,53 @@
+ '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);
+ }
+ }
+}
diff --git a/src/Controller/EconomicSimulationController.php b/src/Controller/EconomicSimulationController.php
new file mode 100644
index 0000000..ad4ed09
--- /dev/null
+++ b/src/Controller/EconomicSimulationController.php
@@ -0,0 +1,88 @@
+ '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, gmdate('Y-m-d'));
+
+ 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'],
+ 'approval_as_of' => $result['approval_as_of'],
+ 'model' => $input->model,
+ 'billing_basis' => $result['billing_basis'],
+ 'currency' => $result['currency'],
+ '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) {
+ 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/Controller/EconomicWorkbenchController.php b/src/Controller/EconomicWorkbenchController.php
new file mode 100644
index 0000000..7d7c8b9
--- /dev/null
+++ b/src/Controller/EconomicWorkbenchController.php
@@ -0,0 +1,63 @@
+ 'no-store, private',
+ 'X-Content-Type-Options' => 'nosniff',
+ 'X-Frame-Options' => 'DENY',
+ 'Referrer-Policy' => 'no-referrer',
+ 'Cross-Origin-Resource-Policy' => 'same-origin',
+ ];
+
+ public function __construct(private string $enabled)
+ {
+ }
+
+ #[Route('/internal/pricing-workbench', methods: ['GET'])]
+ public function page(): Response
+ {
+ return $this->asset('pricing-workbench.html', 'text/html; charset=UTF-8', true);
+ }
+
+ #[Route('/internal/pricing-workbench.css', methods: ['GET'])]
+ public function stylesheet(): Response
+ {
+ return $this->asset('pricing-workbench.css', 'text/css; charset=UTF-8');
+ }
+
+ #[Route('/internal/pricing-workbench.js', methods: ['GET'])]
+ public function script(): Response
+ {
+ return $this->asset('pricing-workbench.js', 'text/javascript; charset=UTF-8');
+ }
+
+ private function asset(string $name, string $contentType, bool $html = false): Response
+ {
+ if ($this->enabled !== '1') {
+ return new Response('', 404, self::HEADERS);
+ }
+
+ $content = @file_get_contents(__DIR__.'/../Ui/'.$name);
+ if (!is_string($content)) {
+ return new Response('', 503, self::HEADERS);
+ }
+
+ $headers = self::HEADERS + ['Content-Type' => $contentType];
+ if ($html) {
+ $headers['Content-Security-Policy'] = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
+ }
+
+ return new Response($content, 200, $headers);
+ }
+}
diff --git a/src/Domain/EconomicParameterMatrix.php b/src/Domain/EconomicParameterMatrix.php
index 4f2ba8b..e37eeb0 100644
--- a/src/Domain/EconomicParameterMatrix.php
+++ b/src/Domain/EconomicParameterMatrix.php
@@ -23,7 +23,7 @@ private function __construct(private array $document, private string $sha256)
|| !in_array($document['scope'] ?? null, ['SYNTHETIC_ONLY', 'PRIVATE_ECONOMICS'], true)
|| !in_array($document['approval_status'] ?? null, ['research_only', 'approved_for_quotes'], true)
|| !self::identifier($document['parameter_set_id'] ?? null)
- || !self::identifier($document['parameter_set_version'] ?? null)
+ || !self::versionIdentifier($document['parameter_set_version'] ?? null)
|| !is_array($document['models'] ?? null)
|| !is_array($document['parameters'] ?? null)
|| !array_is_list($document['parameters'])
@@ -184,6 +184,12 @@ private static function identifier(mixed $value): bool
&& preg_match('/^[A-Za-z][A-Za-z0-9._-]{0,127}$/D', $value) === 1;
}
+ private static function versionIdentifier(mixed $value): bool
+ {
+ return is_string($value)
+ && preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/D', $value) === 1;
+ }
+
private static function validDate(mixed $value): bool
{
if (!is_string($value) || preg_match('/^(\d{4})-(\d{2})-(\d{2})$/D', $value, $matches) !== 1) {
diff --git a/src/Domain/EconomicScenarioInput.php b/src/Domain/EconomicScenarioInput.php
new file mode 100644
index 0000000..aae9982
--- /dev/null
+++ b/src/Domain/EconomicScenarioInput.php
@@ -0,0 +1,38 @@
+model, ['cloud', 'managed', 'customer_infrastructure'], true)
+ || preg_match('/^[A-Za-z0-9][A-Za-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..c343013
--- /dev/null
+++ b/src/Domain/EconomicSimulationEngine.php
@@ -0,0 +1,168 @@
+ */
+ public function simulate(EconomicScenarioInput $input, ?string $approvalDate = null): 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(),
+ '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' => [
+ '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));
+ }
+
+ // 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';
+ }
+
+ 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/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/src/Ui/pricing-workbench.css b/src/Ui/pricing-workbench.css
new file mode 100644
index 0000000..c14994f
--- /dev/null
+++ b/src/Ui/pricing-workbench.css
@@ -0,0 +1,114 @@
+/* SPDX-FileCopyrightText: 2026 LibreSign contributors
+ SPDX-License-Identifier: AGPL-3.0-or-later */
+
+:root {
+ color-scheme: light;
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ --canvas: #f5f7f7;
+ --surface: #ffffff;
+ --surface-alt: #f7faf9;
+ --text: #14251f;
+ --muted: #52665e;
+ --border: #dce6e0;
+ --accent: #186b4c;
+ --accent-dark: #115036;
+ --accent-soft: #e8f5ed;
+ --warning: #fff8e7;
+ --warning-border: #dfc98c;
+ --danger: #a52d32;
+ --shadow: 0 5px 22px rgba(17, 43, 30, .04);
+}
+* { box-sizing: border-box; }
+html { min-height: 100%; }
+body { margin: 0; background: var(--canvas); color: var(--text); line-height: 1.5; }
+.container { max-width: 1110px; margin: 0 auto; padding: 0 24px; }
+.site-header { background: var(--surface); border-bottom: 1px solid var(--border); }
+.header-content { min-height: 72px; display: flex; align-items: center; justify-content: space-between; gap: 16px; }
+.brand { font-weight: 750; color: var(--accent); letter-spacing: -.025em; font-size: 1.14rem; }
+.brand-light { font-weight: 450; color: var(--text); }
+.header-meta { font-size: .82rem; color: var(--muted); }
+.main-content { padding-top: 42px; padding-bottom: 72px; }
+.intro { max-width: 800px; margin: 0 0 28px; }
+.intro h1 { margin: 0 0 10px; font-size: clamp(1.8rem, 3.6vw, 2.7rem); letter-spacing: -.04em; line-height: 1.15; }
+.intro > p { color: var(--muted); }
+.intro .eyebrow { margin: 0 0 8px; text-transform: uppercase; letter-spacing: .11em; font-size: .72rem; font-weight: 750; color: var(--accent); }
+.notice { padding: 13px 16px; border: 1px solid var(--warning-border); border-radius: 10px; background: var(--warning); color: #57441d !important; font-size: .9rem; }
+.notice p { margin: 4px 0 0; }
+.panel { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; box-shadow: var(--shadow); padding: 28px; margin-bottom: 20px; }
+.panel-heading { display: flex; align-items: flex-start; gap: 16px; margin-bottom: 25px; }
+.panel-heading h2 { font-size: 1.25rem; letter-spacing: -.025em; margin: 0 0 4px; }
+.panel-heading p { margin: 0; color: var(--muted); font-size: .91rem; }
+.step { flex: 0 0 auto; display: grid; place-items: center; width: 39px; height: 39px; border-radius: 11px; background: var(--accent-soft); color: var(--accent); font-weight: 750; font-size: .85rem; }
+.field-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; }
+.field-row { display: flex; gap: 18px; align-items: end; }
+.field { min-width: 0; flex: 1; }
+.field.wide { flex: 1 1 auto; }
+.field label { display: block; color: var(--text); font-size: .88rem; font-weight: 650; margin-bottom: 7px; }
+.field small { display: block; color: var(--muted); margin-top: 6px; font-size: .77rem; }
+input, select, button { font: inherit; }
+input, select { background: var(--surface); color: var(--text); border: 1px solid #aebeb4; width: 100%; height: 44px; border-radius: 8px; padding: 0 12px; }
+input:focus-visible, select:focus-visible, button:focus-visible, summary:focus-visible { outline: 3px solid #84c8a8; outline-offset: 2px; }
+input::placeholder { color: #7e9088; }
+fieldset { border: 0; margin: 0; padding: 0; min-width: 0; }
+fieldset:disabled { opacity: .6; }
+.actions { display: flex; gap: 10px; align-items: center; margin-top: 25px; }
+.button { border: 1px solid transparent; min-height: 44px; padding: 10px 17px; border-radius: 9px; font-weight: 650; cursor: pointer; }
+.button.primary { background: var(--accent); color: #fff; }
+.button.primary:hover:not(:disabled) { background: var(--accent-dark); }
+.button.secondary { color: var(--text); border-color: var(--border); background: var(--surface-alt); }
+.button:hover:not(:disabled) { filter: brightness(.96); }
+.button:disabled { opacity: .6; cursor: not-allowed; }
+.align-bottom { flex-shrink: 0; }
+.matrix-info { margin: 24px 0 0; display: grid; gap: 8px; grid-template-columns: repeat(3, minmax(0, 1fr)); border-top: 1px solid var(--border); padding-top: 18px; }
+.matrix-info div { min-width: 0; }
+.matrix-info dt, .trace-details dt { font-size: .76rem; color: var(--muted); }
+.matrix-info dd, .trace-details dd { font-weight: 650; margin: 4px 0 0; overflow-wrap: anywhere; }
+.feedback { margin: 18px 0 0; min-height: 25px; color: var(--muted); font-size: .9rem; }
+.feedback[data-level="error"] { color: var(--danger); }
+.feedback[data-level="success"] { color: var(--accent); }
+.results { border-top: 3px solid var(--accent); }
+.headline-values { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
+.value-card { background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 21px; min-width: 0; }
+.value-card.highlight { background: var(--accent-soft); border-color: #bee3ca; }
+.value-card p { font-size: .85rem; font-weight: 650; margin: 0 0 6px; }
+.value-card strong { font-size: clamp(1.45rem, 2.8vw, 2.1rem); display: block; font-variant-numeric: tabular-nums; letter-spacing: -.025em; overflow-wrap: anywhere; }
+.value-card small { color: var(--muted); display: block; margin-top: 5px; font-size: .75rem; }
+.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin-top: 16px; }
+.detail-panel { padding: 18px 21px; border: 1px solid var(--border); border-radius: 10px; }
+.detail-panel h3 { margin: 0 0 12px; font-size: .98rem; }
+.number-list { margin: 0; }
+.number-list div { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; border-top: 1px solid var(--border); padding: 10px 0; }
+.number-list dt { font-size: .81rem; color: var(--muted); }
+.number-list dd { margin: 0; font-variant-numeric: tabular-nums; font-weight: 690; white-space: nowrap; }
+.candidate { margin-top: 16px; }
+.fine-print { margin: 18px 0 0; font-size: .78rem; color: var(--muted); }
+.trace { border-top: 1px solid var(--border); margin-top: 20px; padding-top: 16px; }
+.trace summary { cursor: pointer; font-weight: 650; }
+.trace-details { margin: 13px 0 0; }
+.trace-details div { margin-bottom: 10px; }
+.trace-details code { font-size: .75rem; overflow-wrap: anywhere; font-weight: 450; }
+.table-scroll { overflow-x: auto; }
+table { width: 100%; border-collapse: collapse; font-size: .87rem; }
+th, td { padding: 12px; text-align: left; border-bottom: 1px solid var(--border); white-space: nowrap; }
+th { color: var(--muted); font-size: .78rem; }
+.site-footer { border-top: 1px solid var(--border); color: var(--muted); padding: 25px 0; font-size: .79rem; }
+[hidden] { display: none !important; }
+@media (max-width: 750px) {
+ .main-content { padding-top: 24px; }
+ .panel { padding: 19px; }
+ .field-grid, .detail-grid, .headline-values, .matrix-info { grid-template-columns: 1fr; }
+ .field-row { flex-direction: column; align-items: stretch; }
+ .field-row .button { width: 100%; }
+ .number-list div { flex-wrap: wrap; }
+ .header-meta { display: none; }
+}
+@media (prefers-color-scheme: dark) {
+ :root { color-scheme: dark; --canvas: #101a16; --surface: #18251f; --surface-alt: #1b2d24; --text: #ecf5ee; --muted: #b1c2b6; --border: #344c40; --accent: #83d6ad; --accent-dark: #166e49; --accent-soft: #244434; --warning: #3c3220; --warning-border: #826e43; --danger: #ffa9ab; --shadow: none; }
+ .brand, .step { color: var(--accent); }
+ .button.primary { background: #227c56; color: #fff; }
+ .button.primary:hover:not(:disabled) { background: #176443; }
+ input, select { border-color: #657d6f; }
+ input::placeholder { color: #a6b4aa; }
+ .notice { color: #ffeba8 !important; }
+ .value-card.highlight { border-color: #3d7957; }
+}
diff --git a/src/Ui/pricing-workbench.html b/src/Ui/pricing-workbench.html
new file mode 100644
index 0000000..aa9e6ba
--- /dev/null
+++ b/src/Ui/pricing-workbench.html
@@ -0,0 +1,180 @@
+
+
+
+
+
+
+
+ Simulador econômico · LibreSign Pricing
+
+
+
+
+
+
+
+
+
Ferramenta de apoio à decisão
+
Simulador de precificação
+
Compare custos, retorno cooperativista e preços de referência nas três modalidades. A calculadora não altera contratos nem realiza cobranças.
+
Importante: resultados demonstrativos não representam uma proposta comercial aprovada. Os parâmetros são carregados exclusivamente do ambiente privado.
+
+
+
+
+
01
+
+
Conectar à matriz de parâmetros
+
Informe a credencial de analista e carregue a versão do catálogo do servidor.
+
+
+
+
+ Credencial de análise
+
+ Mantida apenas nesta página até ser limpa ou fechada. Não é gravada em arquivos ou armazenamento local.
+
+
Carregar configuração
+
+
+
Versão —
+
Tipo de dados —
+
Homologação —
+
+
+
+
+
+
02
+
+
Configurar simulação
+
Altere apenas os dados do cenário. Custos e premissas permanecem no catálogo externo.
+
+
+
+ Carregue a configuração para iniciar.
+
+
+
+
+
+
Parâmetros incompletos.
+
A simulação foi bloqueada porque faltam valores que não podem ser presumidos como zero:
+
+
+
+
+
+
Preço de preservação por contrato/período
+
—
+
Considera o benchmark configurado para retorno cooperativista.
+
+
+
Implantação inicial, cobrada uma única vez
+
—
+
Separada da operação recorrente ou manutenção opcional.
+
+
+
+
+ Composição de custos
+
+
Custo de caixa por contrato —
+
Custo completo por contrato —
+
Base de preservação cooperativista —
+
Custo da implantação —
+
+
+
+ Referências de preço
+
+
Piso incremental ilustrativo —
+
Preço de recuperação integral —
+
Margem configurada —
+
Ocupação projetada —
+
+
+
+
+ Comparação do preço candidato
+
+
Preço informado —
+
Contribuição incremental estimada —
+
Resultado após custo completo —
+
Diferença para a preservação —
+
+
+
Indicadores de simulação econômica. A apuração real da produção cooperativista e a autorização de propostas continuam processos separados.
+
+
+ Rastreabilidade da simulação
+
+
Conjunto de parâmetros —
+
Versão —
+
SHA-256 do arquivo —
+
Impressão digital da simulação —
+
Situação comercial —
+
+
+
+
+
+
+
04
+
+
Comparação nesta sessão
+
Resultados guardados apenas em memória enquanto esta aba permanecer aberta.
+
+
+
+
+
+
+
+
+
diff --git a/src/Ui/pricing-workbench.js b/src/Ui/pricing-workbench.js
new file mode 100644
index 0000000..3f97fc1
--- /dev/null
+++ b/src/Ui/pricing-workbench.js
@@ -0,0 +1,270 @@
+// SPDX-FileCopyrightText: 2026 LibreSign contributors
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+"use strict";
+
+(() => {
+ const el = (id) => document.getElementById(id);
+ const label = {
+ cloud: "Cloud",
+ managed: "Managed",
+ customer_infrastructure: "Infraestrutura do cliente",
+ };
+ const errorLabels = {
+ unauthorized: "A credencial de analista não foi aceita.",
+ economic_matrix_unavailable: "A matriz econômica não está disponível ou é inválida neste ambiente.",
+ invalid_economic_input: "Confira a modalidade, a quantidade de clientes e a capacidade do catálogo.",
+ invalid_input: "Os valores informados não são válidos.",
+ rate_limited: "Muitas tentativas. Aguarde antes de simular novamente.",
+ };
+ const history = [];
+ let loaded = null;
+ let busy = false;
+
+ function message(text, level = "info") {
+ const target = el("feedback");
+ target.textContent = text;
+ target.dataset.level = level;
+ }
+
+ function setText(id, value) {
+ el(id).textContent = String(value);
+ }
+
+ function money(value) {
+ const source = String(value);
+ if (!/^-?[0-9]+(?:\.[0-9]{1,2})?$/.test(source)) return "—";
+ const negative = source.startsWith("-");
+ const parts = (negative ? source.slice(1) : source).split(".");
+ const integer = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
+ const cents = (parts[1] || "").padEnd(2, "0");
+ return (negative ? "−" : "") + "R$ " + integer + "," + cents;
+ }
+
+ function decimal(value) {
+ return String(value).replace(".", ",");
+ }
+
+ function fractionPercent(value) {
+ const raw = String(value);
+ if (!/^(?:0|1)(?:\.[0-9]{1,8})?$/.test(raw)) return decimal(raw) + " (fração)";
+ const parts = raw.split(".");
+ if (parts[0] === "1") return "100%";
+ const digits = (parts[1] || "").padEnd(8, "0");
+ const whole = String(Number(digits.slice(0, 2)));
+ const tail = digits.slice(2).replace(/0+$/, "");
+ return whole + (tail ? "," + tail : "") + "%";
+ }
+
+ function candidatePrice(raw) {
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+ if (!/^(?:0|[1-9][0-9]{0,8})(?:[.,][0-9]{1,2})?$/.test(trimmed)) {
+ throw new Error("Digite o preço sem separador de milhar, com até duas casas decimais.");
+ }
+ return trimmed.replace(",", ".");
+ }
+
+ function setBusy(value) {
+ busy = value;
+ el("load-matrix").disabled = value;
+ el("run-simulation").disabled = value;
+ el("clear-session").disabled = value;
+ }
+
+ async function api(path, method = "GET", payload = null) {
+ const token = el("analyst-token").value.trim();
+ if (!token) throw new Error("Informe sua credencial de analista.");
+ const headers = { Authorization: "Bearer " + token, Accept: "application/json" };
+ if (payload !== null) headers["Content-Type"] = "application/json";
+ let response;
+ try {
+ response = await fetch(path, {
+ method,
+ headers,
+ body: payload === null ? undefined : JSON.stringify(payload),
+ credentials: "omit",
+ cache: "no-store",
+ redirect: "error",
+ referrerPolicy: "no-referrer",
+ });
+ } catch (_error) {
+ throw new Error("Não foi possível acessar a API interna. Verifique a conexão.");
+ }
+ const data = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ const code = typeof data.error === "string" ? data.error : "";
+ throw new Error(errorLabels[code] || "A consulta não pôde ser concluída (HTTP " + response.status + ").");
+ }
+ return data;
+ }
+
+ async function loadMatrix() {
+ if (busy) return;
+ setBusy(true);
+ loaded = null;
+ el("simulation-fields").disabled = true;
+ el("matrix-info").hidden = true;
+ el("results").hidden = true;
+ try {
+ message("Consultando a configuração...");
+ const data = await api("/v1/economic-metadata");
+ if (!data || !data.parameters || !data.parameters.version || !data.models) {
+ throw new Error("A API retornou uma configuração incompleta.");
+ }
+ for (const id of Object.keys(label)) {
+ if (typeof data.models[id] !== "string") {
+ throw new Error("O catálogo não contém as três modalidades esperadas.");
+ }
+ }
+ loaded = data.parameters;
+ setText("matrix-version", loaded.version);
+ setText("matrix-scope", loaded.scope === "SYNTHETIC_ONLY" ? "Exemplo fictício" : "Configuração privada");
+ setText("matrix-approval", loaded.approval_status === "approved_for_quotes" ? "Aprovação declarada no catálogo" : "Em revisão");
+ el("matrix-info").hidden = false;
+ el("simulation-fields").disabled = false;
+ message("Matriz carregada. Configure e execute o cenário.", "success");
+ } catch (error) {
+ message(error.message, "error");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ function trace(result) {
+ setText("trace-set", result.parameters.id);
+ setText("trace-version", result.parameters.version);
+ setText("trace-sha", result.parameters.sha256);
+ setText("trace-fingerprint", result.simulation_fingerprint);
+ setText("trace-approval", result.commercialization.quote_allowed ? "Proposta autorizada pelo catálogo" : "Apenas simulação; não autoriza comercialização");
+ }
+
+ function appendHistory(result) {
+ history.push(result);
+ if (history.length > 10) history.shift();
+ const tbody = el("history-rows");
+ tbody.replaceChildren();
+ for (const item of history) {
+ const tr = document.createElement("tr");
+ const values = [
+ label[item.input.model],
+ String(item.input.customers),
+ money(item.calculation.preservation_price_with_margin),
+ money(item.calculation.one_time_setup_preservation_price),
+ ];
+ for (const value of values) {
+ const td = document.createElement("td");
+ td.textContent = value;
+ tr.appendChild(td);
+ }
+ tbody.appendChild(tr);
+ }
+ el("history-panel").hidden = history.length === 0;
+ }
+
+ function showResult(result) {
+ el("results").hidden = false;
+ trace(result);
+ setText("result-context", label[result.input.model] + " · " + result.input.customers + " cliente(s) · versão " + result.parameters.version);
+ if (result.status === "incomplete") {
+ el("calculated").hidden = true;
+ el("incomplete").hidden = false;
+ const list = el("missing-list");
+ list.replaceChildren();
+ for (const id of result.missing_parameters || []) {
+ const li = document.createElement("li");
+ li.textContent = id;
+ list.appendChild(li);
+ }
+ message("A simulação foi bloqueada: existem parâmetros não preenchidos.", "error");
+ return;
+ }
+ if (result.status !== "calculated" || !result.calculation) {
+ throw new Error("A API retornou um resultado que não pôde ser interpretado.");
+ }
+
+ el("incomplete").hidden = true;
+ el("calculated").hidden = false;
+ const calc = result.calculation;
+ setText("preservation-price", money(calc.preservation_price_with_margin));
+ setText("setup-price", money(calc.one_time_setup_preservation_price));
+ setText("cash-cost", money(calc.cash_cost));
+ setText("full-cost", money(calc.full_cost));
+ setText("preservation-cost", money(calc.preservation_cost));
+ setText("setup-cost", money(calc.one_time_setup_cost));
+ setText("incremental-floor", money(calc.incremental_floor));
+ setText("full-price", money(calc.full_price_with_margin));
+ setText("margin-target", fractionPercent(calc.margin_target));
+ setText("utilization", decimal(calc.utilization_percent) + "%");
+ el("candidate-analysis").hidden = calc.candidate_price === undefined;
+ if (calc.candidate_price !== undefined) {
+ setText("candidate-value", money(calc.candidate_price));
+ setText("candidate-contribution", money(calc.candidate_incremental_contribution));
+ setText("candidate-margin", money(calc.candidate_full_margin));
+ setText("candidate-delta", money(calc.candidate_preservation_delta));
+ }
+ appendHistory(result);
+ message("Cálculo concluído. Confira o identificador da matriz e a situação comercial.", "success");
+ }
+
+ async function submit(event) {
+ event.preventDefault();
+ if (busy) return;
+ if (!loaded) {
+ message("Carregue a matriz antes de simular.", "error");
+ return;
+ }
+ const quantity = Number(el("customers").value);
+ if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > 1000000) {
+ message("Informe uma quantidade inteira e positiva de clientes.", "error");
+ return;
+ }
+ let candidate;
+ try {
+ candidate = candidatePrice(el("candidate-price").value);
+ } catch (error) {
+ message(error.message, "error");
+ return;
+ }
+ const payload = {
+ model: el("model").value,
+ parameter_version: loaded.version,
+ customers: quantity,
+ };
+ if (candidate !== null) payload.candidate_price = candidate;
+ setBusy(true);
+ try {
+ message("Executando cálculo com a matriz carregada...");
+ const result = await api("/v1/economic-simulations", "POST", payload);
+ showResult(result);
+ if (loaded.sha256 !== result.parameters.sha256) {
+ message("O arquivo de parâmetros mudou desde a leitura inicial. Recarregue a matriz e confira a nova versão e o SHA-256.", "error");
+ }
+ } catch (error) {
+ el("results").hidden = true;
+ message(error.message, "error");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ function clearSession() {
+ if (busy) return;
+ loaded = null;
+ history.length = 0;
+ el("analyst-token").value = "";
+ el("candidate-price").value = "";
+ el("customers").value = "1";
+ el("model").value = "cloud";
+ el("matrix-info").hidden = true;
+ el("simulation-fields").disabled = true;
+ el("results").hidden = true;
+ el("history-panel").hidden = true;
+ el("history-rows").replaceChildren();
+ message("Sessão limpa. Informe sua credencial para carregar a matriz.");
+ }
+
+ el("load-matrix").addEventListener("click", loadMatrix);
+ el("economic-form").addEventListener("submit", submit);
+ el("clear-session").addEventListener("click", clearSession);
+})();
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/Http/EconomicMetadataHttpTest.php b/tests/Http/EconomicMetadataHttpTest.php
new file mode 100644
index 0000000..b44c9c5
--- /dev/null
+++ b/tests/Http/EconomicMetadataHttpTest.php
@@ -0,0 +1,98 @@
+ */
+ private array $tempFiles = [];
+
+ protected function tearDown(): void
+ {
+ foreach ($this->tempFiles as $file) {
+ @unlink($file);
+ }
+ }
+
+ public function testAnalystCanLoadMatrixVersionWithoutEconomicValues(): void
+ {
+ $controller = $this->controller();
+ $request = $this->request('analyst-'.str_repeat('x', 33));
+ $response = $controller($request);
+ self::assertSame(200, $response->getStatusCode());
+ $result = json_decode((string) $response->getContent(), true, 32, JSON_THROW_ON_ERROR);
+
+ self::assertSame('fictional-v2', $result['parameters']['version']);
+ self::assertSame('SYNTHETIC_ONLY', $result['parameters']['scope']);
+ self::assertSame('BRL', $result['currency']);
+ self::assertArrayHasKey('cloud', $result['models']);
+ self::assertArrayHasKey('managed', $result['models']);
+ self::assertArrayHasKey('customer_infrastructure', $result['models']);
+ self::assertStringNotContainsString('fixed_pool', (string) $response->getContent());
+ self::assertStringNotContainsString('collective_hour', (string) $response->getContent());
+ self::assertStringNotContainsString('cost_per_', (string) $response->getContent());
+ self::assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control'));
+ }
+
+ public function testNoTokenOrQuoteTokenIsRejected(): void
+ {
+ $controller = $this->controller();
+ foreach (['', 'quotes-'.str_repeat('y', 33)] as $token) {
+ $request = $this->request($token);
+ $response = $controller($request);
+ self::assertSame(401, $response->getStatusCode());
+ self::assertStringNotContainsString('fictional-v2', (string) $response->getContent());
+ }
+ }
+
+ public function testUnavailableMatrixDoesNotLeakFilePath(): void
+ {
+ $controller = $this->controller('/nonexistent/private/economic-matrix.json');
+ $response = $controller($this->request('analyst-'.str_repeat('x', 33)));
+ self::assertSame(503, $response->getStatusCode());
+ self::assertStringNotContainsString('/nonexistent', (string) $response->getContent());
+ }
+
+ private function controller(?string $matrixPath = null): EconomicMetadataController
+ {
+ return new EconomicMetadataController(
+ new EconomicMatrixLoader($matrixPath ?? dirname(__DIR__, 2).'/tests/Fixtures/economic-historical-synthetic.json'),
+ new EconomicBearerAuthenticator(
+ $this->tempFile('analyst-'.str_repeat('x', 33)),
+ $this->tempFile('quotes-'.str_repeat('y', 33)),
+ ),
+ );
+ }
+
+ private function request(string $token): Request
+ {
+ return Request::create(
+ '/v1/economic-metadata',
+ 'GET',
+ [],
+ [],
+ [],
+ $token === '' ? [] : ['HTTP_AUTHORIZATION' => 'Bearer '.$token],
+ );
+ }
+
+ private function tempFile(string $contents): string
+ {
+ $path = tempnam(sys_get_temp_dir(), 'pricing-metadata-');
+ self::assertNotFalse($path);
+ $this->tempFiles[] = $path;
+ file_put_contents($path, $contents);
+ return $path;
+ }
+}
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/Http/EconomicSimulationHttpTest.php b/tests/Http/EconomicSimulationHttpTest.php
new file mode 100644
index 0000000..0d1bdd0
--- /dev/null
+++ b/tests/Http/EconomicSimulationHttpTest.php
@@ -0,0 +1,168 @@
+ */
+ 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::assertStringContainsString('no-store', (string) $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['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);
+ 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';
+ }
+}
diff --git a/tests/Http/EconomicWorkbenchHttpTest.php b/tests/Http/EconomicWorkbenchHttpTest.php
new file mode 100644
index 0000000..1aa623c
--- /dev/null
+++ b/tests/Http/EconomicWorkbenchHttpTest.php
@@ -0,0 +1,73 @@
+request('GET', $path);
+ self::assertResponseStatusCodeSame(404);
+ }
+ }
+
+ public function testExplicitlyEnabledWorkbenchServesLocalAssetsOnly(): void
+ {
+ $controller = new EconomicWorkbenchController('1');
+ $page = $controller->page();
+ self::assertSame(200, $page->getStatusCode());
+ self::assertStringContainsString('text/html', (string) $page->headers->get('Content-Type'));
+ self::assertStringContainsString("script-src 'self'", (string) $page->headers->get('Content-Security-Policy'));
+ self::assertStringContainsString("frame-ancestors 'none'", (string) $page->headers->get('Content-Security-Policy'));
+ self::assertStringContainsString('no-store', (string) $page->headers->get('Cache-Control'));
+ self::assertStringContainsString('/internal/pricing-workbench.js', (string) $page->getContent());
+ self::assertStringNotContainsString('