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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions backend/api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,6 +614,30 @@ class AutopilotRun(BaseModel):
use_ai: bool = False


class RevenueSetup(BaseModel):
model_config = ConfigDict(extra="forbid")
revision: int
currency: str = "USD"
price_period: str | None = None
days_per_year: float | None = None
hours_per_day: float | None = None
sales: list[dict]


@app.post("/api/assessments/{key}/revenue-setup")
def revenue_setup(key: str, setup: RevenueSetup):
"""Entry-page revenue: user-chosen stream, price and unit; approved when complete."""
from backend.revenue.setup import apply

if store.get(key).get("running"):
raise HTTPException(409, "Wait for the current calculation to finish")
try:
out = apply(store, key, setup.revision, setup.model_dump())
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
return {"approved": out["approved"], "questions": out["questions"], "revision": out["state"]["revision"]}


@app.post("/api/assessments/{key}/autopilot", status_code=202)
def run_autopilot(key: str, options: AutopilotRun):
"""One action: approve for a provisional run, pick models, run every stage."""
Expand Down
111 changes: 111 additions & 0 deletions backend/revenue/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""Structured revenue set-up from the Entry page (no free-text interpretation).

The user picks what is sold (an M&E stream, optionally the component actually
sold), the price, unit and currency, and the operating schedule. Python writes
the sales lines and the Revenue Box sentence that authorises them, then runs
the normal revenue approval, which validates the full revenue calculation.
Because the user chose every term, nothing is left for an AI to interpret;
an item without a price stays visibly unpriced and is not approved.
"""

import copy
import re
from datetime import date

from .authority import update


def _slug(text):
return re.sub(r"[^a-z0-9]+", "-", str(text).casefold()).strip("-")[:40] or "product"


def _stream(report, key):
entity = next((e for e in report.get("entities", []) if e.get("key") == key), None)
if not entity or entity.get("kind") != "material":
raise ValueError("Choose a material stream from the M&E balance")
return entity


def sentence(sale, stream_tag):
what = sale["name"] + (f" ({sale['component']} in stream {stream_tag})" if sale.get("component")
else f" (stream {stream_tag})")
if sale.get("unit_price") is None:
return f"We sell {what}; price to be confirmed."
return f"We sell {what} at {sale['unit_price']:g} {sale['currency']} per {sale['quantity_unit']}."


def apply(store, key, revision, setup):
"""Save the set-up as revenue inputs and approve them when complete.

