# python manage.py test ProjectHub
# Set PROJECTHUB_DOC_LOG=/path/log.json to also dump every request/response (used to build the API txt files).
import json
import os
from datetime import timedelta

from django.test import TestCase
from django.utils import timezone
from rest_framework.test import APIClient

from Company.models import company_details
from Employee.leave_models import ReportingHierarchy
from Employee.models import Department, EmployeeDT
from Timesheet.models import TimesheetEntry

from .models import ChangeRequest, DailyWorkReport, ProjectPlan, ProjectTask, TaskDependency

LOG = []


def mk_company(email):
    return company_details.objects.create(email=email, password="x", contact_no=str(abs(hash(email)))[:10],
                                          Registered_Company_Name="Zenith Corp", Company_address="Pune")


def mk_emp(co, name, dept=None, **kw):
    e = EmployeeDT(company=co, name=name, email=f"{name.split()[0].lower()}@x.com", Employee_Status="Activate", is_active=True,
                   department=dept, Department=dept.name if dept else None, Designation=kw.pop("Designation", "Engineer"), **kw)
    e.save()
    return e


def client(user):
    c = APIClient()
    c.force_authenticate(user=user)
    return c


class HubTests(TestCase):
    def setUp(self):
        self.co, self.other = mk_company("hub1@x.com"), mk_company("hub2@x.com")
        self.a, self.oa = client(self.co), client(self.other)
        self.dept = Department.objects.create(company=self.co, name="Technology & Engineering")
        self.boss = mk_emp(self.co, "Amit Joshi", self.dept, Designation="Engineering Manager")
        self.rahul = mk_emp(self.co, "Rahul Sharma", self.dept, Designation="Backend Engineer")
        self.vik = mk_emp(self.co, "Vikram Rao", self.dept, Designation="QA Engineer")
        self.t = timezone.localdate()

    # ---- helpers ----
    def call(self, who, method, url, body=None, expect=None, title=None, section=None):
        c = {"admin": self.a, "boss": client(self.boss), "rahul": client(self.rahul), "vik": client(self.vik)}[who]
        r = getattr(c, method.lower())(url, body, format="json") if method in ("POST", "PATCH", "PUT") else getattr(c, method.lower())(url)
        if expect:
            self.assertEqual(r.status_code, expect, f"{method} {url} -> {r.status_code} {r.content[:400]}")
        try:
            js = r.json()
        except Exception:
            js = None
        if title:
            LOG.append({"section": section, "title": title, "side": "employee" if who != "admin" else "admin", "method": method, "url": url,
                        "body": body, "status": r.status_code, "response": js})
        return js

    def d(self, day):
        return str(self.t + timedelta(days=day))

    # ---- the whole story, in the order the screens are used ----
    def test_full_flow(self):
        A = lambda m, u, b=None, e=None, t=None, s=None: self.call("admin", m, u, b, e, t, s)
        S1 = "1. SIDEBAR / MENU / DROPDOWNS"
        menu = A("GET", "/api/project-hub/menu/", None, 200, "Sidebar + tabs for Admin/HR", S1)["data"]
        self.assertEqual([c["label"] for c in menu["sidebar"][0]["children"]], ["Projects & Milestones", "Daily Work Reports", "Progress & Analytics"])
        self.assertEqual(len(menu["tabs"]), 7)
        A("GET", "/api/project-hub/meta/", None, 200, "Dropdown data for every form", S1)

        S2 = "2. PROJECTS & TASKS TAB"
        empty = A("GET", "/api/project-hub/projects/summary/", None, 200, "Summary cards (empty state)", S2)["data"]
        self.assertEqual(empty["total_projects"], 0)
        self.assertEqual(A("POST", "/api/project-hub/projects/", {"title": "x", "priority": "Urgent"}, 400)["code"], "VALIDATION")
        p = A("POST", "/api/project-hub/projects/", {"code": "PRJ-ZEN-01", "title": "Zenith Cloud Migration Platform", "client_department": "Technology & Engineering",
              "manager_employee_code": self.boss.employee_code, "status": "Active", "priority": "High", "budget_hours": 1000, "budget_amount": 2500000,
              "start_date": self.d(0), "end_date": self.d(60), "description": "Lift and shift of the billing stack"}, 201, "Create New Project", S2)["data"]
        self.assertEqual((p["priority"], p["baseline_end_date"], p["approved_end_date"]), ("High", self.d(60), self.d(60)))
        pid = p["id"]
        self.assertEqual(ProjectPlan.objects.filter(project_id=pid).count(), 1)
        A("POST", "/api/project-hub/projects/", {"title": "Internal HR Portal", "status": "Planning"}, 201, "Create project (minimum fields)", S2)
        sm = A("GET", "/api/project-hub/projects/summary/", None, 200, "Summary cards", S2)["data"]
        self.assertEqual((sm["total_projects"], sm["active_projects"], sm["planning_and_on_hold"]), (2, 1, 1))
        A("GET", "/api/project-hub/projects/?status=Active&search=zenith", None, 200, "Project list with filters", S2)
        al = A("POST", f"/api/project-hub/projects/{pid}/allocate/", {"employee_codes": [self.rahul.employee_code, self.vik.employee_code], "allocation_percent": 50, "role": "Engineer"},
               201, "Add team members (uses the Timesheet allocation table)", S2)["data"]
        self.assertEqual(len(al["allocations"]), 2)

        ms = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "Design Phase", "is_milestone": True, "start_date": self.d(0), "due_date": self.d(10)},
               201, "Create milestone (phase)", S2)["data"]
        t1 = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "Architecture document", "parent": ms["id"], "assignee_employee_code": self.rahul.employee_code,
               "priority": "High", "planned_hours": 16, "start_date": self.d(0), "due_date": self.d(4)}, 201, "Create task under milestone", S2)["data"]
        self.assertEqual((ms["wbs_code"], t1["wbs_code"]), ("1", "1.1"))
        t2 = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "Database schema", "parent": ms["id"], "assignee_employee_code": self.rahul.employee_code,
               "planned_hours": 24, "start_date": self.d(5), "due_date": self.d(9), "predecessors": [t1["id"]]}, 201, "Create task with predecessor", S2)["data"]
        self.assertEqual(t2["predecessors"], [t1["id"]])
        ms2 = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "Build Phase", "is_milestone": True}, 201)["data"]
        t3 = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "API development", "parent": ms2["id"], "assignee_employee_code": self.vik.employee_code,
               "planned_hours": 40, "start_date": self.d(10), "due_date": self.d(20)}, 201)["data"]
        dep = A("POST", "/api/project-hub/dependencies/", {"predecessor": t2["id"], "successor": t3["id"], "lag_days": 0}, 201, "Add dependency (finish-to-start)", S2)["data"]
        self.assertEqual(A("POST", "/api/project-hub/dependencies/", {"predecessor": t2["id"], "successor": t3["id"]}, 400)["code"], "VALIDATION")        # duplicate
        self.assertEqual(A("POST", "/api/project-hub/dependencies/", {"predecessor": t3["id"], "successor": t1["id"]}, 400)["code"], "VALIDATION")        # circular
        self.assertEqual(TaskDependency.objects.filter(is_active=True).count(), 2)
        A("GET", f"/api/project-hub/projects/{pid}/tasks/", None, 200, "WBS tree of a project", S2)
        A("GET", f"/api/project-hub/tasks/?project={pid}&type=task&status=To Do", None, 200, "Task list with filters", S2)
        self.assertEqual(A("PATCH", f"/api/project-hub/tasks/{t1['id']}/", {"status": "Blocked"}, 400)["code"], "VALIDATION")                           # needs reason
        A("PATCH", f"/api/project-hub/tasks/{t1['id']}/", {"status": "Blocked", "blocked_reason": "Waiting for client sign-off"}, 200, "Update task (blocked)", S2)

        S3 = "3. GANTT & TIMELINE TAB"
        g0 = A("GET", "/api/project-hub/gantt/", None, 200, "Gantt - no project selected", S3)["data"]
        self.assertEqual(g0["cards"]["critical_path_tasks"]["label"], "0 of 0 tasks")
        rc = A("POST", "/api/project-hub/gantt/recalculate/", {"project": pid}, 200, "Recalculate Critical Path & Schedule", S3)["data"]
        self.assertGreaterEqual(rc["critical"], 1)
        g = A("GET", f"/api/project-hub/gantt/?project={pid}&timescale=month&highlight_critical=true", None, 200, "Gantt - project selected", S3)["data"]
        self.assertEqual(g["cards"]["original_baseline_deadline"], self.d(60))
        self.assertIsNotNone(g["cards"]["forecast_projected_finish"])
        self.assertEqual(g["dependency_count"], 2)
        self.assertEqual(A("GET", f"/api/project-hub/gantt/?project={pid}&timescale=year", None, 400)["code"], "VALIDATION")
        A("PATCH", f"/api/project-hub/tasks/{t1['id']}/", {"status": "In Progress", "progress": 50}, 200)

        S4 = "4. MEETINGS & MINUTES TAB"
        m = A("POST", "/api/project-hub/meetings/", {"project": pid, "title": "Sprint 1 planning", "meeting_type": "Sprint Planning", "start_at": f"{self.d(1)}T10:00:00",
              "end_at": f"{self.d(1)}T11:00:00", "location": "Alpha Room", "agenda": "Scope the first sprint", "attendee_employee_codes": [self.rahul.employee_code, self.vik.employee_code]},
              201, "Record New Meeting", S4)["data"]
        self.assertEqual(len(m["participants"]), 2 + 0)
        from Communication.models import Meeting
        self.assertEqual(Meeting.objects.filter(title="Sprint 1 planning").count(), 1)                          # schedule stored ONCE, in Communication
        A("PATCH", f"/api/project-hub/meetings/{m['id']}/", {"minutes": "Agreed sprint scope.", "decisions": "Freeze schema by Friday", "rca": "n/a",
          "action_items": [{"title": "Share ERD", "owner_code": self.rahul.employee_code, "due_date": self.d(3), "done": False}]}, 200, "Add minutes / decisions / action items", S4)
        self.assertEqual(len(A("GET", f"/api/project-hub/meetings/?project={pid}&meeting_type=Sprint Planning&date={self.d(1)}&search=schema", None, 200, "Meeting list with filters", S4)["data"]), 1)
        self.assertEqual(A("POST", "/api/project-hub/meetings/", {"project": pid, "title": "bad", "start_at": f"{self.d(1)}T10:00:00", "end_at": f"{self.d(1)}T09:00:00"}, 400)["code"], "VALIDATION")

        S5 = "5. BUG MANAGEMENT TAB"
        b = A("POST", "/api/project-hub/bugs/", {"project": pid, "title": "Login API returns 500", "severity": "High", "description": "500 on empty password",
              "steps_to_reproduce": "POST /login with empty password", "task": t3["id"], "assignee_employee_code": self.rahul.employee_code}, 201, "Report New Bug", S5)["data"]
        self.assertEqual((b["bug_id"], b["qa_result"], b["status"]), ("BUG-0001", "Pending", "Open"))
        A("PATCH", f"/api/project-hub/bugs/{b['id']}/", {"status": "Fixed", "rca": "Missing validation", "resolution": "Added serializer validation"}, 200, "Update bug (fixed + RCA)", S5)
        q = A("POST", f"/api/project-hub/bugs/{b['id']}/qa-result/", {"qa_result": "Failed", "remarks": "Still fails for whitespace"}, 200, "QA result - Failed (reopens)", S5)["data"]
        self.assertEqual(q["status"], "Reopened")
        q = A("POST", f"/api/project-hub/bugs/{b['id']}/qa-result/", {"qa_result": "Passed"}, 200, "QA result - Passed (closes)", S5)["data"]
        self.assertEqual(q["status"], "Closed")
        A("GET", f"/api/project-hub/bugs/?project={pid}&severity=High&status=Closed&search=BUG-0001", None, 200, "Bug list with filters", S5)

        S6 = "6. CHANGE REQUESTS TAB"
        cr = A("POST", "/api/project-hub/change-requests/", {"project": pid, "reason": "Client added SSO integration", "scope_impact": "SSO module + 2 screens",
               "budget_impact": 150000, "hours_impact": 120, "revised_target_date": self.d(75)}, 201, "New Change Request", S6)["data"]
        self.assertEqual(cr["cr_id"], "CR-0001")
        self.assertEqual(A("POST", f"/api/project-hub/change-requests/{cr['id']}/reject/", {}, 400)["code"], "VALIDATION")
        ap = A("POST", f"/api/project-hub/change-requests/{cr['id']}/approve/", {"remarks": "Approved by sponsor"}, 200, "Approve change request", S6)["data"]
        self.assertEqual(ap["status"], "Approved")
        self.assertEqual(A("POST", f"/api/project-hub/change-requests/{cr['id']}/approve/", {}, 409)["code"], "CONFLICT")
        self.assertEqual(A("PATCH", f"/api/project-hub/change-requests/{cr['id']}/", {"reason": "x"}, 400)["code"], "VALIDATION")                     # locked after decision
        pr = A("GET", f"/api/project-hub/projects/{pid}/", None, 200, "Project after approved change request (deadline & budget moved)", S6)["data"]
        self.assertEqual((pr["baseline_end_date"], pr["approved_end_date"], pr["budget_amount"], pr["budget_hours"]), (self.d(60), self.d(75), 2650000.0, 1120.0))
        cr2 = A("POST", "/api/project-hub/change-requests/", {"project": pid, "reason": "Extra reports", "budget_impact": 10000}, 201)["data"]
        A("POST", f"/api/project-hub/change-requests/{cr2['id']}/reject/", {"remarks": "Out of scope"}, 200, "Reject change request", S6)
        A("GET", f"/api/project-hub/change-requests/?project={pid}&status=Approved", None, 200, "Change request list with filters", S6)

        S7 = "7. DAILY WORK REPORTS TAB"
        TimesheetEntry.objects.create(company=self.co, employee=self.rahul, project_id=pid, work_date=self.t, week_start=self.t - timedelta(days=self.t.weekday()),
                                      task_summary="x", hours=6, status="Submitted")
        r1 = A("POST", "/api/project-hub/daily-reports/", {"employee_code": self.rahul.employee_code, "project": pid, "task": t1["id"], "report_date": str(self.t),
               "summary": "Finished the architecture draft", "progress_percent": 80}, 201, "Create report for an employee (hours taken from Timesheet)", S7)["data"]
        self.assertEqual(r1["hours"], 6.0)
        self.assertEqual(A("POST", "/api/project-hub/daily-reports/", {"employee_code": self.rahul.employee_code, "project": pid, "task": t1["id"], "report_date": str(self.t),
                          "summary": "dup", "hours": 2}, 400)["code"], "VALIDATION")
        r2 = A("POST", "/api/project-hub/daily-reports/", {"employee_code": self.vik.employee_code, "project": pid, "task": t3["id"], "report_date": str(self.t - timedelta(days=1)),
               "summary": "API scaffolding", "hours": 7.5, "blockers": "Waiting for DB access"}, 201)["data"]
        r3 = A("POST", "/api/project-hub/daily-reports/", {"employee_code": self.vik.employee_code, "project": pid, "report_date": str(self.t - timedelta(days=2)),
               "summary": "Test cases", "hours": 4}, 201)["data"]
        c = A("GET", "/api/project-hub/daily-reports/summary/", None, 200, "Summary cards", S7)["data"]
        self.assertEqual((c["total_reports"], c["pending_review"]), (3, 3))
        A("POST", f"/api/project-hub/daily-reports/{r1['id']}/approve/", {"remarks": "Good progress"}, 200, "Approve report", S7)
        self.assertEqual(ProjectTask.objects.get(pk=t1["id"]).progress, 80)                         # approval pushed progress to the task
        self.assertEqual(A("POST", f"/api/project-hub/daily-reports/{r2['id']}/request-revision/", {}, 400)["code"], "VALIDATION")
        A("POST", f"/api/project-hub/daily-reports/{r2['id']}/request-revision/", {"remarks": "Add what was blocked"}, 200, "Request revision", S7)
        self.assertEqual(A("PATCH", f"/api/project-hub/daily-reports/{r1['id']}/", {"summary": "edit"}, 400)["code"], "VALIDATION")                  # approved = locked
        A("POST", "/api/project-hub/daily-reports/approve-all-pending/", {"project": pid}, 200, "Approve all pending", S7)
        A("GET", f"/api/project-hub/daily-reports/?status=Approved&project={pid}&date={self.t}", None, 200, "Report list with filters", S7)
        c = A("GET", "/api/project-hub/daily-reports/summary/", None, 200)["data"]
        self.assertEqual((c["approved_reports"], c["revisions_requested"], c["total_hours_logged"]), (2, 1, 10.0))

        S8 = "8. ANALYTICS & PERFORMANCE TAB"
        A("PATCH", f"/api/project-hub/tasks/{t1['id']}/", {"status": "Completed", "deliverable_verified": True}, 200, "Complete task + verify deliverable", S8)
        an = A("GET", f"/api/project-hub/analytics/?project={pid}", None, 200, "Analytics for a project", S8)["data"]
        self.assertEqual(an["cards"]["on_time_task_delivery"]["percent"], 100)
        self.assertEqual(an["cards"]["overdue_and_blocked"]["total"], 0)
        self.assertEqual(an["employee_contributions"]["rows"][0]["employee"]["employee_code"], self.rahul.employee_code)
        A("GET", "/api/project-hub/analytics/", None, 200, "Analytics for all projects", S8)

        # ---- B2B isolation + permissions ----
        self.assertEqual(self.call("admin", "GET", "/api/project-hub/tasks/", None, 200)["meta"]["total"], 5)
        o = self.oa.get("/api/project-hub/tasks/").json()
        self.assertEqual(o["meta"]["total"], 0)
        self.assertEqual(self.oa.get(f"/api/project-hub/projects/{pid}/").status_code, 404)
        self.assertEqual(self.oa.post("/api/project-hub/tasks/", {"project": pid, "title": "spy"}, format="json").status_code, 400)
        self.assertEqual(client(self.rahul).get("/api/project-hub/tasks/").status_code, 403)                  # employee without HR role
        # delete + undelete safety
        A("DELETE", f"/api/project-hub/tasks/{t3['id']}/", None, 200, "Delete task (soft delete)", S2)
        self.assertEqual(TaskDependency.objects.filter(is_active=True).count(), 1)
        A("DELETE", f"/api/project-hub/change-requests/{cr2['id']}/", None, 409)
        A("POST", f"/api/project-hub/projects/{pid}/delete/", None, 200, "Delete project (POST style)", S2)
        self.assertEqual(self.call("admin", "GET", f"/api/project-hub/projects/{pid}/", None).get("code"), "NOT_FOUND")

    # ---- employee side ----
    def test_employee_side(self):
        A = lambda m, u, b=None, e=None, t=None, s=None: self.call("admin", m, u, b, e, t, s)
        R = lambda m, u, b=None, e=None, t=None, s=None: self.call("rahul", m, u, b, e, t, s)
        B = lambda m, u, b=None, e=None, t=None, s=None: self.call("boss", m, u, b, e, t, s)
        V = lambda m, u, b=None, e=None, t=None, s=None: self.call("vik", m, u, b, e, t, s)
        pid = A("POST", "/api/project-hub/projects/", {"code": "PRJ-ZEN-01", "title": "Zenith Cloud Migration Platform", "manager_employee_code": self.boss.employee_code,
                "status": "Active", "start_date": self.d(-5), "end_date": self.d(60)}, 201)["data"]["id"]
        other = A("POST", "/api/project-hub/projects/", {"code": "PRJ-OTH-02", "title": "Not mine"}, 201)["data"]["id"]
        A("POST", f"/api/project-hub/projects/{pid}/allocate/", {"employee_codes": [self.rahul.employee_code, self.vik.employee_code]}, 201)
        ms = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "Design Phase", "is_milestone": True}, 201)["data"]
        t1 = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "Architecture document", "parent": ms["id"], "assignee_employee_code": self.rahul.employee_code,
               "planned_hours": 16, "start_date": self.d(-4), "due_date": self.d(-1)}, 201)["data"]
        t2 = A("POST", "/api/project-hub/tasks/", {"project": pid, "title": "Vik task", "assignee_employee_code": self.vik.employee_code}, 201)["data"]
        S = "E1. MENU / DASHBOARD"
        mm = B("GET", "/employee/project-hub/menu/", None, 200, "Employee sidebar (project manager sees the review item)", S)["data"]
        self.assertTrue(mm["is_project_manager"])
        self.assertFalse(R("GET", "/employee/project-hub/menu/", None, 200, "Employee sidebar (normal employee)", S)["data"]["is_project_manager"])
        d = R("GET", "/employee/project-hub/dashboard/", None, 200, "My dashboard", S)["data"]
        self.assertEqual((d["my_projects"], d["tasks_open"], d["tasks_overdue"]), (1, 1, 1))
        S = "E2. MY PROJECTS & TASKS"
        pl = R("GET", "/employee/project-hub/projects/", None, 200, "My projects", S)["data"]
        self.assertEqual([x["code"] for x in pl], ["PRJ-ZEN-01"])
        R("GET", f"/employee/project-hub/projects/{pid}/", None, 200, "My project detail (team + WBS tree)", S)
        self.assertEqual(R("GET", f"/employee/project-hub/projects/{other}/", None, 404)["code"], "NOT_FOUND")
        self.assertEqual(len(R("GET", "/employee/project-hub/tasks/?overdue=true", None, 200, "My tasks (overdue filter)", S)["data"]), 1)
        self.assertEqual(R("GET", f"/employee/project-hub/tasks/{t2['id']}/", None, 404)["code"], "NOT_FOUND")                       # someone else's task
        self.assertEqual(R("PATCH", f"/employee/project-hub/tasks/{t1['id']}/update/", {"status": "Cancelled"}, 400)["code"], "VALIDATION")
        self.assertEqual(R("POST", f"/employee/project-hub/tasks/{t1['id']}/update/", {"deliverable_verified": True}, 400)["code"], "VALIDATION")  # not an employee field
        x = R("POST", f"/employee/project-hub/tasks/{t1['id']}/update/", {"status": "In Progress", "progress": 60}, 200, "Update my task progress", S)["data"]
        self.assertEqual((x["status"], x["progress"]), ("In Progress", 60))
        R("PATCH", f"/employee/project-hub/tasks/{t1['id']}/update/", {"status": "Blocked", "blocked_reason": "Waiting for access"}, 200, "Mark my task blocked", S)
        S = "E3. MY BUGS"
        bg = R("POST", "/employee/project-hub/bugs/", {"project": pid, "title": "Export button crashes", "severity": "Medium", "description": "Crash on click"}, 201, "Report a bug", S)["data"]
        self.assertEqual(R("POST", "/employee/project-hub/bugs/", {"project": other, "title": "x"}, 400)["code"], "VALIDATION")
        bid = A("POST", "/api/project-hub/bugs/", {"project": pid, "title": "Timeout on save", "assignee_employee_code": self.rahul.employee_code}, 201)["data"]["id"]
        self.assertEqual(len(R("GET", "/employee/project-hub/bugs/", None, 200, "My bugs (assigned to me or reported by me)", S)["data"]), 2)
        self.assertEqual(R("PATCH", f"/employee/project-hub/bugs/{bid}/update/", {"status": "Closed"}, 400)["code"], "VALIDATION")
        R("POST", f"/employee/project-hub/bugs/{bid}/update/", {"status": "Fixed", "resolution": "Raised timeout to 30s", "rca": "Default timeout too low"}, 200, "Update my assigned bug", S)
        self.assertEqual(R("POST", f"/employee/project-hub/bugs/{bg['id']}/update/", {"status": "Fixed"}, 403)["code"], "FORBIDDEN")        # reporter is not the assignee
        S = "E4. CHANGE REQUESTS"
        cr = R("POST", "/employee/project-hub/change-requests/", {"project": pid, "reason": "Need 2 extra weeks for integration", "revised_target_date": self.d(74), "hours_impact": 80}, 201, "Raise a change request", S)["data"]
        self.assertEqual(cr["status"], "Pending")
        R("GET", "/employee/project-hub/change-requests/", None, 200, "My change requests", S)
        self.assertEqual(R("POST", f"/employee/project-hub/change-requests/{cr['id']}/delete/", None, 200, "Withdraw a pending change request", S)["code"], "MY_HUB_CR_WITHDRAWN")
        S = "E5. PROJECT MEETINGS"
        A("POST", "/api/project-hub/meetings/", {"project": pid, "title": "Kickoff", "meeting_type": "Kickoff", "start_at": f"{self.d(1)}T10:00:00", "attendee_employee_codes": [self.rahul.employee_code]}, 201)
        A("POST", "/api/project-hub/meetings/", {"project": pid, "title": "Vik only", "start_at": f"{self.d(2)}T10:00:00", "attendee_employee_codes": [self.vik.employee_code]}, 201)
        ml = R("GET", "/employee/project-hub/meetings/?status=Scheduled", None, 200, "My project meetings", S)["data"]
        self.assertEqual([m["title"] for m in ml], ["Kickoff"])
        R("GET", f"/employee/project-hub/meetings/{ml[0]['id']}/", None, 200, "Meeting detail with minutes", S)
        S = "E6. DAILY WORK REPORTS"
        TimesheetEntry.objects.create(company=self.co, employee=self.rahul, project_id=pid, work_date=self.t, week_start=self.t - timedelta(days=self.t.weekday()),
                                      task_summary="x", hours=7, status="Submitted")
        r = R("POST", "/employee/project-hub/reports/", {"project": pid, "task": t1["id"], "summary": "Worked on the architecture", "progress_percent": 70}, 201, "Submit today's report (hours from Timesheet)", S)["data"]
        self.assertEqual((r["hours"], r["status"]), (7.0, "Pending"))
        self.assertEqual(R("POST", "/employee/project-hub/reports/", {"project": other, "summary": "x", "hours": 1}, 400)["code"], "VALIDATION")
        self.assertEqual(R("POST", "/employee/project-hub/reports/", {"project": pid, "task": t2["id"], "summary": "x", "hours": 1}, 400)["code"], "VALIDATION")   # Vik's task
        R("POST", f"/employee/project-hub/reports/{r['id']}/update/", {"summary": "Worked on architecture + review", "hours": 7.5}, 200, "Edit my pending report", S)
        r2 = R("POST", "/employee/project-hub/reports/", {"project": pid, "report_date": self.d(-1), "summary": "Scratch", "hours": 2}, 201)["data"]
        R("POST", f"/employee/project-hub/reports/{r2['id']}/delete/", None, 200, "Delete my pending report", S)
        R("GET", "/employee/project-hub/reports/?status=Pending", None, 200, "My reports", S)
        S = "E7. REPORT REVIEW (PROJECT MANAGER)"
        self.assertEqual(R("GET", "/employee/project-hub/review/pending/", None, 200)["meta"]["total"], 0)                          # not a manager
        q = B("GET", "/employee/project-hub/review/pending/", None, 200, "Reports waiting for my review", S)
        self.assertEqual(q["meta"]["total"], 1)
        self.assertEqual(B("POST", f"/employee/project-hub/review/{r['id']}/request-revision/", {}, 400)["code"], "VALIDATION")
        B("POST", f"/employee/project-hub/review/{r['id']}/request-revision/", {"remarks": "Split the hours by task"}, 200, "Request revision", S)
        R("POST", f"/employee/project-hub/reports/{r['id']}/update/", {"summary": "Split by task: architecture 5h, review 2.5h"}, 200)        # resubmit
        self.assertEqual(DailyWorkReport.objects.get(pk=r["id"]).status, "Pending")
        ok = B("POST", f"/employee/project-hub/review/{r['id']}/approve/", {"remarks": "OK"}, 200, "Approve report", S)["data"]
        self.assertEqual(ok["status"], "Approved")
        self.assertEqual(ProjectTask.objects.get(pk=t1["id"]).progress, 70)
        self.assertEqual(V("POST", f"/employee/project-hub/review/{r['id']}/approve/", {}, 404)["code"], "NOT_FOUND")
        S = "E8. MY PERFORMANCE"
        an = R("GET", "/employee/project-hub/analytics/", None, 200, "My performance score", S)["data"]
        self.assertEqual(an["tasks_assigned"], 1)
        self.assertEqual(an["report_consistency_rate"] is not None, True)

    def test_logging(self):                                  # last test alphabetically: persist the log if requested
        path = os.environ.get("PROJECTHUB_DOC_LOG")
        if path and LOG:
            with open(path, "w", encoding="utf-8") as f:
                json.dump(LOG, f, indent=1, default=str)
