Catalyst / admin/Apex 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Apex

public

Bid Management and Orchestration Tool with AI Capability

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Apex / Synapse-Apexv2 / backend / app / routers / commercial.py 14504 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
from datetime import datetime, timezone
from decimal import Decimal

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.ai import load_prompt
from app.core.database import get_db
from app.core.deps import audit, get_current_user, require_roles
from app.models import (
    ROLE_ADMIN,
    ROLE_APPROVER,
    ROLE_BID_MANAGER,
    ROLE_FINANCE,
    Bid,
    BidRequirement,
    BidResponse,
    CostLine,
    CostSheet,
    EffortRule,
    LicenceCost,
    Package,
    PricingScenario,
    ResourceType,
    User,
)
from app.schemas import (
    CostInputs,
    CostLineOut,
    CostLineUpdate,
    PricingIn,
    PricingOut,
)
from app.services import ai
from app.schemas import NonPeopleCostIn
from app.services.costing import (
    compute_effort_lines,
    compute_licence_lines,
    compute_non_people_lines,
    price_scenario,
    sheet_totals,
)

router = APIRouter(prefix="/api/bids", tags=["commercial"])
finance = require_roles(ROLE_ADMIN, ROLE_FINANCE, ROLE_BID_MANAGER)


# --- Module 3: cost sheet ---
@router.post("/{bid_id}/cost/build")
def build_cost(bid_id: int, body: CostInputs, db: Session = Depends(get_db), actor: User = Depends(finance)):
    bid = db.get(Bid, bid_id)
    if not bid:
        raise HTTPException(404, "Not found")
    rules = db.execute(select(EffortRule).where(EffortRule.active == True)).scalars().all()  # noqa: E712
    rt_map = {rt.id: rt for rt in db.execute(select(ResourceType)).scalars().all()}
    rule_dicts = []
    for r in rules:
        rt = rt_map.get(r.resource_type_id)
        rule_dicts.append({
            "name": r.name, "trigger": r.trigger, "endpoint_type": r.endpoint_type,
            "per_qty": r.per_qty, "resource_type_id": r.resource_type_id,
            "resource_name": rt.name if rt else "Resource",
            "hourly_cost_rate": rt.hourly_cost_rate if rt else Decimal("0"),
            "hours_recurring": r.hours_recurring, "hours_oneoff": r.hours_oneoff,
        })
    licences = [{"name": l.name, "unit": l.unit, "unit_cost": l.unit_cost, "billing": l.billing}
                for l in db.execute(select(LicenceCost).where(LicenceCost.active == True)).scalars().all()]  # noqa: E712

    inputs = body.model_dump()
    inputs = _jsonable(inputs)
    # preserve any previously entered non-people costs unless the caller supplies them
    existing = db.query(CostSheet).filter(CostSheet.bid_id == bid_id).first()
    if not inputs.get("non_people") and existing:
        inputs["non_people"] = existing.inputs.get("non_people", [])
    lines = (
        compute_effort_lines(rule_dicts, inputs)
        + compute_licence_lines(licences, inputs)
        + compute_non_people_lines(inputs)
    )

    sheet = existing
    if sheet:
        for l in list(sheet.lines):
            db.delete(l)
        sheet.inputs = inputs
    else:
        sheet = CostSheet(bid_id=bid_id, inputs=inputs)
        db.add(sheet)
        db.flush()
    for ln in lines:
        db.add(CostLine(
            sheet_id=sheet.id, group=ln["group"], description=ln["description"],
            resource_type_id=ln.get("resource_type_id"), qty=ln["qty"], hours=ln["hours"],
            rate_snapshot=ln["rate_snapshot"], monthly=ln["monthly"], oneoff=ln["oneoff"],
            engine_value=ln["monthly"] + ln["oneoff"], overridden=False,
        ))
    db.commit()
    audit(db, actor, "cost_sheet_built", "bid", bid_id, bid_id=bid_id)
    return get_cost(bid_id, db)  # type: ignore