Returns {"state", "approved", "questions"}.
"""
state = store.get(key)
report = state.get("scoped_report") or state.get("effective_report") or (state.get("parsed") or {}).get("report") or {}
currency = str(setup.get("currency") or "USD").upper()
period = str(setup.get("price_period") or (state.get("plan", {}).get("cost_translation") or {}).get("target_period") or "")
if not re.fullmatch(r"[A-Z]{3}", currency) or not re.fullmatch(r"\d{4}(?:-\d{2})?", period):
raise ValueError("Enter a three-letter currency and a price date (YYYY or YYYY-MM)")
sales, mechanisms, sentences = [], [], []
for raw in setup.get("sales") or []:
stream = _stream(report, raw.get("stream_key"))
price = raw.get("unit_price")
price = None if price in (None, "") else float(price)
if price is not None and price < 0:
raise ValueError("A selling price cannot be negative")
unit = str(raw.get("quantity_unit") or "kg")
if unit not in {"kg", "tonne", "lb", "m3", "L"}:
raise ValueError("Choose kg, tonne, lb, m3 or L as the selling unit")
component = str(raw.get("component") or "").strip() or None
name = str(raw.get("name") or component or stream.get("identifier") or "Product").strip()
sale = {"name": name, "component": component, "unit_price": price, "currency": currency, "quantity_unit": unit}
quote = sentence(sale, stream.get("identifier"))
ident = _slug(name)
while any(s["id"] == ident for s in sales):
ident += "-2"
sales.append({
"id": ident, "intent_id": ident, "name": name, "role": "main_product" if not sales else "co_product",
"stream_key": stream["key"], "component": component, "quantity_unit": unit,
"price_mode": "assumed_price", "unit_price": price,
"allocation_fraction": 1, "saleable_fraction": 1, "sold_fraction": 1, "cost_markup_fraction": 0,
"net_freight_deduction_per_unit": 0, "net_packaging_deduction_per_unit": 0,
"context_quote": quote,
"rationale": "Selected by the user on the Entry page: stream, " + ("component, " if component else "")
+ "price and unit.",
"specification_basis": f"{component + ' component' if component else 'Total'} flow of stream "
f"{stream.get('identifier')} from the M&E balance.",
"uncertainty": "User-entered price; market, specification and delivery terms not verified.",
})
mechanisms.append({"id": ident, "category": "product_sales", "context_quote": quote,
"interpretation": "Product sale chosen explicitly on the Entry page."})
sentences.append(quote)
if not sales:
raise ValueError("Add at least one product the project sells")
config = copy.deepcopy((state.get("plan") or {}).get("operating_economics") or {})
config["sales"] = sales
config["commercial_lines"] = [] # the set-up defines all payments
config["commercial_intent"] = {"status": "explicit", "mechanisms": mechanisms, "questions": []}
config["price_basis"] = {**(config.get("price_basis") or {}), "currency": currency, "price_period": period}
operating = dict(config.get("operating") or {})
operating["days_per_year"] = float(setup.get("days_per_year") or operating.get("days_per_year") or 330)
operating["hours_per_day"] = float(setup.get("hours_per_day") or operating.get("hours_per_day") or 24)
if setup.get("days_per_year") or setup.get("hours_per_day") or not operating.get("rationale"):
operating["rationale"] = "Operating schedule entered or confirmed on the Entry page"
config["operating"] = operating
config.setdefault("assumption_date", date.today().isoformat())
config["revenue_setup"] = {"origin": "entry_page", "sales": [
{k: s[k] for k in ("id", "name", "stream_key", "component", "unit_price", "quantity_unit")} for s in sales]}
state["plan"]["operating_economics"] = config
state = store.put(state, revision)
text = "\n".join(sentences)
state = update(store, key, state["revision"], text=text)
if all(s["unit_price"] is not None for s in sales):
try:
state = update(store, key, state["revision"], approve=True)
return {"state": state, "approved": True, "questions": []}
except ValueError as exc:
return {"state": state, "approved": False, "questions": [str(exc)]}
except KeyError as exc:
hint = ("Set the analysis and construction years on the Entry page, then save again."
if str(exc).strip("'") == "financial" else f"Missing revenue input: {exc}.")
return {"state": state, "approved": False, "questions": [hint]}
return {"state": state, "approved": False, "questions": state.get("revenue_questions") or []}
36 changes: 36 additions & 0 deletions backend/tests/test_revenue_setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Entry-page revenue set-up writes approvable sales lines without AI."""

import pytest

from backend.blocks.execution import run_stage
from backend.revenue.setup import apply
from backend.tests.test_autopilot import _study


def test_setup_approves_and_revenue_calculates_without_ai(tmp_path):
import backend.api.app as api

original = api.store
try:
store, key = _study(tmp_path)
from backend.blocks.cashflow.schedule import apply_policy, make_policy

state = store.get(key)
state["analysis_schedule"] = make_policy(20, 2)
state["plan"]["operating_economics"] = apply_policy(state["plan"].get("operating_economics", {}), state["analysis_schedule"])
state = store.put(state, state["revision"])
stream = next(e for e in state["stage_outputs"]["engineering_data"]["report"]["entities"]
if e["kind"] == "material")
out = apply(store, key, state["revision"], {"currency": "USD", "price_period": "2026",
"sales": [{"stream_key": stream["key"], "name": "Water", "unit_price": 0.5, "quantity_unit": "kg"}]})
assert out["approved"], out["questions"]
assert "We sell Water" in out["state"]["revenue_description"]
state = run_stage(store, key, "revenue", use_ai=False)
assert state["stage_runs"]["revenue"]["status"] == "ready"
missing = apply(store, key, state["revision"], {"sales": [{"stream_key": stream["key"], "name": "Water", "unit_price": None}],
"price_period": "2026"})
assert not missing["approved"]
with pytest.raises(ValueError):
apply(store, key, missing["state"]["revision"], {"sales": [{"stream_key": "nope", "unit_price": 1}], "price_period": "2026"})
finally:
api.store = original
14 changes: 3 additions & 11 deletions frontend/src/blocks/guided/entry-board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { EquipmentInspector } from './equipment-inspector';
import { OriginChip, Panel, RunBar, type StageProps } from './flow';
import { matchChip, pending, QuickMatchPanel, useQuickMatches } from './quick-match';
import { AutopilotCard } from './autopilot';
import { RevenueSetup } from './revenue-setup';

