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 / bids.py 14227 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
from datetime import date

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

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_CONTRIBUTOR,
    AuditLog,
    Bid,
    BidPlan,
    BidRequirement,
    BidResponse,
    ComplianceFramework,
    Document,
    PlanTask,
    User,
    WorkflowTemplate,
)
from app.schemas import (
    BidIn,
    BidOut,
    PlanTaskOut,
    PlanTaskUpdate,
    RequirementIn,
    RequirementOut,
    ResponseOut,
    ResponseUpdate,
    StateChangeIn,
)
from app.services import storage
from app.services.scheduling import build_plan
from app.workers.tasks import extract_requirements, generate_response

router = APIRouter(prefix="/api/bids", tags=["bids"])
manager = require_roles(ROLE_ADMIN, ROLE_BID_MANAGER)
contributor = require_roles(ROLE_ADMIN, ROLE_BID_MANAGER, ROLE_CONTRIBUTOR)

TRANSITIONS = {
    "draft": ["planning"],
    "planning": ["in_progress", "draft"],
    "in_progress": ["in_review", "planning"],
    "in_review": ["approved", "in_progress"],
    "approved": ["submitted", "in_review"],
    "submitted": ["won", "lost", "withdrawn"],
    "won": [],
    "lost": [],
    "withdrawn": [],
}