@router.post("/{bid_id}/cost/non-people")
def add_non_people(bid_id: int, body: NonPeopleCostIn, db: Session = Depends(get_db), actor: User = Depends(finance)):
    sheet = db.query(CostSheet).filter(CostSheet.bid_id == bid_id).first()
    if not sheet:
        sheet = CostSheet(bid_id=bid_id, inputs={"endpoints": {}, "term_months": 12, "non_people": []})
        db.add(sheet)
        db.flush()
    inputs = dict(sheet.inputs)
    items = list(inputs.get("non_people", []))
    items.append({"description": body.description, "monthly": str(body.monthly), "oneoff": str(body.oneoff)})
    inputs["non_people"] = items
    sheet.inputs = inputs
    _rebuild(db, bid_id, sheet, inputs)
    db.commit()
    audit(db, actor, "non_people_cost_added", "bid", bid_id, {"description": body.description}, bid_id=bid_id)
    return get_cost(bid_id, db)  # type: ignore


@router.delete("/{bid_id}/cost/non-people/{index}")
def delete_non_people(bid_id: int, index: int, db: Session = Depends(get_db), actor: User = Depends(finance)):
    sheet = db.query(CostSheet).filter(CostSheet.bid_id == bid_id).first()
    if not sheet:
        raise HTTPException(404, "No cost sheet")
    inputs = dict(sheet.inputs)
    items = list(inputs.get("non_people", []))
    if 0 <= index < len(items):
        items.pop(index)
    inputs["non_people"] = items
    sheet.inputs = inputs
    _rebuild(db, bid_id, sheet, inputs)
    db.commit()
    audit(db, actor, "non_people_cost_removed", "bid", bid_id, bid_id=bid_id)
    return get_cost(bid_id, db)  # type: ignore


def _rebuild(db: Session, bid_id: int, sheet, inputs: dict) -> None:
    """Recompute all engine lines from inputs (keeps non-people costs in sync)."""
    rules = db.execute(select(EffortRule).where(EffortRule.active == True)).scalars().all()  # noqa: E712
    rt_map = {rt.id: rt for rt in db.execute(select(ResourceType)).scalars().all()}
    rule_dicts = []
    for r in rules:
        rt = rt_map.get(r.resource_type_id)
        rule_dicts.append({
            "name": r.name, "trigger": r.trigger, "endpoint_type": r.endpoint_type,
            "per_qty": r.per_qty, "resource_type_id": r.resource_type_id,
            "resource_name": rt.name if rt else "Resource",
            "hourly_cost_rate": rt.hourly_cost_rate if rt else Decimal("0"),
            "hours_recurring": r.hours_recurring, "hours_oneoff": r.hours_oneoff,
        })
    licences = [{"name": l.name, "unit": l.unit, "unit_cost": l.unit_cost, "billing": l.billing}
                for l in db.execute(select(LicenceCost).where(LicenceCost.active == True)).scalars().all()]  # noqa: E712
    lines = (
        compute_effort_lines(rule_dicts, inputs)
        + compute_licence_lines(licences, inputs)
        + compute_non_people_lines(inputs)
    )
    for l in list(sheet.lines):
        db.delete(l)
    db.flush()
    for ln in lines:
        db.add(CostLine(
            sheet_id=sheet.id, group=ln["group"], description=ln["description"],
            resource_type_id=ln.get("resource_type_id"), qty=ln["qty"], hours=ln["hours"],
            rate_snapshot=ln["rate_snapshot"], monthly=ln["monthly"], oneoff=ln["oneoff"],
            engine_value=ln["monthly"] + ln["oneoff"], overridden=False,
        ))