const WORKBOOK = /\.(xlsx|xls|xlsm)$/i;

Expand Down Expand Up @@ -151,16 +152,6 @@ export function EntryBoard(props: StageProps) {
<span>Describe your process</span>
<textarea value={description} maxLength={12000} onChange={(e) => setDescription(e.target.value)} placeholder="Inputs, outputs, location and design requirements." />
</label>
<label className="gf-field">
<span>Revenue Box — how will this project earn income?</span>
<textarea
value={revenue}
maxLength={6000}
onChange={(e) => setRevenue(e.target.value)}
placeholder="e.g. treatment fee per m³; product sales; capacity payments. Include prices if known."
/>
<small>Only the Revenue Box authorises income. Producing an output does not mean it is sold.</small>
</label>
<div className="gf-grid-2">
<label className="gf-field">
<span>Analysis years</span>
Expand All @@ -182,6 +173,7 @@ export function EntryBoard(props: StageProps) {
<button type="button" className="gf-primary gf-extract" disabled={running || (!file && !hook.id)} onClick={() => void hook.action(extract)}>
{file ? `Extract equipment from ${file.name}` : !state ? 'Extract equipment' : 'Re-extract with this brief'}
</button>
{state && !previous && <RevenueSetup props={props} />}
{previous && (
<p className="gf-note">
New study: {previous.name} is saved and unchanged.{' '}
Expand Down Expand Up @@ -286,7 +278,7 @@ export function EntryBoard(props: StageProps) {
))}
</ul>
{list(state?.revenue_questions).length > 0 && (
<p className="gf-note">Revenue Box needs clarification. You can answer it on the Revenue stage.</p>
<p className="gf-note">Revenue needs a choice: set what the project sells under “How does this project earn money?”.</p>
)}
</div>

Expand Down
11 changes: 11 additions & 0 deletions frontend/src/blocks/guided/guided.css
Original file line number Diff line number Diff line change
Expand Up @@ -385,3 +385,14 @@ polyline.gf-tone-c { stroke: var(--gf-tone-c); }
.gf-autopilot-review li small { flex-basis: 100%; color: var(--gf-muted); }
.gf-autopilot-review li .gf-link { margin-left: auto; }
.gf-autopilot-review .gf-review-blocked, .gf-autopilot-review .gf-review-unpriced { border-left: 3px solid var(--gf-warn); }

/* Revenue set-up on the Entry board */
.gf-revenue-setup { display: grid; gap: 10px; margin-top: 14px; padding: 14px; border: 1px solid var(--gf-line); border-radius: var(--gf-radius); background: var(--gf-raised); }
.gf-revenue-setup h3 { margin: 0; font-size: 16px; }
.gf-revenue-setup p { margin: 0; font-size: 13px; }
.gf-rev-row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding: 10px; border-radius: 10px; border: 1px solid var(--gf-line); background: var(--gf-surface); }
.gf-rev-row .gf-link { justify-self: start; font-size: 12px; }
.gf-revenue-setup > .gf-link { justify-self: start; font-size: 13px; }
.gf-ok { color: var(--gf-user); font-weight: 600; font-size: 13px; }
@media (max-width: 600px) { .gf-rev-row { grid-template-columns: 1fr; } }
.gf-rev-effects { margin: 0 0 12px; font-size: 13px; }
6 changes: 5 additions & 1 deletion frontend/src/blocks/guided/revenue-playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,12 @@ export function RevenuePlayground(props: StageProps) {
return (
<div className="gf-play">
<StageHeading kicker="STAGE 05 · REVENUE" title="Revenue playground">
Income comes only from your Revenue Box and the explicit revenue worksheet. Prices you give are your assumptions; unpriced income stays unpriced.
Income comes only from what you set on the Entry board and the explicit revenue worksheet. Prices you give are your assumptions; unpriced income stays unpriced.
</StageHeading>
<p className="gf-warn gf-rev-effects" role="note">
Changing revenue also changes the OPEX lines that are a share of revenue (administration, distribution &amp; sales, R&amp;D, royalties), so variable
operating cost (VCOP), total OPEX and the cash flow move with it. Fixed operating cost (FCOP) is not affected. Run OPEX and Financial again after a change.
</p>
<div className="gf-kpis">
<div className="gf-kpi-hero">
<small>Sales revenue · operating year 1</small>
Expand Down
Loading
Loading