@router.get("", response_model=list[BidOut])
def list_bids(db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    return db.execute(select(Bid).order_by(Bid.created_at.desc())).scalars().all()


@router.get("/dashboard")
def dashboard(db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    bids = db.execute(select(Bid).order_by(Bid.submission_date)).scalars().all()
    out = []
    for b in bids:
        reqs = db.query(BidRequirement).filter(BidRequirement.bid_id == b.id).all()
        approved = 0
        for r in reqs:
            resp = db.query(BidResponse).filter(BidResponse.requirement_id == r.id).first()
            if resp and resp.status == "approved":
                approved += 1
        completeness = round(100 * approved / len(reqs)) if reqs else 0
        prod_cost = _production_cost(db, b.id)
        out.append({
            "id": b.id, "ref": b.ref, "title": b.title, "client": b.client,
            "state": b.state, "submission_date": b.submission_date,
            "completeness": completeness,
            "production_cost": prod_cost,
        })
    return out


def _production_cost(db: Session, bid_id: int) -> dict:
    plan = db.query(BidPlan).filter(BidPlan.bid_id == bid_id).first()
    planned = actual = 0.0
    if plan:
        for t in plan.tasks:
            planned += float(t.planned_hours or 0)
            actual += float(t.actual_hours or 0)
    # rough £ using a blended internal rate of 45/hr for the first version
    return {"planned_hours": planned, "actual_hours": actual,
            "planned_cost": round(planned * 45, 2), "actual_cost": round(actual * 45, 2)}


@router.post("", response_model=BidOut, status_code=201)
def create_bid(body: BidIn, db: Session = Depends(get_db), actor: User = Depends(manager)):
    if body.start_date >= body.submission_date:
        raise HTTPException(400, "Start date must be before submission date")
    ref = body.ref or f"BID-{date.today():%Y}-{db.query(Bid).count() + 1:04d}"
    bid = Bid(
        ref=ref, title=body.title, client=body.client,
        start_date=body.start_date, submission_date=body.submission_date,
        frameworks=body.frameworks, win_themes=body.win_themes,
        opportunity_value=body.opportunity_value,
        contract_duration_months=body.contract_duration_months,
        web_link=body.web_link,
        state="draft", created_by=actor.id,
    )
    db.add(bid)
    db.commit()
    db.refresh(bid)
    audit(db, actor, "bid_created", "bid", bid.id, {"ref": ref}, bid_id=bid.id)
    return bid


@router.get("/{bid_id}", response_model=BidOut)
def get_bid(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    bid = db.get(Bid, bid_id)
    if not bid:
        raise HTTPException(404, "Not found")
    return bid


@router.patch("/{bid_id}", response_model=BidOut)
def update_bid(bid_id: int, body: BidIn, db: Session = Depends(get_db), actor: User = Depends(manager)):
    bid = db.get(Bid, bid_id)
    if not bid:
        raise HTTPException(404, "Not found")
    for k in ("title", "client", "start_date", "submission_date", "frameworks", "win_themes",
              "opportunity_value", "contract_duration_months", "web_link"):
        setattr(bid, k, getattr(body, k))
    db.commit()
    db.refresh(bid)
    audit(db, actor, "bid_updated", "bid", bid.id, bid_id=bid.id)
    return bid


@router.post("/{bid_id}/state", response_model=BidOut)
def change_state(bid_id: int, body: StateChangeIn, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
    bid = db.get(Bid, bid_id)
    if not bid:
        raise HTTPException(404, "Not found")
    if body.state not in TRANSITIONS.get(bid.state, []):
        raise HTTPException(400, f"Illegal transition {bid.state} -> {body.state}")
    if body.state in ("approved", "in_review") and not (
        ROLE_APPROVER in user.roles or ROLE_ADMIN in user.roles or ROLE_BID_MANAGER in user.roles
    ):
        raise HTTPException(403, "Insufficient role for this transition")
    prev = bid.state
    bid.state = body.state
    db.commit()
    db.refresh(bid)
    audit(db, user, "bid_state_changed", "bid", bid.id, {"from": prev, "to": body.state}, bid_id=bid.id)
    # Answer Library: push won/lost outcome onto answers harvested from this bid.
    if body.state in ("won", "lost", "submitted"):
        from app.services import library as lib
        lib.propagate_outcome(db, bid)
    return bid


# --- documents ---
@router.post("/{bid_id}/documents")
async def upload_tender(bid_id: int, kind: str = Form("tender"), files: list[UploadFile] = None,
                        db: Session = Depends(get_db), actor: User = Depends(contributor)):
    bid = db.get(Bid, bid_id)
    if not bid:
        raise HTTPException(404, "Not found")
    doc_ids = []
    for f in files or []:
        data = await f.read()
        path, sha = storage.save_file(data, f.filename)
        text = storage.extract_text(data, f.filename, f.content_type or "")
        doc = Document(bid_id=bid_id, kind=kind, filename=f.filename, path=path,
                       mime=f.content_type or "", size=len(data), sha256=sha,
                       text_content=text, uploaded_by=actor.id)
        db.add(doc)
        db.flush()
        doc_ids.append(doc.id)
    db.commit()
    audit(db, actor, "tender_uploaded", "bid", bid_id, {"docs": doc_ids, "count": len(doc_ids)}, bid_id=bid_id)
    return {"document_ids": doc_ids}


@router.get("/{bid_id}/documents")
def list_documents(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    docs = db.query(Document).filter(Document.bid_id == bid_id).all()
    return [{"id": d.id, "filename": d.filename, "kind": d.kind, "size": d.size} for d in docs]


# --- requirements ---
@router.post("/{bid_id}/requirements/extract")
def extract(bid_id: int, db: Session = Depends(get_db), actor: User = Depends(contributor)):
    docs = db.query(Document).filter(Document.bid_id == bid_id, Document.kind == "tender").all()
    if not docs:
        raise HTTPException(400, "Upload tender documents first")
    task = extract_requirements.delay(bid_id, [d.id for d in docs])
    audit(db, actor, "requirement_extraction_started", "bid", bid_id, bid_id=bid_id)
    return {"task_id": task.id}


@router.get("/{bid_id}/requirements", response_model=list[RequirementOut])
def list_requirements(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    return db.query(BidRequirement).filter(BidRequirement.bid_id == bid_id).order_by(BidRequirement.id).all()


@router.post("/{bid_id}/requirements", response_model=RequirementOut, status_code=201)
def add_requirement(bid_id: int, body: RequirementIn, db: Session = Depends(get_db), _: User = Depends(contributor)):
    req = BidRequirement(bid_id=bid_id, **body.model_dump())
    db.add(req)
    db.commit()
    db.refresh(req)
    return req


@router.patch("/requirements/{req_id}", response_model=RequirementOut)
def update_requirement(req_id: int, body: RequirementIn, db: Session = Depends(get_db), _: User = Depends(contributor)):
    req = db.get(BidRequirement, req_id)
    if not req:
        raise HTTPException(404, "Not found")
    for k, v in body.model_dump().items():
        setattr(req, k, v)
    db.commit()
    db.refresh(req)
    return req


@router.delete("/requirements/{req_id}")
def delete_requirement(req_id: int, db: Session = Depends(get_db), _: User = Depends(contributor)):
    req = db.get(BidRequirement, req_id)
    if req:
        db.delete(req)
        db.commit()
    return {"ok": True}


# --- responses ---
@router.post("/{bid_id}/responses/generate")
def generate_all(bid_id: int, db: Session = Depends(get_db), actor: User = Depends(contributor)):
    reqs = db.query(BidRequirement).filter(BidRequirement.bid_id == bid_id).all()
    task_ids = [generate_response.delay(r.id).id for r in reqs]
    audit(db, actor, "response_generation_started", "bid", bid_id, {"count": len(task_ids)}, bid_id=bid_id)
    return {"tasks": task_ids, "count": len(task_ids)}


@router.post("/requirements/{req_id}/generate")
def generate_one(req_id: int, db: Session = Depends(get_db), _: User = Depends(contributor)):
    task = generate_response.delay(req_id)
    return {"task_id": task.id}


@router.get("/{bid_id}/responses", response_model=list[ResponseOut])
def list_responses(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    req_ids = [r.id for r in db.query(BidRequirement).filter(BidRequirement.bid_id == bid_id).all()]
    if not req_ids:
        return []
    return db.query(BidResponse).filter(BidResponse.requirement_id.in_(req_ids)).all()


@router.patch("/responses/{resp_id}", response_model=ResponseOut)
def update_response(resp_id: int, body: ResponseUpdate, db: Session = Depends(get_db), actor: User = Depends(contributor)):
    resp = db.get(BidResponse, resp_id)
    if not resp:
        raise HTTPException(404, "Not found")
    if body.final_text is not None:
        resp.final_text = body.final_text
    if body.status is not None:
        if body.status not in ("draft", "in_review", "approved"):
            raise HTTPException(400, "Invalid status")
        resp.status = body.status
    resp.edited_by = actor.id
    db.commit()
    db.refresh(resp)
    req = db.get(BidRequirement, resp.requirement_id)
    audit(db, actor, "response_updated", "response", resp.id,
          {"status": resp.status, "ref": req.ref if req else ""},
          bid_id=req.bid_id if req else None)
    # Answer Library auto-harvest: approved responses feed the catalogue.
    if resp.status == "approved":
        from app.services import library as lib
        lib.harvest_response(db, resp, actor.id)
    return resp


# --- plan ---
@router.post("/{bid_id}/plan/generate")
def gen_plan(bid_id: int, db: Session = Depends(get_db), actor: User = Depends(manager)):
    bid = db.get(Bid, bid_id)
    if not bid:
        raise HTTPException(404, "Not found")
    wf = db.query(WorkflowTemplate).filter(WorkflowTemplate.is_default == True).first()  # noqa: E712
    milestones = wf.milestones if wf else []
    reqs = db.query(BidRequirement).filter(BidRequirement.bid_id == bid_id).all()
    req_dicts = [{"id": r.id, "ref": r.ref} for r in reqs]
    tasks = build_plan(bid.start_date, bid.submission_date, milestones, req_dicts)

    plan = db.query(BidPlan).filter(BidPlan.bid_id == bid_id).first()
    if plan:
        for t in list(plan.tasks):
            db.delete(t)
    else:
        plan = BidPlan(bid_id=bid_id)
        db.add(plan)
        db.flush()
    for t in tasks:
        db.add(PlanTask(
            plan_id=plan.id, name=t["name"], kind=t["kind"],
            requirement_id=t.get("requirement_id"),
            start=date.fromisoformat(t["start"]) if t.get("start") else None,
            due=date.fromisoformat(t["due"]) if t.get("due") else None,
            planned_hours=t.get("planned_hours", 0), status="pending",
        ))
    if bid.state == "draft":
        bid.state = "planning"
    db.commit()
    audit(db, actor, "plan_generated", "bid", bid_id, {"tasks": len(tasks)}, bid_id=bid_id)
    return {"tasks": len(tasks)}


@router.get("/{bid_id}/plan", response_model=list[PlanTaskOut])
def get_plan(bid_id: int, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    plan = db.query(BidPlan).filter(BidPlan.bid_id == bid_id).first()
    if not plan:
        return []
    return db.query(PlanTask).filter(PlanTask.plan_id == plan.id).order_by(PlanTask.due).all()


@router.patch("/plan/tasks/{task_id}", response_model=PlanTaskOut)
def update_task(task_id: int, body: PlanTaskUpdate, db: Session = Depends(get_db), _: User = Depends(contributor)):
    task = db.get(PlanTask, task_id)
    if not task:
        raise HTTPException(404, "Not found")
    for k, v in body.model_dump(exclude_none=True).items():
        setattr(task, k, v)
    db.commit()
    db.refresh(task)
    return task


# --- per-bid audit trail ---
@router.get("/{bid_id}/audit")
def bid_audit(bid_id: int, limit: int = 200, db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    rows = (
        db.query(AuditLog)
        .filter(AuditLog.bid_id == bid_id)
        .order_by(AuditLog.ts.desc())
        .limit(min(limit, 500))
        .all()
    )
    return [
        {"id": r.id, "ts": r.ts, "actor": r.actor, "action": r.action,
         "entity": r.entity, "entity_id": r.entity_id, "detail": r.detail}
        for r in rows
    ]


# --- helpers for frontend selects ---
@router.get("/meta/frameworks")
def all_frameworks(db: Session = Depends(get_db), _: User = Depends(get_current_user)):
    rows = db.query(ComplianceFramework).filter(ComplianceFramework.active == True).all()  # noqa: E712
    return [{"id": f.id, "name": f.name} for f in rows]