@router.get("/{bid_id}/cost")
def get_cost(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    sheet = db.query(CostSheet).filter(CostSheet.bid_id == bid_id).first()
    if not sheet:
        return {"inputs": {}, "lines": [], "totals": None}
    lines = db.query(CostLine).filter(CostLine.sheet_id == sheet.id).all()
    term = int(sheet.inputs.get("term_months", 12))
    line_dicts = [{"monthly": l.monthly, "oneoff": l.oneoff} for l in lines]
    return {
        "sheet_id": sheet.id,
        "inputs": sheet.inputs,
        "lines": [CostLineOut.model_validate(l).model_dump() for l in lines],
        "totals": sheet_totals(line_dicts, term),
    }


@router.patch("/cost/lines/{line_id}")
def update_line(line_id: int, body: CostLineUpdate, db: Session = Depends(get_db), actor: User = Depends(finance)):
    line = db.get(CostLine, line_id)
    if not line:
        raise HTTPException(404, "Not found")
    for k, v in body.model_dump(exclude_none=True).items():
        setattr(line, k, v)
    line.overridden = True
    db.commit()
    audit(db, actor, "cost_line_overridden", "cost_line", line.id)
    return CostLineOut.model_validate(line).model_dump()


# --- Module 4: pricing ---
def _base_cost(db: Session, bid_id: int) -> tuple[Decimal, int]:
    sheet = db.query(CostSheet).filter(CostSheet.bid_id == bid_id).first()
    if not sheet:
        return Decimal("0"), 12
    term = int(sheet.inputs.get("term_months", 12))
    lines = db.query(CostLine).filter(CostLine.sheet_id == sheet.id).all()
    totals = sheet_totals([{"monthly": l.monthly, "oneoff": l.oneoff} for l in lines], term)
    return Decimal(str(totals["total_contract"])), term


@router.get("/{bid_id}/pricing", response_model=list[PricingOut])
def list_pricing(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    return db.query(PricingScenario).filter(PricingScenario.bid_id == bid_id).all()


@router.post("/{bid_id}/pricing", response_model=PricingOut, status_code=201)
def create_pricing(bid_id: int, body: PricingIn, db: Session = Depends(get_db), actor: User = Depends(finance)):
    base, term = _base_cost(db, bid_id)
    try:
        computed = price_scenario(base, body.risk_pct, body.mgmt_pct, body.margin_pct, term)
    except ValueError as e:
        raise HTTPException(400, str(e))
    scenario = PricingScenario(
        bid_id=bid_id, name=body.name, risk_pct=body.risk_pct, mgmt_pct=body.mgmt_pct,
        margin_pct=body.margin_pct, computed=_jsonable(computed),
    )
    # first scenario becomes selected
    if not db.query(PricingScenario).filter(PricingScenario.bid_id == bid_id).count():
        scenario.selected = True
    db.add(scenario)
    db.commit()
    db.refresh(scenario)
    audit(db, actor, "pricing_scenario_created", "bid", bid_id, {"name": body.name}, bid_id=bid_id)
    return scenario


@router.post("/pricing/{scenario_id}/justify")
def justify(scenario_id: int, db: Session = Depends(get_db), actor: User = Depends(finance)):
    sc = db.get(PricingScenario, scenario_id)
    if not sc:
        raise HTTPException(404, "Not found")
    bid = db.get(Bid, sc.bid_id)
    system = load_prompt("pricing_justification")
    prompt = (
        f"PRICING WATERFALL: {sc.computed}\n"
        f"RISK %: {sc.risk_pct}  MGMT %: {sc.mgmt_pct}  MARGIN %: {sc.margin_pct}\n"
        f"WIN THEMES: {bid.win_themes if bid else ''}"
    )
    text, meta = ai.generate_text(system, prompt, max_tokens=2000)
    sc.justification_text = text
    db.commit()
    return {"justification": text, "meta": meta}


@router.post("/pricing/{scenario_id}/select")
def select_scenario(scenario_id: int, db: Session = Depends(get_db), actor: User = Depends(finance)):
    sc = db.get(PricingScenario, scenario_id)
    if not sc:
        raise HTTPException(404, "Not found")
    for other in db.query(PricingScenario).filter(PricingScenario.bid_id == sc.bid_id).all():
        other.selected = (other.id == scenario_id)
    db.commit()
    return {"ok": True}


# --- Module 6: package assembly ---
@router.post("/{bid_id}/package/assemble")
def assemble(bid_id: int, db: Session = Depends(get_db), actor: User = Depends(finance)):
    bid = db.get(Bid, bid_id)
    if not bid:
        raise HTTPException(404, "Not found")
    reqs = db.query(BidRequirement).filter(BidRequirement.bid_id == bid_id).all()
    sections = []
    unanswered = 0
    for r in reqs:
        resp = db.query(BidResponse).filter(BidResponse.requirement_id == r.id).first()
        text = (resp.final_text or resp.draft_text) if resp else ""
        approved = bool(resp and resp.status == "approved")
        if not approved:
            unanswered += 1
        sections.append({"ref": r.ref, "question": r.question_text,
                         "response": text, "approved": approved})
    scenario = db.query(PricingScenario).filter(
        PricingScenario.bid_id == bid_id, PricingScenario.selected == True  # noqa: E712
    ).first()
    snapshot = {
        "bid": {"ref": bid.ref, "title": bid.title, "client": bid.client},
        "sections": sections,
        "pricing": scenario.computed if scenario else None,
        "justification": scenario.justification_text if scenario else "",
        "unanswered": unanswered,
    }
    version = db.query(Package).filter(Package.bid_id == bid_id).count() + 1
    pkg = Package(bid_id=bid_id, version=version, snapshot=snapshot,
                  status="assembled" if unanswered == 0 else "incomplete")
    db.add(pkg)
    db.commit()
    db.refresh(pkg)
    audit(db, actor, "package_assembled", "bid", bid_id, {"version": version, "unanswered": unanswered}, bid_id=bid_id)
    return {"package_id": pkg.id, "version": version, "unanswered": unanswered, "snapshot": snapshot}


@router.post("/package/{pkg_id}/approve")
def approve_package(pkg_id: int, db: Session = Depends(get_db), actor: User = Depends(require_roles(ROLE_ADMIN, ROLE_APPROVER))):
    pkg = db.get(Package, pkg_id)
    if not pkg:
        raise HTTPException(404, "Not found")
    if pkg.snapshot.get("unanswered", 0) > 0:
        raise HTTPException(400, "Cannot approve: unanswered/unapproved requirements remain")
    pkg.status = "approved"
    pkg.approved_by = actor.id
    pkg.approved_at = datetime.now(timezone.utc)
    bid = db.get(Bid, pkg.bid_id)
    if bid and bid.state == "in_review":
        bid.state = "approved"
    db.commit()
    audit(db, actor, "package_approved", "package", pkg.id, {"version": pkg.version}, bid_id=pkg.bid_id)
    return {"ok": True, "status": pkg.status}


@router.post("/package/{pkg_id}/request-changes")
def request_changes(pkg_id: int, payload: dict, db: Session = Depends(get_db), actor: User = Depends(require_roles(ROLE_ADMIN, ROLE_APPROVER))):
    if not payload.get("comment"):
        raise HTTPException(400, "A comment is required")
    pkg = db.get(Package, pkg_id)
    if not pkg:
        raise HTTPException(404, "Not found")
    pkg.status = "changes_requested"
    bid = db.get(Bid, pkg.bid_id)
    if bid and bid.state in ("in_review", "approved"):
        bid.state = "in_progress"
    db.commit()
    audit(db, actor, "package_changes_requested", "package", pkg.id, {"comment": payload["comment"]}, bid_id=pkg.bid_id)
    return {"ok": True}


@router.get("/{bid_id}/package")
def get_package(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    pkg = db.query(Package).filter(Package.bid_id == bid_id).order_by(Package.version.desc()).first()
    if not pkg:
        return None
    return {"package_id": pkg.id, "version": pkg.version, "status": pkg.status, "snapshot": pkg.snapshot}


def _jsonable(d: dict) -> dict:
    import json
    return json.loads(json.dumps(d, default=str))