
Every requirement in the PRD (R-01 to R-30), the out-of-scope list, the non-functional requirements, the success criteria and the Definition of Done, traced to the code that implements it, the test that covers it, and a screenshot or a live API call that proves it.
One row per requirement. The number is implemented items over all items; click a row to open its evidence. 9 groups carry a minor difference to refine, 7 carry only a decision, tenant or operational note, the rest are complete.
Everything that is not a plain implemented, grouped by what it needs. Items marked "Configurable in Legal settings" are changed by the GC in the workspace without a release.
All 29 items in Feedback Round 1 of PRJ-049 (17 to 24 Nov 2026), each read against the approved PRD and checked on the build. Click a chip to filter, click a row for the PRD reference, what we found and the proposed action.
Each group opens to what is not a plain implemented, then the screenshots, then the line-by-line evidence table and the live API proofs.
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC4 | Given a lawyer switches on the out-of-office toggle, or turns on Outlook automatic replies, then the LMS shows them as out of office and doesn't assign them new requests. | Implemented | apps/api/src/lg/middleware/lg-auth.ts:153 isOutOfOffice: outlookAutoReply flag OR oooOn within optional oooFrom/oooUntil (UAE day)apps/api/src/lg/services/lg-routing.ts:80 decideAssignment: candidates = queue lawyers filtered by !isOutOfOffice; team-lead fallback also skipped when out (line 106)apps/api/src/lg/routes/profile.ts:70 PATCH /lg/profile { oooOn, oooFrom, oooUntil } , the toggle; audited per fieldapps/api/src/lg/services/lg-admin.ts:458 listPeople exposes outOfOfficeNow; People & roles shows an 'Out of office' chip (OrgSections.tsx line 230)apps/api/src/lg/services/integrations/directory.ts:109 Outlook automatic replies then outlookAutoReply when the directory sync is live; otherwise the GC's 'Outlook automatic replies on' toggle simulates it (lg-admin personPatchSchema line 489) | core.test.ts confidential then GC; Arabic then Arabic speakers; same counterparty first; out of office skippedconfig.test.ts lawyers need a queue; one GC; defaults validated; out of office respects datespi-legal-counsel /workspace/pi-for-legal/lg/profile Switch 'Out of office' on; as pi-legal-requester submit a Commercial request (1.1) then the Overview assignment shows Rami/Nadia, not Shikha; as GC, Settings › People & roles shows Shikha with an 'Out of office' chip. |
| Desc: Outlook automatic replies count as out of office | A user counts as out of office when ... their Outlook automatic replies are on. Live only with MS_GRAPH_* + LG_DIRECTORY_SYNC=1; locally the flag is set by hand. | Needs the M365 tenant | apps/api/src/lg/services/integrations/directory.ts:56 autoRepliesOn reads Graph mailboxSettings/automaticRepliesSetting (alwaysEnabled, or scheduled and inside the window)apps/api/src/lg/services/integrations/directory.ts:169 runDirectorySync (hourly from lg-jobs integrations step) refreshes every profile so replies switched on in Outlook take effect without opening the LMSapps/api/src/lg/services/lg-admin.ts:489 Simulator: personPatchSchema.outlookAutoReply , the GC toggles 'Outlook automatic replies on' in People & rolesapps/api/prisma/schema.prisma:4601 LgProfile.outlookAutoReply: 'Simulated Outlook automatic replies (Graph mailboxSettings in production)' | integrations.test.ts reads automatic replies, including a scheduled windowpi-legal-gc /workspace/pi-for-legal/lg/admin/people Edit Shikha then 'Outlook automatic replies on' then save: chip 'Out of office'; her /lg/profile says 'yours are on right now'; new Commercial requests route past her. |
| AC5 | Given the out-of-office end date passes, or Outlook automatic replies are turned off, then the lawyer is available for assignment again. | Implemented | apps/api/src/lg/middleware/lg-auth.ts:157 isOutOfOffice compares today (UAE) to oooFrom/oooUntil on every call , past the end date the toggle no longer countsapps/api/src/lg/services/integrations/directory.ts:114 Each sync writes outlookAutoReply = autoRepliesOn(replies): replies off then false (hourly runDirectorySync, line 169)apps/web/src/lg/pages/LgProfilePage.tsx:104 'When the end date passes you're available again. Outlook automatic replies also count as out of office' | config.test.ts lawyers need a queue; one GC; defaults validated; out of office respects datespi-legal-counsel /workspace/pi-for-legal/lg/profile Set Out of office with an end date in the past then the header shows no 'out today'; GET /api/workspace/pi-for-legal/portal/lg/profile returns outOfOfficeNow=false and a new Commercial request can route to Shikha again. |
| AC6 | Given a lawyer profile, then it holds queues, Arabic speaker, initials and the out-of-office setting. | Implemented | apps/api/prisma/schema.prisma:4585 LgProfile: arabicSpeaker, initials, oooOn/oooFrom/oooUntil, outlookAutoReply, delegateUserId, defaultEntityId/defaultBusinessUnitId; queues via LgQueueMember (line 4623)apps/api/src/lg/routes/profile.ts:42 GET /lg/profile returns queues (with isLead), arabicSpeaker, initials, ooo* and outOfOfficeNowapps/api/src/lg/services/lg-admin.ts:481 personPatchSchema: initials 2-4 letters, required for lawyers ('Lawyers need initials. They go into file names', line 505); lawyers need at least one queue (line 509)apps/web/src/lg/pages/LgProfilePage.tsx:140 Lawyer card shows Queues, Initials (in file names), Arabic speaker (read-only; GC sets them) | admin.test.ts out of office with dates and a delegate; FYI emails offcore.test.ts reports legal roles from the profile, not the workspace rolepi-legal-counsel /workspace/pi-for-legal/lg/profile Queues 'Commercial (team lead)', Initials 'SK', Arabic speaker 'Yes', the Out of office switch with start/end dates. |
| AC7 | Given an approver names a delegate, then the delegate receives their approvals while they're out of office. | Implemented | apps/api/src/lg/services/lg-approvals.ts:179 resolveActing: approver out of office then delegateUserId acts (one further hop if the delegate is away too); no delegate then stays + lawyer alertedapps/api/src/lg/services/lg-approvals.ts:200 activate(): actingUserId stored and the APPROVAL_REQUESTED email goes to the delegateapps/api/src/lg/services/lg-approvals.ts:323 canActOnApproval: the delegate may decide only while the approver is out; decision audited 'on behalf of' (line 347)apps/api/src/lg/routes/profile.ts:75 delegateUserId must be another person from the directoryapps/web/src/lg/pages/LgProfilePage.tsx:109 'Delegate for approvals' picker; 'You're the delegate for …' line | approvals.test.ts an out-of-office approver's approval goes to the delegate, logged "on behalf of"; no delegate then lawyer alertedapprovals.test.ts a delegate decides only while the approver is awaypi-legal-approver /workspace/pi-for-legal/lg/profile Tariq: delegate = Ahmad, Out of office on. As pi-legal-counsel send a 1.1 contract (> AED 1m) for approval; sign in as Ahmad (ahmad@7x.ae) then /lg/approvals lists it 'on behalf of Tariq Al Suwaidi'. |
| Desc: requester default legal entity and business unit pre-fill intake | Each requester has a default legal entity and business unit, used to pre-fill intake (R-05). | Implemented | apps/api/src/lg/services/lg-intake.ts:435 New draft starts with entityId/businessUnitId = actor.profile.defaultEntityId/defaultBusinessUnitIdapps/api/src/lg/routes/profile.ts:30 PATCH /lg/profile accepts defaultEntityId/defaultBusinessUnitId, validated (no dissolved entity; BU must belong to the entity) via validateRequesterDefaultsapps/api/src/lg/services/lg-admin.ts:490 The GC can also set them per personapps/web/src/lg/pages/LgProfilePage.tsx:55 Entity + Business unit pickers (units filtered by entity) | config.test.ts lawyers need a queue; one GC; defaults validated; out of office respects datespi-legal-requester /workspace/pi-for-legal/lg/new After setting entity EPGL + a BU on /lg/profile, the conversation's entity step is pre-filled with EPGL and the BU list is EPGL's. |
| Desc: roles table (requester = any employee; lawyer linked to queues; one fixed team lead per queue; GC; approver incl. ad-hoc; IT admin settings only) | Roles: Requester any 7X employee; Lawyer linked to one or more queues; Team lead one fixed per queue; GC; Approver anyone in the matrix / any 7X user ad-hoc; IT administrator settings only. | Implemented | apps/api/src/lg/middleware/lg-auth.ts:67 loadLgActor: isGc/isLawyer/isItAdmin from LgProfile, queues from LgQueueMember, leadQueues from LgQueue.teamLeadUserId; everyone signed in is a requester; a workspace admin gets no content access by being admin (comment lines 14-15)apps/api/prisma/schema.prisma:4611 LgQueue.teamLeadUserId , one lead per queue; updateQueue makes the lead a member (lg-admin line 334)apps/api/src/lg/services/lg-admin.ts:509 A lawyer must have at least one queue; one GC at a time (handOverGc line 511)apps/api/src/lg/services/lg-approvals.ts:118 buildRoute: ad-hoc approvers (any directory user) added as a final parallel step; matrix approvers can't be removed | core.test.ts reports legal roles from the profile, not the workspace roleadmin.test.ts queues accept lawyers only; the team lead is always a memberAPI GET /api/workspace/pi-for-legal/portal/lg/me 200 with isWorkspaceAdmin=true, isItAdmin=true, isLawyer=false, isGc=false, isLegal=false, canViewSettings=true. |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | GET /profile | 200 | data returned expected: 200 queues, arabic, initials, out-of-office, delegate |
| counsel | GET /me | 200 | data returned expected: 200 role flags |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given the GC changes a setting, then no code release is needed and the change is logged. | Implemented | apps/api/src/lg/routes/admin.ts:82 PUT /admin/settings/:key (requireGc) then updateSetting; same for types, queues, business units, holidays, emails, peopleapps/api/src/lg/services/lg-settings.ts:100 setLgSetting upserts LgSetting and writes a SETTING audit row with old/new value and actorapps/api/src/lg/services/lg-admin.ts:256 updateType audits each changed field; createQueue/updateQueue/saveUnit/addHoliday/removeHoliday/updatePerson do the same (lines 317, 343-352, 374-383, 398, 405, 525-531)apps/web/src/lg/pages/LgAdminPage.tsx:29 Settings sections: Categories, Request types, Queues, Business units, SLAs & calendar, Naming & documents, Emails, Mailbox & uploads, People & roles, Approval matrix, Templates & playbooks, Integrations, Audit trail | admin.test.ts GC edits; team leads and IT admins view; others are refusedadmin.test.ts sets legal roles; there is always a GC; role changes are access eventspi-legal-gc /workspace/pi-for-legal/lg/admin/mailbox Change the upload limit and save; then /lg/admin/audit shows a 'setting' row for Setting uploadLimitMb with before then after and Adeeb as actor. |
| AC2 | Given a team lead or IT administrator opens settings, then they can view them but not change them. | Implemented | apps/api/src/lg/middleware/lg-auth.ts:95 canViewSettings = isGc || leads a queue || isItAdmin; requireSettingsViewer (line 135) / requireGc (line 131)apps/api/src/lg/routes/admin.ts:71 router.use(requireSettingsViewer); every write route adds requireGc (lines 82, 92, 97, 106, 111, 118, 123, 130, 135, 141, 146, 154)apps/api/src/lg/middleware/lg-auth.ts:141 requireGcToChange: templates/playbooks/contract types readable by viewers, writable by the GC onlyapps/web/src/lg/pages/LgAdminPage.tsx:64 readOnly = !isGc then every section gets readOnly, inputs disabled, 'View only' header | admin.test.ts GC edits; team leads and IT admins view; others are refusedconfig.test.ts team leads and IT read templates, playbooks and contract types; only the GC changes themapprovals.test.ts only the GC changes it; team leads and IT admins can read itAPI PUT /api/workspace/pi-for-legal/portal/lg/admin/settings/uploadLimitMb {"value":30} 403 'Only the General Counsel can do that' while GET /lg/admin/settings returns 200; in the UI /lg/admin shows 'View only' with disabled controls for Mohammed and Khalifa. |
| AC3 | Given the GC changes an SLA, a question or a form, then it applies to new requests only. | Implemented | apps/api/src/lg/services/lg-intake.ts:440 scriptSnapshot (questions, documents, version) copied onto the draft when the type is chosen (and re-copied on type change, line 490); every later read uses r.scriptSnapshot (lines 171, 582, 618, 691)apps/api/src/lg/services/lg-intake.ts:717 On submit takeSettingsSnapshot() then LgRequest.settingsSnapshot (naming convention, contract ref format, upload limit, approval matrix, working days, holidays)apps/api/src/lg/services/lg-sla.ts:44 applySla sets slaDays/slaDueAt at assignment and is not re-run when the type's SLA changes later; reclassify recomputes on the frozen calendar (lg-routing line 262)apps/api/src/lg/services/lg-admin.ts:243 updateType bumps version only on a real script change; UI says 'New requests use script vN' (TypesSection line 73) | admin.test.ts edits a script, bumps the version, validates conditions; submitted requests keep their snapshotconfig.test.ts a submitted request keeps its naming convention, ref format and approval matrixpi-legal-gc /workspace/pi-for-legal/lg/admin/types Add a question to 1.1 and save ('New requests use script v2'); open an existing 1.1 request then Overview answers still follow the old script; a new 1.1 intake asks the new question. In /lg/admin/calendar change 1.1's SLA then existing requests keep their due date. |
| AC4 | Given the GC adds a public holiday, then SLA due dates for new requests skip that day. | Implemented | apps/api/src/lg/services/lg-admin.ts:393 addHoliday then LgHoliday (unique date), auditedapps/api/src/lg/services/lg-calendar.ts:16 loadCalendar reads workingDays setting + LgHoliday; isBusinessDay / addBusinessDays skip holidays (lines 55-68)apps/api/src/lg/services/lg-sla.ts:50 slaDueAt = addBusinessDays(assignedAt, days, calendar)apps/web/src/lg/components/admin/ConfigSections.tsx:126 CalendarSection: working week toggles + holiday list with add/remove | admin.test.ts adding a holiday shifts SLA days for new requests (calendar)core.test.ts skips weekends and holidayspi-legal-gc /workspace/pi-for-legal/lg/admin/calendar Add a holiday on the next working day; submit a new request as pi-legal-requester then the confirmation's expected date / Overview SLA due date is one working day later than before. |
| AC5 | Given the GC adds a business unit and links it to an entity, then it appears at intake for that entity. | Implemented | apps/api/src/lg/services/lg-admin.ts:362 saveUnit: name unique, entityIds validated against the register, auditedapps/api/src/lg/routes/me.ts:78 GET /lg/reference returns businessUnits with entityIdsapps/web/src/lg/components/intake/Conversation.tsx:213 Intake lists only units whose entityIds include the chosen entity (also FormView.tsx 92, AnswerInput.tsx 316)apps/api/src/lg/services/lg-intake.ts:340 Server-side: submit blocked if the BU is inactive or doesn't belong to the entity | admin.test.ts business units link to entitiespi-legal-gc /workspace/pi-for-legal/lg/admin/units Add 'Fleet' and tick EPGL; as pi-legal-requester start a request, choose EPGL then 'Fleet' is in the business unit list, and absent when 7X is chosen. |
| Desc: everything the GC configures (categories/types/scripts, queues+leads, BUs↔entities, SLAs/working week/holidays, naming/doc types/contract ref format, approval matrix, contract types/templates/playbooks, email wording, triage inbox, upload limit 25 MB) | What the GC configures: request categories, types and intake scripts (questions, order, options, M/O, conditions, documents); queues, lawyers, team lead; business units and entities (initial 7X, nxn, EPGL, Emirates Post); SLAs per type, UAE working week, holidays; naming convention, document type list, contract reference format; approval matrix; contract types, templates, playbooks; email wording; legal triage inbox; file upload limits (default 25 MB). | Implemented | apps/api/src/lg/services/lg-admin.ts:160 questionSchema/documentSchema: key, label, type, required, options, showIf conditions, deadline; validateScript checks conditions point at earlier questions (line 184)apps/api/src/lg/services/lg-admin.ts:38 SETTING_SCHEMAS: namingConvention, contractRefFormat, documentTypes, uploadLimitMb (1-55), legalMailbox, triageInbox, workingDays, emailTemplates, urgentSlaDays, tenderScopeSla, escalation, categories, fxRates, retentionpackages/shared/src/legalModules.ts:1047 LG_DEFAULT_UPLOAD_LIMIT_MB = 25apps/api/src/lg/services/lg-settings.ts:13 LG_SETTING_DEFAULTS incl. triageInbox 'legal.triage@7x.ae'apps/api/src/lg/routes/admin.ts:105 Queues (POST/PUT with teamLeadUserId + memberIds), business units, holidays, emails, peopleapps/web/src/lg/pages/LgAdminPage.tsx:94 Approval matrix mounts ApprovalMatrixSection (rules CRUD in routes/approvals.ts, GC only); Templates & playbooks link to /lg/templates and /lg/playbooks (requireGcToChange)apps/api/prisma/workspace/seed-pi-for-legal.ts:73 Seed entities 7X (Emirates Post Group Company PJSC), Emirates Post, EPGL, nxn with business units | config.test.ts adds a queue and a category, numbers its types, hides switched-off categories from intakeconfig.test.ts urgent and tender-scope SLAs and the reminder timings come from settingsadmin.test.ts overrides, previews and resets a template; new emails use itpi-legal-gc /workspace/pi-for-legal/lg/admin/naming Pattern with tokens + live preview; document types textarea; contract ref format. Then /lg/admin/mailbox: legal mailbox, triage inbox, upload limit (25). |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | PUT /admin/settings/sla{"value": {}} | 403 | Only the General Counsel can do that expected: 403: team lead views only |
| it | PUT /admin/settings/sla{"value": {}} | 403 | Only the General Counsel can do that expected: 403 |
| counsel | GET /admin/settings | 200 | data returned expected: 200 |
| gc | GET /admin/holidays | 200 | data returned expected: 200 list of GC-set public holidays |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a lawyer opens the register, then they can see all entities in a list and in a group structure view, and filter them. | Implemented | apps/api/src/lg/routes/registers.ts:356 GET /registers/entities with status, legalForm, jurisdiction, businessUnitId, q, flag filtersapps/api/src/lg/routes/registers.ts:378 GET /registers/entities/tree builds parentthenchildren nodesapps/web/src/lg/components/registers/EntitiesView.tsx:164 List/Group structure toggle (line 222), filters Status, Legal form, Jurisdiction, Business unit, flag (lines 204-217), TreeNode (line 136) | registers.test.ts shows the group structure and never deletesregisters.test.ts only the GC creates; lawyers view; business users get 404pi-legal-counsel /workspace/pi-for-legal/lg/registers/entities List of 7X, Emirates Post, EPGL, nxn; 'Group structure' shows EPGL/nxn/Emirates Post under 7X; Legal form = LLC filter leaves EPGL. |
| AC2 | Given a user who isn't the GC, then they can view entity records but can't create or edit them. | Implemented | apps/api/src/lg/services/lg-registers.ts:21 canEdit('entities') then GC onlyapps/api/src/lg/routes/registers.ts:424 POST /entities and PATCH /entities/:id then 403 'Only the General Counsel can create or edit legal entities' (forbidEdit line 70)apps/api/src/lg/routes/registers.ts:420 Detail returns canEdit so the UI hides New/Edit for non-GC | registers.test.ts only the GC creates; lawyers view; business users get 404API PATCH /api/workspace/pi-for-legal/portal/lg/registers/entities/<epgl-id> {"trn":"1"} 403; GET of the same record 200. In the UI Shikha sees no 'New entity'/'Edit' buttons, Adeeb does. |
| AC3 | Given a trade licence expires in 90, 60 or 30 days, then an alert is sent. On expiry, the 'Licence expired' flag shows. | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:49 Hourly timer: licence (and every dated registration) at LG_ALERTS.entityLicence [90,60,30] then REGISTER_ALERT email to GC + Corporate queue; one 'expired' alert after the date; idempotent via alertsSent keyed by datepackages/shared/src/legalModules.ts:1026 entityLicence: [90, 60, 30]apps/api/src/lg/services/lg-registers.ts:47 entityFlags.licenceExpired = days left < 0 (computed, so the flag shows the day after expiry without the timer)apps/web/src/lg/components/registers/EntitiesView.tsx:128 'Licence expired' chip in list, tree and detail; 'Licence expired' filter (line 217); stat strip hint (LgRegistersPage line 66) | config.test.ts blocks parent loops, links the signatory POA, names documents by the entity, alerts again after a renewalregisters.test.ts only the GC creates; lawyers view; business users get 404API POST /api/workspace/pi-for-legal/portal/lg/jobs/run {"now":"<licence expiry minus 30 days>"} 200 with registers.entityAlerts ≥ 1; /lg/mailbox Outbox shows a REGISTER_ALERT to Adeeb + Corporate lawyers; set an entity's licence expiry to yesterday then red 'Licence expired' chip on /lg/registers/entities. |
| AC4 | Given an entity's status is Dissolved, then it no longer appears at intake, but its record and history remain. | Implemented | apps/api/src/lg/routes/me.ts:77 GET /lg/reference hides DISSOLVED entities from non-legal usersapps/web/src/lg/components/intake/Conversation.tsx:224 Intake pickers filter status !== 'DISSOLVED' for everyone (also FormView 129, AnswerInput 307)apps/api/src/lg/services/lg-intake.ts:336 Submit blocked: 'That entity is no longer available. Choose another'apps/api/src/lg/routes/registers.ts:319 DELETE refused with 405 + DELETE_BLOCKED audit; history kept in LgAuditEvent | registers.test.ts shows the group structure and never deletespi-legal-gc /workspace/pi-for-legal/lg/registers/entities Edit nxn then status Dissolved. As pi-legal-requester /lg/new no longer lists nxn; the GC still opens nxn in the register with the status change in History. |
| AC5 | Given a business unit is linked to an entity, then it appears in the business unit list for that entity at intake. | Implemented | apps/api/prisma/schema.prisma:4694 LgBusinessUnit.entityIdsapps/web/src/lg/components/intake/Conversation.tsx:213 units filtered by entityIds.includes(entityId)apps/api/src/lg/routes/registers.ts:371 Entity rows/detail list their businessUnits | admin.test.ts business units link to entitiespi-legal-requester /workspace/pi-for-legal/lg/new Choose entity EPGL then the business unit list only shows EPGL's units (as linked in Settings › Business units). |
| AC6 | Given an entity with governing law, courts and a default signatory, then generated contracts for that entity use them unless the template overrides governing law and courts. | Implemented | apps/api/src/lg/services/lg-templates.ts:225 planRender: ENTITY-sourced fields read entityTemplateData values; governingLaw/courts replaced by the template's governingLawOverride when set (lines 232-233)apps/api/src/lg/services/lg-entities.ts:25 entityTemplateData returns legalName, address, licenceNumber, governingLaw, courts, signatoryName, signatoryTitle in the template languageapps/api/src/lg/services/lg-esign.ts:68 Default 7X signatory for e-signature comes from the entity register (signatoryUserId / signatoryNameEn + title) | generation.test.ts v01 keeps the entity details it was generated with, even after the register changesregisters.test.ts lawyer-handled entries wait for the lawyer to confirm; courts come from the entity (G-05, G-16)signature.test.ts defaults the signatory from the entity, checks authority, sends counterparty firstpi-legal-requester /workspace/pi-for-legal/lg/new?generate=<NDA contractTypeId> Generate an NDA for EPGL then the Word file carries EPGL's governing law/courts and signatory from the register; in /lg/templates (GC) set a governing-law override on the template and regenerate then the override text appears instead. |
| AC7 | Given an entity without its Arabic fields completed, when a requester chooses an Arabic template for it, then generation is blocked and the GC is alerted. | Implemented | apps/api/src/lg/services/lg-generation.ts:386 lang AR and entity not complete then REGISTER_ALERT email to the GC naming the missing fields, then 409 'The Arabic template can't be used for this entity yet…'apps/api/src/lg/services/lg-entities.ts:14 REQUIRED AR fields: nameAr, addressAr, governingLawAr, courtsAr, signatoryNameAr, signatoryTitleArapps/api/src/lg/routes/registers.ts:419 Entity detail returns templateReadiness {EN, AR} (shown in the detail sheet) | generation.test.ts an Arabic template can't be used for an entity without its Arabic fieldsregisters.test.ts supplies template data and flags missing Arabic fieldspi-legal-requester /workspace/pi-for-legal/lg/new?generate=<contractTypeId with an Active AR template> Pick entity nxn (nameAr null in the seed), language Arabic then error 'Its Arabic details are incomplete (…) Legal has been told'; GC's /lg/mailbox Outbox has the REGISTER_ALERT. |
| AC8 | Given any change to a record, then the previous value, the user and the time are kept. | Implemented | apps/api/src/lg/routes/registers.ts:453 PATCH then lgAuditDiff('Entity', …, ENTITY_FIELDS, actor): one EDIT row per changed field with old/new valueapps/api/src/lg/services/lg-audit.ts:90 lgAuditDiff; rows carry actorUserId/actorName/createdAtapps/api/src/lg/routes/registers.ts:253 GET /:kind/:id/history returns the record's non-VIEW audit rows; shown by HistoryList in the detail sheet | registers.test.ts shareholdings must total 100%; edits keep the previous value in historypi-legal-gc /workspace/pi-for-legal/lg/registers/entities Edit EPGL's TRN and save then the detail sheet's History lists 'trn: old then new · Adeeb Jouhar · time'. |
| AC9 | Given a user outside the legal team, then they can't open the register. | Implemented | apps/api/src/lg/routes/registers.ts:57 handle(): !actor.isLegal then 404 'Not found' on every entity/POA/IP route (contracts open only for owned/requested entries)apps/web/src/lg/pages/LgRegistersPage.tsx:38 Non-legal users are redirected to /lg/registers/contracts ('My contracts'); the Entities/POAs/IP tabs are not rendered | registers.test.ts only the GC creates; lawyers view; business users get 404API GET /api/workspace/pi-for-legal/portal/lg/registers/entities 404 (same for pi-legal-requester and pi-legal-approver); the UI bounces /lg/registers/entities to 'My contracts'. |
| Desc: entity record fields | Each record holds: names EN/AR + short name; legal form (LLC, branch, free zone company, other); parent entity; jurisdiction, emirate/free zone, licensing authority; trade licence number/issue/expiry/activities; registered address EN/AR; share capital + shareholders with %; managers/directors with appointment dates; business units; TRN; other registrations with expiry; date established; governing law and courts EN/AR; default signatory EN/AR linked to the POA register; status (Under formation, Active, Under liquidation, Dissolved) + 'Licence expired' flag. | Implemented | apps/api/prisma/schema.prisma:4704 LgEntity has every listed column; shareholders/managers/registrations/documents as JSONapps/api/src/lg/routes/registers.ts:92 entitySchema validates all fields; shareholders must total 100% (line 193); parent cycles refused (line 174); signatoryPoaId must be a POA granted by this entity (line 443)packages/shared/src/legalModules.ts:1013 LG_ENTITY_STATUSES = UNDER_FORMATION, ACTIVE, UNDER_LIQUIDATION, DISSOLVED; LG_LEGAL_FORMS = LLC, Branch, Free zone company, Otherapps/api/src/lg/routes/registers.ts:401 Detail shows signatoryAuthority: the signatory's Active POAs and a warning when none | config.test.ts blocks parent loops, links the signatory POA, names documents by the entity, alerts again after a renewalpi-legal-gc /workspace/pi-for-legal/lg/registers/entities Open EPGL: Arabic name/address right-to-left, licence dates, shareholders grid, managers, registrations, governing law/courts EN+AR, default signatory with linked POA and 'Signing authority' card. |
| Desc: Corporate request completed then lawyer prompted to ask the GC to update the record; request linked | When a Corporate request is completed (creation, amendment, restructuring or governance change), the lawyer is prompted to ask the GC to update the record. The request is linked to the record. | Implemented | apps/api/src/lg/routes/registers.ts:458 POST /entities/:id/link-request: completed Corporate request only, requireAct; sets LgRequest.linkedEntityId, audits, emails the GC (REGISTER_ALERT)apps/api/src/lg/routes/registers.ts:483 POST /entities/new-from-request for 2.4 'Creation of legal entity' (entity not in the register yet); asked onceapps/web/src/lg/request/tabs/LgOverviewTab.tsx:77 Overview prompt 'ask the GC to update the entity' (and new-from-request at line 254); EntitiesView links the new entity to the request on save (line 369)apps/api/src/lg/routes/registers.ts:398 Entity detail lists linkedRequests | config.test.ts the Corporate prompt needs a completed request, an actor who can act, and runs oncepi-legal-gc /workspace/pi-for-legal/lg/requests/<completed 2.5 reference> Overview shows the Corporate completion card 'Ask the GC to update the entity register'; after clicking, the entity's detail sheet lists the request under 'Linked requests'. |
| Desc: records never deleted; Excel import at launch and export | Dissolved entities are kept, never deleted. Existing data can be imported from Excel at launch, and the register can be exported to Excel. | Implemented | apps/api/src/lg/routes/registers.ts:319 DELETE /:kind/:id then 405 + DELETE_BLOCKED auditapps/api/src/lg/routes/registers.ts:271 GET /:kind/export (xlsx, audited EXPORT); POST /:kind/import {content, apply} preview then applyapps/api/src/lg/services/lg-register-io.ts:1 One column spec per register drives export and import; rows match on short name; imports never remove rowsapps/web/src/lg/components/registers/shared.tsx:411 ImportExportButtons + ImportDialog with preview | registers.test.ts exports a workbook that imports back as updates, with a preview firstregisters.test.ts shows the group structure and never deletespi-legal-gc /workspace/pi-for-legal/lg/registers/entities 'Export' downloads entities-register-<date>.xlsx; 'Import' with that file previews 'update' rows then applies. DELETE via API returns 405. |
| As | Call | HTTP | Response |
|---|---|---|---|
| req | GET /registers/entities | 404 | Not found expected: 403: outside legal team cannot open the register |
| counsel | POST /registers/entities{"nameEn": "Test LLC", "shortName": "TEST", "legalForm": "LLC"} | 403 | Only the General Counsel can create or edit legal entities expected: 403: only the GC creates entity records |
| counsel | GET /registers/entities/tree | 200 | data returned expected: 200 group structure |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a user who isn't a Corporate-queue lawyer or the GC, then they can view records but can't create or edit them. | Implemented | apps/api/src/lg/services/lg-registers.ts:25 canEdit('poas') = GC or actor.queues includes CORPORATE (queues include led queues, lg-auth line 92)apps/api/src/lg/routes/registers.ts:593 POST /poas, PATCH /poas/:id, POST /poas/:id/revoke, import, document upload then 403 'Only Corporate-queue lawyers and the General Counsel can create or edit POAs' | registers.test.ts Corporate-queue lawyers and the GC create; others view onlyAPI POST /api/workspace/pi-for-legal/portal/lg/registers/poas {entityId, attorneyName:"X"} 403 for Shikha (Commercial); 201 for yousef@7x.ae (Corporate lead, PiForLegal!2026) or pi-legal-gc; Shikha's /lg/registers/poas has no New/Edit/Revoke buttons. |
| AC2 | Given a POA reaches its expiry date, then it becomes Expired automatically, and the attorney fails the signing check (R-21). | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:89 Hourly timer: Active POA with daysUntil(expiry) <= 0 then status EXPIRED + audit 'Expired automatically'apps/api/src/lg/services/lg-poas.ts:66 findAuthorisingPoas only returns ACTIVE POAs with expiryDate > today (UAE) , fails the signing check on the expiry date even before the timer runsapps/api/src/lg/services/lg-esign.ts:106 authorityCheck uses findAuthorisingPoas; sending blocked unless the GC overrides with a reason (authorityGate line 137)docs/pi-for-legal/DESIGN.md:121 Decision: a POA is Expired on its expiry date, not the day after | registers.test.ts alerts at 30 days once, and expires automaticallyconfig.test.ts expires on the expiry date; external attorneys get the alertssignature.test.ts blocks a signatory without a covering POA unless the GC overrides with a reasonAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run {"now":"<Omar's POA expiry date>"} 200 with registers.poaExpired ≥ 1; the POA shows Expired on /lg/registers/poas; sending the EPGL contract for signature on the request's Approval & signature tab then says the signatory holds no Active POA. |
| AC3 | Given a POA expires in 60, 30 or 7 days, then the attorney and the Corporate queue are alerted. | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:95 LG_ALERTS.poaExpiry [60,30,7] then REGISTER_ALERT to attorneyUserId (or attorneyEmail for non-7X attorneys) + Corporate queue members and lead; idempotent per datepackages/shared/src/legalModules.ts:1027 poaExpiry: [60, 30, 7]apps/api/src/lg/services/lg-registers.ts:60 poaFlags.expiring (≤ 60 days) drives the 'expiring' chip and filter | registers.test.ts alerts at 30 days once, and expires automaticallyconfig.test.ts expires on the expiry date; external attorneys get the alertsAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run {"now":"<expiry minus 7 days>"} 200 registers.poaAlerts ≥ 1; /lg/mailbox Outbox shows REGISTER_ALERT addressed to the attorney (Omar) and Yousef/Dana (Corporate); running again sends nothing. |
| AC4 | Given a lawyer revokes a POA, when they enter the date and reason and upload the revocation document, then it becomes Revoked and stays in the register. | Implemented | apps/api/src/lg/routes/registers.ts:644 POST /poas/:id/revoke requires date, reason and document; stores the document (docType Revocation), sets REVOKED + revokedAt/revocationReason/revocationDocumentId, auditsapps/web/src/lg/components/registers/PoasView.tsx:156 RevokeDialog: date, reason, file; 'The POA stays in the register as Revoked' | registers.test.ts a renewal supersedes the old POA; revocation needs date, reason and documentpi-legal-gc /workspace/pi-for-legal/lg/registers/poas Open an Active POA then Revoke then the dialog refuses without a file/reason; after submit the row shows Revoked with the revocation document in Documents and the status change in History. |
| AC5 | Given a renewal is completed, then the new POA is linked to the old one, and the old one is marked Superseded. | Implemented | apps/api/src/lg/routes/registers.ts:602 POST /poas with supersedesId: old must be Active/Pending/Expired; new row gets supersedesId; supersede() sets old to SUPERSEDED + supersededById when the renewal is Active (line 610), or when it later becomes Active (PATCH line 631)apps/api/src/lg/routes/registers.ts:562 GET /poas/prefill/:requestId for a completed 2.1 Renewal pre-fills supersedesId with the current POAapps/api/src/lg/routes/registers.ts:581 Detail returns 'related' (supersedes / supersededBy references) | registers.test.ts a renewal supersedes the old POA; revocation needs date, reason and documentconfig.test.ts a renewal supersedes the old POA only when it becomes Activepi-legal-gc /workspace/pi-for-legal/lg/registers/poas Open an Active POA then 'Renew' then save the new POA as Active: the old one flips to Superseded and both detail sheets show each other under Related. |
| AC6 | Given a search by entity, document type and value, then only Active POAs that meet all three are returned. | Implemented | apps/api/src/lg/routes/registers.ts:526 GET /poas/search?entityId&documentType&value¤cy then findAuthorisingPoasapps/api/src/lg/services/lg-poas.ts:49 ACTIVE + in date + entity, exact document-type match (line 27) AND value limit ≥ value in AED (line 37)apps/web/src/lg/components/registers/PoasView.tsx:109 'Who can sign…' panel: document type, entity, currency, value | registers.test.ts search returns only Active POAs covering the entity, document type and valuesignature.test.ts POA limits compare in AED; document types match exactlypi-legal-counsel /workspace/pi-for-legal/lg/registers/poas 'Who can sign…' Contract / EPGL / AED 1,000,000 then Omar's POA (limit 2m); AED 3,000,000 then 'No Active POA covers that document type and value for this entity'. |
| AC7 | Given anyone tries to delete a POA record, then the system blocks it. | Implemented | apps/api/src/lg/routes/registers.ts:319 DELETE /poas/:id then 405 'Register records are never deleted. Change the status instead.' + DELETE_BLOCKED audit (open to any signed-in user, always refused)apps/web/src/lg/components/registers/PoasView.tsx:1 No delete action in the UI | registers.test.ts shows the group structure and never deletesAPI DELETE /api/workspace/pi-for-legal/portal/lg/registers/poas/<id> 405; Settings › Audit trail shows a 'delete blocked' row for Poa <id>. |
| AC8 | Given a user outside the legal team, then they can't open the register. | Implemented | apps/api/src/lg/routes/registers.ts:57 handle(): non-legal then 404 on every /poas routeapps/web/src/lg/pages/LgRegistersPage.tsx:38 Non-legal users are redirected to contracts | registers.test.ts Corporate-queue lawyers and the GC create; others view onlyAPI GET /api/workspace/pi-for-legal/portal/lg/registers/poas 404 (also for pi-legal-approver and pi-legal-it-admin). |
| Desc: POA record fields | Reference number; granting entity; attorney name, Emirates ID/passport, job title; scope categories (contracts, government and authorities, banking, litigation, employment, other), document types, free text; value limit + currency; issue/expiry dates; notarized + notary reference; attested/legalized + country; status (Pending execution, Active, Expired, Revoked/Cancelled, Superseded); revocation date/reason/document; where the original is kept; linked POA request and documents. | Implemented | apps/api/prisma/schema.prisma:4747 LgPoa has every listed column (reference unique, attorneyIdNumber, scopeCategories[], documentTypes[], valueLimit/currency, notarized/notaryReference, attested/attestedCountry, revokedAt/revocationReason/revocationDocumentId, originalLocation, requestId, supersedesId/supersededById)packages/shared/src/legalModules.ts:1016 LG_POA_STATUSES and LG_POA_SCOPE_CATEGORIES match the PRD listsapps/api/src/lg/routes/registers.ts:111 poaSchema; reference allocated by nextPoaReference (line 606); document types must come from the GC's list (canonicalDocTypes line 160) | registers.test.ts A-26: imported POA scope categories and document types must be on their lists; stored canonicallypi-legal-gc /workspace/pi-for-legal/lg/registers/poas Open Omar's POA: reference, entity EPGL, attorney ID/title, scope chips, document types, limit AED 2,000,000, dates, notarized/attested, original location, linked request, Documents and History. |
| Desc: completed 2.1 request then lawyer creates/updates the record from the request | When a POA request (2.1) is completed, the lawyer creates or updates the record from the request. Renewals link to the POA they replace. | Implemented | apps/api/src/lg/routes/registers.ts:542 GET /poas/prefill/:requestId: completed 2.1 only; New/Renewal then draft (entity, attorney, scope, limit, dates, notarized, requestId, supersedesId); Revocation then the POA to revoke + reasonapps/api/src/lg/routes/registers.ts:611 Creating with requestId sets LgRequest.linkedPoaId; revoke with requestId does the same (line 658)apps/web/src/lg/components/registers/PoasView.tsx:230 'From request' flow fetches the prefill and opens the create or revoke dialog | config.test.ts a revocation request revokes; prefill needs a completed request the actor can seepi-legal-gc /workspace/pi-for-legal/lg/registers/poas 'From request' then enter a completed 2.1 reference then the create form is pre-filled from the request answers and the saved POA shows the linked request. |
| Desc: lawyers search by entity, attorney, scope, document type and value; every change logged; Excel import/export | Lawyers can search by entity, attorney, scope, document type and value. Every change is logged. Existing POAs can be imported from Excel at launch, and the register can be exported. | Implemented | apps/api/src/lg/routes/registers.ts:506 GET /poas?entityId&status&attorney&scope&documentType&value¤cy&q&flagapps/api/src/lg/routes/registers.ts:629 PATCH audited field by field (lgAuditDiff 'Poa'); create/revoke/supersede auditedapps/api/src/lg/routes/registers.ts:336 commonRoutes('poas'): export, import (preview/apply), history | registers.test.ts exports a workbook that imports back as updates, with a preview firstconfig.test.ts an Excel import can't revoke, supersede or revive a POApi-legal-counsel /workspace/pi-for-legal/lg/registers/poas Filters by entity/status/scope/document type and the search box narrow the list; GC sees Import/Export buttons; History on a record lists each edited field. |
| As | Call | HTTP | Response |
|---|---|---|---|
| gc | DELETE /registers/poas/372af221-ac2a-4eb9-a74c-948bfefe50ff | 405 | Register records are never deleted. Change the status instead. expected: 4xx: records are never deleted |
| counsel | PATCH /registers/poas/372af221-ac2a-4eb9-a74c-948bfefe50ff{"notes": "x"} | 403 | Only Corporate-queue lawyers and the General Counsel can create or edit POAs expected: 403: only Corporate-queue lawyers and the GC edit |
| dana | PATCH /registers/poas/372af221-ac2a-4eb9-a74c-948bfefe50ff{"originLocation": "Legal safe, HQ"} | 200 | data returned expected: 200 |
| req | GET /registers/poas | 404 | Not found expected: 403 |
| counsel | GET /registers/poas/search?entityId=c8ebd7d5-9017-4d7d-855c-96611dd89fe3 | 200 | [] expected: 200 |
| counsel | GET /registers/poas/search?entityId=6bf7b929-6886-4260-b2ed-4e494b49ad29&documentType=Contract&value=1500000 | 200 | [["POA-2026-001", "ACTIVE", "Tariq Al Suwaidi", 5000000]] expected: exactly POA-2026-001 (Tariq, AED 5m): POA-2025-007 (expired, 500k) and the other entities are excluded |
| counsel | GET /registers/poas/search?entityId=6bf7b929-6886-4260-b2ed-4e494b49ad29&documentType=Contract&value=6000000 | 200 | [] expected: []: no Active POA covers AED 6m |
| counsel | GET /registers/poas/search?entityId=c8ebd7d5-9017-4d7d-855c-96611dd89fe3&documentType=Contract&value=100000 | 200 | [] expected: []: POA-2026-004 (Dubai Branch) expires today 2026-11-24, so it no longer passes the authority check |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a requester opens the landing page, then they're greeted by first name and can type a request or pick a category. | Implemented | apps/web/src/lg/pages/LgHomePage.tsx:54 greeting + me.firstName; line 55 asks 'What do you need help with today?'apps/web/src/lg/pages/LgHomePage.tsx:58 free-text box; Start navigates to /lg/new?q=… (line 45)apps/web/src/lg/pages/LgHomePage.tsx:73 one quick-pick card per category from /lg/reference (6 categories) then /lg/new?category=KEYapps/web/src/lg/pages/LgIntakePage.tsx:55 ?q= / ?type= start a draft once and redirect to /lg/new/:draftId | no automated test pi-legal-requester /workspace/pi-for-legal/lg 'Good …, Jerees.' heading, the text box with Start, six category cards (Contracts and Letters … General) |
| AC2 | Given the requester signs in, then their name and department are pre-filled and can't be edited. | Implemented | apps/api/src/lg/services/lg-intake.ts:431 createDraft copies requesterName/requesterEmail/department from the actor's profileapps/api/src/lg/routes/intake.ts:50 patchSchema has no name/department fields, so they cannot be changed through the draft APIapps/web/src/lg/components/intake/FormView.tsx:126 Requester shown as read-only textapps/web/src/lg/components/intake/ReviewPanel.tsx:48 Requester row has no Edit link | intake.test.ts starts a draft prefilled from the profile; name/department fixedpi-legal-requester /workspace/pi-for-legal/lg/new (switch to Form view) 'Requester: Jerees Thomas · Procurement' as plain text, no input |
| AC3 | Given the profile includes an entity and business unit, then both are pre-filled for confirmation. Given a business unit that doesn't belong to the entity, then it's blocked. | Implemented | apps/api/src/lg/services/lg-intake.ts:435 entityId/businessUnitId default from LgProfile.defaultEntityId/defaultBusinessUnitIdapps/api/src/lg/services/lg-intake.ts:332 validateDraft: entity must be confirmed (line 333) and BU must be in bu.entityIds (line 342) else blocking issueapps/web/src/lg/components/intake/Conversation.tsx:213 BU chips filtered to units of the chosen entity; help text 'Pre-filled from your profile' | intake.test.ts starts a draft prefilled from the profile; name/department fixedintake.test.ts blocks a business unit that does not belong to the entityAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {entityId:<other entity>, confirm:['entityId','businessUnitId']} 200 with issues[] containing businessUnitId "… doesn't belong to the chosen entity" |
| AC4 | Given the requester types "I want a contract reviewed", when AI identifies the type, then they're asked to confirm "Contract review" before any type questions. | Implemented | apps/api/src/lg/services/lg-intake-ai.ts:140 classifyRequest: aiComplete('lg-intake-classify') with deterministic keyword fallback (line 116)apps/web/src/lg/components/intake/Conversation.tsx:129 'It sounds like <type>. Is that right?' with 'Yes, that's it' / 'Choose something else'apps/web/src/lg/components/intake/steps.ts:22 type step precedes common and type questions | intake.test.ts suggests Contract review from what the requester typespi-legal-requester /workspace/pi-for-legal/lg then type 'I want a contract reviewed' then Start 'It sounds like Contract review … Is that right?' before any question |
| AC5 | Given AI can't identify the type, then the categories and then the types in the chosen category are shown. | Implemented | apps/web/src/lg/components/intake/Conversation.tsx:104 no code and not a legal question then setBrowsing(true)apps/web/src/lg/components/intake/Conversation.tsx:143 category grid, then types of the chosen category with one-line descriptions (lines 168-179)apps/api/src/lg/services/lg-intake-ai.ts:129 code null when confidence < 0.45 | no automated test pi-legal-requester /workspace/pi-for-legal/lg then type 'xyzzy frobnicate' then Start 'Pick the area it belongs to' with 6 categories, then the types list after choosing one |
| AC6 | Given a mandatory question or document, then it can't be skipped and the request can't be submitted without it. | Implemented | apps/api/src/lg/services/lg-intake.ts:360 required question empty then blocking issue; line 387 required document missing then blocking issueapps/api/src/lg/services/lg-intake.ts:713 submitDraft refuses (400) while issues existapps/web/src/lg/components/intake/Conversation.tsx:362 Skip button rendered only when !q.requiredapps/web/src/lg/components/intake/DocumentsStep.tsx:184 Continue disabled while a required document is missing | intake.test.ts a mandatory answer cannot be skippedintake.test.ts Contract review: contract is mandatory; optional skipped shows as not provided; submit assigns and emailsAPI POST /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id/submit (6.1 draft with 'question' answered null) 400 'Some answers are still missing' with issues [{key:'question'}] |
| AC7 | Given an optional question is skipped, then it shows "Not provided" on the summary. | Implemented | apps/web/src/lg/components/intake/AnswerInput.tsx:346 formatAnswer returns 'Not provided' for null/emptyapps/web/src/lg/components/intake/ReviewPanel.tsx:63 type answers rendered via formatAnswer; line 70 optional document without file then 'Not provided'apps/web/src/lg/components/requests/AnswersSummary.tsx:197 post-submission Overview also shows 'Not provided' for skipped optional answers | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (type 1.1, Skip 'Agreed terms') Review panel row 'Agreed terms: Not provided' |
| AC8 | Given a conditional question whose condition isn't met, then it's never shown. | Implemented | apps/api/src/lg/services/lg-intake.ts:133 resolveScript drops questions/documents whose showIf does not hold (holds() line 120; hidden parents hide children)apps/web/src/lg/components/intake/steps.ts:31 steps built only from the server-resolved view.questions | intake.test.ts unpaid invoices = No hides the invoice questions and documents (3.2)intake.test.ts customs question only for flagged contract typesAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id (3.2) {answers:{unpaidInvoices:false}} 200; questions[] has no 'debtAcknowledged', documents[] has no 'invoices' |
| AC9 | Given "Is this urgent?" = Yes, or a captured deadline within 10 business days, then the urgent SLA applies and a reason is required. | Implemented | apps/api/src/lg/services/lg-intake.ts:581 applyAutoUrgent: any question flagged deadline within LG_AUTO_URGENT_WINDOW (10) business days then autoUrgent; re-run on every draftView (line 168)apps/api/src/lg/services/lg-intake.ts:353 urgent or autoUrgent without urgentReason then blocking issueapps/api/src/lg/services/lg-intake.ts:311 draftSlaDays returns getUrgentSlaDays() when urgent/autoUrgentapps/web/src/lg/components/intake/Conversation.tsx:262 Urgent=Yes shows 'Why is it urgent?' textarea and Send is disabled until filled; auto-urgent step at line 482 | intake.test.ts a deadline within 10 business days makes it urgent and asks whyintake.test.ts auto-urgent is re-checked when a saved draft is opened againAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id (3.1) {answers:{firstHearing:<today+3d>}} 200; common.autoUrgent=true, sla.days=2, issues contains urgentReason |
| AC10 | Given an uploaded document in Arabic, then Arabic support is set to Yes automatically. | Implemented | apps/api/src/lg/services/lg-documents.ts:198 storeDocument sets arabicDetected via detectArabic(extracted text)apps/api/src/lg/services/lg-intake.ts:652 afterIntakeDocument: arabic then arabic:true, arabicAuto:true, 'arabic' auto-confirmed, requester told why (notice line 660)apps/api/src/lg/services/lg-intake-ai.ts:52 detectArabic: ≥20 Arabic letters and ≥15% of letters | intake.test.ts an Arabic document turns Arabic support on, and the requester cannot clear itintake.test.ts finds Arabic in an .xlsx workbookpi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (documents step, upload an Arabic .docx) toast 'We found Arabic in … so Arabic support is now on'; Arabic question shows Yes and is disabled |
| AC11 | Given the requester uploads a trade licence, then the counterparty details are pre-filled for confirmation. | Implemented | apps/api/src/lg/services/lg-intake.ts:663 spec.tradeLicence then extractTradeLicence then __prefill.counterpartyName/Type; conflict prompt when already answered (line 674)apps/api/src/lg/services/lg-intake-ai.ts:212 extractTradeLicence: aiComplete('lg-intake-licence') with regex fallback (line 198)apps/web/src/lg/components/intake/Conversation.tsx:329 'Fill from their trade licence' button on counterparty questions; prefill shown as 'Pre-filled … Confirm or change it' (line 344) | intake.test.ts a trade licence pre-fills the counterparty for confirmationintake.test.ts Word preferred is asked once; the licence that disagrees asks "use it?" oncepi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (1.1, at 'Counterparty name' click 'Fill from their trade licence' and upload a licence PDF) field pre-filled with the licensee name and help 'Pre-filled from what you shared. Confirm or change it.' |
| AC12 | Given the requester asks a legal question, then the assistant doesn't answer it and offers to raise a Legal advice / query. | Implemented | apps/api/src/lg/routes/intake.ts:79 /classify returns refusal text when legalQuestionapps/api/src/lg/services/lg-intake-ai.ts:184 a legal question always lands on 6.1 whatever the model said; fallback regex line 86apps/web/src/lg/components/intake/Conversation.tsx:117 refusal bubble + 'Raise a Legal advice / query' button | intake.test.ts does not answer a legal question; offers Legal advice / querypi-legal-requester /workspace/pi-for-legal/lg then type 'Can we legally share customer data with a partner?' 'I can't give legal advice here…' and the 'Raise a Legal advice / query' button |
| AC13 | Given the requester leaves mid-conversation, when they return, then they can resume the draft with all answers kept. | Implemented | apps/api/src/lg/services/lg-intake.ts:477 every step is a PATCH that persists answers/common fields on the LgRequest (DRAFT)apps/api/src/lg/services/lg-intake.ts:396 loadOwnDraft: requester-only resume by id or referenceapps/web/src/lg/pages/LgMyRequestsPage.tsx:80 Drafts section with Resume then /lg/new/:id; LgHomePage 'Pick up where you left off' (line 95)apps/web/src/lg/components/intake/steps.ts:50 currentStep resumes at the first unanswered step | intake.test.ts drafts are the requester's alone; they can be deletedpi-legal-requester /workspace/pi-for-legal/lg/my Drafts section then Resume opens the conversation with earlier answers in the transcript |
| AC14 | Given the requester submits, then they see the reference number, queue, expected response date and tracking link, and receive a confirmation email. | Implemented | apps/api/src/lg/services/lg-intake.ts:731 lgEmail SUBMITTED to requester + cc with queue and due; returns reference/queue/expectedBy/whatNext/link (737-756)apps/web/src/lg/components/intake/ConfirmationCard.tsx:16 reference, queue, handled by, expected response, what happens next, 'Track this request' linkapps/api/src/lg/services/lg-notify.ts:27 SUBMITTED template '[{reference}] Request received… Expected response by {due}' | intake.test.ts Contract review: contract is mandatory; optional skipped shows as not provided; submit assigns and emailspi-legal-requester /workspace/pi-for-legal/lg/new/:draftId then Submit request 'Request submitted' card with LGL-xxxxxx, Queue, Expected response by, Track this request; GC sees the email under /lg/mailbox?tab=sent |
| AC15 | Given a confidential request after submission, then only the GC can change the people in copy. | Implemented | apps/api/src/lg/services/lg-access.ts:113 business canManageCc = isRequester && !confidential; confidential branch (line 118) never grants lawyers; GC always canManageCc (line 105)apps/api/src/lg/routes/requests.ts:350 POST /:id/cc and DELETE /:id/cc/:userId then 403 'Only the GC can change the people in copy on a confidential request'apps/web/src/lg/components/requests/CopyList.tsx:16 UI hides add/remove unless access.canManageCc; explains GC-only on confidential (line 41) | requests.test.ts requester manages copy on non-confidential; only the GC on confidentialAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<confidential LGL ref>/cc {userId} 403; same call as pi-legal-gc then 200 |
| AC16 | Given the GC changes a question, its order or M/O, then new conversations use the change and submitted requests aren't affected. | Implemented | apps/api/src/lg/services/lg-admin.ts:225 PATCH /admin/types/:code validates the script and bumps version on a real change (lines 240-253)apps/api/src/lg/services/lg-intake.ts:440 createDraft snapshots the current script onto the draft; draftView reads scriptSnapshot first (line 171)apps/web/src/lg/components/admin/TypesSection.tsx:1 GC script editor: order, wording, type, M/O, options, conditions, deadline flag, documents | admin.test.ts edits a script, bumps the version, validates conditions; submitted requests keep their snapshotpi-legal-gc /workspace/pi-for-legal/lg/admin (Request types then 6.1, add a question, save); then pi-legal-requester starts a new 6.1 draft new draft asks the new question; an already-submitted 6.1 request's Overview answers are unchanged |
| AC17 | Given "Switch to form view", then the same questions appear as a form with the same rules. | Implemented | apps/web/src/lg/pages/LgIntakePage.tsx:173 Conversation / Form view toggle (persisted in localStorage); line 193 renders FormViewapps/web/src/lg/components/intake/FormView.tsx:86 same view.questions/documents, same PATCH, server issues shown per field; stepProblem shared with the conversation (line 68)apps/api/src/lg/services/lg-intake.ts:322 validateDraft is the single rule set for both renderings | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new/:draftId then 'Form view' one form with Area/Type, About the request, type questions, Documents, Review; required fields show the same blocking messages |
| AC18 | Given a submitted request, when the requester opens it from "My requests", then they see every lawyer reply and their own replies in the thread, with attachments, but no internal notes. | Implemented | apps/api/src/lg/routes/thread.ts:115 GET /thread/:id filters internal:false unless access.canSeeInternal; ordered by sentAtapps/web/src/lg/request/tabs/LgThreadTab.tsx:68 entries rendered in date order via ThreadEntryRow; attachments at ThreadEntryRow.tsx:95apps/web/src/lg/pages/LgMyRequestsPage.tsx:105 row links to /lg/requests/:ref | thread.test.ts notes are legal-only and never emailedthread.test.ts confidential: other lawyers get 404; the GC notes; the requester sees replies onlypi-legal-requester /workspace/pi-for-legal/lg/my then open a request then Thread tab lawyer replies and own replies with attachment chips; no 'Internal note · legal only' rows (visible to pi-legal-counsel on the same request) |
| Desc: landing links to My requests to track and resume drafts | Links to “My requests”, where the requester can track requests and resume drafts. | Implemented | apps/web/src/lg/pages/LgHomePage.tsx:108 'My requests' section with 'See all' then /lg/my; drafts 'Pick up where you left off' (line 95)apps/web/src/components/layout/Sidebar.tsx:330 sidebar item 'My requests' then /lg/myapps/web/src/lg/pages/LgMyRequestsPage.tsx:77 Drafts (Resume/Delete) + Requests with status, lawyer, SLA | no automated test pi-legal-requester /workspace/pi-for-legal/lg/my Drafts section with Resume, Requests list with status badges |
| Desc: categories/types with one-line descriptions; every category except General has an Other type | the system shows the categories and then the types in the chosen category, each with a one-line description. Every category except General has an “Other” type. | Implemented | packages/shared/src/legalModules.ts:323 1.6 Other contract request; 2.8 (457), 3.4 (523), 4.5 (584), 5.4 (628) all isOther; General has only 6.1 (636)apps/web/src/lg/components/intake/Conversation.tsx:169 type list shows code, name and description | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?category=CONTRACTS types 1.0…1.6 each with a one-line description, '1.6 Other contract request' last; General shows only 6.1 |
| Desc: offer to generate when an Active 7X template exists for the contract type | If the requester wants a new contract and an Active 7X template exists for the contract type, the system offers to generate it (1.0, R-24). | Implemented | apps/api/src/lg/services/lg-intake.ts:195 draftView.templateOffer when activeTemplatesFor(contractTypeId) has EN or AR; __templateAvailable pseudo-key resolves whyNotTemplate (line 121)apps/web/src/lg/components/intake/Conversation.tsx:505 1.0 hand-off: 'Generate the contract' or fall back to 1.2 New contract drafting; 1.2 shows the offer at the whyNotTemplate question (line 491)apps/web/src/lg/pages/LgIntakePage.tsx:105 generate(): carries entity/BU/title/cc/urgency over to /generation/drafts and opens ?generate=packages/shared/src/legalModules.ts:211 whyNotTemplateQ showIf __templateAvailable | intake.test.ts Contract review: contract is mandatory… (asserts whyNotTemplate hidden when no template)pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.2 then pick a contract type that has an Active template (e.g. NDA from the demo seed) '7X has a template for this contract. Would you like to generate it yourself instead?' with 'Generate it from the template' |
| Desc: common questions a-k asked after the type, in that order (conversation in English) | Common questions (asked for every request, after the type is confirmed): a Requester name … k Do you need support in Arabic? | Implemented | apps/api/src/lg/services/lg-intake.ts:55 COMMON_KEYS entityId, businessUnitId, title, description, neededBy, urgent, confidential, cc, arabic (name/department read-only)apps/web/src/lg/lib/intakeApi.ts:138 COMMON_STEPS in the same order; labels match the PRD wordingpackages/shared/src/legalModules.ts:666 LG_COMMON_QUESTIONS a-k with M/Oapps/web/src/lg/components/intake/steps.ts:30 common steps after type, before type questions | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new/:draftId after confirming the type: entity then business unit then title then description then needed by then urgent then confidential then copy then Arabic, all in English |
| Desc: (e) title suggested from the conversation, (f) description pre-filled from the first message, both editable | e Short title: Suggested from the conversation, editable. f Description: Pre-filled from the first message, editable. | Implemented | apps/api/src/lg/routes/intake.ts:97 POST /drafts: title = classification.suggestedTitleapps/api/src/lg/services/lg-intake.ts:438 description = first messageapps/web/src/lg/components/intake/Conversation.tsx:242 title input 'Suggested from what you wrote. Edit it if you like.'; description textarea 'Taken from your first message' (line 248) | no automated test pi-legal-requester /workspace/pi-for-legal/lg then type 'Please review the NDA from Gulf Freight' then Start title pre-filled 'Please review the NDA from Gulf Freight', description pre-filled with the message, both editable |
| Desc: (g) needed-by suggested from the type's SLA; later allowed, past blocked | g When do you need this by? Suggested from the type’s SLA; can be a later date, not in the past. | Implemented | apps/api/src/lg/services/lg-intake.ts:183 sla.suggestedNeededBy = today + slaDays business daysapps/api/src/lg/services/lg-intake.ts:349 neededBy before today then blocking issueapps/web/src/lg/components/intake/Conversation.tsx:256 date input min=today, default suggestedNeededBy | no automated test API PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {neededBy:'2020-01-01'} 200 with issues containing neededBy "can't be in the past" |
| Desc: (i) confidential note and (j) people in copy from the 7X directory, several allowed | i Is this confidential? Note: only the requester, the GC and people in copy will see it. j Anyone else to keep in copy? Search of the 7X directory; several people allowed. | Implemented | apps/web/src/lg/components/intake/Conversation.tsx:279 confidential help text; Employment types suggest Yes (type.suggestConfidential)apps/web/src/lg/components/intake/Conversation.tsx:291 cc Picker multiple over refData.directoryapps/api/src/lg/services/lg-intake.ts:540 updateDraft validates cc ids against users, writes LgRequestCc rows | intake.test.ts Contract review … submit assigns and emails (cc receives SUBMITTED)pi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (confidential and copy steps) lock note 'Only you, the General Counsel and the people you copy…'; copy picker lets you add two directory people |
| Desc: (k) Arabic support used for routing only; only the GC or the assigned lawyer can clear auto-Arabic | k Do you need support in Arabic? Used for routing only (R-14). … Only the GC or the assigned lawyer can clear it. | Implemented | apps/api/src/lg/services/lg-routing.ts:81 arabic then candidates filtered to arabicSpeaker lawyersapps/api/src/lg/services/lg-intake.ts:503 requester clearing arabic while arabicAuto then 409apps/api/src/lg/routes/requests.ts:530 POST /requests/:id/arabic allowed for GC or assigned lawyer only | requests.test.ts only GC or the assigned lawyer clear Arabic supportintake.test.ts an Arabic document turns Arabic support on, and the requester cannot clear itAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {arabic:false} on a draft with an Arabic document 409 'We found Arabic in one of your documents, so Arabic support stays on' |
| Desc: type questions one at a time in script order; answer formats (single, multi, text, money AED, date, Yes/No, picks) | Asked one at a time, in the order of that type’s script. Answer formats: single choice, multiple choice, free text, number with currency (AED by default), date, Yes/No, or a pick from a list (entities, business units, contract types). | Implemented | apps/web/src/lg/components/intake/Conversation.tsx:489 only the current question's composer is rendered; answered ones stay in the transcriptapps/web/src/lg/components/intake/AnswerInput.tsx:267 text, longtext, number, money, date, yesno, single, multi, entity, entities, business_unit, people, contract_type, contract_ref, shareholders, poa_scopeapps/web/src/lg/components/intake/Conversation.tsx:326 money defaults to { currency: 'AED' } | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.1 one question at a time: contract type picker, counterparty text, type single-choice, value with AED currency… |
| Desc: pre-fill answers found in an earlier message or document for confirmation | If an earlier message or an uploaded document already contains an answer, the system pre-fills it for the requester to confirm. | Implemented | apps/api/src/lg/services/lg-intake.ts:252 prefillFor maps the first message's amount/deadline/question (and licence facts) onto this type's keysapps/api/src/lg/services/lg-intake-ai.ts:101 prefillByRegex amounts + ISO dates; AI prefill counterpartyName/contractValue/deadline (line 153)apps/web/src/lg/components/intake/Conversation.tsx:325 composer initial value from view.prefill with 'Pre-filled from what you shared. Confirm or change it.' | intake.test.ts the first message pre-fills the type's amount and the legal questionpi-legal-requester /workspace/pi-for-legal/lg then 'Horizon Transport is claiming AED 450,000 from us in court' then pick 3.1 'Amount claimed' pre-filled with AED 450,000 for confirmation |
| Desc: documents asked by name; several files; accepted formats; 25 MB; mandatory not skippable; Word-preferred asked once without blocking | The system asks for each document by name… One or more files per item… Accepted formats: Word, PDF, Excel, images and email files (.msg, .eml). Default limit 25 MB per file. Mandatory documents can’t be skipped. Where Word is preferred and a PDF is uploaded, the system asks once for Word but doesn’t block submission. | Implemented | apps/web/src/lg/components/intake/DocumentsStep.tsx:27 one DocumentDrop per requested document (label, Required/Optional, multiple files, drag-drop)apps/api/src/lg/services/lg-intake.ts:610 extension check against LG_ACCEPTED_EXTENSIONS, size vs uploadLimitMb (default 25)apps/api/src/lg/services/lg-intake.ts:225 wordNudge shown until answered (__wordNudged); never a blocking issuepackages/shared/src/legalModules.ts:1046 LG_ACCEPTED_EXTENSIONS doc/docx/pdf/xls/xlsx/csv/images/msg/eml | intake.test.ts rejects unaccepted formatsintake.test.ts Word preferred is asked once; the licence that disagrees asks "use it?" oncedocuments.test.ts rejects unsupported formats and files over the GC limitpi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (1.1, documents step, upload a PDF as the contract) 'Word is preferred for this one… Keep the PDF' banner; Continue enabled once the required contract is in; .exe refused |
| Desc: review summary with Edit links; go back to any answer; type change keeps common answers and restarts type questions; progress indicator | A summary screen groups all answers and documents, each with an Edit link. The requester can go back to any earlier answer. If they change the request type, the common answers are kept and the type questions restart. A progress indicator shows how far along they are. | Implemented | apps/web/src/lg/components/intake/ReviewPanel.tsx:47 groups Your request / type details / Documents, each row with Editapps/web/src/lg/components/intake/Conversation.tsx:57 every transcript bubble has an Edit link (setEditing)apps/api/src/lg/services/lg-intake.ts:480 type change: deletes type answers (except keepAnswers), keeps common columns, re-snapshots the scriptapps/web/src/lg/pages/LgIntakePage.tsx:169 progress bar + % from view.progress | intake.test.ts changing the type keeps the common answers and restarts the type questionspi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (reach the review) 'Here's everything…' summary with Edit per row; header progress %; Edit 'Type' then common answers kept, type questions asked again |
| Desc: after submission the requester replies in the thread or by replying to the request email | The requester reads lawyer replies and answers them in the thread, or by replying to the request email (R-06). | Implemented | apps/api/src/lg/routes/thread.ts:202 POST /thread/:id/business-reply for requester / ccapps/api/src/lg/services/lg-mailbox.ts:292 email from requester/cc with the reference then REQUESTER_REPLY thread entryapps/web/src/lg/components/thread/ThreadComposer.tsx:1 composer offered to the business side when canReplyAsBusiness | thread.test.ts send back reopens only the ticked answers; a requester reply moves it back and closes the roundmailbox.test.ts requester reply on Awaiting requester is captured and moves it back to In progresspi-legal-requester /workspace/pi-for-legal/lg/requests/:ref/thread reply composer at the bottom; the email path is proven via the GC simulator (see R-06 AC8) |
| Desc: people in copy after submission , non-confidential: requester and assigned lawyer add/remove | After submission, on non-confidential requests the requester and the assigned lawyer can add or remove people. On confidential requests, only the GC can. | Implemented | apps/api/src/lg/services/lg-access.ts:143 lawyer canManageCc = assigned || leads || requester rule; requester rule at line 113apps/api/src/lg/routes/requests.ts:350 cc add/remove gated on access.canManageCc, audited as ACCESSapps/web/src/lg/request/tabs/LgOverviewTab.tsx:182 CopyList on the Overview tab | requests.test.ts requester manages copy on non-confidential; only the GC on confidentialpi-legal-counsel /workspace/pi-for-legal/lg/requests/:ref (Overview then People in copy) 'Add people' and remove (x) available to the assigned lawyer and to the requester; absent for a person only in copy |
| Desc: assistant only collects intake; AI limited to type suggestion, prefill, Arabic detection and empty/meaningless answer flags | The assistant only collects intake information. It doesn’t give legal advice… AI is used only to suggest the request type, pre-fill answers for confirmation (including trade licence extraction), detect Arabic documents, and flag free-text answers that are empty or meaningless. | Implemented | apps/api/src/lg/services/lg-intake-ai.ts:1 the only AI entry points for intake: classifyRequest, extractTradeLicence, detectArabic (heuristic), isMeaningless (heuristic)apps/api/src/lg/services/lg-intake.ts:40 lg-intake imports only those four; questions come from fixed scripts (scriptSnapshot)apps/api/src/lg/services/lg-intake.ts:347 meaningless description/free text then non-blocking warning shown on the review (ReviewPanel.tsx:77)apps/web/src/lg/components/intake/Conversation.tsx:422 'I only collect your request; I don't give legal advice.' | intake.test.ts does not answer a legal question; offers Legal advice / querypi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (answer Background with 'asdf') review warning '"Background" looks empty. Add a little detail' that does not block Submit |
| Desc: drafts autosave, resume from My requests, reminder every 3 days, no SLA; answers saved as structured fields | Progress saves automatically as a Draft (R-13). Drafts can be resumed from “My requests”. The requester is reminded every 3 days until they submit or delete it. Drafts have no SLA… Answers are saved as structured fields for routing and reporting. | Implemented | apps/api/src/lg/services/lg-request-timers.ts:47 DRAFT_REMINDER every draftReminderDays (3) calendar days, idempotent via lastReminderAtapps/api/src/lg/services/lg-routing.ts:187 applySla only at routeAndAssign, so a draft has no slaDueAtapps/api/src/lg/services/lg-intake.ts:557 columnsFromAnswers keeps contractTypeId/side/counterparty/contractValue/currency/tenderStatus/linked ids in step with the answersapps/api/src/lg/services/lg-intake.ts:599 deleteDraft by the requester | timers.test.ts reminds drafts every 3 days, once per windowAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run {now:<draft.createdAt + 4 days>} 200; requests.draftReminders ≥ 1 and a DRAFT_REMINDER row under /lg/mailbox?tab=sent |
| Desc: works on desktop and mobile browsers | Works on desktop and mobile browsers. | Implemented | apps/web/src/lg/components/intake/Conversation.tsx:148 responsive grids (grid-cols-2 sm:grid-cols-3), max-w bubbles, ml-10 composerapps/web/src/lg/pages/LgIntakePage.tsx:169 progress hidden below sm; page uses px-4 lg:px-6 and max-w-3xlshots/R05-mobile-landing.png Verified in this run: the landing page and the conversation render correctly at a 390 px phone viewport (screenshot R05 mobile landing). | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new/:draftId at a 390px viewport no horizontal scroll; composers and pickers usable; documents drop zone tappable |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given an email from a 7X address without a request reference, when it reaches the legal mailbox, then a Draft request is created within 5 minutes and the sender gets the reference and a link. Logic is complete; only the mail transport is simulated locally (Graph app registration absent). 'Within 5 minutes' holds through the webhook; if a notification is missed, the catch-up poll runs hourly (integrations/index.ts), not every 5 minutes. | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:235 processInbound: no reference then createDraft(source EMAIL) + DRAFT_FROM_EMAIL email with linkPath /lg/new/:id (line 264)apps/api/src/lg/routes/hooks.ts:77 REAL adapter: Graph change-notification webhook (validationToken handshake, clientState check) then captureGraphMessage then processInboundapps/api/src/lg/services/integrations/graph-mail.ts:116 REAL adapter: fetchInboundMessage + ensureMailboxSubscription (line 156); hourly catch-up poll in integrations/index.ts:46apps/api/src/lg/routes/mailbox.ts:55 SIMULATOR: POST /lg/mailbox/inbound (GC only, off in production unless LG_SIMULATORS=1); UI composer LgMailboxPage.tsx:136 | mailbox.test.ts a 7X sender without a reference gets a Draft, the cc become people in copyintegrations.test.ts answers the validation handshake, refuses a wrong client state, captures once per messagepi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=simulate (from Jerees, subject without LGL-, body text) 'Draft created: LGL-…; the sender got the reference and a link'; Sent tab shows '[LGL-…] We started a legal request from your email'; Jerees sees it under /lg/my Drafts 'From email' |
| AC2 | Given the sender opens the link, then the conversation is pre-filled from the email and their profile, and they must confirm entity and business unit before submitting. | Implemented | apps/api/src/lg/services/lg-mailbox.ts:239 createDraft with the sender's LgProfile (department, default entity/BU), subject then title, body then description, classification prefillapps/api/src/lg/services/lg-intake.ts:333 entityId and businessUnitId must be in __confirmed or submission is blockedapps/web/src/lg/components/intake/FormView.tsx:130 explicit Confirm buttons for entity and BU; conversation asks them as steps | mailbox.test.ts a 7X sender without a reference gets a Draft… (asserts issues contain entityId, businessUnitId)pi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (the draft started from the simulated email) title/description taken from the email, 'Attached to your email' file list, entity/BU pre-filled from the profile but asked to confirm |
| AC3 | Given the email has people in copy, then they're added as people in copy on the request. Only directory users are added; outside cc addresses are dropped silently (consistent with the 7X-directory rule). | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:248 to+cc addresses (minus the legal mailbox) resolved to users then LgRequestCc rowsapps/api/src/lg/services/integrations/graph-mail.ts:135 REAL adapter maps toRecipients/ccRecipientsapps/api/src/lg/routes/mailbox.ts:55 SIMULATOR endpoint | mailbox.test.ts a 7X sender without a reference gets a Draft, the cc become people in copypi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=simulate (from Jerees, Cc Ahmad) Jerees's draft review shows 'In copy: Ahmad Al Blooshi' |
| AC4 | Given a draft from email isn't submitted, then the sender is reminded every 3 days, and no SLA runs. | Implemented | apps/api/src/lg/services/lg-request-timers.ts:47 all DRAFT rows (any source) reminded every draftReminderDays calendar daysapps/api/src/lg/services/lg-intake.ts:442 createDraft sets lastReminderAt=now, no slaDueAt | timers.test.ts reminds drafts every 3 days, once per windowAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run {now:<+4 days>} 200, requests.draftReminders ≥ 1; GET /requests/<draft ref> as requester shows sla.state NONE |
| AC5 | Given a lawyer replies from Outlook to a request email, or sends an email with the reference in the subject and the legal mailbox in copy, then it's captured into the thread within 5 minutes with sender, recipients, time sent, body and attachments. Transport simulated. Quirk: graph-mail.ts:140 passes sentDateTime as receivedAt and never sets sentAt, so for live Graph mail LgInboundEmail.sentAt stays null (the thread entry still gets the sent time because receivedAt carries it). | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:279 reference in subject + sender on the legal side then postThreadEntry(kind REPLY, source EMAIL, recipients, sentAt, documentIds)apps/api/src/lg/services/lg-thread.ts:84 entry stores authorEmail, recipients, body (quoted history stripped), documentIds, sentAtapps/api/src/lg/services/lg-mailbox.ts:95 original kept as .eml next to the attachmentsapps/api/src/lg/routes/hooks.ts:59 REAL adapter captureGraphMessage; SIMULATOR routes/mailbox.ts:55 | mailbox.test.ts lawyer email to the requester is a reply; to legal colleagues only it is an internal notemailbox.test.ts a requester email added to a draft keeps its .eml dated when it was sent; a held email added later keeps its sent timepi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=simulate (from Shikha, To jerees@7x.ae, subject '[LGL-…] Comments', attach a file) Thread tab of that request shows Shikha's reply 'via email', 'To Jerees Thomas', the attachment chip |
| AC6 | Given a captured lawyer email sent only to legal colleagues, then it's captured as an internal note. | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:287 all recipients (excluding the legal mailbox) are lawyers/GC then INTERNAL_NOTE, internal:true | mailbox.test.ts lawyer email to the requester is a reply; to legal colleagues only it is an internal notepi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=simulate (from Shikha, To adeeb@7x.ae, subject with the reference) Received tab says 'Captured as an internal note'; the requester's Thread view does not show it |
| AC7 | Given a captured lawyer reply, then the lawyer is prompted to tag it "Response" or "Final reply". | Implemented | apps/web/src/lg/components/thread/ThreadEntryRow.tsx:34 needsTag for EMAIL-source REPLY without tag then 'Captured from Outlook. Was this a substantive answer?' with Tag as Response / Final reply (line 100)apps/api/src/lg/routes/thread.ts:289 PATCH /thread/:id/entries/:entryId/tag, only for untagged EMAIL lawyer replies; RESPONSE meets the SLA at sentAt | thread.test.ts the lawyer tags an untagged captured reply once; tagging Response meets the SLApi-legal-counsel /workspace/pi-for-legal/lg/requests/:ref/thread (after a simulated Outlook reply from Shikha) dashed prompt under the entry with 'Tag as Response' / 'Final reply'; disappears once tagged |
| AC8 | Given the requester or a person in copy replies by email, then the reply is captured into the thread, and if the request was Awaiting requester or awaiting feedback, it returns to In progress (or Under review). | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:292 sender is requester or cc then REQUESTER_REPLYapps/api/src/lg/services/lg-thread.ts:137 REQUESTER_REPLY while AWAITING_* then moveStatus(workingStatus(path)) i.e. In progress / Under review; round closed by lifecycle | mailbox.test.ts requester reply on Awaiting requester is captured and moves it back to In progresspi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=simulate (from Jerees, subject 'RE: [LGL-…] Action needed' on a request in Awaiting requester) 'Captured as the requester's reply'; request status badge now In progress |
| AC9 | Given an email with a request reference from a 7X address not on the request, then it's held for the assigned lawyer (or the GC) to add or discard, and no one else sees it. | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:296 HELD + HELD_EMAIL email to the assigned lawyer (GC if confidential/unassigned); attachment bytes kept only while heldapps/api/src/lg/services/lg-mailbox.ts:327 resolveHeld ADD/DISCARD: assigned lawyer (non-confidential) or GC only, 403 otherwiseapps/api/src/lg/routes/mailbox.ts:73 GET /mailbox/inbound hides HELD rows from everyone but the holder/GC | mailbox.test.ts another 7X sender is held for the assigned lawyer, who adds or discards itmailbox.test.ts held emails are invisible to other lawyers; their attachments reach the thread when addedpi-legal-counsel /workspace/pi-for-legal/lg/mailbox?tab=held (after the GC simulates an email from Omar with Shikha's request reference) Held row with 'Add to the thread' / 'Discard'; pi-legal-litigation's Held tab is empty |
| AC10 | Given an email from outside 7X, then no request is created, nothing is captured, no reply is sent, and the email is forwarded to the legal triage inbox. The triage forward goes through the platform mailer (sendRawEmail), which is held in workspaces unless WORKSPACE_EMAIL_ENABLED=1. | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:181 domain not in internalDomains (or sender not a workspace member) then TRIAGE row, sendRawEmail to triageInbox setting, audit; no draft, no thread entry, no reply to senderapps/api/src/lg/services/lg-settings.ts:25 triageInbox / internalDomains are GC settings (R-02) | mailbox.test.ts outside 7X: nothing is created; forwarded to triagepi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=simulate (outside address someone@gmail.com) 'From outside 7X. Nothing was created; forwarded to the legal triage inbox.'; row under the 'Outside 7X' tab; no new LGL reference |
| Desc: every LMS email carries the reference in the subject and replies go to the legal mailbox | Every email the LMS sends about a request carries the reference in the subject, and replies go to the legal mailbox. | Implemented | apps/api/src/lg/services/lg-notify.ts:198 subject forced to include [reference] even after a GC template editapps/api/src/lg/services/lg-notify.ts:111 Reply-To = legalMailbox setting for both Graph and platform transports | integrations.test.ts sends with Reply-To the legal mailbox and attaches reply documents; confidential gets neither text nor filesintegrations.test.ts keeps the reference in a GC-edited subject, states the action, and lets the requester turn off the FYI "assigned" emailpi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=sent every subject starts with [LGL-…]; expanded row shows 'Replies to legal@7x.ae' |
| Desc: emails the LMS sent itself aren't captured again | Emails the LMS sent itself aren’t captured again. | Implemented | apps/api/src/lg/services/lg-mailbox.ts:173 from == senderMailbox | legalMailbox | platform from-address then IGNORED_SELF | mailbox.test.ts the LMS's own emails are not captured againmailbox.test.ts B-4: mail from the platform's own sender address is ignored toopi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=simulate (outside address legal@7x.ae, subject with a reference) 'Ignored (our own)' outcome, no thread entry |
| Desc: draft from email uses the body as description and the attachments as documents | The system creates a Draft request… with the email body as the description and the attachments as documents. | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:245 message: e.body then description; storeAttachmentsDetailed stores every accepted attachment + the .eml (line 255); refused files reported back to the senderapps/api/src/lg/services/lg-intake.ts:688 assignDraftDocument: the requester slots an email attachment into a requested document ('Use as…', DocumentsStep.tsx:108) | mailbox.test.ts an email that started a draft shows no body to lawyers; a refused attachment is listed for the senderintake.test.ts a file already on the draft can be used as a requested document, and then countspi-legal-requester /workspace/pi-for-legal/lg/new/:draftId (draft from a simulated email with a PDF attached) 'Attached to your email' box listing the PDF with a 'Use as…' select; description = the email body |
| Desc: a lawyer can upload an outside email to a request's thread manually | A lawyer can upload it to a request’s thread manually. | Implemented | apps/api/src/lg/routes/thread.ts:256 POST /thread/:id/upload then UPLOADED entry (.msg/.eml kept as email file)apps/web/src/lg/components/thread/ThreadComposer.tsx:3 composer mode 'Upload a communication' | thread.test.ts uploads an outside communication marked Uploadedpi-legal-counsel /workspace/pi-for-legal/lg/requests/:ref/thread then Upload entry badged 'Uploaded' with the .eml attachment chip |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | GET /mailbox | 404 | {"_raw": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /api/workspace/pi-for-le expected: 200 held emails + captured |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Desc: 7 types, Commercial queue except 1.0 (self-service), common questions first | Question scripts for the 7 Contracts and Letters request types. All go to the Commercial queue, except 1.0, which is self-service (R-24). The common questions in R-05 are asked first. | Implemented | packages/shared/src/legalModules.ts:223 1.0 … 1.6 all `queue: 'COMMERCIAL'`; 1.0 has `slaDays: null, selfService: true`apps/api/src/lg/services/lg-intake.ts:425 createDraft: `path: pathForCategory(category, selfService)` then GENERATION path for 1.0apps/api/src/lg/services/lg-intake.ts:712 submitDraft refuses a self-service draft (409 'generated, not submitted')apps/web/src/lg/components/intake/steps.ts:30 steps: type then COMMON_STEPS (R-05) then type questions then urgentReason then docs then reviewapps/api/prisma/workspace/seed-pi-for-legal.ts:210 scripts seeded into LgRequestType from LG_REQUEST_TYPES; each draft snapshots the script (createDraft line 439) | intake.test.ts Contract review: contract is mandatory; optional skipped shows as not provided; submit assigns and emailspi-legal-requester /workspace/pi-for-legal/lg/new?type=1.1 Entity, business unit, title, description, needed-by, urgent, confidential, cc, Arabic are asked before the contract-type question; after submit the confirmation says queue 'Commercial'. |
| Type 1.0 Generate a contract | 1.0 Generate a contract. Offered whenever an Active template exists for the chosen contract type. Continues in R-24. Contract type questions 1-3 (side; category+type from R-23 list; customs only for flagged types). | Implemented | packages/shared/src/legalModules.ts:223 1.0: questions [contractTypeQ, customsQ], documents [], selfServicepackages/shared/src/legalModules.ts:198 contractTypeQ (type contract_type = side+category+type, M) and customsQ (yesno, M, showIf customsFlagged)apps/api/src/lg/services/lg-intake.ts:201 draftView.templateOffer when an Active EN/AR template exists; `noTemplateForGeneration` otherwiseapps/web/src/lg/components/intake/Conversation.tsx:505 handoff step: template then 'Generate the contract'; none then offer to raise as 1.2 keeping contractType+customs | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.0 Pick a contract type with an Active template (e.g. NDA): 'Generate the contract' button; pick one without: offer to raise New contract drafting. |
| Type 1.1 Contract review | 1.1 Contract review: 1 contract type (M); 2 template offer + 'Why can't the 7X template be used?' (M); 3 counterparty name (M); 4 counterparty type Gov/Semi-gov/Private/Individual/Other (O); 5 value+currency (O); 6 agreed terms (O); 7 anything specific (O). Docs: contract Word preferred (M); trade licence (O, prefill); correspondence (O). | Implemented | packages/shared/src/legalModules.ts:230 1.1 questions: contractTypeQ, customsQ, whyNotTemplateQ(showIf __templateAvailable), counterpartyName M, counterpartyType O (5 options), contractValue O money, agreedTerms O, focus Opackages/shared/src/legalModules.ts:241 documents: contract M preferWord; tradeLicence O tradeLicence:true; correspondence Oapps/web/src/lg/components/intake/Conversation.tsx:491 at whyNotTemplate: '7X has a template for this contract. Would you like to generate it yourself instead?' + Generate button | intake.test.ts Contract review: contract is mandatory; optional skipped shows as not provided; submit assigns and emailspi-legal-requester /workspace/pi-for-legal/lg/new?type=1.1 Question order and Optional tags match; 'Counterparty type' shows the 5 options; documents step lists The contract (required, Word nudge on PDF), trade licence, correspondence. |
| Type 1.2 New contract drafting | 1.2: 1 contract type (M); 2 offer generation first, then 'Why can't the 7X template be used?' (M); 3 counterparty name (M); 4 counterparty type (O); 5 'Describe the deal and its scope.' (M); 6 value+currency (O); 7 'What are the key commercial terms?' (M). Docs: trade licence (O, prefill); term sheet/proposal/quotation (O); other supporting (O). | Implemented | packages/shared/src/legalModules.ts:248 1.2 questions and documents match the PRD exactly (keys dealScope M, keyTerms M; docs tradeLicence O, termSheet O, supporting O) | intake.test.ts customs question only for flagged contract typesAPI POST /api/workspace/pi-for-legal/portal/lg/intake/drafts {typeCode:'1.2'} then GET /intake/drafts/:id 200; questions[] keys contractType, counterpartyName, counterpartyType, dealScope, contractValue, keyTerms (customs/whyNotTemplate appear once the type is chosen and flagged / has a template) |
| Type 1.3 Existing contract - amendment, renewal or termination | 1.3: 1 counterparty and contract reference (M, pickable from register R-27); 2 'What do you need?' Amendment/Renewal/Termination (M); 3 'What is changing?' (amend/renew) or 'Why do you want to terminate?' (M); 4 effective date (M); 5 value if it changes (O); 6 notice period or deadline (O). Docs: signed contract (M unless from register); previous amendments (O); correspondence (O). | Implemented | packages/shared/src/legalModules.ts:266 1.3 questions: contractRef (contract_ref M), need single M 3 options, changing showIf need in [Amendment,Renewal], whyTerminate showIf Termination, effectiveDate M, contractValue O, noticeDeadline Opackages/shared/src/legalModules.ts:279 signedContract required, showIf __contractFromRegister=falseapps/api/src/lg/services/lg-intake.ts:154 contractFromRegister = Boolean(answers.contractRef.contractId)apps/web/src/lg/components/intake/AnswerInput.tsx:167 ContractRefInput: Picker from /registers/contracts or free text | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.3 Pick a contract from the register then documents step no longer requires 'The signed contract'; choose Termination then 'Why do you want to terminate?' replaces 'What is changing?'. |
| Type 1.4 Contractual notice or letter | 1.4: 1 Sending/Replying (M); 2 counterparty (M); 3 related contract (M); 4 purpose Breach/Demand/Termination/Other (M); 5 'When is the response due?' only if Replying, within 10 business days then auto-urgent (M); 6 amount claimed (O). Docs: related contract (M); letter received only if Replying (M); invoices or evidence (O). | Implemented | packages/shared/src/legalModules.ts:285 1.4 questions: direction, counterpartyName, relatedContract (contract_ref M), purpose (4 options), purposeOther (extra, showIf Other), responseDue date M deadline:true showIf Replying, amountClaimed Opackages/shared/src/legalModules.ts:297 docs: relatedContract M; letterReceived M showIf direction=Replying; evidence Oapps/api/src/lg/services/lg-intake.ts:580 applyAutoUrgent: any visible question with deadline:true within LG_AUTO_URGENT_WINDOW (10) business days then autoUrgent | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.4 Choose Replying then 'When is the response due?' appears and the documents step requires 'The letter received'; a due date 3 days out flips the draft to urgent and asks why. |
| Type 1.5 Customer tender | 1.5: 1 issuer (M); 2 tender reference (M); 3 services bidding for, multiple choice from 'We are the supplier' categories (M); 4 estimated value (M); 5 submission deadline, within 10 business days then auto-urgent, reason required (M); 6 tender status Preparing bid/Submitted/Awarded/Not awarded (M, lawyer-updatable field); 7 review scope Full pack/Draft contract only/Deviations and clarifications/Bonds and declarations (M). Docs: tender documents (M); draft bid (O). | Implemented | packages/shared/src/legalModules.ts:304 1.5 questions: issuer, tenderReference, services multi options ['__supplierCategories'], estimatedValue money M, submissionDeadline date M deadline:true, tenderStatus single 4 options, reviewScope multi 4 optionsapps/api/src/lg/services/lg-intake.ts:155 supplierCategories resolved from active SUPPLIER contract types in the DB; substituted at line 138apps/api/src/lg/services/lg-intake.ts:568 columnsFromAnswers stores tenderStatus as a request column (lawyer-updatable field, R-13)apps/api/src/lg/services/lg-intake.ts:311 draftSlaDays: tender SLA = max of the GC's per-scope SLAs for the chosen reviewScope values | lifecycle-gaps.test.ts (uses 1.5 submissionDeadline fixtures)pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.5 'Which services are you bidding for?' lists the supplier categories from Legal settings › contract types; a deadline within 10 business days makes it urgent and asks for a reason. |
| Type 1.6 Other contract request | 1.6: 1 description (M); 2 counterparty (O); 3 contract value and currency (O). Docs: supporting documents (O). | Implemented | packages/shared/src/legalModules.ts:322 1.6 details M, counterpartyName O, contractValue O; supporting O; isOther | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.6 Three questions, two optional; one optional document. |
| AC1 | Given a contract type the GC flagged 'Ask customs clearance', then the customs question is asked. Otherwise it isn't. | Implemented | packages/shared/src/legalModules.ts:204 customsQ showIf { key: 'contractType', customsFlagged: true }apps/api/src/lg/services/lg-intake.ts:123 holds(): customsFlagged condition then ctx.customsFlaggedapps/api/src/lg/services/lg-intake.ts:153 customsFlagged = Boolean(lgContractType.askCustoms) for the chosen contractTypeIdapps/api/src/lg/routes/templates.ts:124 GC PATCH /templates/contract-types/:id { askCustoms } | intake.test.ts customs question only for flagged contract typesintake.test.ts Contract review: contract is mandatory; optional skipped shows as not provided; submit assigns and emailspi-legal-requester /workspace/pi-for-legal/lg/new?type=1.2 Pick Supplier › Courier › International then 'Does this require customs clearance?' appears; pick Customer › General › Services then it does not. |
| AC2 | Given Contract review or New contract drafting for a type with an Active template, then generation is offered, and if the requester continues, the reason is mandatory. | Implemented | packages/shared/src/legalModules.ts:211 whyNotTemplateQ required:true, showIf __templateAvailable=true; used by 1.1 and 1.2apps/api/src/lg/services/lg-intake.ts:152 templateAvailable = activeTemplatesFor(contractTypeId).EN || .ARapps/api/src/lg/services/lg-intake.ts:360 validateDraft blocks on a required visible question left emptyapps/web/src/lg/components/intake/Conversation.tsx:491 offer with 'Generate it from the template' button at the whyNotTemplate step | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.1 Pick a contract type that has an Active template (Templates page lists them): the generate offer appears and the next question 'Why can't the 7X template be used?' has no Optional tag and blocks review until answered. |
| AC3 | Given no Active template exists for the type, then generation isn't offered and no reason is asked. | Implemented | apps/api/src/lg/services/lg-intake.ts:137 resolveScript drops whyNotTemplate when __templateAvailable is falseapps/api/src/lg/services/lg-intake.ts:201 templateOffer null when no Active template | intake.test.ts Contract review: contract is mandatory; optional skipped shows as not provided; submit assigns and emailsAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{contractType:{side:'CUSTOMER',category:'General',contractTypeId:<Services id>}}} 200; data.questions has no 'whyNotTemplate'; data.templateOffer === null |
| AC4 | Given an uploaded counterparty trade licence, then counterparty details are pre-filled for confirmation. | Implemented | apps/api/src/lg/services/lg-intake.ts:663 afterIntakeDocument: tradeLicence slot then extractTradeLicence then answers.__prefill.counterpartyName/Type; conflict notice when already answeredapps/api/src/lg/services/lg-intake-ai.ts:212 extractTradeLicence: AI (lg-intake-licence) with regex fallback; type constrained to the 5 PRD optionsapps/web/src/lg/components/intake/Conversation.tsx:325 QuestionComposer seeds the answer from view.prefill and shows 'Pre-filled from what you shared. Confirm or change it.'; 'Fill from their trade licence' button on prefillFromLicence questions | intake.test.ts a trade licence pre-fills the counterparty for confirmationintake.test.ts Word preferred is asked once; the licence that disagrees asks "use it?" oncepi-legal-requester /workspace/pi-for-legal/lg/new?type=1.1 At 'Counterparty name' click 'Fill from their trade licence' and upload a licence PDF/text: the field is pre-filled with the trade name and must be confirmed. |
| AC5 | Given Contractual notice or letter with 'Sending', then the response date and 'letter received' aren't asked. | Implemented | packages/shared/src/legalModules.ts:294 responseDue showIf direction=Replyingpackages/shared/src/legalModules.ts:299 letterReceived showIf direction=Replyingapps/api/src/lg/services/lg-intake.ts:141 documents filtered by showIf in resolveScript | no automated test API PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{direction:'Sending'}} (draft of type 1.4) 200; questions exclude 'responseDue'; documents exclude 'letterReceived' |
| AC6 | Given a response due date or tender deadline within 10 business days, then the request is auto-urgent and a reason is required. | Implemented | apps/api/src/lg/services/lg-intake.ts:580 applyAutoUrgent: deadline-flagged answers within 10 business days (withinBusinessDays, holiday calendar) then autoUrgent; re-run on every draftView and updateDraftapps/api/src/lg/services/lg-intake.ts:353 validateDraft: autoUrgent without urgentReason is a blocking issueapps/api/src/lg/services/lg-calendar.ts:85 withinBusinessDays(date, 10, cal)apps/web/src/lg/components/intake/Conversation.tsx:45 urgentReason step: 'The deadline you gave is within 10 business days, so I've marked this urgent.' | intake.test.ts a deadline within 10 business days makes it urgent and asks whyintake.test.ts auto-urgent is re-checked when a saved draft is opened againAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{submissionDeadline:<today+3d>}} (type 1.5) 200; common.autoUrgent true; issues contains key 'urgentReason'; sla.days = urgent SLA |
| AC7 | Given Contract review with no contract uploaded, then the request can't be submitted. | Implemented | apps/api/src/lg/services/lg-intake.ts:387 required document without a file then blocking issue doc:<key>apps/api/src/lg/services/lg-intake.ts:713 submitDraft throws 400 'Some answers are still missing' when issues exist | intake.test.ts Contract review: contract is mandatory; optional skipped shows as not provided; submit assigns and emailsAPI POST /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id/submit (1.1 draft, all answers, no contract file) 400 with issues [{key:'doc:contract'}] |
| AC8 | Given the GC adds a contract type to the shared list, then it appears in these scripts without a code change. | Implemented | apps/api/src/lg/routes/templates.ts:117 POST /templates/contract-types (GC) adds { side, category, name, askCustoms }apps/web/src/lg/components/intake/AnswerInput.tsx:138 ContractTypeInput builds side then category then type from refData.contractTypes (GET /reference, DB-backed)apps/api/src/lg/services/lg-intake.ts:155 tender 'services' options come from active SUPPLIER contract types in the DB | templates.test.ts keeps the contract type list, with "Ask customs clearance"pi-legal-gc /workspace/pi-for-legal/lg/templates (Contract types panel) then as pi-legal-requester /workspace/pi-for-legal/lg/new?type=1.1 Add a type (e.g. Supplier › Lab › 'Lab Pact') then it is selectable in the contract-type picker of 1.1 and appears as a category in 1.5 'Which services are you bidding for?'. |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Desc: 8 types, all to the Corporate queue, common questions first | Question scripts for the 8 Corporate request types. All go to the Corporate queue. The common questions in R-05 are asked first. | Implemented | packages/shared/src/legalModules.ts:334 2.1 … 2.8 all category CORPORATE, queue CORPORATEapps/web/src/lg/components/intake/steps.ts:30 common steps precede type questions | no automated test API GET /api/workspace/pi-for-legal/portal/lg/reference 200; types with codes 2.1-2.8 all have queueKey 'CORPORATE' |
| Type 2.1 Power of attorney (POA) | 2.1: 1 New/Renewal/Revocation (M); 2 7X entity or person granting (M); 3 attorney name (M); 4 scope of powers: categories, document types, description (M); 5 duration date range, blocked beyond 1 year (M); 6 value limit (O); 7 notarized Yes/No (M). Docs: attorney's Emirates ID or passport (M); existing POA for renewal/revocation only (M). | Implemented | packages/shared/src/legalModules.ts:334 2.1: poaAction (3 options), grantorKind + grantingEntity/grantingPerson (conditional), attorneyName, scope poa_scope, durationFrom/durationTo (validate maxOneYear), valueLimit O, notarized yesnopackages/shared/src/legalModules.ts:349 docs: attorneyId M; existingPoa M showIf poaAction in [Renewal, Revocation] | intake.test.ts POA longer than a year is blocked; existing POA only for renewal/revocationintake.test.ts a POA or NOC can be granted by a person; 2.7 takes several changes; "Other" asks whatpi-legal-requester /workspace/pi-for-legal/lg/new?type=2.1 Question 2 asks entity-or-person then the entity picker / person name; duration is two dates; Renewal makes 'The existing POA' a required document. |
| Type 2.2 NOC (government / authority) | 2.2: 1 7X entity or person granting (M); 2 'Which authority is it addressed to?' (M); 3 purpose (M); 4 required addressee wording (O). Docs: authority's required format (O); supporting documents (O). | Implemented | packages/shared/src/legalModules.ts:355 2.2 grantorKind split as in 2.1; authority M; purpose M; addresseeWording O; docs requiredFormat O, supporting O | intake.test.ts a POA or NOC can be granted by a person; 2.7 takes several changes; "Other" asks whatpi-legal-requester /workspace/pi-for-legal/lg/new?type=2.2 Four questions (last optional) and two optional documents. |
| Type 2.3 Board / shareholder resolution | 2.3: 1 entity (M); 2 board or shareholder (M); 3 matter to approve (M); 4 signing method Meeting/Circulation (M). Docs: supporting documents (M); draft resolution (O). | Implemented | packages/shared/src/legalModules.ts:372 2.3 entity, body [Board, Shareholder], matter, signingMethod [Meeting, Circulation]; supporting M, draftResolution O | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=2.3 Supporting documents is required at the documents step; draft resolution optional. |
| Type 2.4 Creation of legal entity | 2.4: 1 proposed name (M); 2 jurisdiction or free zone (M); 3 legal form (M); 4 business activities (M); 5 shareholders and ownership % totalling 100% (M); 6 share capital and currency (M); 7 proposed managers or directors (M); 8 target date (M). Docs: business case (M); internal approval (M); shareholder documents (O). | Implemented | packages/shared/src/legalModules.ts:387 2.4 all 8 questions M; legalForm single [LLC, Branch, Free zone company, Other] + legalFormOther; shareholders validate total100; targetDate validate notPast; docs businessCase M, internalApproval M, shareholderDocs O | intake.test.ts shareholders must total 100%pi-legal-requester /workspace/pi-for-legal/lg/new?type=2.4 Shareholder rows with a running total; the step refuses 60/30 and accepts 60/40. |
| Type 2.5 Legal entity amendment | 2.5: 1 entity (M); 2 what is changing: Name/Activities/Capital/Shareholders/Managers/Address/MoA-AoA/Trade licence activities (M); 3 details (M); 4 justification (M); 5 effective date (M). Docs: internal approval (M); current trade licence (M); list of proposed activities only if Activities or Trade licence activities (M). | Implemented | packages/shared/src/legalModules.ts:408 2.5 changing multi with the 8 PRD options; details, justification, effectiveDate M; docs internalApproval M, currentLicence M, proposedActivities M showIf changing in [Activities, Trade licence activities]apps/api/src/lg/services/lg-intake.ts:126 holds(): `in` on an array answer = any overlap | no automated test API PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{changing:['Activities']}} (type 2.5) 200; documents include proposedActivities with required:true; with ['Name'] it is absent |
| Type 2.6 Restructuring | 2.6: 1 entities involved (M); 2 type Merger/Share or business transfer/Liquidation/Re-domiciliation/Other (M); 3 rationale (M); 4 timeline (M). Docs: internal approval (M); current and proposed structure chart (O). | Implemented | packages/shared/src/legalModules.ts:425 2.6 entities (entities picker), restructuringType 5 options + restructuringTypeOther, rationale, timeline; docs internalApproval M, structureChart O | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=2.6 Type options match; choosing Other asks 'What kind of restructuring?' |
| Type 2.7 Governance change | 2.7: 1 entity (M); 2 what is changing: Board or committee composition / Delegation of authority / Authorized signatories / Governance policies (M); 3 details (M); 4 effective date (M). Docs: internal approval (M); current delegation of authority or policy (O). | Implemented | packages/shared/src/legalModules.ts:441 2.7 entity, changing multi 'Choose all that apply' with the 4 PRD options, details, effectiveDate; docs internalApproval M, currentDoa O | intake.test.ts a POA or NOC can be granted by a person; 2.7 takes several changes; "Other" asks whatpi-legal-requester /workspace/pi-for-legal/lg/new?type=2.7 'What is changing? Choose all that apply' accepts several options. |
| Type 2.8 Other corporate request | 2.8: 1 description (M); 2 entity (O). Docs: supporting documents (O). | Implemented | packages/shared/src/legalModules.ts:456 2.8 details M, entity O; supporting O; isOther | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=2.8 Description required, entity optional, one optional document. |
| AC1 | Given a POA with a duration longer than 1 year, then the system blocks it and explains the limit. | Implemented | apps/api/src/lg/services/lg-intake.ts:288 stepIssue maxOneYear: end > start+1y then 'A power of attorney can last at most 1 year. Choose an end date within a year of the start'apps/api/src/lg/services/lg-intake.ts:511 updateDraft throws 400 at the step (conversation can't move past)apps/api/src/lg/services/lg-intake.ts:379 validateDraft re-applies stepIssue at submitapps/web/src/lg/components/intake/Conversation.tsx:337 step stays open and shows the server message | intake.test.ts POA longer than a year is blocked; existing POA only for renewal/revocationintake.test.ts POA over a year and shareholders ≠ 100% stop the conversation at the stepAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{poaAction:'New',durationFrom:'2027-01-01',durationTo:'2028-03-01'}} 400, message matches /at most 1 year/ |
| AC2 | Given a new POA, then 'existing POA' isn't asked. Given a renewal or revocation, it's mandatory. | Implemented | packages/shared/src/legalModules.ts:351 existingPoa required:true, showIf poaAction in [Renewal, Revocation]apps/api/src/lg/services/lg-intake.ts:387 required visible document missing then blocks submit | intake.test.ts POA longer than a year is blocked; existing POA only for renewal/revocationAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{poaAction:'Renewal'}} 200; documents include existingPoa required:true; with 'New' it is absent |
| AC3 | Given Creation of legal entity, when shareholder percentages don't total 100%, then the requester can't continue. | Implemented | apps/api/src/lg/services/lg-intake.ts:298 stepIssue total100: 'Shareholder percentages must total 100% (now N%)'; names requiredapps/api/src/lg/services/lg-intake.ts:511 updateDraft refuses the step with 400apps/web/src/lg/components/intake/AnswerInput.tsx:335 ShareholdersInput widget | intake.test.ts shareholders must total 100%API PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{shareholders:[{name:'A',percent:60},{name:'B',percent:30}]}} 400, message matches /total 100%/ |
| AC4 | Given Legal entity amendment with Activities selected, then the list of proposed activities is mandatory. | Implemented | packages/shared/src/legalModules.ts:421 proposedActivities required:true showIf changing in [Activities, Trade licence activities]apps/api/src/lg/services/lg-intake.ts:126 `in` condition matches any overlap with the multi answer | no automated test API POST /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id/submit (2.5 with changing ['Activities'], other docs uploaded, no proposedActivities) 400 with issue key 'doc:proposedActivities' |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Desc: 4 types, all to the Disputes queue, common questions first | Question scripts for the 4 Disputes request types. All go to the Disputes queue. The common questions in R-05 are asked first. | Implemented | packages/shared/src/legalModules.ts:467 3.1 … 3.4 category DISPUTES, queue DISPUTES | no automated test API GET /api/workspace/pi-for-legal/portal/lg/reference types 3.1-3.4 queueKey 'DISPUTES' |
| Type 3.1 Court claim against 7X | 3.1: 1 counterparty (M); 2 claim amount (M); 3 facts (M); 4 date served (M); 5 court and case number (M); 6 first hearing date, within 10 business days then auto-urgent (M); 7 related contract (O). Docs: claim documents (M); contract (O); correspondence (O). | Implemented | packages/shared/src/legalModules.ts:467 3.1 matches exactly; firstHearing deadline:true; docs claimDocuments M, contract O, correspondence O | intake.test.ts a deadline within 10 business days makes it urgent and asks whypi-legal-requester /workspace/pi-for-legal/lg/new?type=3.1 Seven questions in PRD order, last optional; claim documents required. |
| Type 3.2 Court claim by 7X | 3.2: 1 counterparty (M); 2 related contract or cheque (M); 3 claim amount (M); 4 facts (M); 5 unpaid invoices Yes/No (M); 6 if Yes: debt acknowledged (M); 7 if Yes: issues reported, with details (M). Docs: evidence (M); business approval to sue (M); invoices and statement of account only for unpaid invoices (M). | Implemented | packages/shared/src/legalModules.ts:486 3.2: unpaidInvoices yesno; debtAcknowledged + serviceIssues showIf unpaidInvoices=true; serviceIssueDetails showIf serviceIssues=true; docs evidence M, approvalToSue M, invoices M showIf unpaidInvoices=true | intake.test.ts unpaid invoices = No hides the invoice questions and documents (3.2)pi-legal-requester /workspace/pi-for-legal/lg/new?type=3.2 Answer Yes to unpaid invoices then two follow-ups and the invoices document; No then neither. |
| Type 3.3 Contingent liability (early warning) | 3.3: 1 counterparty (M); 2 what happened and when (M); 3 estimated exposure in AED (M); 4 legal action threatened Yes/No (M); 5 contractual notice deadline (O). Docs: correspondence (M); other supporting documents (O). | Implemented | packages/shared/src/legalModules.ts:506 3.3 matches; exposure is a number (AED); noticeDeadline date O (not deadline-flagged, as the PRD does not auto-urgent it) | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=3.3 Five questions, last optional; correspondence required. |
| Type 3.4 Other dispute request | 3.4: 1 description (M); 2 counterparty (O). Docs: supporting documents (O). | Implemented | packages/shared/src/legalModules.ts:522 3.4 details M, counterpartyName O; supporting O | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=3.4 Two questions, one optional document. |
| AC1 | Given Court claim against 7X with a first hearing within 10 business days, then the request is auto-urgent. | Implemented | packages/shared/src/legalModules.ts:476 firstHearing deadline:trueapps/api/src/lg/services/lg-intake.ts:580 applyAutoUrgent | intake.test.ts a deadline within 10 business days makes it urgent and asks whyAPI PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{firstHearing:<today+3d>}} (type 3.1) 200; common.autoUrgent true; issues contain 'urgentReason'; sla.days = urgent SLA (2) |
| AC2 | Given Court claim by 7X with 'unpaid invoices' = No, then the invoice questions and documents aren't asked. | Implemented | packages/shared/src/legalModules.ts:495 debtAcknowledged/serviceIssues/invoices showIf unpaidInvoices=trueapps/api/src/lg/services/lg-intake.ts:137 hidden questions cascade (serviceIssueDetails hidden when serviceIssues is hidden) | intake.test.ts unpaid invoices = No hides the invoice questions and documents (3.2)API PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{unpaidInvoices:false}} (type 3.2) 200; questions exclude debtAcknowledged/serviceIssues; documents exclude invoices |
| AC3 | Given Court claim by 7X with no business approval to sue uploaded, then the request can't be submitted. | Implemented | packages/shared/src/legalModules.ts:501 approvalToSue required:trueapps/api/src/lg/services/lg-intake.ts:387 missing required doc then blocking issueapps/api/src/lg/services/lg-intake.ts:713 submit 400 while issues exist | no automated test API POST /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id/submit (3.2 complete, evidence uploaded, no approvalToSue) 400 with issue key 'doc:approvalToSue' |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Desc: 5 types, Employment queue, common questions first, Confidential suggested not forced | Question scripts for the 5 Employment request types. All go to the Employment queue. The common questions in R-05 are asked first. For every Employment request, the system suggests ticking Confidential but doesn't force it. | Implemented | packages/shared/src/legalModules.ts:533 4.1 … 4.5 queue EMPLOYMENT, suggestConfidential:true on all five | intake.test.ts changing the type keeps the common answers and restarts the type questionsAPI GET /api/workspace/pi-for-legal/portal/lg/reference types 4.1-4.5 queueKey 'EMPLOYMENT' and suggestConfidential true |
| Type 4.1 Termination / disciplinary | 4.1: 1 employee name and ID (O); 2 issue (M); 3 proposed action (M); 4 previous warnings Yes/No (M). Docs: employment contract (M); relevant records (M). | Implemented | packages/shared/src/legalModules.ts:533 4.1 matches exactly | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=4.1 Employee name optional; both documents required; confidential step shows 'Employment matters are usually confidential. We suggest Yes.' |
| Type 4.2 Labour complaint / MoHRE | 4.2: 1 employee name and ID (M); 2 complaint details (M); 3 authority deadline, within 10 business days then auto-urgent (O). Docs: complaint papers (M); employment contract (O). | Implemented | packages/shared/src/legalModules.ts:548 4.2 matches; authorityDeadline date O deadline:true | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=4.2 Authority deadline optional; a date within 10 business days turns the draft urgent. |
| Type 4.3 Employment contracts | 4.3: 1 role (M); 2 non-standard terms: Secondment/Non-compete/Settlement/Other (M). Docs: draft offer or agreement (M). | Implemented | packages/shared/src/legalModules.ts:562 4.3 role M; terms multi 4 options + termsOther when Other; draftOffer M | intake.test.ts a POA or NOC can be granted by a person; 2.7 takes several changes; "Other" asks whatpi-legal-requester /workspace/pi-for-legal/lg/new?type=4.3 Terms is a multi-select; Other asks 'Which other terms?' |
| Type 4.4 HR advisory | 4.4: 1 question (M); 2 background (M). Docs: relevant policy (O). | Implemented | packages/shared/src/legalModules.ts:573 4.4 matches exactly | intake.test.ts changing the type keeps the common answers and restarts the type questionspi-legal-requester /workspace/pi-for-legal/lg/new?type=4.4 Two required questions, one optional document. |
| Type 4.5 Other employment request | 4.5: 1 description (M). Docs: supporting documents (O). | Implemented | packages/shared/src/legalModules.ts:583 4.5 matches exactly | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=4.5 One question, one optional document. |
| AC1 | Given Labour complaint with an authority deadline within 10 business days, then the request is auto-urgent. | Implemented | packages/shared/src/legalModules.ts:554 authorityDeadline deadline:trueapps/api/src/lg/services/lg-intake.ts:580 applyAutoUrgent (same rule as 3.1) | no automated test API PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{authorityDeadline:<today+2d>}} (type 4.2) 200; common.autoUrgent true |
| AC2 | Given any Employment request, then the system suggests ticking Confidential but doesn't force it. | Implemented | apps/api/src/lg/services/lg-intake.ts:206 draftView.type.suggestConfidential from the type rowapps/web/src/lg/components/intake/Conversation.tsx:279 confidential step help: 'Employment matters are usually confidential. We suggest Yes.' , Yes/No both allowedapps/api/src/lg/services/lg-intake.ts:351 validation only requires the confidential answer to be confirmed, not Yes | intake.test.ts changing the type keeps the common answers and restarts the type questionspi-legal-requester /workspace/pi-for-legal/lg/new?type=4.1 Confidential step shows the suggestion; answering No still lets the request proceed and submit. |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Desc: 4 types, IP queue, common questions first | Question scripts for the 4 IP request types. All go to the IP queue. The common questions in R-05 are asked first. | Implemented | packages/shared/src/legalModules.ts:591 5.1 … 5.4 category IP, queue IP | no automated test API GET /api/workspace/pi-for-legal/portal/lg/reference types 5.1-5.4 queueKey 'IP' |
| Type 5.1 Trademark registration | 5.1: 1 mark (M); 2 classes (O); 3 jurisdictions (O); 4 New/Renewal/Opposition (M). Docs: logo or mark file (M); existing registration certificate for renewals only (O). | Implemented | packages/shared/src/legalModules.ts:591 5.1 mark M, classes O, jurisdictions O, filing single 3 options; docs logo M, existingCertificate O showIf filing=Renewal | registers.test.ts IP: one record per jurisdiction; renewals link to the existing right; alerts go to the responsible lawyer (G-07, G-08, G-10)pi-legal-requester /workspace/pi-for-legal/lg/new?type=5.1 Renewal then optional 'Existing registration certificate' slot appears; New/Opposition then only the logo slot. |
| Type 5.2 Brand use / infringement | 5.2: 1 who is using what, and where (M); 2 when it was discovered (O). Docs: evidence (M). | Implemented | packages/shared/src/legalModules.ts:606 5.2 who M, discovered date O; evidence M | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=5.2 Evidence is a required document. |
| Type 5.3 IP in projects | 5.3: 1 project (M); 2 who creates the IP (M); 3 question (M). Docs: related contract (O). | Implemented | packages/shared/src/legalModules.ts:616 5.3 matches exactly | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=5.3 Three required questions; related contract optional. |
| Type 5.4 Other IP request | 5.4: 1 description (M). Docs: supporting documents (O). | Implemented | packages/shared/src/legalModules.ts:627 5.4 matches exactly | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?type=5.4 One question, one optional document. |
| AC1 | Given Trademark registration as a new filing, then the existing registration certificate isn't asked. | Implemented | packages/shared/src/legalModules.ts:602 existingCertificate showIf filing=Renewalapps/api/src/lg/services/lg-intake.ts:141 documents filtered by showIf | no automated test API PATCH /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id {answers:{filing:'New'}} (type 5.1) 200; documents = [logo] only; with 'Renewal' existingCertificate (required:false) is added |
| AC2 | Given Brand use / infringement with no evidence uploaded, then the request can't be submitted. | Implemented | packages/shared/src/legalModules.ts:613 evidence required:trueapps/api/src/lg/services/lg-intake.ts:387 missing required doc blocksapps/api/src/lg/services/lg-intake.ts:713 submit 400 | no automated test API POST /api/workspace/pi-for-legal/portal/lg/intake/drafts/:id/submit (5.2 answered, no evidence file) 400 with issue key 'doc:evidence' |
| AC3 | Given a renewal or infringement request, then the lawyer can link it to the IP record (R-29). | Implemented | apps/api/src/lg/routes/registers.ts:903 POST /registers/ip/:id/link-request { requestId } (IP-queue lawyers + GC via canEdit('ip')); IP-category requests only; sets lgIpRecord.linkedRequestIds and lgRequest.linkedIpId; auditedapps/web/src/lg/components/registers/IpView.tsx:213 'Linked requests' section: reference input + Link button (canEdit)apps/api/src/lg/services/lg-ip.ts:24 createIpFromRequest: a 5.1 Renewal/Opposition or 5.2 infringement auto-links to the existing record (same mark/jurisdiction or the record the request was raised from) when it moves to With IP agent / officeapps/api/src/lg/routes/registers.ts:918 raise-request from a record then /lg/new?type=5.1&ip=<id>; LgIntakePage.tsx:63 stores answers.ipRecord; lg-intake.ts:574 maps it to linkedIpId | registers.test.ts IP: one record per jurisdiction; renewals link to the existing right; alerts go to the responsible lawyer (G-07, G-08, G-10)pi-legal-gc /workspace/pi-for-legal/lg/registers/ip Open an IP record then 'Linked requests' then type the reference of a 5.1 renewal or 5.2 request then Link; the reference appears in the list and the request's overview shows the linked record. |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given the requester can't find a matching type, when they choose "I'm not sure", then the system offers Legal advice / query. | Implemented | apps/web/src/lg/components/intake/TypeStart.tsx:80 'Not sure? Legal advice / query' starts a 6.1 draftapps/web/src/lg/components/intake/Conversation.tsx:181 on the category/type browser: 'Not sure? Send it as a Legal advice / query' then onPick('6.1')packages/shared/src/legalModules.ts:637 6.1 description 'A legal question, or anything you're not sure where to put.' | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new 'Not sure? Legal advice / query' link; clicking it opens a 6.1 draft (Question / Background / Business decision) |
| AC2 | Given the lawyer reclassifies a General request, then it moves to the correct queue (R-14). | Implemented | apps/api/src/lg/services/lg-routing.ts:221 reclassify: new typeCode/category/queueKey/path, re-snapshots the script, re-routes (decideAssignment/applySla line 262)apps/api/src/lg/routes/requests.ts:333 POST /requests/:id/reclassify (assigned lawyer or GC, reason required)apps/web/src/lg/components/requests/RequestActions.tsx:1 Reclassify action on the request page | requests.test.ts reclassifying into another queue moves and reassigns; SLA from the original assignmentAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<6.1 ref>/reclassify {typeCode:'1.1', reason:'It is a contract review'} 200; detail.queueKey 'COMMERCIAL', assignedLawyer in the Commercial queue, contractRef allocated |
| AC3 | Given the lawyer answers the query, from the LMS or from Outlook, then the answer is saved in the request thread and visible to the requester and people in copy. | Implemented | apps/api/src/lg/routes/thread.ts:138 POST /thread/:id/reply (tag Response/Final reply) then postThreadEntry, emailed to requester + cc (lg-thread.ts:120)apps/api/src/lg/services/lg-mailbox.ts:287 Outlook reply addressed to the business then REPLY entry (visible, internal:false)apps/api/src/lg/routes/thread.ts:115 GET thread shows non-internal entries to requester and cc | thread.test.ts a Response starts work, meets the SLA and is emailed to requester and copymailbox.test.ts lawyer email to the requester is a reply; to legal colleagues only it is an internal notepi-legal-requester /workspace/pi-for-legal/lg/requests/<6.1 ref>/thread the lawyer's reply tagged Response (posted from the LMS by pi-legal-counsel, or simulated from Outlook by the GC) with its attachments |
| Desc: General has one type (6.1) in the General queue, no Other; common questions first | General has one request type, which goes to the General queue. There’s no “Other” type in General… The common questions in R-05 are asked first. | Implemented | packages/shared/src/legalModules.ts:636 6.1 Legal advice / query, category GENERAL, queue GENERAL; it is the only 6.x typeapps/web/src/lg/components/intake/steps.ts:30 common steps precede type questions | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?category=GENERAL a single type '6.1 Legal advice / query'; after picking it the entity/BU/title… questions come first |
| Desc: 6.1 script , Question (M), Background (M), Business decision it supports (M); related documents (O) | 6.1 Legal advice / query: 1. Question (M) 2. Background (M) 3. Business decision it supports (M). Documents: related documents (O) | Implemented | packages/shared/src/legalModules.ts:638 questions question/background/decision all required; documents related optionalapps/api/src/lg/services/lg-intake.ts:266 the first message pre-fills 'Question' | intake.test.ts a mandatory answer cannot be skippedintake.test.ts a confidential submission goes straight to the GC (submits a full 6.1)pi-legal-requester /workspace/pi-for-legal/lg/new?type=6.1 three mandatory questions without Skip, then an optional 'Related documents' upload |
| Desc: the advice stays on the request; completing requires a final reply | The lawyer gives the advice as a reply in the request thread… tagged “Response”. The advice and any attachments stay on the request. Completing the request requires a final reply (R-13). | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:214 completion gate: a FINAL_REPLY thread entry since the last reopen is required for Completedapps/api/src/lg/routes/thread.ts:309 thread entries immutable (405 on edit/delete), so the advice stays | requests.test.ts complete needs a final reply; requester confirms or reopensthread.test.ts a final reply can complete the request in one stepAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<6.1 ref>/status {to:'COMPLETED'} with no Final reply posted 409 explaining a final reply is needed; after POST /thread/:id/reply {tag:'FINAL_REPLY', complete:true} the status is COMPLETED |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given any request, when someone tries a status move not listed in this model, then the system blocks it. | Implemented | packages/shared/src/legalModules.ts:878 lgCanMove(): filters the path's transition table by from/to/category/type and mover; returns ok:false with a plain-language reason for anything not listedapps/api/src/lg/services/lg-lifecycle.ts:87 moveStatus() is the only writer of status; it calls lgCanMove and throws LgMoveError(409) when not okapps/api/src/lg/routes/requests.ts:230 POST /requests/:id/status re-checks lgCanMove before the first-action auto-start and also refuses moves that must happen elsewhere (thread, approvals, case) via moveElsewhereReasonapps/api/src/lg/services/lg-requests.ts:29 LG_MOVES_ELSEWHERE / LG_CASE_MOVES: send-back, feedback, approval, signature, case moves are refused on the generic route | core.test.ts blocks moves that are not listed and requires reasonsrequests.test.ts starts on first action, needs a reason and resume date for hold, refuses moves made elsewhereAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<id>/status { "to": "CLOSED" } on an In progress request 409 "A request can't move from In progress to Closed" |
| AC2 | Given a status change, then the user, time and reason are logged. The reason is mandatory for On hold, Withdrawn, Cancelled by legal and Reopen. | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:140 status update + LgStatusEvent (fromStatus, toStatus, actorUserId, actorName, reason) + LgAuditEvent written in one transactionapps/api/src/lg/services/lg-lifecycle.ts:94 reason mandatory when check.needsReason (400) for any non-system moverpackages/shared/src/legalModules.ts:723 LG_REASON_REQUIRED = ON_HOLD, WITHDRAWN, CANCELLEDpackages/shared/src/legalModules.ts:897 needsReason also when leaving CLOSED / CLOSED_COMPLETED or COMPLETED->IN_PROGRESS (Reopen)apps/api/src/lg/routes/requests.ts:283 POST /:id/reopen requires a non-empty reason (zod)apps/web/src/lg/request/tabs/LgHistoryTab.tsx:50 History tab shows actor, time and reason per status event | core.test.ts records who, when and why; enforces the folder and final-reply gatesrequests.test.ts starts on first action, needs a reason and resume date for hold, refuses moves made elsewherepi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/history each status row shows who, when and the reason; Put on hold / Cancel / Reopen dialogs refuse an empty reason |
| AC3 | Given a completed request, when 5 business days pass without the requester confirming, then it closes automatically. | Implemented | apps/api/src/lg/services/lg-request-timers.ts:113 COMPLETED (non-generation) -> CLOSED by system once businessDaysBetween(statusChangedAt, now) >= completedAutoClose (5)apps/api/src/lg/services/lg-generation-timers.ts:39 same for generated contracts (G7)packages/shared/src/legalModules.ts:1137 completedAutoClose: 5 business days (GC-editable via settings, lg-settings getLgTimers) | timers.test.ts closes a completed request after 5 business daysAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run { "now": "<completedAt + 6 business days>" } 200; the request then reads status CLOSED with a ledger row reason "Closed automatically after 5 business days" |
| AC4 | Given a request withdrawn for "No response", when the requester replies within 10 business days, then it returns to In progress with the same reference. | Implemented | apps/api/src/lg/services/lg-thread.ts:144 REQUESTER_REPLY on WITHDRAWN with withdrawnNoResponse within reopenAfterNoResponse (10 bd of closedAt) -> moveStatus(workingStatus, system)packages/shared/src/legalModules.ts:765 WITHDRAWN -> IN_PROGRESS by system is a listed move (and WITHDRAWN -> UNDER_REVIEW for disputes, line 838)apps/api/src/lg/services/lg-lifecycle.ts:132 withdrawnNoResponse flag set on the system withdrawal; reference is never rewrittenapps/api/src/lg/services/lg-mailbox.ts:312 an email reply by reference is captured as REQUESTER_REPLY through the same postThreadEntry path | thread.test.ts a "No response" withdrawal reopens when the requester replies within 10 business daysAPI POST /api/workspace/pi-for-legal/portal/lg/thread/<id>/business-reply { "body": "Here it is" } on a request auto-withdrawn < 10 bd ago 201; GET /requests/<id> shows status IN_PROGRESS and the same reference |
| AC5 | Given a dispute with a case opened, then it can't be Cancelled by legal, only Closed (completed). | Implemented | packages/shared/src/legalModules.ts:892 lgCanMove refuses CANCELLED when caseOpened or from CASE_OPENED/JUDGEMENT/EXECUTIONapps/api/src/lg/services/lg-lifecycle.ts:128 caseOpened set true on the move to CASE_OPENEDapps/api/src/lg/services/lg-lifecycle.ts:104 with an open case, Closed (completed) must come through the Case tab (outcome, amounts, closing note) | requests.test.ts dispute with a case opened cannot be cancelledcore.test.ts blocks moves that are not listed and requires reasonsAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<dispute-with-case>/status { "to": "CANCELLED", "reason": "dup" } 409 "A dispute with a case opened can't be cancelled. Close it as Closed (completed)" |
| AC6 | Given a generated request, then it follows the generation path, and Cancelled by legal isn't available until it converts. | Implemented | packages/shared/src/legalModules.ts:845 GENERATION_TRANSITIONS has no CANCELLED row (only Withdraw by the requester)packages/shared/src/legalModules.ts:660 pathForCategory(selfService) -> GENERATION; lgTransitionsFor picks the table by pathapps/api/src/lg/routes/requests.ts:223 generic status route refuses everything but WITHDRAWN/CLOSED on a GENERATION request; the rest goes through the Generation tabapps/api/src/lg/services/lg-generation.ts:436 generate -> GENERATED, markSentToCounterparty -> WITH_COUNTERPARTY, upload -> RETURNED / COMPARISON_FAILED, all via moveStatus | core.test.ts blocks moves that are not listed and requires reasonsAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<generated-id>/status { "to": "CANCELLED", "reason": "x" } 409 "Generated contracts move through the Generation tab" |
| AC7 | Given a generated request converts, then it continues as Contract review with the same reference number and history. | Implemented | apps/api/src/lg/services/lg-generation.ts:470 convertToContractReview: same LgRequest row updated to path CORE, type 1.1, status SUBMITTED; LgStatusEvent + audit + thread event written; then routeAndAssignapps/api/src/lg/services/lg-generation.ts:486 Arabic generated contract -> arabic:true, arabicAuto:true on conversionapps/api/src/lg/services/lg-generation.ts:563 a locked-section change converts automatically; 'Ask legal for help' / 'Send to legal' convert with a reason (LG_CONVERTIBLE statuses) | generation.test.ts a tracked change in a locked section converts to a Contract review with the same referencegeneration.test.ts an unreadable scan fails the comparison; Send to legal converts with a reasonpi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation 'Ask legal for help' with a reason; the page keeps the same LGL reference, type becomes 1.1 Contract review, History shows GENERATED -> SUBMITTED -> ASSIGNED |
| AC8 | Given a declined or expired signature, then an event is recorded and the request returns to In progress (or Generated). | Implemented | apps/api/src/lg/services/lg-esign.ts:298 signatureProblem(): thread EVENT entry + moveStatus to GENERATED (generation) or IN_PROGRESS, sender emailed SIGNATURE_PROBLEMapps/api/src/lg/services/lg-esign.ts:526 runSignatureTimers expires envelopes and calls signatureProblemapps/api/src/lg/services/lg-status-moves.ts:126 manual Awaiting signature -> In progress (wet ink declined/expired): reason required, open envelopes voided, EVENT posted to the threadpackages/shared/src/legalModules.ts:779 AWAITING_SIGNATURE -> IN_PROGRESS by system/lawyer with reason:true; generation AWAITING_SIGNATURE -> GENERATED by system (line 860) | signature.test.ts reminds 7 and 2 days before expiry, then expires and sends the request backlifecycle-gaps.test.ts declined or expired signature: reason required, envelopes voided, event visible on the threadAPI POST /api/workspace/pi-for-legal/portal/lg/signature/envelopes/<MOCK-id>/simulate { "event": "declined", "reason": "wrong entity" } 200; request status IN_PROGRESS, thread shows an Event 'Signature declined: wrong entity' (DocuSign side is the mock adapter locally) |
| AC9 | Given a lawyer clicks "Complete" (or "Closed (completed)" for a dispute), then they must write a final reply to the requester, which is saved in the thread and emailed (R-22). | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:213 assertCompletable: a FINAL_REPLY thread entry since the last reopen is required, else 409 'Write a final reply to the requester first'apps/api/src/lg/routes/thread.ts:337 POST /thread/:id/reply { tag: FINAL_REPLY, complete: true } posts the reply and completes in one step; gates checked before the email goes outapps/api/src/lg/services/lg-thread.ts:120 FINAL_REPLY emailed to requester + people in copy (event FINAL_REPLY)apps/web/src/lg/components/requests/RequestActions.tsx:288 Complete without a final reply sends the lawyer to the Thread tab (?compose=final)apps/api/src/lg/services/lg-lifecycle.ts:113 disputes: Closed (completed) also needs outcome + amounts (assertDisputeClose) or the Case tab close | requests.test.ts complete needs a final reply; requester confirms or reopensthread.test.ts a final reply can complete the request in one steplifecycle-gaps.test.ts a dispute without a case closes only with its outcome and amounts , from the menu or the final replypi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview Complete on a request with no final reply opens 'Write final reply' and lands on the Thread composer in Final reply mode; after sending with 'and complete' the status is Completed and the Outbox shows the FINAL_REPLY email |
| AC10 | Given the system completes a request after signature, then the executed copy is posted to the thread as the final reply. | Implemented | apps/api/src/lg/services/lg-esign.ts:440 completeWithExecutedCopy posts REPLY tagged FINAL_REPLY with the EXECUTED document attached, then moveStatus(COMPLETED, system, skipCompletionGate)apps/api/src/lg/services/lg-esign.ts:428 Corporate exception (R-13 B): the signed/notarized copy is posted as an event and the request returns to In progress , recorded in DESIGN.md 'Decisions to confirm' | signature.test.ts wet ink: Awaiting signature, sender reminded after 14 days, upload completesintegrations.test.ts a signed Connect callback completes the request with DocuSign's signed PDF and certificate; a forged one is refusedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread after the mock envelope is 'signed' (Approval & signature tab -> Simulate), the last thread entry is a Final reply 'Signed by all parties. The executed copy is attached' and the status is Completed |
| Desc: Reopening keeps the same reference number | Reopening keeps the same reference number. | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:133 reopen moves only clear closedAt/completedAt/withdrawnNoResponse; the reference column is never touchedapps/api/src/lg/routes/requests.ts:283 POST /:id/reopen moves COMPLETED/CLOSED/CLOSED_COMPLETED back to the working status with a reason | requests.test.ts complete needs a final reply; requester confirms or reopenspi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/overview Reopen (with reason) on a Completed request: same LGL reference in the header, status In progress |
| Desc: Replies drive the status; a reply alone doesn't change it except where listed | Lawyer replies, requester replies and internal notes are captured in the request thread (R-18). A reply alone doesn't change the status, except where listed below. | Implemented | apps/api/src/lg/services/lg-thread.ts:137 only a REQUESTER_REPLY in Awaiting requester / business / HR feedback (or on 1.5 Submitted to business, or a 'No response' withdrawal) moves the status; lawyer replies and notes never doapps/api/src/lg/routes/thread.ts:148 a lawyer reply only triggers ensureStarted (Assigned -> In progress, the first action), nothing else | thread.test.ts a Response starts work, meets the SLA and is emailed to requester and copypi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread post a Reply on an In progress request: status stays In progress |
| Desc: On hold needs a reason and a resume date | On hold , Lawyer or GC; reason and resume date required. Resumed -> In progress; or Withdrawn / Cancelled by legal. | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:95 ON_HOLD without resumeDate -> 400; reason enforced by LG_REASON_REQUIREDapps/api/src/lg/routes/requests.ts:236 resumeDate validated, must not be in the pastapps/web/src/lg/components/requests/RequestActions.tsx:278 hold dialog asks for the resume date; confirm disabled without it | requests.test.ts starts on first action, needs a reason and resume date for hold, refuses moves made elsewherepi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview Put on hold: Reason + Resume date both required; afterwards 'Resume' returns it to In progress |
| Desc: Table A , core statuses (rows 1-10) | Draft -> Submitted (requester) / delete; Submitted -> Assigned (system); Assigned -> In progress (first action); In progress -> send back / category status / hold / complete; Awaiting requester -> In progress on reply, Withdrawn 'No response' at 15 bd, requester withdraws; On hold -> resume / withdrawn / cancelled; Completed -> Closed on confirm or 5 bd, reopen -> In progress; Closed -> lawyer reopens with reason; Withdrawn final except 'No response' reply within 10 bd; Cancelled by legal final, reason required. | Implemented | packages/shared/src/legalModules.ts:751 CORE_TRANSITIONS rows 752-765 map every row of table A: DRAFT->SUBMITTED (requester), SUBMITTED->ASSIGNED (system), ASSIGNED->IN_PROGRESS (system/lawyer), IN_PROGRESS->AWAITING_REQUESTER (lawyer), AWAITING_REQUESTER->IN_PROGRESS (system on reply), AWAITING_REQUESTER->WITHDRAWN (system/requester, reason), IN_PROGRESS<->ON_HOLD (reason), IN_PROGRESS->COMPLETED, COMPLETED->CLOSED (system/requester), COMPLETED->IN_PROGRESS (reopen, reason), CLOSED->IN_PROGRESS (lawyer, reason), WITHDRAWN->IN_PROGRESS (system)packages/shared/src/legalModules.ts:808 '*' -> WITHDRAWN (requester, reason) and '*' -> CANCELLED (lawyer/GC, reason) any time before a final status; lgCanMove excludes DRAFT and final statuses from '*'apps/api/src/lg/services/lg-lifecycle.ts:305 ensureStarted: Assigned -> In progress on the lawyer's first action, called by every lawyer routeapps/api/src/lg/services/lg-routing.ts:188 routeAndAssign: Submitted -> Assigned by the systemapps/api/src/lg/services/lg-request-timers.ts:73 Awaiting requester: final warning at 12 bd, withdrawn 'No response' at 15 bd; Completed -> Closed after 5 bdapps/api/src/lg/routes/requests.ts:263 requester withdraw/confirm/reopen routes; DRAFT withdraw refused ('Delete the draft instead') | core.test.ts blocks moves that are not listed and requires reasonsrequests.test.ts requester withdraws with a reasontimers.test.ts awaiting requester: reminders, final warning at 12 business days, withdrawn at 15; feedback never withdrawnpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview the action menu on an In progress 6.1 request offers exactly Send back (via thread), Put on hold, Complete, Cancel , never Closed or Withdrawn; the requester's menu offers Withdraw only |
| Desc: Table B , Contracts and Letters (1.1-1.6) | Awaiting business feedback (reminder every 3 days); With counterparty (lawyer chooses sender; counterparty's version uploaded -> In progress; sender reminded every 3 days); Awaiting approval (system; approved -> In progress or Awaiting signature; rejected/returned -> In progress); Awaiting signature (DocuSign or wet ink; all sign / executed copy -> Completed; declined/expired -> In progress + event); Sent (1.4 only, on uploading the sent letter -> Completed); Submitted to business (1.5 only; business confirms or deadline passes -> Completed; questions -> In progress); tender status is a field. | Implemented | packages/shared/src/legalModules.ts:766 rows 766-784: AWAITING_BUSINESS_FEEDBACK, WITH_COUNTERPARTY (CONTRACTS/IP), AWAITING_APPROVAL (system only), AWAITING_APPROVAL->AWAITING_SIGNATURE, AWAITING_SIGNATURE->COMPLETED (system only) / ->IN_PROGRESS (reason), SENT (types 1.4), SUBMITTED_TO_BUSINESS (types 1.5) with the three exitsapps/api/src/lg/services/lg-status-moves.ts:52 captureNeeds: Sent needs the sent letter; Submitted to business needs the review (posted as the Response); With counterparty needs the sender; counterparty's version needed to come backapps/api/src/lg/services/lg-status-moves.ts:175 completeSubmittedReview: business confirms or the 1.5 submission deadline passes -> review posted as final reply -> Completedapps/api/src/lg/services/lg-thread.ts:142 a business reply on Submitted to business = 'Questions' -> In progressapps/api/src/lg/services/lg-approvals.ts:364 finishRound: approved -> Awaiting signature when the round needs signature, else In progress; rejected/returned -> working statusapps/api/src/lg/services/lg-request-timers.ts:92 With counterparty reminder goes to the sender (requester+cc when they sent it, else the lawyer) every 3 days; business feedback reminders every 3 daysapps/api/src/lg/routes/thread.ts:276 upload flagged counterpartyVersion on With counterparty -> In progress (system)apps/api/src/lg/routes/requests.ts:538 PATCH /:id/tender-status , a field on 1.5, not a status | lifecycle-gaps.test.ts Sent (1.4) needs the sent letter; With authority needs the authority and date; With external counsel the firmlifecycle-gaps.test.ts With counterparty records the sender, reminds the requester when they send it, and an upload brings it backlifecycle-gaps.test.ts the review goes to the requester as the Response; the business confirms then Completed with the review as the final replylifecycle-gaps.test.ts a business reply means questions then In progress; the passed deadline completes itrequests.test.ts tender status is a field on 1.5 onlypi-legal-counsel /workspace/pi-for-legal/lg/requests/<1.4 ref>/overview 'Letter sent' asks for the sent letter upload; on a 1.1 the menu shows Ask for business feedback / Sent to counterparty (asks who sends) but no Sent / Submitted to business |
| Desc: Table B , Corporate | Awaiting business feedback (reminder every 3 days); Awaiting approval (approved -> In progress or Awaiting signature / notarization; rejected/returned -> In progress); Awaiting signature / notarization (lawyer; signed or notarized copy uploaded -> In progress or With authority; declined/expired -> In progress, event); With authority (lawyer records authority + submission date; approved -> Completed; query/rejection -> In progress). | Implemented | packages/shared/src/legalModules.ts:786 rows 786-793: AWAITING_APPROVAL->AWAITING_SIGNATURE_NOTARIZATION (system), IN_PROGRESS->AWAITING_SIGNATURE_NOTARIZATION (lawyer), ->IN_PROGRESS (system/lawyer), ->WITH_AUTHORITY (lawyer), IN_PROGRESS->WITH_AUTHORITY, WITH_AUTHORITY->COMPLETED / ->IN_PROGRESSapps/api/src/lg/services/lg-status-moves.ts:56 With authority captures authorityName + submittedOn; from notarization also the signed/notarized copy; declined/expired accepts a reason instead and posts an eventapps/api/src/lg/services/lg-approvals.ts:399 signingTargetFromApproval: Corporate approved -> AWAITING_SIGNATURE_NOTARIZATIONapps/api/src/lg/services/lg-esign.ts:428 Corporate executed copy -> event + back to In progress (no contract register entry) , DESIGN.md 'Corporate signature / notarization' decision | lifecycle-gaps.test.ts Sent (1.4) needs the sent letter; With authority needs the authority and date; With external counsel the firmpi-legal-counsel /workspace/pi-for-legal/lg/requests/<2.x ref>/overview 'With authority' dialog requires the authority name and submission date; from Awaiting signature / notarization the dialog requires the signed copy or a declined/expired reason |
| Desc: Table B , Employment | Awaiting HR feedback (HR replies -> In progress; reminder every 3 days); Awaiting approval (approved, rejected or returned -> In progress); Awaiting signature (signed -> Completed; declined/expired -> In progress, event); With authority (outcome uploaded -> In progress or Completed; the lawyer can open a case R-28). | Implemented | packages/shared/src/legalModules.ts:794 rows 794-803: AWAITING_HR_FEEDBACK, WITH_AUTHORITY->CASE_OPENED (EMPLOYMENT) and the case chain; AWAITING_SIGNATURE rows include EMPLOYMENT; AWAITING_APPROVAL->AWAITING_SIGNATURE is CONTRACTS only so Employment approval returns to In progressapps/api/src/lg/services/lg-status-moves.ts:66 Employment With authority -> In progress / Completed requires the authority's outcome documentapps/api/src/lg/services/lg-cases.ts:48 employment cases open only from With authorityapps/api/src/lg/routes/thread.ts:191 feedback on an EMPLOYMENT request defaults to HR -> AWAITING_HR_FEEDBACK | signature.test.ts Employment: an approved round returns to In progress (R-13 B), Contracts move on to signature (E4)thread.test.ts employment feedback goes to HR; outsiders and lawyers cannot answer as the businesscases.test.ts employment cases only from With authoritypi-legal-counsel /workspace/pi-for-legal/lg/requests/<4.x ref>/thread the composer offers 'Ask HR'; status becomes Awaiting HR feedback; on With authority the Case tab offers Open case |
| Desc: Table B , Intellectual Property and General | IP: Awaiting business feedback; With IP agent / office (on uploading the filing receipt; filing confirmed -> Completed; IP register updated R-29); With counterparty (cease-and-desist; reply uploaded -> In progress). General: core statuses only. | Implemented | packages/shared/src/legalModules.ts:804 rows 804-806: IN_PROGRESS->WITH_IP_AGENT (lawyer), WITH_IP_AGENT->COMPLETED / ->IN_PROGRESS; WITH_COUNTERPARTY and AWAITING_BUSINESS_FEEDBACK rows include IP; no category rows for GENERALapps/api/src/lg/services/lg-status-moves.ts:58 With IP agent / office requires the filing receipt documentapps/api/src/lg/routes/requests.ts:251 move to WITH_IP_AGENT calls createIpFromRequest (IP register entry FILED / OPPOSED) | core.test.ts blocks moves that are not listed and requires reasonsAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<6.1 id>/status { "to": "WITH_COUNTERPARTY", "sender": "LEGAL" } 409 'A request can't move from In progress to With counterparty' (General has core statuses only); the same on a 5.2 request returns 200 |
| Desc: Table C , Disputes path | Under review (instead of In progress); Awaiting business feedback; Awaiting approval; With external counsel (firm and date; advice/filing uploaded -> Under review or Case opened); Case opened (Open case R-28; judgment -> Judgement; settlement -> Closed (completed)); Judgement (appeal -> Case opened; enforce/pay -> Execution; nothing further -> Closed (completed)); Execution (amounts recorded -> Closed (completed)); Closed (completed) (outcome, amounts, final reply required; GC can reopen with a reason); Cancelled by legal only before a case is opened. | Implemented | packages/shared/src/legalModules.ts:813 DISPUTE_TRANSITIONS rows 814-841 map every row of table C, including CLOSED_COMPLETED->UNDER_REVIEW by 'gc' with reason and WITHDRAWN->UNDER_REVIEW by systemapps/api/src/lg/services/lg-lifecycle.ts:77 workingStatus(DISPUTE) = UNDER_REVIEW used by ensureStarted, replies, reopenapps/api/src/lg/services/lg-status-moves.ts:59 With external counsel captures the firm + date; back to Under review needs the advice or filingapps/api/src/lg/services/lg-cases.ts:249 judgment -> JUDGEMENT, appeal -> CASE_OPENED, execution -> EXECUTION, close -> CLOSED_COMPLETED with outcome/amounts/closing note, all via moveStatus(fromCase)apps/api/src/lg/services/lg-lifecycle.ts:65 assertDisputeClose: outcome + final amount required when closing a dispute without a case | cases.test.ts judgment then appeal (new level) then judgment then executioncases.test.ts closing needs outcome, final amount, closing note and a final replycases.test.ts a closed dispute reopened by the GC reopens the SAME case record (G-04)cases.test.ts judgment, execution and close never bypass the case record (G-01, G-02)pi-legal-litigation /workspace/pi-for-legal/lg/requests/<3.x ref>/case first action shows Under review (not In progress); Open case -> Case opened; Record judgment -> Judgement; Appeal -> Case opened; Close asks outcome, amounts and closing note; only the GC sees Reopen on Closed (completed) |
| Desc: Table D , Generation path (G1-G8, Withdrawn, Converted) | Draft -> Generated (generate succeeds) / deleted; Generated -> With counterparty / Awaiting approval / Awaiting signature (resend) / Returned (new version) / Converted / Withdrawn; With counterparty (requester) -> Returned on upload, reminder every 3 days; Returned: locked sections compared with v01 , no change -> Awaiting approval or Awaiting signature, change -> Converted, comparison fails twice -> Comparison failed; Comparison failed -> Returned on new file / Converted (Send to legal), reminder every 3 days; Awaiting approval -> Awaiting signature / Generated; Awaiting signature -> Completed / Generated (declined or expired); Completed -> Closed (confirm or 5 bd); Closed final; Withdrawn any time before Completed; Converted continues as 1.1 with same reference and history. | Implemented | packages/shared/src/legalModules.ts:845 GENERATION_TRANSITIONS rows 846-862 map G1-G8 plus Withdraw; lgCanMove refuses Withdraw from COMPLETED on this path (line 889)apps/api/src/lg/services/lg-generation.ts:209 draft deleted (G1); line 436 generate -> GENERATED; line 465 Sent to counterparty (requester) -> WITH_COUNTERPARTYapps/api/src/lg/services/lg-generation.ts:546 uploadReturnedVersion -> RETURNED (also from RETURNED for a newer version), compares locked sections: CHANGED -> convertToContractReview, FAILED -> COMPARISON_FAILEDapps/api/src/lg/services/lg-compare.ts:261 compareAndRecord retries once on a system error (attempts<2) before reporting FAILED , the 'fails twice' rule is applied inside one uploadapps/api/src/lg/services/lg-approvals.ts:369 generation: approved -> AWAITING_SIGNATURE, rejected/returned -> GENERATEDapps/api/src/lg/services/lg-esign.ts:309 declined/expired on a generation request -> GENERATED with an eventapps/api/src/lg/services/lg-generation-timers.ts:22 With counterparty and Comparison failed reminders every 3 days; Completed -> Closed after 5 bd | generation.test.ts no change to locked sections then Returned, ready for approval or signaturegeneration.test.ts a tracked change in a locked section converts to a Contract review with the same referencegeneration.test.ts an unreadable scan fails the comparison; Send to legal converts with a reasongeneration.test.ts reminds the requester every 3 days while with the counterpartysignature.test.ts a generated contract goes to approval or signature only after a clean comparison; redlines stay with legal (F-12, F-02)pi-legal-requester /workspace/pi-for-legal/lg/requests/<generated ref>/generation Generated -> 'Sent to counterparty' -> upload their version -> Returned with the comparison report; a changed locked clause flips the request to 1.1 Contract review with the same reference |
| Desc: Table E , Register statuses | Legal entity: Under formation -> Active -> Under liquidation -> Dissolved, flag 'Licence expired'. POA: Pending execution -> Active -> Expired / Revoked / Cancelled / Superseded. Contract: Active -> Expired / Terminated / Superseded, flag 'Expiring' (within 90 days). IP: Filed -> Published -> Opposed -> Registered -> Expired; also Abandoned, Cancelled; flag 'Renewal due'. Register records are never deleted, and every status change is logged. POA has no distinct 'Cancelled' status (merged into REVOKED, labelled 'Revoked / Cancelled'). The status sequences are vocabularies, not enforced transitions: a register PATCH may set any listed status in any order (e.g. Dissolved -> Active). Never-deleted and change logging are in place. Configurable in Legal settings Settings: register status labels are vocabularies; the "Revoked / Cancelled" label can be split without a release only as wording. | Minor difference | packages/shared/src/legalModules.ts:1013 LG_ENTITY_STATUSES, LG_POA_STATUSES (PENDING_EXECUTION, ACTIVE, EXPIRED, REVOKED, SUPERSEDED , REVOKED labelled 'Revoked / Cancelled'), LG_CONTRACT_STATUSES, LG_IP_STATUSES (7 incl. ABANDONED, CANCELLED)apps/api/src/lg/services/lg-registers.ts:53 licenceExpired flag; line 70 contract expiring <= 90 days; line 85-87 IP renewalDueapps/api/src/lg/routes/registers.ts:319 DELETE on any register -> 405 + DELETE_BLOCKED audit rowapps/api/src/lg/routes/registers.ts:453 PATCH on entities/POAs/contracts/IP audits every changed field incl. status via lgAuditDiff; revoke/supersede/opposition changes audited explicitly (lines 640, 663; lg-contracts-register.ts 154, 166; lg-ip.ts 38) | config.test.ts a renewal supersedes the old POA only when it becomes Activeconfig.test.ts expires on the expiry date; external attorneys get the alertspi-legal-gc /workspace/pi-for-legal/lg/registers/poas status picker shows Pending execution / Active / Expired / Revoked / Superseded (no separate Cancelled); Delete is absent / refused; History panel logs each status change |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | POST /requests/bf64aefd-6617-4647-8fc7-82a98883e54a/status{"to": "CLOSED"} | 409 | A request can't move from In progress to Closed expected: 4xx: move AssignedthenClosed is not in the table |
| counsel | POST /requests/4829be56-c4d6-457d-9595-578cc3448193/status{"to": "ON_HOLD"} | 400 | A reason is required for this change expected: 4xx: reason + resume date mandatory for On hold |
| counsel | POST /requests/4829be56-c4d6-457d-9595-578cc3448193/status{"to": "COMPLETED"} | 409 | Write a final reply to the requester first. It's saved in the thread and emailed expected: 4xx: completion requires a final reply (and decided red lines, no open consults) |
| lit | POST /requests/07da3720-1f46-4704-9fec-9a76bd9f1fe9/status{"to": "CANCELLED_BY_LEGAL", "reason": "test"} | 400 | to: Unknown status expected: 4xx: a dispute with a case opened cannot be cancelled by legal |
| req | POST /requests/bf64aefd-6617-4647-8fc7-82a98883e54a/withdraw | 400 | reason: Required expected: 400: reason required |
| counsel | POST /requests/c5c89df3-063e-48f6-aaa4-3b8a9ad2efaf/reopen | 400 | reason: Required expected: 400: reason required |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given Arabic support = Yes, then only Arabic-speaking lawyers in the queue are considered, then same counterparty, then fewest open requests. | Implemented | apps/api/src/lg/services/lg-routing.ts:80 candidates = queue members, not OOO, not excluded; if r.arabic filter arabicSpeaker (line 81); then same counterparty among candidates (85-97); then fewest open incl. consults (99-101) | core.test.ts confidential then GC; Arabic then Arabic speakers; same counterparty first; out of office skippedpi-legal-requester /workspace/pi-for-legal/lg/new submit a request with 'Do you need support in Arabic?' = Yes in the Commercial queue; the confirmation / Overview shows the assigned lawyer is an Arabic speaker (Legal settings > People shows the Arabic flag); History reason 'Fewest open requests in the queue' or 'Handled <counterparty> before' |
| AC2 | Given Arabic support = No, then the request goes to the lawyer who handled the same counterparty, otherwise to the lawyer with the fewest open requests. | Implemented | apps/api/src/lg/services/lg-routing.ts:85 prior request with same counterpartyName (case-insensitive) assigned to a candidate -> SAME_COUNTERPARTY; else FEWEST_OPEN by openCountsForapps/api/src/lg/services/lg-routing.ts:40 openCountsFor counts open requests + open consults per lawyer | core.test.ts confidential then GC; Arabic then Arabic speakers; same counterparty first; out of office skippedpi-legal-requester /workspace/pi-for-legal/lg/new submit two 1.1 requests naming the same counterparty; the second lands on the same lawyer and History shows 'SAME_COUNTERPARTY: Handled <name> before.' |
| AC3 | Given a lawyer is out of office (toggle or Outlook), then they aren't assigned new requests. | Implemented | apps/api/src/lg/middleware/lg-auth.ts:153 isOutOfOffice: outlookAutoReply flag OR oooOn within oooFrom/oooUntil (UAE day)apps/api/src/lg/services/lg-routing.ts:80 OOO profiles filtered out of candidates; team lead also skipped when OOO (line 106)apps/api/src/lg/services/integrations/directory.ts:1 Graph directory sync sets outlookAutoReply from Outlook automatic replies when LG_DIRECTORY_SYNC=1; the admin People section toggles it for demo | core.test.ts confidential then GC; Arabic then Arabic speakers; same counterparty first; out of office skippedintegrations.test.ts roles, queues and profile follow Entra groups and Microsoft 365; Outlook automatic replies mark out of officepi-legal-counsel /workspace/pi-for-legal/lg/profile switch Out of office on; a new Commercial request submitted by Jerees is assigned to another Commercial lawyer (Work page > My queue shows the OOO badge) |
| AC4 | Given no lawyer meets the rules, then the request goes to the queue's team lead, or to the GC if the team lead is also out. | Implemented | apps/api/src/lg/services/lg-routing.ts:104 no candidate -> queue.teamLeadUserId if not OOO (TEAM_LEAD) else GC (GC_FALLBACK) | no automated test pi-legal-gc /workspace/pi-for-legal/lg/requests/<ref>/history with every Commercial lawyer out of office, a new request's history reads 'TEAM_LEAD: No lawyer met the rules…'; with the lead out too, 'GC_FALLBACK: …went to the GC' |
| AC5 | Given a confidential request, then it's assigned to the GC. If the GC is out of office, it's flagged on the GC's dashboard. | Implemented | apps/api/src/lg/services/lg-routing.ts:70 confidential -> GC always (even OOO), gcOutOfOffice reportedapps/api/src/lg/services/lg-routing.ts:184 assignedWhileGcOoo stamped on the request; SLA applied regardless (applySla line 187)apps/api/src/lg/services/lg-dashboard.ts:496 GC view: confidentialWhileGcOoo count + rows, gcOutOfOfficeNowapps/web/src/lg/pages/LgDashboardPage.tsx:252 'Confidential while GC away' metric with warning toneapps/web/src/lg/request/tabs/LgOverviewTab.tsx:59 banner 'The GC is out of office … the SLA keeps running' on the request | core.test.ts confidential then GC; Arabic then Arabic speakers; same counterparty first; out of office skippeddashboard.test.ts confidential requests routed while the GC was away are counted from the routing stamp (G-20)pi-legal-gc /workspace/pi-for-legal/lg/dashboard with the GC out of office (Profile) and a confidential request submitted, the GC dashboard shows 'Confidential while GC away: 1' and the request's assigned lawyer is the GC |
| AC6 | Given a request with the same counterparty and a similar description or type as an earlier one, then the lawyer sees a "possibly similar" flag and can link the requests or cancel the new one as a duplicate. | Implemented | apps/api/src/lg/services/lg-routing.ts:146 findSimilar: same counterparty (case-insensitive) and same type or >=40% word overlap of title+description -> possibleDuplicateOfId set at routing (line 183)apps/api/src/lg/routes/requests.ts:459 POST /:id/link links both ways; POST /:id/duplicate links and cancels as 'Duplicate of <ref>'; /similar/dismissapps/web/src/lg/request/tabs/LgOverviewTab.tsx:111 'Possibly similar to <ref>' card with Open / Link them / Cancel as duplicate / Not similar | requests.test.ts links similar requests and cancels a duplicatepi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview a second 1.1 request for the same counterparty shows the 'Possibly similar to LGL-…' card; 'Cancel as duplicate' sets Cancelled by legal with reason 'Duplicate of LGL-…' |
| AC7 | Given a team lead or the GC reassigns a request, then a reason is required and logged. | Implemented | apps/api/src/lg/routes/requests.ts:301 POST /:id/reassign: canReassign (lead or GC), reason min(1); team leads limited to their own queue (400)apps/api/src/lg/services/lg-routing.ts:201 reassign(): reason required, REASSIGN audit row with old/new lawyer + reason, ASSIGNED emails; assignedAt preserved | requests.test.ts team lead reassigns within the queue with a reason; others cannotpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview Reassign dialog (Shikha is Commercial team lead): Reason mandatory; History tab shows the REASSIGN row with the reason |
| AC8 | Given a lawyer reclassifies a request into another queue, then it moves and is reassigned, the reason is logged, the new type's SLA counts from the original assignment date, and ageing still counts from the original submission. | Implemented | apps/api/src/lg/services/lg-routing.ts:221 reclassify(): reason required; type/category/queue/path updated; audit EDIT typeCode; applySla on the request's frozen calendar; decideAssignment + reassign when the queue changes (273-276)apps/api/src/lg/services/lg-sla.ts:42 applySla computes slaDueAt from r.assignedAt (never reset by reassign/reclassify)apps/api/src/lg/services/lg-sla.ts:83 ageingFor walks the status ledger from the first event; total from submittedAt , unaffected by reclassificationapps/api/src/lg/routes/requests.ts:333 only the assigned lawyer or the GC may reclassify (403) | requests.test.ts reclassifying into another queue moves and reassigns; SLA from the original assignmentconfig.test.ts A-3: a reclassify into Contracts uses the frozen ref format, and recomputes the SLA on the submit-time calendarlifecycle-gaps.test.ts reclassifying a request out of a category status is refused; moving into Contracts allocates a contract referencepi-legal-counsel /workspace/pi-for-legal/lg/requests/<1.1 ref>/overview Change request type -> 2.2 NOC with a reason: queue becomes Corporate, a Corporate lawyer is assigned, SLA due date = original assignment + 5 bd, 'Age since submission' unchanged |
| AC9 | Given Arabic support set automatically (Arabic document at intake, or a converted Arabic generated contract), then the request routes to Arabic-speaking lawyers only. | Implemented | apps/api/src/lg/services/lg-intake.ts:652 Arabic detected in an intake document -> arabic:true, arabicAuto:true (requester can't clear it, line 503)apps/api/src/lg/services/lg-generation.ts:486 AR-language generated contract converts with arabic:true, arabicAuto:true before routeAndAssignapps/api/src/lg/services/lg-routing.ts:81 r.arabic (whatever its origin) restricts candidates to arabicSpeakerapps/api/src/lg/routes/requests.ts:524 only the GC or the assigned lawyer can clear Arabic support | requests.test.ts only GC or the assigned lawyer clear Arabic supportpi-legal-requester /workspace/pi-for-legal/lg/new upload an Arabic PDF during intake: the Arabic question is forced to Yes ('We found Arabic in one of your documents'); after submit the assigned lawyer is an Arabic speaker |
| Desc: Reassignment , team leads within their queue, the GC any request | Reassignment. Team leads can reassign within their queue. The GC can reassign any request. A reason is required. The GC cannot reassign a confidential request (deliberate, to keep R-19 confidentiality; must untick Confidential first). Not recorded in DESIGN.md's decisions list. | Minor difference | apps/api/src/lg/routes/requests.ts:309 confidential request: reassign refused for everyone incl. the GC (409 'A confidential request stays with the GC')apps/api/src/lg/routes/requests.ts:311 team lead target must be a member or lead of the request's queue; GC unrestricted otherwise | lifecycle-gaps.test.ts a confidential request stays with the GC; its SLA escalation never reaches the team leadAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<confidential id>/reassign { "toUserId": "<lawyer>", "reason": "cover" } 409 (by design: R-19 confidential handling); the same call on a non-confidential request returns 200 |
| As | Call | HTTP | Response |
|---|---|---|---|
| gc | POST /requests/4829be56-c4d6-457d-9595-578cc3448193/reassign{"toUserId": "00000000-0000-0000-0000-000000000000"} | 400 | reason: Required expected: 400: reason required |
| counsel | POST /requests/4829be56-c4d6-457d-9595-578cc3448193/reclassify{"typeCode": "6.1"} | 400 | reason: Required expected: 400: reason required |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given the primary lawyer adds a consult, then the consulted lawyer is notified and can see the request while the consult is open. | Implemented | apps/api/src/lg/services/lg-consults.ts:68 CONSULT_ADDED email to the assignee with the due dateapps/api/src/lg/services/lg-access.ts:92 isConsult = assignee of an OPEN consult -> canView + canSeeInternal; list visibility via consults.some(status OPEN) (line 167)apps/api/src/lg/routes/consults.ts:61 GET /consults/mine lists the consulted lawyer's open consultsapps/web/src/lg/request/tabs/LgConsultsTab.tsx:105 Add consult dialog (category, colleague, due date, question) | thread.test.ts validates assignee queue and due date; the consulted lawyer sees the request only while open; completion waitspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/consults add a Corporate consult; the Outbox (Mailbox page) shows CONSULT_ADDED to the colleague; signed in as that colleague the request appears under Work > Consults |
| AC2 | Given a consult due date later than the request's SLA date, then the system blocks it. | Implemented | apps/api/src/lg/services/lg-consults.ts:51 due > startOfDay(slaDueAt) -> 400 'The consult must be due by the request's SLA date'apps/api/src/lg/services/lg-routing.ts:263 after reclassification open consults later than the new SLA date are pulled inapps/web/src/lg/request/tabs/LgConsultsTab.tsx:158 date input max = SLA date | thread.test.ts validates assignee queue and due date; the consulted lawyer sees the request only while open; completion waitsAPI POST /api/workspace/pi-for-legal/portal/lg/consults/<id> { "category": "CORPORATE", "assigneeId": "<corp lawyer>", "dueDate": "<slaDueAt + 1 day>", "question": "q" } 400 'The consult must be due by the request's SLA date (…)' |
| AC3 | Given any consult is still open, when the primary lawyer tries to complete the request, then completion is blocked. | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:212 assertCompletable: openConsults > 0 -> 'Close every open consult before completing the request'apps/api/src/lg/services/lg-lifecycle.ts:274 assertRedLinesDecided also blocks sending for signature while a consult is open (signing completes the request) | thread.test.ts validates assignee queue and due date; the consulted lawyer sees the request only while open; completion waitscore.test.ts refuses signature while a consult is open or a red line is undecided (signing completes the request)API POST /api/workspace/pi-for-legal/portal/lg/thread/<id>/reply { "body": "Done", "tag": "FINAL_REPLY", "complete": true } with an open consult 409 'Close every open consult before completing the request' and no final reply posted |
| AC4 | Given the consult is closed, then the consulted lawyer can no longer see the request. | Implemented | apps/api/src/lg/services/lg-access.ts:69 openConsultAssigneeIds built only from status OPEN consults; closed consults give no access (404 on the request) | thread.test.ts on a confidential request only the GC adds consultsAPI GET /api/workspace/pi-for-legal/portal/lg/requests/<id> after closing the consult on a Commercial request 404 (200 while the consult was open) |
| AC5 | Given a confidential request, then only the GC can add consults. | Implemented | apps/api/src/lg/routes/consults.ts:103 confidential && !isGc -> 403; canAdd in GET mirrors it (line 83) | thread.test.ts on a confidential request only the GC adds consultspi-legal-gc /workspace/pi-for-legal/lg/requests/<confidential ref>/consults the Consult button is shown for the GC only (confidential requests are assigned to the GC, so no other lawyer even opens the tab) |
| AC6 | Given a consulted lawyer closes a consult, then a written reply is required and saved in the thread as an internal note, not visible to the requester. | Implemented | apps/api/src/lg/services/lg-consults.ts:82 empty reply -> 400; postThreadEntry kind CONSULT_REPLY internal:true with consultId; consult CLOSEDapps/api/src/lg/routes/thread.ts:114 GET thread filters internal entries unless canSeeInternal (requester never sees them)apps/web/src/lg/request/tabs/LgConsultsTab.tsx:47 'Reply and close' refuses an empty reply | thread.test.ts validates assignee queue and due date; the consulted lawyer sees the request only while open; completion waitspi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/thread after the colleague closes the consult, the lawyer's thread shows 'Consult reply · legal only'; the requester's thread view does not contain it |
| AC7 | Given workload reporting, then open consults count towards the consulted lawyer's workload, and the request counts once under its primary type. | Implemented | apps/api/src/lg/services/lg-routing.ts:48 openCountsFor adds OPEN consults per assignee (also used for fewest-open routing)apps/api/src/lg/services/lg-dashboard.ts:334 team lead workload: consults per lawyer counted separately; line 81 lawyer view includes consults; the request itself remains one row under its category/typeCodeapps/api/src/lg/services/lg-requests.ts:1 GET /requests/workload per-lawyer open + consults | dashboard.test.ts lawyers see their open, overdue and waiting work, consults and hearingsrequests.test.ts team leads see queue workload; lawyers cannotpi-legal-counsel /workspace/pi-for-legal/lg/work?scope=queue the per-lawyer workload panel shows 'open' and 'consults' columns; the consulted lawyer's consult count rises by one while the request stays counted once under Contracts |
| Desc: Secondary streams , the assigned lawyer or the GC can add other categories | Secondary streams: the assigned lawyer or the GC can add other categories to a request. A consult is a linked task on the same request, with its own assignee, a due date, and its own comments and documents. | Implemented | apps/api/src/lg/routes/consults.ts:119 POST /consults/:id/streams and DELETE …/streams/:category (assigned lawyer or GC; removal refused while a consult on that area is open)apps/api/src/lg/services/lg-consults.ts:61 adding a consult also records the secondary categoryapps/api/src/lg/routes/consults.ts:29 serialize returns each consult's own comments (INTERNAL_NOTE with consultId) and documents (consultId)apps/api/src/lg/routes/thread.ts:230 notes with consultId allowed for the consulted lawyer / primary / GC while open | lifecycle-gaps.test.ts only the assigned lawyer or the GC adds consults and streams; consults carry their own comments and documentspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/consults 'Also involves' bar lets the assigned lawyer add Data protection/Corporate etc.; each consult card has its own comments and documents |
| Desc: Consult replies from Outlook land as internal notes | The consulted lawyer gives their input as internal notes in the request thread, in the LMS or from Outlook. Closing a consult requires a written reply. | Implemented | apps/api/src/lg/services/lg-mailbox.ts:286 an email by reference from a legal member sent only to legal colleagues is captured as INTERNAL_NOTEapps/api/src/lg/services/lg-consults.ts:77 closing still requires the written reply in the LMS | mailbox.test.ts lawyer email to the requester is a reply; to legal colleagues only it is an internal notepi-legal-gc /workspace/pi-for-legal/lg/mailbox simulate an email from the consulted lawyer to the primary lawyer with the LGL reference in the subject: it appears in the thread as an Internal note (not attached to the consult card) |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | POST /consults/4829be56-c4d6-457d-9595-578cc3448193{"category": "EMPLOYMENT", "assigneeId": "00000000-0000-0000-0000-000000000000", "dueDate": "2030-01-01", "question": "test"} | 400 | Consults on Employment go to a lawyer in the Employment queue expected: 400: due date later than the SLA date is blocked |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a lawyer's first action on a request, then they're prompted to link or create a SharePoint folder, and the request can't move past In progress (or Under review) until they do. | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:97 moveStatus refuses any move from IN_PROGRESS/UNDER_REVIEW on a non-generation request without sharepointFolderUrl, except Awaiting requester / On hold / Withdrawn / Cancelled (lines 97-101); same gate on the final-reply path at 233-235apps/api/src/lg/services/lg-requests.ts:432 flags.needsFolder = canAct && no folder && not generation && not terminal/draft/submittedapps/web/src/lg/components/requests/FolderCard.tsx:38 banner on every tab + auto-opened Link-a-folder dialog once per session when needsFolder (lines 19-48, 68-72)apps/api/src/lg/routes/requests.ts:395 POST /requests/:id/sharepoint (mode new|existing) also calls ensureStarted (line 439) | core.test.ts records who, when and why; enforces the folder and final-reply gatesrequests.test.ts suggests a folder; linking moves intake documentsAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<id-in-progress-no-folder>/status body {"to":"WITH_COUNTERPARTY"} 409 'Link a SharePoint folder to this request first'; in the UI the request page shows the blue 'Link a SharePoint folder' banner and opens the dialog on first visit |
| AC3 | Given any document saved through the system, then its name follows the convention and users can't change it. | Implemented | apps/api/src/lg/services/lg-documents.ts:177 storeDocument builds fileName with lgFileName(pattern from the GC's namingConvention setting, date=day saved, entity short name, counterparty, docType from the GC list, version, initials); the client's name is kept only as originalNamepackages/shared/src/legalModules.ts:1060 lgFileName / lgCleanNamePart strip spaces and special characters, keep letters incl. Arabicapps/api/src/lg/routes/documents.ts:202 PUT/PATCH/DELETE /documents/:requestId/:documentId then 405 'Documents can't be renamed, replaced or deleted'apps/api/src/lg/routes/registers.ts:207 register documents (entity/POA/contract/IP) are also named by the convention via nameParts (entity short name, contract counterparty, uploader initials)apps/web/src/lg/components/admin/ConfigSections.tsx:304 GC edits the convention pattern in Legal settings › Naming & documents | documents.test.ts names by convention, versions per type, detects Arabic, stores on SharePoint when a folder is linkedadmin.test.ts previews the naming convention and contract referenceAPI PATCH /api/workspace/pi-for-legal/portal/lg/documents/<requestId>/<documentId> body {"fileName":"x.docx"} 405; and an upload of 'Our draft.docx' (POST /lg/documents/<requestId>) returns fileName like 20261124EPGLGulfFreightServicesLLCContractv01_SK.docx |
| AC4 | Given a new version is uploaded, then it's saved as the next version, earlier versions are kept, and the signed copy is marked EXECUTED. | Implemented | apps/api/src/lg/services/lg-documents.ts:148 nextVersion: versionNo = last+1 per request+docType; label vNN, or FINAL/EXECUTED when passed (never overwrites , a new LgDocument row each time)apps/api/src/lg/routes/documents.ts:139 versionLabel FINAL|EXECUTED accepted on upload, legal only (155)apps/api/src/lg/services/lg-esign.ts:250 storeExecuted stores the signed copy (and certificate) with versionLabel EXECUTEDapps/web/src/lg/request/tabs/LgDocumentsTab.tsx:61 grouped by type, newest first, 'Show N earlier versions'; FINAL/EXECUTED badges (23-24) | documents.test.ts names by convention, versions per type, detects Arabic, stores on SharePoint when a folder is linkedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/documents upload the same type twice then v01 then v02 both listed; 'Mark as FINAL' upload then FINAL badge; after the DocuSign simulate 'signed' the executed copy and certificate carry EXECUTED |
| AC5 | Given a self-service generated contract, then the generated file isn't stored, and returned versions and executed copies are stored in the system only. | Implemented | apps/api/src/lg/services/lg-generation.ts:425 generateContract saves only LgGeneration (template version + answers + fileName); no LgDocument row for v01apps/api/src/lg/services/lg-generation.ts:450 download re-renders v01 from template version + answers (buildV01); line 538: 'v01 is the generated file (not stored), so stored returns start at v02'apps/api/src/lg/services/lg-documents.ts:113 namePartsFor: path GENERATION then folderUrl null then storage SYSTEM, initials SSapps/api/src/lg/routes/requests.ts:405 folder link refused for GENERATION requests (409) until they convert | documents.test.ts no counterparty then Internal; self-service files are SS and stay in the systempi-legal-requester /workspace/pi-for-legal/lg/requests/<generated-ref>/documents no v01 row after Generate (download comes from the Generation tab); the uploaded returned version is v02 with _SS and a hard-drive (LMS) icon; no Link-a-folder prompt |
| AC7 | Given a Contracts and Letters request is submitted, then it gets a unique contract reference number in the GC's format. | Implemented | apps/api/src/lg/services/lg-intake.ts:719 submitDraft: category CONTRACTS without contractRef then nextContractRef(entity short name, now, snapshot contractRefFormat)apps/api/src/lg/services/lg-refs.ts:127 nextContractRef: GC format ({entity}-CTR-{year}-{seq4} default), LgCounter compare-and-set so references are unique; LgContract.contractRef is @uniqueapps/api/src/lg/services/lg-generation.ts:399 generated contracts get the reference at generation time (1.0 rule)apps/web/src/lg/components/admin/ConfigSections.tsx:340 GC sets contractRefFormat in Naming & documents | lifecycle-gaps.test.ts reclassifying a request out of a category status is refused; moving into Contracts allocates a contract referenceadmin.test.ts previews the naming convention and contract referencepi-legal-requester /workspace/pi-for-legal/lg/new submit a 1.1 Contract review then confirmation card and Overview show a contract reference like EPGL-CTR-2026-0003 |
| AC8 | Given a request with no counterparty, then the file name holds the authority, the court or 'Internal'. | Implemented | apps/api/src/lg/services/lg-documents.ts:111 counterparty = counterpartyName ?? answers.counterpartyName ?? answers.authority ?? answers.issuer ?? courtName(answers) ?? 'MoHRE' for 4.2 ?? 'Internal'apps/api/src/lg/services/lg-documents.ts:126 courtName strips the case number from a 'court and case number' answer | documents.test.ts no counterparty then Internal; self-service files are SS and stay in the systempi-legal-counsel /workspace/pi-for-legal/lg/requests/<internal-advice-ref>/documents a file uploaded on a request with no counterparty is named …<Entity>Internal<Type>v01_<initials>; a Disputes request names the court instead |
| AC10 | Given an attachment to a reply or a captured email, then it's saved to the request's folder and renamed, and the original email is saved as an email file. The 'email file' is reconstructed from the parsed headers and text body (plain-text .eml); the original message (raw MIME/HTML, inline images, .msg) is not preserved. | Minor difference | apps/api/src/lg/routes/thread.ts:63 reply/note attachments go through storeDocument (convention name; SHAREPOINT when a folder is linked, else held)apps/api/src/lg/services/lg-mailbox.ts:94 toEml builds a .eml from From/To/Cc/Subject/Date + plain-text body; stored as docType Correspondence, isEmailFile (lines 114-131, 254, 311)apps/api/src/lg/services/integrations/graph-mail.ts:119 live capture fetches body as text + attachments separately; the raw MIME ($value) is never fetched | mailbox.test.ts a requester email added to a draft keeps its .eml dated when it was sent; a held email added later keeps its sent timepi-legal-counsel /workspace/pi-for-legal/lg/mailbox simulate an email carrying [LGL-xxxxxx] with an attachment then the request's Documents tab shows the attachment renamed by the convention plus a '<subject>.eml' Correspondence file |
| AC11 | Given a search, then matching requests and documents are returned, within the user's access rights (R-19). | Implemented | apps/api/src/lg/routes/documents.ts:47 GET /documents/search: visibleRequestWhere(actor) + filters (lawyer, entity, bu, type, docType, from/to, q over fileName/originalName/reference/contractRef/counterparty/title); internal-only attachments and non-approved versions hidden (89-107)apps/api/src/lg/services/lg-requests.ts:205 request list search: reference, contractRef, title, counterparty, entity, BU, type, lawyer/requester name, datesapps/web/src/lg/pages/LgDocumentsSearchPage.tsx:32 /lg/documents page with docType, entity, BU, lawyer, date filters | documents.test.ts search returns only documents on requests the user can seelifecycle-gaps.test.ts search hides internal-only attachments from a lawyer who is only the requester on a confidential requestpi-legal-requester /workspace/pi-for-legal/lg/documents?q=Gulf only documents on own/cc requests appear; the same search as pi-legal-counsel returns the Commercial queue's documents too; a confidential request's files never show to the requester's colleagues |
| Desc: Intake documents are held in the system until the folder is linked | Intake documents are held in the system until the folder is linked, then move to the folder automatically. | Implemented | apps/api/src/lg/services/lg-documents.ts:180 storage = SYSTEM when the request has no folderUrl; SHAREPOINT otherwiseapps/web/src/lg/request/tabs/LgDocumentsTab.tsx:84 'Held in the LMS until a SharePoint folder is linked on the Overview tab; they move there automatically.' | lifecycle-gaps.test.ts linking the folder renames held documents with the assigned lawyer's initialspi-legal-counsel /workspace/pi-for-legal/lg/requests/<new-assigned-ref>/documents intake uploads show the hard-drive icon and the 'Held in the LMS' note until the folder is linked |
| Desc: Naming parts , date saved, entity short name, GC document type list, lawyer initials from profile / SS | Date: the day the version is saved. Entity: the short name from R-03. Document type: from the GC's list. Lawyer initials: from the lawyer's profile (R-01). 'SS' for self-service files. | Implemented | apps/api/src/lg/services/lg-documents.ts:134 uaeNow() = save day on the UAE calendar; renameForFolder keeps each document's original createdAt date (line 260)apps/api/src/lg/services/lg-documents.ts:105 entity.shortName and LgProfile.initials of the assigned lawyer; SS only for path GENERATION (119); empty until a lawyer is assigned, fixed on folder linkapps/api/src/lg/services/lg-documents.ts:140 assertDocumentType refuses a type not on the GC's documentTypes setting (used by documents.ts:161, thread.ts:64) | lifecycle-gaps.test.ts document types come from the GC's list; approvers see only the document under approvalAPI POST /api/workspace/pi-for-legal/portal/lg/documents/<requestId> body {file:{...}, docType:"Napkin"} 400 '"Napkin" isn't on the document type list. Pick one from the list' |
| Desc: Search by reference, contract reference, counterparty, entity, business unit, type, lawyer and date | Search. By reference, contract reference, counterparty, entity, business unit, type, lawyer and date. | Implemented | apps/api/src/lg/services/lg-requests.ts:205 listWhere: from/to on createdAt; q matches reference, contractRef, title, counterpartyName, entity (EN/AR/short), BU name, type name/code, lawyer or requester name; explicit lawyer/entity/bu/type filters aboveapps/web/src/lg/pages/LgWorkPage.tsx:1 Work page search + filter chips | requests.test.ts scopes lists and never shows confidential requests to people without accesspi-legal-counsel /workspace/pi-for-legal/lg/work?q=EPGL-CTR typing a contract reference, a counterparty or a lawyer's name narrows the list; date filters apply |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | GET /admin/naming-preview?requestId=9d9eeddd-9579-4c3c-bcdd-0b5ad6d385c1&documentType=Contract&version=2 | 200 | {"fileName": "202611247XGulfFreightServicesLLCContractv02_SK.docx", "arabicFileName": "202611247X\u0634\u0631\u0643\u0629\u0627\u0644\u062e\u0644\u064a\u062c\u0 expected: 200: convention name, not user-editable |
| counsel | GET /documents/search?q=Arabian | 200 | data returned expected: 200 within access rights |
| req | GET /documents/search?q=Falcon | 200 | data returned expected: 200, only own requests (confidential Falcon not returned) |
| counsel | DELETE /documents/9d9eeddd-9579-4c3c-bcdd-0b5ad6d385c1/00000000-0000-0000-0000-000000000000 | 405 | Documents can't be renamed, replaced or deleted. Upload a new version instead expected: 405: versions never overwritten/deleted |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a request is assigned, then its SLA due date is set from its type's SLA in business days, skipping weekends and GC-set public holidays. | Implemented | apps/api/src/lg/services/lg-routing.ts:187 routeAndAssign -> applySla after assignedAt is setapps/api/src/lg/services/lg-sla.ts:42 applySla: slaDays from the type (DB row, else shared default) and slaDueAt = addBusinessDays(assignedAt, days, calendar)apps/api/src/lg/services/lg-calendar.ts:16 calendar = workingDays setting + LgHoliday rows; isBusinessDay skips both (UAE day) | core.test.ts assigns, sets the SLA and moves to Assignedcore.test.ts skips weekends and holidayspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview SLA row shows '<due date> · 5 bd' for a 1.1 assigned on a Thursday -> due the following Thursday (weekend skipped; add a holiday in Settings > SLAs & holidays before submitting and the due date moves) |
| AC2 | Given a request is urgent or auto-urgent, then the urgent SLA (2 days) applies. | Implemented | apps/api/src/lg/services/lg-sla.ts:30 urgent || autoUrgent -> getUrgentSlaDays() (setting, default LG_URGENT_SLA_DAYS = 2)packages/shared/src/legalModules.ts:648 LG_URGENT_SLA_DAYS = 2; LG_AUTO_URGENT_WINDOW = 10 business days (line 681) | config.test.ts urgent and tender-scope SLAs and the reminder timings come from settingspi-legal-requester /workspace/pi-for-legal/lg/new answer 'Is this urgent?' = Yes (or a needed-by date within 10 business days): after submission the Overview SLA shows 2 bd |
| AC3 | Given a request is waiting on someone outside legal, then the SLA clock keeps running and the time is recorded in the matching ageing bucket. | Implemented | apps/api/src/lg/services/lg-sla.ts:64 slaState only compares slaMetAt/now against slaDueAt , no pause anywhere; slaDueAt is never pushed by a waiting statusapps/api/src/lg/services/lg-sla.ts:94 ageingFor assigns each ledger interval to lgAgeingBucket(toStatus)apps/web/src/lg/components/requests/AgeingBar.tsx:1 stacked bar of business days per bucket next to the SLA badge on the Overview | lifecycle-gaps.test.ts ageing stops at close and is recorded; rounds record how they ended and are reportedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview send the request back, wait a business day: SLA badge still counts down / turns Breached, and the ageing bar shows days under 'With requester' |
| AC4 | Given a self-service generated contract, then no SLA applies. If it converts, the Contract review SLA starts at assignment. | Implemented | apps/api/src/lg/services/lg-sla.ts:29 path GENERATION -> null SLApackages/shared/src/legalModules.ts:224 type 1.0 slaDays: null, selfServiceapps/api/src/lg/services/lg-generation.ts:499 conversion -> routeAndAssign sets assignedAt now and applySla with the 1.1 SLA (5 bd) | generation.test.ts a tracked change in a locked section converts to a Contract review with the same referencepi-legal-requester /workspace/pi-for-legal/lg/requests/<generated ref>/overview no SLA row while Generated; after 'Ask legal for help' the SLA row shows 5 bd from the assignment time |
| AC5 | Given a dispute, then the SLA is met by the lawyer's first reply tagged "Response". | Implemented | apps/api/src/lg/services/lg-thread.ts:113 REPLY tagged RESPONSE -> recordResponse(sentAt) regardless of pathapps/api/src/lg/services/lg-sla.ts:54 recordResponse sets slaMetAt once (or earlier if a captured reply was sent before) | thread.test.ts a Response starts work, meets the SLA and is emailed to requester and copypi-legal-litigation /workspace/pi-for-legal/lg/requests/<3.x ref>/thread post a Reply ticked 'Response': the Overview shows 'First response <time>' and the SLA badge reads Met |
| AC6 | Given a request is overdue, then the lawyer is alerted every 3 business days, and the lawyer and team lead at 5 business days past due. | Implemented | apps/api/src/lg/services/lg-request-timers.ts:125 overdue = slaDueAt < now, slaMetAt null, open: first SLA_BREACHED to the lawyer, repeat every slaOverdueEvery (3 bd), lawyer + team lead at slaEscalateTeamLead (5 bd); confidential never reaches the leadpackages/shared/src/legalModules.ts:1139 slaOverdueEvery: 3, slaEscalateTeamLead: 5 (GC-editable) | timers.test.ts alerts the lawyer on breach, every 3 business days, and the team lead at 5 past duelifecycle-gaps.test.ts a confidential request stays with the GC; its SLA escalation never reaches the team leadAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run { "now": "<slaDueAt + 6 business days>" } 200; Mailbox > Outbox shows SLA_BREACHED to the lawyer, then to lawyer + Commercial team lead ('Team lead informed') |
| AC7 | Given a request is closed or withdrawn, then its total time and time per ageing bucket, including any open send-back round, are recorded. | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:156 leaving a waiting status closes the open LgRound with businessDays and an outcome (ANSWERED / WITHDRAWN / CANCELLED / ON_HOLD …)apps/api/src/lg/services/lg-lifecycle.ts:171 terminal move -> snapshotAgeing (total, draftDays, buckets, rounds frozen in ageingSnapshot)apps/api/src/lg/services/lg-sla.ts:91 ageingFor caps 'now' at closedAt; open rounds count their open time | lifecycle-gaps.test.ts ageing stops at close and is recorded; rounds record how they ended and are reportedAPI GET /api/workspace/pi-for-legal/portal/lg/requests/rounds 200 with rounds incl. outcome WITHDRAWN and businessDays for a request withdrawn mid send-back; GET /requests/<id> ageing.total frozen |
| AC8 | Given the GC changes an SLA, then it applies only to new requests. | Implemented | apps/api/src/lg/services/lg-sla.ts:47 slaDays/slaDueAt are written onto the request at assignment (and reclassification) and never recomputed from the type afterwards; editing LgRequestType.slaDays touches no requestapps/api/src/lg/services/lg-admin.ts:5 admin header: changes apply to new requests only; SLA per type edited at line 209apps/api/src/lg/services/lg-calendar.ts:31 working week/holidays frozen per request in settingsSnapshot (requestCalendar) | config.test.ts A-3: a reclassify into Contracts uses the frozen ref format, and recomputes the SLA on the submit-time calendarpi-legal-gc /workspace/pi-for-legal/lg/admin/types change 1.1's SLA to 3: an existing assigned 1.1 keeps its 5 bd due date on the Overview; a newly submitted 1.1 shows 3 bd |
| AC9 | Given the lawyer's first reply tagged "Response", sent from the LMS or captured from Outlook, then the SLA is met at the time it was sent. | Implemented | apps/api/src/lg/services/lg-thread.ts:113 LMS reply tagged RESPONSE -> recordResponse(sentAt)apps/api/src/lg/routes/thread.ts:500 tagging a captured EMAIL reply as RESPONSE -> recordResponse(entry.sentAt) (the email's sent time, lg-mailbox sentTime)apps/api/src/lg/services/lg-sla.ts:56 an earlier-sent reply tagged later moves slaMetAt back to its sentAt | thread.test.ts the lawyer tags an untagged captured reply once; tagging Response meets the SLAthread.test.ts a Response starts work, meets the SLA and is emailed to requester and copypi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread a captured Outlook reply shows 'Tag as Response'; after tagging, Overview 'First response' equals the email's sent time, not the tagging time |
| AC10 | Given only internal notes, send-backs or feedback requests, then the SLA isn't met. | Implemented | apps/api/src/lg/services/lg-thread.ts:113 recordResponse only for kind REPLY && tag RESPONSE; notes, SEND_BACK, FEEDBACK_REQUEST, untagged replies and FINAL_REPLY don't count | thread.test.ts send back reopens only the ticked answers; a requester reply moves it back and closes the roundpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread post an internal note and a send-back: the Overview still shows no 'First response' and the SLA badge keeps counting |
| Desc: Default SLA table (business days) | Urgent 2; 1.0 none unless it converts; 1.1 5; 1.2 5; 1.3 5; 1.4 3; 1.5 full pack 7 / draft contract only 5 / deviations 5 / bonds 3 (longest selected); 1.6 5; 2.x 5; 3.1 2; 3.2-3.4 5; 4.2 2; 4.1, 4.3-4.5 5; 5.x 5; 6.1 5. | Implemented | packages/shared/src/legalModules.ts:224 LG_REQUEST_TYPES slaDays checked type by type: 1.0 null; 1.1/1.2/1.3 5; 1.4 3; 1.5 7; 1.6 5; 2.1-2.8 5; 3.1 2; 3.2/3.3/3.4 5; 4.1 5; 4.2 2; 4.3/4.4/4.5 5; 5.1-5.4 5; 6.1 5 , all matchpackages/shared/src/legalModules.ts:648 LG_URGENT_SLA_DAYS 2; LG_TENDER_SCOPE_SLA Full pack 7 / Draft contract only 5 / Deviations and clarifications 5 / Bonds and declarations 3 , keys equal the 1.5 'reviewScope' options (line 313)apps/api/src/lg/services/lg-sla.ts:31 1.5: max over the selected reviewScope values (longest selected applies); otherwise the type's slaDays from the DB row (GC-editable) or the shared default | config.test.ts urgent and tender-scope SLAs and the reminder timings come from settingscore.test.ts assigns, sets the SLA and moves to Assignedpi-legal-gc /workspace/pi-for-legal/lg/admin/types the SLA column reads 5/5/5/3/7/5 for 1.1-1.6, 2 for 3.1 and 4.2, 5 elsewhere, none for 1.0; Settings > SLAs shows Urgent 2 and the four tender scopes 7/5/5/3 |
| Desc: Ageing bucket table | With legal: Submitted, Assigned, In progress, Under review. With requester: Draft (separately), Awaiting requester, Completed, Generated, Comparison failed. With business: Awaiting business feedback, Awaiting HR feedback, Submitted to business. With counterparty: With counterparty. With approvers: Awaiting approval. With signatories: Awaiting signature, Awaiting signature / notarization. With third parties: With authority, With external counsel, With IP agent / office, Case opened, Judgement, Execution. On hold: On hold. Not counted: Closed, Closed (completed), Withdrawn, Cancelled by legal. | Implemented | packages/shared/src/legalModules.ts:928 LG_AGEING_BUCKETS: LEGAL 4 statuses ✓, REQUESTER 5 ✓ (Draft included), BUSINESS 3 ✓, COUNTERPARTY ✓, APPROVERS ✓, SIGNATORIES 2 ✓, THIRD_PARTIES 6 ✓, ON_HOLD ✓, NOT_COUNTED 4 ✓ plus SENT and RETURNED which the PRD table omitsapps/api/src/lg/services/lg-sla.ts:99 ageingFor: DRAFT time reported separately as draftDays; RETURNED is re-routed to the REQUESTER bucket (line 100); SENT time is dropped (NOT_COUNTED zeroed at line 103) | lifecycle-gaps.test.ts ageing stops at close and is recorded; rounds record how they ended and are reportedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview the ageing bar legend lists With legal / With requester / With business / With counterparty / With approvers / With signatories / With third parties / On hold; a request that sat Awaiting approval shows days under 'With approvers' |
| Desc: SLA runs from assignment to the first reply tagged Response; the clock never pauses | The SLA runs from assignment to the lawyer's first reply tagged 'Response'. The time sent is used. The clock never pauses. Time waiting on others is measured separately (ageing) and shown next to the SLA result. | Implemented | apps/api/src/lg/services/lg-sla.ts:42 due from assignedAt; met at slaMetAt (sentAt of the Response); no code path pauses or extends slaDueAtapps/api/src/lg/services/lg-requests.ts:131 detail returns sla {days, dueAt, metAt, state} and ageing side by sideapps/web/src/lg/request/tabs/LgOverviewTab.tsx:134 SLA badge + 'First response' + AgeingBar on the same card | thread.test.ts a Response starts work, meets the SLA and is emailed to requester and copypi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview SLA badge (On track / Due soon / Breached / Met) with the ageing bar directly beneath |
| Desc: Self-service ageing reported separately | Self-service ageing (generated contracts) is reported separately from legal ageing. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:362 selfServiceAgeing computed over open GENERATION requests, separate from 'ageing'apps/web/src/lg/pages/LgDashboardPage.tsx:189 panel 'Self-service generated contracts … kept apart from legal ageing' | dashboard.test.ts the GC sees the metrics; filters change thempi-legal-gc /workspace/pi-for-legal/lg/dashboard two ageing panels: 'Ageing by bucket' (legal) and 'Self-service generated contracts' |
| Desc: GC sees all breaches on the dashboard; reminders to requesters/business/HR every 3 days | The GC sees all breaches on the dashboard (R-30). Requesters, business and HR are reminded every 3 days while a request waits on them. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:325 GC gets every queue's workload incl. the 'breached' list (line 357, listable = everything for the GC) plus sla.breached / openBreached counts (216-223)apps/web/src/lg/pages/LgDashboardPage.tsx:232 'Overdue' rows across queues; 'Overdue now' metric (line 415)apps/api/src/lg/services/lg-request-timers.ts:56 SENT_BACK reminder to requester + cc every waitingReminderDays (3 calendar days) for Awaiting requester / business / HR / Submitted to business | timers.test.ts awaiting requester: reminders, final warning at 12 business days, withdrawn at 15; feedback never withdrawndashboard.test.ts the GC sees the metrics; filters change thempi-legal-gc /workspace/pi-for-legal/lg/dashboard 'Overdue now' tile and the Overdue list across all queues incl. confidential |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | GET /requests/LGL-000547 | 200 | data returned expected: 200: sla.dueAt, urgent, ageing buckets on the request |
| gc | GET /admin/settings | 200 | data returned expected: 200 settings incl. sla, urgentSla, reminders, retention |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given any request, then all lawyer replies, requester replies and internal notes appear in one thread, in date order, with author, recipients, time sent, attachments and source (LMS or email). | Implemented | apps/api/src/lg/routes/thread.ts:113 GET /thread/:id: all LgThreadEntry for the request ordered by sentAt asc (internal filtered for non-legal)apps/api/src/lg/services/lg-thread.ts:84 each entry stores kind, tag, author (id/name/email), recipients, body, source (LMS/EMAIL/UPLOAD/SYSTEM), documentIds, sentAtapps/web/src/lg/components/thread/ThreadEntryRow.tsx:79 row shows author, recipients, time, tag, attachments, source badges | thread.test.ts send back reopens only the ticked answers; a requester reply moves it back and closes the roundpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread one timeline mixing replies, send-backs, requester replies, internal notes; each shows 'To: …', the sent time and an Email/Uploaded badge where applicable |
| AC2 | Given a lawyer posts a reply in the LMS, then it's saved in the thread and emailed to the requester and people in copy. | Implemented | apps/api/src/lg/services/lg-thread.ts:119 source LMS, kind REPLY -> lgEmail LAWYER_REPLY / FINAL_REPLY to businessRecipients (requester + cc) with attachments | thread.test.ts a Response starts work, meets the SLA and is emailed to requester and copypi-legal-counsel /workspace/pi-for-legal/lg/mailbox after posting a reply, Outbox lists LAWYER_REPLY to the requester and everyone in copy with the reference in the subject |
| AC3 | Given a lawyer replies from Outlook, then the reply is captured into the thread (R-06). | Needs the M365 tenant | apps/api/src/lg/services/lg-mailbox.ts:286 inbound email by reference from a legal member -> REPLY (to the business) or INTERNAL_NOTE (legal only), source EMAIL, sentAt = email sent time; lawyer prompted to tagapps/api/src/lg/routes/hooks.ts:77 real adapter: Graph change-notification webhook POST /:slug/hooks/lg/graph (validation handshake, client-state secret) when MS_GRAPH_* + LG_PUBLIC_API_URL are setapps/api/src/lg/routes/mailbox.ts:55 simulator: POST /lg/mailbox/inbound (legal-only; refused in production unless LG_SIMULATORS=1) and the Mailbox page composer | mailbox.test.ts lawyer email to the requester is a reply; to legal colleagues only it is an internal noteintegrations.test.ts answers the validation handshake, refuses a wrong client state, captures once per messagepi-legal-counsel /workspace/pi-for-legal/lg/mailbox 'Simulate an email' from shikha@7x.ae to the requester with the LGL reference in the subject: the thread gains a Reply with the Email badge and a 'Tag as Response' prompt |
| AC4 | Given an internal note, then only legal can see it and it isn't emailed outside legal. | Implemented | apps/api/src/lg/services/lg-thread.ts:119 emails only when !internal; INTERNAL_NOTE / CONSULT_REPLY always internalapps/api/src/lg/routes/thread.ts:114 internal entries excluded unless canSeeInternal; note writing limited by canWriteNote (lawyer on it, consulted lawyer, team lead, GC) | thread.test.ts notes are legal-only and never emailedthread.test.ts confidential: other lawyers get 404; the GC notes; the requester sees replies onlypi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/thread the note the lawyer wrote is absent from the requester's thread; Outbox has no email for it |
| AC5 | Given a reply tagged "Response", then the first one meets the SLA. Given a reply tagged "Final reply", then the request can be completed. | Implemented | apps/api/src/lg/services/lg-thread.ts:113 RESPONSE -> recordResponse (first only, via updateMany slaMetAt null)apps/api/src/lg/services/lg-lifecycle.ts:213 completion gate looks for a FINAL_REPLY entry since the last reopenapps/web/src/lg/components/thread/ThreadComposer.tsx:94 composer modes Reply (tick Response) and Final reply (with 'and complete') | thread.test.ts a final reply can complete the request in one steprequests.test.ts complete needs a final reply; requester confirms or reopenspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread?compose=final Final reply mode with the 'Complete the request' option; Complete from the Overview works only once a Final reply exists |
| AC6 | Given any thread entry, then it can't be edited or deleted once sent. | Implemented | apps/api/src/lg/routes/thread.ts:507 PUT/PATCH/DELETE /entries/:id -> 405; the only PATCH is …/tag, which adds a tag to an untagged captured EMAIL reply once (line 496-498)apps/web/src/lg/components/thread/ThreadEntryRow.tsx:1 no edit/delete controls in the UI | thread.test.ts other lawyers view but cannot reply; nobody edits or deletesAPI DELETE /api/workspace/pi-for-legal/portal/lg/thread/<id>/entries/<entryId> 405 'Thread entries can't be edited or deleted once sent' |
| AC7 | Given a lawyer uploads an outside communication, then it's added to the thread marked "Uploaded". | Implemented | apps/api/src/lg/routes/thread.ts:255 POST /thread/:id/upload stores the file (.msg/.eml flagged isEmailFile) and posts kind UPLOADED, source UPLOAD, optional sentAtapps/web/src/lg/components/thread/ThreadEntryRow.tsx:76 'Uploaded' badge | thread.test.ts uploads an outside communication marked Uploadedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread composer mode 'Upload a communication' with a .eml file: a thread entry with the Uploaded badge and the file attached |
| AC8 | Given a lawyer sends a request back, then it moves to Awaiting requester, and only the ticked answers can be edited. | Implemented | apps/api/src/lg/services/lg-thread.ts:168 pauseForBusiness SEND_BACK: validates fieldsToCorrect against the script, moveStatus AWAITING_REQUESTER, LgRound created, editableAnswerKeys = ticked fieldsapps/api/src/lg/routes/requests.ts:553 PATCH /:id/answers lets the requester change only editableAnswerKeys while Awaiting requesterapps/api/src/lg/services/lg-thread.ts:141 editableAnswerKeys cleared on the replyapps/web/src/lg/components/thread/ThreadComposer.tsx:107 Send back mode with the tick list of intake answers | thread.test.ts send back reopens only the ticked answers; a requester reply moves it back and closes the roundrequests.test.ts requester corrects only the re-opened answers while awaiting thempi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/overview after the lawyer sends back ticking 'Contract value', only that answer shows an Edit control in the answers summary; status Awaiting requester |
| AC9 | Given the requester or a person in copy replies, in the LMS or by email, then the reply is logged under their name and the request returns to In progress (or Under review). | Implemented | apps/api/src/lg/routes/thread.ts:202 POST /business-reply allowed for canReplyAsBusiness (requester or cc); author = actorapps/api/src/lg/services/lg-thread.ts:139 REQUESTER_REPLY in a WAITING status -> workingStatus (IN_PROGRESS / UNDER_REVIEW) by system, lawyer emailedapps/api/src/lg/services/lg-mailbox.ts:293 email from the requester/cc by reference -> REQUESTER_REPLY under the sender's name | thread.test.ts send back reopens only the ticked answers; a requester reply moves it back and closes the roundmailbox.test.ts requester reply on Awaiting requester is captured and moves it back to In progresspi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/thread reply as a person in copy: the entry is under their name and the status flips back to In progress (Under review on a dispute) |
| AC10 | Given a request waits on the requester, business or HR, then reminders go every 3 days to the requester and people in copy. | Implemented | apps/api/src/lg/services/lg-request-timers.ts:91 SENT_BACK reminder to requester + cc every waitingReminderDays (3) for AWAITING_REQUESTER / AWAITING_BUSINESS_FEEDBACK / AWAITING_HR_FEEDBACK (and Submitted to business), marker lastReminderAt | timers.test.ts awaiting requester: reminders, final warning at 12 business days, withdrawn at 15; feedback never withdrawnAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run { "now": "<statusChangedAt + 3 days>" } 200; Outbox shows a SENT_BACK reminder to the requester and cc, none on a second run the same day |
| AC11 | Given 12 business days in Awaiting requester with no reply, then a final warning is sent. At 15 business days, the request is withdrawn with the reason "No response". | Implemented | apps/api/src/lg/services/lg-request-timers.ts:73 final warning at awaitingRequesterFinalWarning (12 bd, marker finalWarningAt); withdraw 'No response' at 15 bd only after the warning went outpackages/shared/src/legalModules.ts:1134 defaults 12 / 15 business days (GC-editable) | timers.test.ts awaiting requester: reminders, final warning at 12 business days, withdrawn at 15; feedback never withdrawnAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run twice: now = sent-back date + 12 bd, then + 15 bd first run: SENT_BACK 'Final warning' email; second: status WITHDRAWN, ledger reason 'No response' |
| AC12 | Given an auto-withdrawn request, when the requester replies within 10 business days, in the LMS or by email, then it reopens in In progress with the same reference. | Implemented | apps/api/src/lg/services/lg-thread.ts:144 WITHDRAWN + withdrawnNoResponse + reply within reopenAfterNoResponse bd of closedAt -> working status; LMS and email replies share postThreadEntryapps/api/src/lg/routes/thread.ts:320 canReplyAsBusiness is not blocked on WITHDRAWN (only DRAFT) | thread.test.ts a "No response" withdrawal reopens when the requester replies within 10 business dayspi-legal-requester /workspace/pi-for-legal/lg/requests/<auto-withdrawn ref>/thread the reply box is still available; sending a reply flips the status to In progress, same reference, History shows WITHDRAWN -> IN_PROGRESS 'Requester replied after "No response"' |
| AC13 | Given Awaiting business feedback or Awaiting HR feedback, then the request is never withdrawn automatically. | Implemented | apps/api/src/lg/services/lg-request-timers.ts:73 final warning / auto-withdraw branch runs only when status === 'AWAITING_REQUESTER'; feedback statuses get reminders only | timers.test.ts awaiting requester: reminders, final warning at 12 business days, withdrawn at 15; feedback never withdrawnAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run { "now": "<feedback date + 40 days>" } 200; the request stays AWAITING_BUSINESS_FEEDBACK (reminders only) |
| AC14 | Given any round, then the dates sent and answered and the business days are recorded and reported in R-17. | Implemented | apps/api/src/lg/services/lg-thread.ts:188 LgRound created per send-back / feedback request (sentAt)apps/api/src/lg/services/lg-lifecycle.ts:156 answeredAt, businessDays and outcome written when the waiting status endsapps/api/src/lg/routes/requests.ts:120 GET /requests/rounds (+ ?format=xlsx): every round with averages by kind, GC / team lead scopedapps/web/src/lg/components/requests/AgeingBar.tsx:20 rounds listed under the ageing bar (Sent back / Business feedback / HR feedback, dates, business days) | lifecycle-gaps.test.ts ageing stops at close and is recorded; rounds record how they ended and are reportedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview under the ageing bar: 'Sent back · <date> -> <date> · N business days' per round; GC dashboard export has the rounds sheet |
| Desc: Entry table , who writes what, from where, who sees it | Reply (lawyer; LMS or Outlook captured; everyone who can see the request). Send-back question / feedback request (lawyer; LMS; everyone). Requester reply (requester or person in copy; LMS or email; everyone). Internal note (lawyer, consulted lawyer, team lead or GC; LMS or Outlook to legal colleagues only; legal only, never emailed outside legal). | Implemented | packages/shared/src/legalModules.ts:947 LG_THREAD_KINDS: REPLY, SEND_BACK, FEEDBACK_REQUEST, REQUESTER_REPLY, INTERNAL_NOTE, CONSULT_REPLY, UPLOADED, EVENTapps/api/src/lg/routes/thread.ts:99 canWriteNote: lawyer on it (canAct), team lead, GC, open-consult assignee; reply requires requireAct; business-reply requires canReplyAsBusinessapps/api/src/lg/services/lg-mailbox.ts:286 Outlook capture: legal sender to business -> REPLY; legal-only recipients -> INTERNAL_NOTE; requester/cc -> REQUESTER_REPLY | thread.test.ts notes are legal-only and never emailedmailbox.test.ts lawyer email to the requester is a reply; to legal colleagues only it is an internal notepi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread composer tabs: Reply / Final reply / Send back / Ask for feedback / Internal note / Upload; as requester only 'Reply' is offered |
| Desc: Ask for feedback moves to Awaiting business / HR feedback; no limit on rounds; corrected answers only in the LMS | Ask for feedback: legal has given its view and needs a business or HR decision -> Awaiting business feedback or Awaiting HR feedback. Corrected intake answers can only be made in the LMS. There's no limit on rounds. | Implemented | apps/api/src/lg/routes/thread.ts:185 POST /feedback { kind: BUSINESS|HR } (HR default for Employment) -> pauseForBusiness -> AWAITING_BUSINESS_FEEDBACK / AWAITING_HR_FEEDBACK + roundapps/api/src/lg/services/lg-thread.ts:188 a new LgRound per request; no counter or capapps/api/src/lg/routes/requests.ts:553 answers are corrected only via PATCH /requests/:id/answers (LMS); email replies land in the thread only | thread.test.ts employment feedback goes to HR; outsiders and lawyers cannot answer as the businesspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread 'Ask for feedback' -> status Awaiting business feedback; repeat send-back / feedback several times , each creates a new round on the Overview |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | DELETE /thread/9d9eeddd-9579-4c3c-bcdd-0b5ad6d385c1/entries/00000000-0000-0000-0000-000000000000 | 405 | Thread entries can't be edited or deleted once sent expected: 405/403: thread entries cannot be edited or deleted |
| gc | PATCH /thread/9d9eeddd-9579-4c3c-bcdd-0b5ad6d385c1/entries/00000000-0000-0000-0000-000000000000{"text": "x"} | 405 | Thread entries can't be edited or deleted once sent expected: 405/403 |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a business user, then they see only requests they raised or are in copy on. | Implemented | apps/api/src/lg/services/lg-access.ts:156 visibleRequestWhere: non-lawyer then requesterId = me OR cc.some(me) (non-draft) , applied on every list/search (lg-requests.ts line 185)apps/api/src/lg/services/lg-access.ts:109 requestAccess: requester/cc get view + reply; anyone else NONE then loadRequestForActor answers 404apps/api/src/lg/routes/requests.ts:52 Every per-request route goes through loadRequestForActor; scope=all is 403 for non-legal (requests.test) | requests.test.ts scopes lists and never shows confidential requests to people without accesscore.test.ts confidential requests are invisible to other lawyers, team leads and ITpi-legal-requester /workspace/pi-for-legal/lg/my Only Jerees's own requests (and those he is in copy on); opening another reference by URL (/lg/requests/LGL-000002) shows 'Request not found'. |
| AC2 | Given a non-confidential request, then every lawyer can view it, but only the assigned lawyer, the queue's team lead and the GC can act on it. | Implemented | apps/api/src/lg/services/lg-access.ts:133 Lawyers: canView true; canAct = assigned || leads the queue; canReassign = leads; GC canAct (line 102)apps/api/src/lg/services/lg-access.ts:201 requireAct then 403 'Only the assigned lawyer, the queue's team lead or the GC can do that'apps/api/src/lg/routes/thread.ts:120 canReply = access.canAct; canWriteNote needs canAct/GC/open consult (line 100) | core.test.ts confidential requests are invisible to other lawyers, team leads and ITthread.test.ts other lawyers view but cannot reply; nobody edits or deletesrequests.test.ts team lead reassigns within the queue with a reason; others cannotAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<Commercial reference>/status {"to":"ON_HOLD","reason":"x","resumeDate":"2026-12-01"} 403 for Khalifa (Disputes lead, not this queue) while GET of the request is 200; the same call as pi-legal-counsel (Commercial lead) is 200. |
| AC3 | Given a confidential request, then only the GC, the requester, people in copy, GC-added consults and approvers for their step can see it. It doesn't appear in anyone else's search or lists. | Implemented | apps/api/src/lg/services/lg-access.ts:118 Confidential branch: consult (open) / requester / cc / activated approver only; every other lawyer, team lead and IT admin then NONEapps/api/src/lg/services/lg-access.ts:162 visibleRequestWhere for lawyers: confidential:false unless requester/cc/open consult , search and lists never return itapps/api/src/lg/services/lg-dashboard.ts:324 Team lead dashboard counts confidentialOpen, never lists (listable() line 248)apps/api/src/lg/services/lg-notify.ts:181 Emails about confidential requests carry 'Confidential request' + reference + link only, no attachmentsapps/api/src/lg/routes/requests.ts:308 Reassigning a confidential request is refused: it stays with the GC | requests.test.ts scopes lists and never shows confidential requests to people without accessthread.test.ts confidential: other lawyers get 404; the GC notes; the requester sees replies onlydashboard.test.ts team leads count confidential requests but never list themapprovals.test.ts approvers see the request and the version under approval; outsiders don'tpi-legal-counsel /workspace/pi-for-legal/lg/work?scope=all&q=<confidential title word> Shikha's Work page and search never list the confidential request (seeded confidential employment matter); the same URL as pi-legal-gc shows it; the team-lead dashboard shows 'Confidential: 1' with no row. |
| AC4 | Given a confidential request after submission, then only the GC can change the people in copy. | Implemented | apps/api/src/lg/services/lg-access.ts:113 canManageCc for the requester only when !confidential; lawyers never reach the lawyer branch on confidential requests; GC always (line 106)apps/api/src/lg/routes/requests.ts:350 POST/DELETE /:id/cc then 403 'Only the GC can change the people in copy on a confidential request'; changes audited as ACCESS | requests.test.ts requester manages copy on non-confidential; only the GC on confidentialAPI POST /api/workspace/pi-for-legal/portal/lg/requests/<confidential reference>/cc {"userId":"<tariq id>"} 403 for the requester of their own confidential request; 200 as pi-legal-gc; the Overview 'People in copy' card hides add/remove for Jerees. |
| AC5 | Given any view, edit, download, upload, status change or access change, then it's logged with who and when, and the log can't be changed. | Implemented | apps/api/src/lg/services/lg-audit.ts:62 lgAudit writes LgAuditEvent (actor, action, entity, field, old/new, createdAt); changes throw if the row can't be written, views are best-effortapps/api/src/lg/services/lg-access.ts:194 loadRequestForActor logs VIEW (one per person per 30 min, lgAuditView) and ACCESS_DENIED for refused opensapps/api/src/lg/routes/documents.ts:191 DOWNLOAD audited; UPLOAD in storeDocument; STATUS in moveStatus (lg-lifecycle); REASSIGN in lg-routing line 209; ACCESS for cc/roles/queue changes (requests.ts 368, lg-admin 348-351, 531)apps/api/prisma/workspace/rls.sql:127 DB trigger lg_audit_event_append_only: UPDATE and DELETE on LgAuditEvent raise insufficient_privilege (only privacy anonymisation of the actor, and VIEW rows older than the ≥7-year retention window, are allowed)apps/web/src/lg/request/tabs/LgHistoryTab.tsx:57 Audit trail table (views toggle) + Export to Excel | nfr.test.ts is append-only in the database; old views age out under retention onlynfr.test.ts records one view per person per half hour, and blocked attemptslifecycle-gaps.test.ts a status move writes its audit row in the same step; opening consults is logged as a viewpi-legal-gc /workspace/pi-for-legal/lg/requests/LGL-000001/history 'Show views' reveals Viewed rows with who/when alongside Status, Uploaded, Downloaded, Assignment and Access rows; no edit/delete control exists. API: no route updates or deletes LgAuditEvent (UPDATE in SQL fails with 'append-only'). |
| AC6 | Given the GC, then they can export the full audit trail for any record. Given a team lead, then only for non-confidential requests in their queue. A register record's full trail is exportable only through Settings › Audit trail (filter Record = Entity/Poa, search the record id); the record detail sheet shows history but has no per-record export button. | Minor difference | apps/api/src/lg/services/lg-admin.ts:560 auditWhere: GC everything; team lead then rows of non-confidential requests in their queues; others 403apps/api/src/lg/services/lg-admin.ts:593 exportAudit then xlsx of every matching row (paged, audited EXPORT); filters entity/action/actor/requestId/q/from/toapps/api/src/lg/routes/requests.ts:641 GET /requests/:id/history/export (xlsx with Status history + Audit trail) for the GC / team lead on non-confidential in-queue requests, else 403apps/web/src/lg/components/admin/AuditSection.tsx:50 Settings › Audit trail: filters + 'Export to Excel'; register records are reachable by Record type + 'Search details' (matches entityId) but there is no export button on a register record's detail sheet | admin.test.ts GC sees everything; team leads only non-confidential requests in their queues; others refusedrequests.test.ts history: GC and team lead see the audit trail; requester sees status onlypi-legal-litigation /workspace/pi-for-legal/lg/admin/audit Khalifa sees only rows linked to Disputes-queue non-confidential requests and can export them; as pi-legal-counsel open a Disputes request's History then no export (403 via API /history/export); as GC everything exports. |
| AC7 | Given an internal note, then the requester, people in copy and approvers can't see it, and on confidential requests only the GC and GC-added consults can. | Implemented | apps/api/src/lg/routes/thread.ts:115 GET /thread/:requestId filters internal entries unless access.canSeeInternal; approvers get 403 on the thread (line 113)apps/api/src/lg/services/lg-access.ts:120 Confidential: canSeeInternal only for the GC and an open consult assignee; requester/cc/approver never get it (canSeeInternal false in business/NONE)apps/api/src/lg/services/lg-thread.ts:48 INTERNAL_NOTE and CONSULT_REPLY are always internal; never emailed (thread.test 'notes are legal-only and never emailed') | thread.test.ts notes are legal-only and never emailedthread.test.ts confidential: other lawyers get 404; the GC notes; the requester sees replies onlypi-legal-requester /workspace/pi-for-legal/lg/requests/LGL-000001/thread Jerees's thread shows replies only , the internal note Shikha posted is absent; as pi-legal-counsel the same thread shows it marked Internal. |
| AC8 | Given a sent reply or note, then no one can edit or delete it. | Implemented | apps/api/src/lg/routes/thread.ts:307 PUT/PATCH/DELETE /:requestId/entries/:entryId then 405 'Thread entries can't be edited or deleted once sent' (only the tag of an untagged captured Outlook reply can be set once, line 289)apps/web/src/lg/request/tabs/LgThreadTab.tsx:1 No edit/delete actions on entries | thread.test.ts other lawyers view but cannot reply; nobody edits or deletesAPI DELETE /api/workspace/pi-for-legal/portal/lg/thread/LGL-000001/entries/<entryId> 405 even for the GC; PATCH with a body is also 405. |
| AC9 | Given an IT administrator, then they can manage settings but can't open request content. IT admin views settings rather than managing them (DESIGN.md decision to confirm with Legal). | By decision | docs/pi-for-legal/DESIGN.md:120 Decision: R-02 says the GC configures, R-19 AC9 says IT 'manage settings' , built per R-02: the GC edits, team leads and the IT admin viewapps/api/src/lg/middleware/lg-auth.ts:95 canViewSettings includes isItAdmin; requireGc on every writeapps/api/src/lg/services/lg-access.ts:156 IT admin is not a lawyer then visibleRequestWhere = own requests/in copy; requestAccess NONE on others; registers 404 (registers.ts 57); mailbox requireLegal (mailbox.ts 53); audit trail 403 (lg-admin 583)apps/api/src/lg/middleware/lg-auth.ts:14 'A workspace owner/admin who is neither GC nor lawyer is NOT given content access by being an admin' | core.test.ts confidential requests are invisible to other lawyers, team leads and ITadmin.test.ts GC edits; team leads and IT admins view; others are refusedregisters.test.ts only the GC creates; lawyers view; business users get 404pi-legal-it-admin /workspace/pi-for-legal/lg/admin Mohammed (workspace owner) opens Legal settings in 'View only' mode with every section visible; /lg/work and /lg/registers/entities are unavailable and /lg/requests/LGL-000001 answers 'Request not found'. |
| Desc: search shows only what the user may see; confidential never appears, not even as a title | Search shows only what the user may see. Confidential requests never appear to people without access, not even as a title. | Implemented | apps/api/src/lg/services/lg-requests.ts:185 Request list/search where starts with visibleRequestWhere(actor)apps/api/src/lg/routes/documents.ts:93 Document search re-checks requestAccess per request and hides internal-only / non-approved filesapps/api/src/lg/services/lg-dashboard.ts:661 Dashboard rows mask counterparty as 'Confidential' outside the GC view; exports show 'Confidential' instead of the title (line 998) | requests.test.ts scopes lists and never shows confidential requests to people without accesslifecycle-gaps.test.ts search hides internal-only attachments from a lawyer who is only the requester on a confidential requestAPI GET /api/workspace/pi-for-legal/portal/lg/requests?scope=all&q=<word from the confidential request title> 200 with an empty array; the same as pi-legal-gc returns the request. |
| Desc: approver views the request and documents for their step; consulted lawyer views while the consult is open; team lead acts/reassigns in their queue | Approver: view the request and documents for their step. Consulted lawyer: view while the consult is open (only the GC adds consults on confidential). Team lead: view; act and reassign in their queue; confidential counted in totals, details hidden. | Implemented | apps/api/src/lg/services/lg-access.ts:71 loadRequestContext: approvers = approvals with activatedAt (their step reached); consults = OPEN onlyapps/api/src/lg/routes/documents.ts:124 approverOnly actors get only approverDocIds (the version under approval); thread 403 for approvers (thread.ts 113)apps/api/src/lg/services/lg-access.ts:135 Team lead: canAct + canReassign when leadQueues includes the request's queueapps/api/src/lg/services/lg-requests.ts:297 Workload per lawyer for team leads (confidential counted, line 319) | approvals.test.ts approvers see the request and the version under approval; outsiders don'tthread.test.ts validates assignee queue and due date; the consulted lawyer sees the request only while open; completion waitsthread.test.ts on a confidential request only the GC adds consultsrequests.test.ts team leads see queue workload; lawyers cannotpi-legal-approver /workspace/pi-for-legal/lg/approvals Tariq opens a pending approval: request summary + the document under approval only; the Thread tab is not offered (API /thread/<ref> then 403). |
| Desc: lawyers see the status history of their own requests; exports to Excel | Lawyers see the status history of their own requests. Exports are to Excel. | Implemented | apps/api/src/lg/routes/requests.ts:603 GET /:id/history: status ledger (LgStatusEvent) for anyone who can view; audit rows only when canAudit (GC / team lead non-confidential in queue)apps/api/src/lg/routes/requests.ts:641 history/export and lg-admin exportAudit write .xlsx via exceljs (formula-safe cells)apps/web/src/lg/request/tabs/LgHistoryTab.tsx:40 Status history timeline for everyone; Audit trail + export only when canExport | requests.test.ts history: GC and team lead see the audit trail; requester sees status onlypi-legal-counsel /workspace/pi-for-legal/lg/requests/<a Disputes reference>/history Shikha (not that queue's lead) sees the Status history timeline but no Audit trail section; on a Commercial request she also gets the Audit trail and 'Export to Excel' (.xlsx). |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | GET /requests/LGL-000005 | 404 | Request not found expected: 404: confidential request not visible to another lawyer (not even as a title) |
| counsel | GET /requests?scope=all&state=all&q=LGL-000005 | 200 | [] expected: 200 with 0 rows |
| it | GET /requests/LGL-000528 | 404 | Request not found expected: 403/404: IT administrator has no content access |
| it | GET /admin/settings | 200 | data returned expected: 200: IT admin can view settings |
| req | GET /requests/LGL-000557 | 404 | Request not found expected: 404: business user sees only own / in-copy requests |
| gc | GET /admin/audit/export?requestId=9d9eeddd-9579-4c3c-bcdd-0b5ad6d385c1 | 200 | {"_raw": "\u2026"} expected: 200 xlsx |
| req | GET /admin/audit/export | 403 | Only the GC and team leads can export the audit trail expected: 403 |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a request type, entity and value, when the lawyer clicks 'Send for approval', then the route is built from the matrix and shown before sending. | Implemented | apps/api/src/lg/services/lg-approvals.ts:67 ruleMatches: active rule by typeCodes, entityIds, min/max value band in AED (FX converted); buildRoute (95-126) merges matching rules' steps in orderapps/api/src/lg/routes/approvals.ts:126 previewView returns rulesMatched, valueAed, valueWarning, steps; GET /approvals/request/:id and POST …/preview (295-303) show it before POST …/start (311-335)apps/web/src/lg/components/approvals/SendForApproval.tsx:26 live preview query re-run when the value or ad-hoc approvers change; 'From the matrix: …' label (88) | approvals.test.ts builds the route from type and value band; ad-hoc approvers are added, never replacing the matrixpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/approvals Send for approval card lists the steps (Head of Commercial; CFO above AED 1m) with 'required' labels and the matched rule names before the Send button is pressed; raising the value above 1,000,000 adds the CFO step |
| AC2 | Given a matrix route, then the lawyer can add approvers but can't remove required ones. | Implemented | apps/api/src/lg/services/lg-approvals.ts:115 matrix approvers are required:true, adHoc:false; extraApproverIds only append a final parallel 'Added by legal' step (118-124) , there is no API to drop a matrix approverapps/api/src/lg/routes/approvals.ts:331 extraApproverIds honoured only when access.canAct (the lawyer), never for the requesterapps/web/src/lg/components/approvals/SendForApproval.tsx:109 remove (X) button rendered only for adHoc approvers; matrix ones show 'required' | approvals.test.ts builds the route from type and value band; ad-hoc approvers are added, never replacing the matrixpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/approvals 'Add approver' appends a person with an X; matrix approvers have no X and read 'required' |
| AC4 | Given a round with a Reject and a Return, then the outcome is Reject. Given only Approves, then the round is approved only when every required approval is in. | Implemented | apps/api/src/lg/services/lg-approvals.ts:355 any REJECTED then finishRound REJECTED; else any RETURNED then RETURNED; else APPROVED only when computeActive().doneapps/api/src/lg/services/lg-approvals.ts:162 computeActive: a group is done when every required approval is APPROVED (ALL) or one is (ANY); sequential groups activate one approver at a time | approvals.test.ts runs steps in order, needs comments to return, and ends approved only when every approval is inAPI POST /api/workspace/pi-for-legal/portal/lg/approvals/<approvalId>/decide body {"decision":"REJECTED","comment":"no"} 200 { roundStatus: 'REJECTED' } even when another parallel approver already returned; GET /lg/approvals/request/<id> shows the round REJECTED |
| AC5 | Given a rejected or returned round, then the request moves to In progress (or Generated), and resubmission starts a new round with all steps restarted. | Implemented | apps/api/src/lg/services/lg-approvals.ts:364 finishRound: GENERATION then GENERATED (or AWAITING_SIGNATURE on approve); lawyer-handled then workingStatus(path) unless approved+needsSignatureapps/api/src/lg/services/lg-approvals.ts:288 startApproval creates round roundNo+1 with the full route and fresh LgApproval rows (all steps restarted); earlier rounds, comments and documentLabel stayapps/web/src/lg/components/approvals/RoundsTimeline.tsx:1 all rounds shown newest first with decisions and comments | approvals.test.ts runs steps in order, needs comments to return, and ends approved only when every approval is inapprovals.test.ts approved then Awaiting signature when it will be signed; the outcome goes to the lawyer handling it nowpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/approvals after a Return the status badge is In progress; 'Send for approval' again creates Round 2 with every step pending; Round 1 remains listed with its comment |
| AC6 | Given an approver is out of office and has a delegate, then the delegate receives the approval and the log shows 'on behalf of'. Without a delegate, the lawyer is alerted. | Implemented | apps/api/src/lg/services/lg-approvals.ts:179 resolveActing: OOO (toggle/dates or outlookAutoReply) then delegate (one extra hop), else outOfOfficeNoDelegateapps/api/src/lg/services/lg-approvals.ts:199 activate emails the delegate (actingUserId) and calls alertApproverAway then APPROVAL_OUTCOME email to the lawyer (231-238)apps/api/src/lg/services/lg-approvals.ts:341 decideApproval records actingUserId and audits 'approved by X on behalf of Y'; GET /approvals/mine lists principals' approvals for the delegate (routes 159-162, 245-263)apps/api/src/lg/services/lg-approvals.ts:434 reminder run re-resolves OOO every tick and alerts the lawyer once when an approver goes away mid-step | approvals.test.ts an out-of-office approver's approval goes to the delegate, logged "on behalf of"; no delegate then lawyer alertedapprovals.test.ts an approver who goes out of office mid-step with no delegate: the lawyer is alerted onceapprovals.test.ts a delegate decides only while the approver is awaypi-legal-approver /workspace/pi-for-legal/lg/profile (set Out of office, delegate Ahmad) then as ahmad@7x.ae /workspace/pi-for-legal/lg/approvals Ahmad sees the approval tagged 'on behalf of Tariq' and can approve; the request History tab logs 'approved by Ahmad … on behalf of Tariq'; with no delegate the counsel's Outbox gets 'waiting on an out-of-office approver' |
| AC7 | Given a pending approval, then the approver is reminded every 2 business days. | Implemented | apps/api/src/lg/services/lg-approvals.ts:424 remindPendingApprovers: for each active approval, due when businessDays(lastReminderAt ?? activatedAt then now) ≥ approvalReminder; emails approver or delegate, stamps lastReminderAtapps/api/src/lg/services/lg-approval-timers.ts:16 wired into runLgTimers (hourly scheduler, lg-jobs.ts:29); LG_TIMERS.approvalReminder = 2 (legalModules.ts:1138), GC-overridable via the escalation setting | approvals.test.ts an out-of-office approver's approval goes to the delegate, logged "on behalf of"; no delegate then lawyer alertedAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run body {"now":"<today + 3 business days>"} 200 with approvalReminders ≥ 1 on the first run and 0 on an immediate rerun; Mailbox › Outbox shows a second APPROVAL_REQUESTED email 'Reminder: approve, return or reject' |
| AC8 | Given an approved round, then the approved document version is recorded with the approval. | Implemented | apps/api/src/lg/services/lg-approvals.ts:278 startApproval stores documentId + documentLabel ('v02 · <file>') on the round (defaults to the latest non-executed version); finishRound audits 'approved version …' (379)apps/api/src/lg/services/lg-esign.ts:152 assertApprovedVersion: only the approved version may be sent for signatureapps/api/src/lg/services/lg-approval-record.ts:75 an approval-record PDF (version, decisions, delegates, comments) is stored on the request when the round endsapps/api/src/lg/routes/approvals.ts:371 GET /approvals/:id/document lets the approver download the exact version under approval | approvals.test.ts runs steps in order, needs comments to return, and ends approved only when every approval is insignature.test.ts only the approved version can be signedv1-gaps.test.ts saves a PDF of the round to the request documents when the round completespi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/approvals the round header shows 'Document: v01 · <file>'; after approval the Documents tab has an 'Approval record round 1' PDF; sending a newer version for signature is refused with 'This version wasn't approved' |
| Desc: Approval matrix , rules by type, entity, value band; steps sequential/parallel, All/Any | The GC sets approval rules by request type, contracting entity and contract value band. Each rule lists its steps. Each step is sequential or parallel, and 'All must approve' or 'Any one'. | Implemented | apps/api/src/lg/routes/approvals.ts:49 ruleSchema/stepSchema (order, mode SEQUENTIAL|PARALLEL, rule ALL|ANY, approverUserIds); CRUD at /approvals/rules GC-only, viewers read (203-242), auditedapps/api/src/lg/services/lg-approvals.ts:60 value bands in AED: 'above' exclusive min, 'up to' inclusive max; unknown value matches every banded rule and the preview warns (routes 134-137)apps/web/src/lg/components/approvals/ApprovalMatrixSection.tsx:1 mounted in Legal settings › Approval matrix | approvals.test.ts only the GC changes it; team leads and IT admins can read itapprovals.test.ts value bands compare in AED across currencies; exactly the minimum is not "above"; a missing value warnspi-legal-gc /workspace/pi-for-legal/lg/admin/approvals rules with type, entity and AED band and steps marked Sequential/Parallel · All/Any; as pi-legal-it-admin the same page is read-only |
| Desc: Contract value is captured at intake or by the lawyer | Contract value is captured at intake or by the lawyer. | Implemented | apps/api/src/lg/routes/approvals.ts:322 POST /start accepts contractValue from the acting lawyer, updates the request and audits the change; preview accepts it too (290-303)apps/web/src/lg/components/approvals/SendForApproval.tsx:20 value input prefilled from the request (intake answer contractValue then request column) | approvals.test.ts value bands compare in AED across currencies; exactly the minimum is not "above"; a missing value warnspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/approvals editing the Contract value field changes the previewed route; the History tab records 'contractValue' edit after sending |
| Desc: Generated contracts , the requester sends for approval using the same matrix | Generated contracts (R-24): the requester sends for approval, using the same matrix. | Implemented | apps/api/src/lg/routes/approvals.ts:76 canStart: the requester of a GENERATION request may start; ad-hoc approvers ignored for them (331)apps/api/src/lg/services/lg-approvals.ts:273 assertGenerationCompared gates on a clean comparison first; status table allows GENERATED/RETURNED then AWAITING_APPROVAL by requester (legalModules.ts:848, 852)apps/api/src/lg/routes/generation.ts:188 POST /generation/:id/approval entry point from the Generation tab | signature.test.ts a generated contract goes to approval or signature only after a clean comparison; redlines stay with legal (F-12, F-02)pi-legal-requester /workspace/pi-for-legal/lg/requests/<generated-ref>/approvals the requester sees the matrix route and a Send for approval button (no 'Add approver'); after the round, outcome email goes to the requester |
| Desc: Out of office , toggle or Outlook automatic reply | While the approver is out of office (toggle or Outlook automatic reply), the approval goes to the delegate. | Needs the M365 tenant | apps/api/src/lg/middleware/lg-auth.ts:153 isOutOfOffice: outlookAutoReply flag OR oooOn within oooFrom/oooUntilapps/api/src/lg/services/integrations/directory.ts:1 REAL: Microsoft 365 directory sync reads automatic replies (LG_DIRECTORY_SYNC=1) and sets outlookAutoReplyapps/web/src/lg/components/admin/OrgSections.tsx:1 SIMULATOR: the Outlook auto-reply flag is editable by the GC in Legal settings › People & roles (DESIGN.md:33) | integrations.test.ts roles, queues and profile follow Entra groups and Microsoft 365; Outlook automatic replies mark out of officepi-legal-gc /workspace/pi-for-legal/lg/admin/people tick 'Outlook automatic reply' on Tariq then a new approval round routes to his delegate without touching his profile toggle |
| Desc: Time waiting is counted under 'With approvers' (R-17) | Time waiting is counted under 'With approvers' (R-17). | Implemented | packages/shared/src/legalModules.ts:933 LG_AGEING_BUCKETS: APPROVERS 'With approvers' = AWAITING_APPROVAL | lifecycle-gaps.test.ts ageing stops at close and is recorded; rounds record how they ended and are reportedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref> Overview ageing bar shows a 'With approvers' segment while the round is open |
| As | Call | HTTP | Response |
|---|---|---|---|
| appr | GET /approvals/mine | 200 | data returned expected: 200 pending approvals for the approver |
| gc | GET /approvals/rules | 200 | data returned expected: 200 approval matrix |
| counsel | GET /approvals/rules | 200 | data returned expected: 200 view |
| counsel | POST /approvals/rules{"name": "x"} | 403 | Only the General Counsel can do that expected: 403 |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given any event in the table, then the listed recipients get an email with the reference, status, action needed and a link. | Implemented | apps/api/src/lg/services/lg-notify.ts:158 lgEmail: subject always carries [reference] (195-198); body card with reference · title, Status, 'Action needed: …' (default 'No action needed, for your information'), 'Open in the LMS' link (200-203); every send recorded in LgOutboundEmail (213-228)packages/shared/src/legalModules.ts:1099 LG_EMAIL_EVENTS mirrors the PRD table (recipients + FYI/Action); every row has a sender , see the per-row entries below | integrations.test.ts keeps the reference in a GC-edited subject, states the action, and lets the requester turn off the FYI "assigned" emailpi-legal-counsel /workspace/pi-for-legal/lg/mailbox?tab=outbox every outbox row: subject '[LGL-…] …', body shows reference · title, Status, Action needed and the 'Open in the LMS' button |
| Desc: table row , Request submitted then Requester, people in copy (FYI) | Request submitted then Requester, people in copy , FYI | Implemented | apps/api/src/lg/services/lg-intake.ts:731 SUBMITTED to [requesterId, ...cc] with queue and expected datepackages/shared/src/legalModules.ts:1127 SUBMITTED is in LG_FYI_EVENTS (opt-out honoured) | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new submit with a person in copy then Outbox (as counsel) shows 'Request received' to both addresses |
| Desc: table row , Request assigned or reassigned then Lawyer (Action); requester (FYI) | Request assigned or reassigned then Lawyer; requester , Action / FYI | Implemented | apps/api/src/lg/services/lg-routing.ts:194 routeAndAssign: ASSIGNED to the lawyer with action 'Review and start work' and to the requester without action (then FYI, lg-notify.ts:81)apps/api/src/lg/services/lg-routing.ts:212 reassign sends the same pair | integrations.test.ts keeps the reference in a GC-edited subject, states the action, and lets the requester turn off the FYI "assigned" emailpi-legal-counsel /workspace/pi-for-legal/lg/mailbox?tab=outbox two 'Assigned' rows per submission: lawyer copy says 'Action needed: Review and start work', requester copy says 'No action needed' |
| Desc: table row , Draft reminder (every 3 days) then Requester | Draft reminder (every 3 days) then Requester , Action | Implemented | apps/api/src/lg/services/lg-request-timers.ts:47 DRAFT_REMINDER to the requester every draftReminderDays (3) from createdAt/lastReminderAt, link to /lg/new/<draft> | timers.test.ts reminds drafts every 3 days, once per windowAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run body {"now":"<today + 4 days>"} 200 draftReminders ≥ 1 when a draft exists; Outbox row 'Your draft request is waiting' |
| Desc: table row , Sent back or feedback requested; reminders every 3 days; final warning then Requester, people in copy | Sent back or feedback requested; reminders every 3 days; final warning (R-18) then Requester, people in copy , Action | Implemented | apps/api/src/lg/services/lg-thread.ts:127 SEND_BACK / FEEDBACK_REQUEST entries email SENT_BACK to requester + cc with the question and attachmentsapps/api/src/lg/services/lg-request-timers.ts:100 waiting reminders every 3 days to requester + cc (status-specific action); final warning at 12 business days (81-89) | thread.test.ts send back reopens only the ticked answers; a requester reply moves it back and closes the roundtimers.test.ts awaiting requester: reminders, final warning at 12 business days, withdrawn at 15; feedback never withdrawnpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread Send back then Outbox 'Action needed' email to requester and cc; POST /lg/jobs/run with now +4 days adds a reminder; +13 business days adds 'Final warning: reply within …' |
| Desc: table row , Lawyer reply (in the LMS), with its text and attachments then Requester, people in copy | Lawyer reply (in the LMS), with its text and attachments then Requester, people in copy , Action | Implemented | apps/api/src/lg/services/lg-thread.ts:120 REPLY from LMS, not internal then LAWYER_REPLY (or FINAL_REPLY) to businessIds with vars.message = body and attachmentDocumentIdsapps/api/src/lg/services/lg-notify.ts:88 loadAttachments attaches the files (≤20 MB total, else linked); none on confidential requests (207) | thread.test.ts a Response starts work, meets the SLA and is emailed to requester and copyintegrations.test.ts sends with Reply-To the legal mailbox and attaches reply documents; confidential gets neither text nor filespi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread post a Response with a file then Outbox row 'Reply from legal' lists the attachment name and the reply text |
| Desc: table row , Requester or person in copy reply (in the LMS or by email) then Lawyer | Requester or person in copy reply (in the LMS or by email) then Lawyer , Action | Implemented | apps/api/src/lg/services/lg-thread.ts:150 REQUESTER_REPLY then email to assignedLawyerId with the text and attachments (both LMS and EMAIL sources pass through postThreadEntry)apps/api/src/lg/services/lg-mailbox.ts:291 a business sender's email with the reference becomes kind REQUESTER_REPLY (304-308) | mailbox.test.ts requester reply on Awaiting requester is captured and moves it back to In progresspi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/thread reply in the thread then the lawyer's Outbox row 'New reply' with action 'Read the reply'; same when the Mailbox simulator sends a reply from the requester's address |
| Desc: table row , Final reply on completion then Requester, people in copy | Final reply on completion then Requester, people in copy , Action | Implemented | apps/api/src/lg/services/lg-thread.ts:122 tag FINAL_REPLY then event FINAL_REPLY 'Read the outcome' to requester + cc; signature completion posts the same tag (lg-esign.ts:440) | thread.test.ts a final reply can complete the request in one steppi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread?compose=final Final reply + Complete then Outbox 'Completed: <title>' to requester and cc, followed by the 'Please confirm' email |
| Desc: table row , Consult added then Consulted lawyer | Consult added then Consulted lawyer , Action | Implemented | apps/api/src/lg/services/lg-consults.ts:68 CONSULT_ADDED to the assignee with the due date and 'Give your input and close the consult' | thread.test.ts validates assignee queue and due date; the consulted lawyer sees the request only while open; completion waitspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/consults add a consult to Khalifa then Outbox 'Your input is needed' addressed to khalifa@7x.ae |
| Desc: table row , Approval requested; reminders every 2 business days then Approver or delegate | Approval requested; reminders every 2 business days then Approver or delegate , Action | Implemented | apps/api/src/lg/services/lg-approvals.ts:207 activate then APPROVAL_REQUESTED to actingUserId ?? approverId with decision buttonsapps/api/src/lg/services/lg-approvals.ts:449 reminders re-send APPROVAL_REQUESTED to the current acting person every 2 business days | approvals.test.ts an out-of-office approver's approval goes to the delegate, logged "on behalf of"; no delegate then lawyer alertedpi-legal-counsel /workspace/pi-for-legal/lg/mailbox?tab=outbox 'Approval requested' to the approver (or the delegate when the approver is out of office) with Approve / Return / Reject buttons |
| Desc: table row , Approval outcome then Lawyer (requester, for generated contracts) | Approval outcome then Lawyer (requester, for generated contracts) , Action | Implemented | apps/api/src/lg/services/lg-approvals.ts:385 finishRound then APPROVAL_OUTCOME to roundOwner (requester for GENERATION, else current assigned lawyer, 225-228) with a next-step action | approvals.test.ts approved then Awaiting signature when it will be signed; the outcome goes to the lawyer handling it nowpi-legal-approver /workspace/pi-for-legal/lg/approvals approve then counsel's Outbox has 'Approval approved: <title>' with 'Send the approved version for signature'; on a generated contract the requester gets it |
| Desc: table row , Signature declined or expired then Sender | Signature declined or expired then Sender , Action | Implemented | apps/api/src/lg/services/lg-esign.ts:312 signatureProblem then SIGNATURE_PROBLEM to env.sentById with outcome + reason | signature.test.ts reminds 7 and 2 days before expiry, then expires and sends the request backpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/approvals Simulate › Declined then Outbox 'Signature declined: <title>' to the person who sent the envelope |
| Desc: table row , Completed (5-day confirmation window) then Requester | Completed (5-day confirmation window) then Requester , Action | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:290 notifyStatus on COMPLETED then COMPLETED email to the requester 'Confirm, or reopen within 5 business days' | no automated test pi-legal-requester /workspace/pi-for-legal/lg/my after legal completes, the Outbox (as counsel) shows 'Please confirm: <title>' to the requester only; the request page offers Confirm / Reopen |
| Desc: table row , Closed, withdrawn or cancelled then Requester, people in copy, lawyer (FYI) | Closed, withdrawn or cancelled then Requester, people in copy, lawyer , FYI | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:292 CLOSED event to requester + cc + assigned lawyer for CLOSED / CLOSED_COMPLETED / WITHDRAWN / CANCELLEDpackages/shared/src/legalModules.ts:1127 CLOSED in LG_FYI_EVENTS | no automated test pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref> Withdraw with a reason then Outbox row '[ref] Withdrawn: <title>' addressed to requester, cc and the lawyer, body 'No action needed' |
| Desc: table row , SLA breached; every 3 business days past due; 5 business days past due then Lawyer; lawyer and team lead | SLA breached; every 3 business days past due; 5 business days past due then Lawyer; lawyer and team lead , Action | Implemented | apps/api/src/lg/services/lg-request-timers.ts:125 SLA_BREACHED to the lawyer on breach, again every slaOverdueEvery (3) business days, and with the queue's team lead at slaEscalateTeamLead (5) , team lead never for confidential | timers.test.ts alerts the lawyer on breach, every 3 business days, and the team lead at 5 past duelifecycle-gaps.test.ts a confidential request stays with the GC; its SLA escalation never reaches the team leadAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run body {"now":"<slaDueAt + 6 business days>"} 200 slaBreaches/teamLeadEscalations ≥ 1; Outbox 'Overdue' emails to the lawyer, the last one also to the team lead with 'Team lead informed' |
| Desc: table row , With counterparty reminder (every 3 days) then Sender | With counterparty reminder (every 3 days) then Sender , Action | Implemented | apps/api/src/lg/services/lg-request-timers.ts:92 COUNTERPARTY_REMINDER every 3 days to the sender: requester (+cc) when counterpartySender = REQUESTER, else the lawyerapps/api/src/lg/services/lg-generation-timers.ts:30 generated contracts: reminder to the requester | timers.test.ts with counterparty reminds the lawyerlifecycle-gaps.test.ts With counterparty records the sender, reminds the requester when they send it, and an upload brings it backAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run body {"now":"<today + 4 days>"} counterpartyReminders ≥ 1 for a request in With counterparty; Outbox 'Still with the counterparty' to whoever sent it |
| Desc: table row , Hearing and deadline reminders (R-28) then Lawyer | Hearing and deadline reminders (R-28) then Lawyer , Action | Implemented | apps/api/src/lg/services/lg-case-reminders.ts:46 HEARING_REMINDER to assignedLawyerId 7 and 1 days before hearings/deadlines (LG_ALERTS.hearing), plus a missing-outcome flag (56-67) | v1-gaps.test.ts flags a hearing with no outcome from the day after, to the case lawyer, onceAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run body {"now":"<hearing date - 1 day>"} Outbox 'Upcoming: Hearing tomorrow …' addressed to the Disputes lawyer (pi-legal-litigation) |
| Desc: table row , Register alerts (licence/registration, POA, contract expiry and notice, IP renewals) then as set in R-03/R-04/R-27/R-29 | Register alerts: licence and registration expiry, POA expiry, contract expiry and notice deadlines, IP renewals then As set in R-03, R-04, R-27 and R-29 , Action | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:44 entities then GC + Corporate queue (79); POAs then attorney (+external email) + Corporate (101-108); contracts then owner + lawyer (158-163); IP then responsible lawyer/IP queue + GC (177-183); all REGISTER_ALERT (Action) | registers.test.ts alerts at 30 days once, and expires automaticallyregisters.test.ts expiry alerts go to the owner and lawyer; the owner can raise a linked 1.3API POST /api/workspace/pi-for-legal/portal/lg/jobs/run body {} 200 with registers counters; Outbox 'Legal register alert: …' rows with links to /lg/registers/<kind>?id=… |
| AC2 | Given a confidential request, then emails show only the reference and a link. | Implemented | apps/api/src/lg/services/lg-notify.ts:190 confidential then subject '[ref] Update on a confidential request', body = reference + 'Open the request' (action buttons are labels only); no attachments (207) | integrations.test.ts sends with Reply-To the legal mailbox and attaches reply documents; confidential gets neither text nor filespi-legal-gc /workspace/pi-for-legal/lg/mailbox?tab=outbox emails of a confidential request show only the reference and the button , no title, status, text or attachment names |
| AC3 | Given a user turns off FYI emails, then they still get all action emails. | Implemented | apps/api/src/lg/services/lg-notify.ts:79 isFyi: explicit fyi, ASSIGNED without action, or SUBMITTED/CLOSED/MONTHLY_REPORT; only then are fyiEmailsOff profiles dropped (164-168) , Action events are never filteredapps/api/src/lg/routes/profile.ts:28 PATCH /profile { fyiEmailsOff }apps/web/src/lg/pages/LgProfilePage.tsx:130 'FYI emails' switch | integrations.test.ts keeps the reference in a GC-edited subject, states the action, and lets the requester turn off the FYI "assigned" emailadmin.test.ts out of office with dates and a delegate; FYI emails offpi-legal-requester /workspace/pi-for-legal/lg/profile switch FYI emails off, submit a request then no 'Request received' in the Outbox for the requester, but the later 'Reply from legal' (Action) still arrives |
| AC4 | Given a lawyer reply in the LMS, then the requester and people in copy get it by email with its text and attachments (only the reference and a link, for confidential requests), and a reply to that email is captured in the thread. | Implemented | apps/api/src/lg/services/lg-thread.ts:120 LAWYER_REPLY with message + attachmentDocumentIds to requester and ccapps/api/src/lg/services/lg-notify.ts:110 Reply-To = legalMailbox setting (Graph and platform transports); subject keeps [reference]apps/api/src/lg/services/lg-mailbox.ts:285 an inbound email to the legal mailbox carrying the reference is captured into the thread (postThreadEntry source EMAIL); Graph webhook hooks.ts:77 or the simulator | integrations.test.ts sends with Reply-To the legal mailbox and attaches reply documents; confidential gets neither text nor filesmailbox.test.ts requester reply on Awaiting requester is captured and moves it back to In progresspi-legal-counsel /workspace/pi-for-legal/lg/mailbox Outbox row shows Reply-To legal@7x.ae and the attachment; 'Simulate an email' from jerees@7x.ae with subject 'Re: [LGL-…]' then captured in that request's thread as the requester's reply |
| AC5 | Given an internal note, then it isn't emailed to the requester or people in copy. | Implemented | apps/api/src/lg/services/lg-thread.ts:119 emails only when source LMS && !internal; INTERNAL_NOTE / CONSULT_REPLY are always internal (48, 65) | thread.test.ts notes are legal-only and never emailedpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/thread post an Internal note then no new Outbox row; the requester's thread view doesn't show the note |
| AC6 | Given the GC edits an email template, then new emails use the updated text. | Implemented | apps/api/src/lg/services/lg-notify.ts:172 lgEmail reads the emailTemplates setting per event at send time; a subject without {reference} is prefixed (198)apps/api/src/lg/services/lg-admin.ts:411 GET/PUT/DELETE /admin/emails/:event + preview, auditedapps/web/src/lg/components/admin/ConfigSections.tsx:355 EmailsSection: per-event subject/body editor with tokens, Preview, Save ('New emails use it'), Reset | admin.test.ts overrides, previews and resets a template; new emails use itpi-legal-gc /workspace/pi-for-legal/lg/admin/emails edit 'Request submitted' subject to '[{reference}] We have it: {title}', save; submit a request as the requester then Outbox subject reads '[LGL-…] We have it: …' |
| Desc: Email only, in English, from a shared mailbox set by the GC | All notifications are sent by email only, in English, from a shared mailbox set by the GC. Locally the From address is the platform sender, not the GC's mailbox. | Needs the M365 tenant | apps/api/src/lg/services/lg-settings.ts:24 senderMailbox setting (GC-editable in Legal settings › Mailbox & uploads)apps/api/src/lg/services/integrations/graph-mail.ts:1 REAL: Microsoft Graph sendMail from the sender mailbox when LG_GRAPH_MAIL=1 (lg-notify.ts:112-129)apps/api/src/lg/services/lg-notify.ts:131 SIMULATOR/fallback: platform mailer sends as '7X Legal <platform address>' (the GC mailbox only with LG_SENDER_VERIFIED=1); workspace mail is held unless WORKSPACE_EMAIL_ENABLED=1 , every message is still recorded in the Outbox | integrations.test.ts goes out from the shared mailbox over Microsoft Graph when livepi-legal-counsel /workspace/pi-for-legal/lg/mailbox?tab=outbox each row shows From (7X Legal <…>), Reply-To legal@7x.ae and transport PLATFORM locally (GRAPH when live) |
| Desc: Every request email carries the reference in the subject and replies go to the legal mailbox | Every email about a request carries the reference in the subject, and replies go to the legal mailbox, so replies by email are captured in the thread (R-06). | Implemented | apps/api/src/lg/services/lg-notify.ts:195 subject = template with {reference}; forced '[ref] ' prefix when a GC wording drops it; confidential subject also carries it (192)apps/api/src/lg/services/lg-notify.ts:110 replyTo = legalMailbox on both transports | integrations.test.ts keeps the reference in a GC-edited subject, states the action, and lets the requester turn off the FYI "assigned" emailpi-legal-counsel /workspace/pi-for-legal/lg/mailbox?tab=outbox every subject starts with [LGL-…]; Reply-To column = the legal mailbox from settings |
| As | Call | HTTP | Response |
|---|---|---|---|
| gc | GET /admin/integrations/outbox | 404 | {"_raw": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /api/workspace/pi-for-le expected: 200 outbound email log |
| gc | GET /admin/emails | 200 | data returned expected: 200 editable wording per event |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Desc: initial contract type list (side / category / type / Ask customs clearance) | Initial list ("asked" = flagged "Ask customs clearance"; "included" = not asked): Supplier Courier/Freight/Logistics/Real estate leasing; Customer General/Courier/Freight/Logistics/Real estate leasing/Manpower; Other MOU/NDA/Collaboration/Partnership | Implemented | packages/shared/src/legalModules.ts:970 LG_DEFAULT_CONTRACT_TYPES: 38 rows; checked row by row against the PRD table , every side/category/type matches and `customs: true` is set exactly on the PRD's "asked" rows (Supplier Courier International + Domestic and international; Supplier Freight Land-international, Land-domestic and international, Air, Sea; Supplier Logistics Warehousing and delivery, Fulfilment…; Customer Courier International + Domestic and international). Customer Freight/Logistics rows are 'included' (no flag), as the PRD says.apps/api/prisma/workspace/seed-pi-for-legal.ts:225 seed creates each default type as an LgContractType row with askCustoms = Boolean(c.customs)apps/api/prisma/schema.prisma:4681 LgContractType { side, category, name, askCustoms, active, sortOrder } @@unique([side, category, name]) | harness.ts harness seeds LG_DEFAULT_CONTRACT_TYPES (line 132)pi-legal-gc /workspace/pi-for-legal/lg/templates?view=types Groups 'We are the supplier · Courier' … 'Other · Partnership'; the Customs switch is on for Supplier Courier International, Air, Sea etc. and off for Customer Freight rows |
| Desc: one shared contract type list across intake, templates and playbooks; a type can exist without a template | One list of contract types is used across intake (R-07), templates and playbooks (R-25). A contract type can exist without a template. Each type sits under a side and a category. | Implemented | apps/api/src/lg/services/lg-intake.ts:145 resolveCtx reads lgContractType by the answered contractTypeId and activeTemplatesFor() for the intake offerapps/api/src/lg/services/lg-playbooks.ts:163 sideFor() derives a playbook's side from the same LgContractType rowapps/api/src/lg/services/lg-templates.ts:340 createTemplate requires an existing LgContractType; types without templates are simply rows with no LgTemplateapps/web/src/lg/components/intake/AnswerInput.tsx:331 intake 'contract_type' composer: side then category then type from /lg/reference contractTypes | templates.test.ts keeps the contract type list, with "Ask customs clearance" (asserts /reference exposes a GC-added type)pi-legal-requester /workspace/pi-for-legal/lg/new Pick a Contracts type: the contract type question offers the same side/category/type list the GC maintains under Templates › Contract types |
| AC1 | Given the GC uploads a Word template, then every [bracketed] and yellow-highlighted placeholder is listed, and the GC can make any other selected text a field. | Implemented | apps/api/src/lg/services/lg-docx.ts:207 spansIn(): [bracket] regex (210-214), consecutive yellow-highlighted runs merged into one placeholder (215-235), manual picks (236-246)apps/api/src/lg/services/lg-docx.ts:250 detectFields() scans body + headers/footers/notes and counts occurrencesapps/api/src/lg/services/lg-templates.ts:449 addManualField(): any selected text that sits in one paragraph becomes a MANUAL fieldapps/api/src/lg/routes/templates.ts:183 POST /lg/templates/:id/fields { text }apps/web/src/lg/components/templates/TemplateEditor.tsx:295 mouse selection in the document pane then 'Make a field' button (355-365) | templates.test.ts detects bracketed fields split across runs and yellow highlightstemplates.test.ts uploads, lists every detected field, and blocks activation until configuredcontracts-gaps.test.ts detects and fills placeholders in headers and footerspi-legal-gc /workspace/pi-for-legal/lg/templates Upload template (.docx with [Fields] and yellow text) then toast 'N fields detected'; Fields pane lists them with '[Brackets]'/'Highlighted' badges; select a phrase in the document pane then 'Make a field' |
| AC2 | Given a field, then the GC can set its source, question, answer type, M/O, options, validation, format, order and condition. | Implemented | apps/api/src/lg/routes/templates.ts:36 fieldSchema: source, sourceKey, question, help, answerType, required, options, validation {min,max,pattern}, format, order, conditionapps/api/src/lg/services/lg-templates.ts:388 updateTemplateConfig merges configuration; keys/placeholders stay file-drivenapps/web/src/lg/components/templates/TemplateEditor.tsx:91 FieldEditor: source (97-106), value key, fixed value, question + help (124-129), answer type (131-135), format (136-144), options (146-150), columns, min/max/pattern (156-170), condition (171-173), Mandatory switch (177-180), order (182-184) | templates.test.ts configures fields and sections, captures locked text, and activatespi-legal-gc /workspace/pi-for-legal/lg/templates?t=<templateId> Expand a field in the Fields pane: every control listed above is present; Save fields |
| Desc: field sources (requester / entity register / counterparty / common intake questions / fixed / system) | Source: asked from the requester; entity register (legal name, address, licence number, governing law, courts, default signatory, in the template's language); counterparty details; common intake questions; a fixed value; or the system (effective date = generation date). | Implemented | apps/api/src/lg/services/lg-templates.ts:31 LgFieldSource = QUESTION | ENTITY | COUNTERPARTY | COMMON | FIXED | SYSTEM; ENTITY_KEYS/COUNTERPARTY_KEYS/COMMON_KEYS/SYSTEM_KEYS at 77-80apps/api/src/lg/services/lg-templates.ts:227 planRender resolves each source; SYSTEM effectiveDate = ctx.effectiveDate (generation date) at 239apps/api/src/lg/services/lg-entities.ts:25 entityTemplateData(entityId, 'EN'|'AR') returns the register values in the template's language | generation.test.ts generates v01 with a contract reference and the SS name; recreates it exactly from the kept answerspi-legal-gc /workspace/pi-for-legal/lg/templates?t=<templateId> 'Where the value comes from' offers Requester question / Entity register / Counterparty / Common intake question / Fixed value / System, with a Value picker for register/counterparty/common/system keys |
| Desc: answer types | Answer type: free text, number, amount and currency, date, Yes/No, single choice, multiple choice, repeating rows or an Excel upload (inserted as a table). | Implemented | apps/api/src/lg/services/lg-templates.ts:32 LgFieldAnswerType: text | longtext | number | money | date | yesno | single | multi | rows | excelapps/web/src/lg/components/generation/GenAnswerInput.tsx:76 money input holds { amount, currency }; rows/excel editor with Excel upload at 166-223 | no automated test pi-legal-gc /workspace/pi-for-legal/lg/templates?t=<templateId> Answer type dropdown lists all ten types |
| Desc: counterparty details are optional and never needed to generate | Counterparty details are optional. They're never needed to generate a contract. | Implemented | apps/api/src/lg/services/lg-templates.ts:408 updateTemplateConfig forces required=false for COUNTERPARTY fieldsapps/api/src/lg/services/lg-templates.ts:249 only QUESTION fields can be missingRequiredapps/web/src/lg/components/templates/TemplateEditor.tsx:178 Mandatory switch disabled for counterparty: 'Counterparty details are always optional' | templates.test.ts configures fields and sections… (asserts counterparty_name.required === false after PATCH with required:true)pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<contractTypeId> Counterparty step has a Skip button; Generate still succeeds |
| AC3 | Given an unconfigured field, then the template can't be activated and the field is named. | Implemented | apps/api/src/lg/services/lg-templates.ts:149 activationCheck: 'Field "<placeholder>" isn't configured', mandatory-without-source, options missing, condition on a missing field, conditional section without/with bad condition, locked section not found, at least one locked sectionapps/api/src/lg/services/lg-templates.ts:474 activateTemplate throws 409 with the problem listapps/web/src/lg/components/templates/TemplateEditor.tsx:488 Activation pane lists 'What's blocking activation'; Activate button disabled while !check.ok (272) | templates.test.ts uploads, lists every detected field, and blocks activation until configured (expects /Purpose.*isn't configured/)API POST /api/workspace/pi-for-legal/portal/lg/templates/<draftId>/activate 409 with message naming the unconfigured field |
| Desc: unconfigured detected fields are flagged | Detected fields that aren't configured are flagged. | Implemented | apps/api/src/lg/routes/templates.ts:78 summary.unconfigured count per templateapps/web/src/lg/pages/LgTemplatesPage.tsx:220 list row shows '<n> to configure' in warning colourapps/web/src/lg/components/templates/TemplateEditor.tsx:316 unconfigured placeholders rendered with a yellow (warning) background in the document pane; Fields tab badge (374) | no automated test pi-legal-gc /workspace/pi-for-legal/lg/templates A freshly uploaded template shows 'N to configure' and yellow field chips |
| AC4 | Given a conditional section whose condition isn't met, then the heading stays, the numbering is unchanged, and the text reads "Not Applicable" (or "لا ينطبق" in Arabic). | Implemented | apps/api/src/lg/services/lg-docx.ts:479 fillDocx: for each excluded section the heading paragraph is kept and the body (bodyStart..bodyEnd) replaced by one paragraph with the GC's wording else LG_NOT_APPLICABLE[lang]; RTL bidi for Arabicpackages/shared/src/legalModules.ts:1160 LG_NOT_APPLICABLE = { EN: 'Not Applicable', AR: 'لا ينطبق' }apps/api/src/lg/services/lg-templates.ts:255 excludedSections(): CONDITIONAL sections whose condition is not met | templates.test.ts fills values, keeps yellow for missing optionals, and writes Not Applicable for excluded sections (expects '3. Rates\nNot Applicable\n4. Law')contracts-gaps.test.ts uses each excluded section's own "Not Applicable" wordingpi-legal-gc /workspace/pi-for-legal/lg/templates?t=<7X Services Agreement id> Preview with pricing basis = 'Spot rates' then downloaded .docx keeps 'Schedule 1 - Rates' heading with body 'Not Applicable' |
| Desc: locked sections generated as written and compared on return; rates example; fixed wording per language set by the GC | Locked: the operative clauses… generated as written and compared when the counterparty's version comes back. Example (Schedule 1 rates): Rates / Spot rates / Both. Fixed wording such as "Not Applicable" and the rates wording is set by the GC for each language. | Implemented | apps/api/src/lg/services/lg-templates.ts:131 captureSections() stores each LOCKED section's text from the Word file; used by the comparisonapps/api/src/lg/services/lg-generation.ts:549 uploadReturnedVersion re-captures locked sections from the regenerated v01 and comparesapps/api/src/lg/services/lg-template-seed.ts:142 demo Services template: 'Schedule 1 - Rates' CONDITIONAL on pricing_basis in [Rates, Both]; 'Schedule 2 - Spot Rates' on [Spot rates, Both] with 'Rates as agreed in the Order.' as template textapps/web/src/lg/components/templates/TemplateEditor.tsx:447 per conditional section: 'When not included, the heading stays and the text reads' (notApplicableText), placeholder 'لا ينطبق' for Arabic templates | templates.test.ts builds, configures and activates the English and Arabic NDAs and the Services agreement (Spot rates then Schedule 1 Not Applicable, Schedule 2 'Rates as agreed in the Order.')pi-legal-gc /workspace/pi-for-legal/lg/templates?t=<Services id> Sections pane: Liability/Termination Locked; Schedule 1/2 Conditional on the pricing basis question; NA wording field per section |
| AC5 | Given an optional field with no value, then the placeholder stays in the contract, highlighted yellow. | Implemented | apps/api/src/lg/services/lg-docx.ts:436 fillParagraph: missing value then every overlapping run gets highlight=true and the placeholder text is left untouched; setHighlight() at 378apps/api/src/lg/services/lg-docx.ts:360 LG_FIELD_REMOVED: a field whose condition is not met is removed instead (not yellow) | templates.test.ts fills values, keeps yellow for missing optionals… (expects <w:highlight w:val="yellow"/> before 'Counter')contracts-gaps.test.ts removes a field whose condition isn't met instead of leaving it yellowpi-legal-requester /workspace/pi-for-legal/lg/new?generate=<contractTypeId> Skip the counterparty then Download Word: '[Counterparty Name]' remains, highlighted yellow |
| AC6 | Given a rates field with an Excel upload, then the rates are inserted as a table. | Implemented | apps/api/src/lg/services/lg-docx.ts:519 excelToTable(): first sheet, first row = columnsapps/api/src/lg/services/lg-docx.ts:410 tableXml() builds a w:tbl; fillParagraph replaces the whole paragraph with the table when the placeholder is the paragraph (445) else appends after itapps/api/src/lg/routes/generation.ts:131 POST /lg/generation/:id/rates { file } (.xlsx only) then table returned for confirmationapps/web/src/lg/components/generation/GenAnswerInput.tsx:208 Excel upload in the rows/excel answer input | templates.test.ts fills values… (table from {columns, rows} then <w:tbl>, <w:bidiVisual/> for AR)pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<Services typeId> Pricing basis = Rates then rates question offers 'Upload Excel'; generated Word has the table under Schedule 1 |
| AC7 | Given a template overrides governing law and courts, then the override is used instead of the entity's values. | Implemented | apps/api/src/lg/services/lg-templates.ts:230 planRender ENTITY governingLaw/courts: override?.governingLaw / override?.courts win over entity.valuesapps/api/prisma/schema.prisma:5110 LgTemplate.governingLawOverride Json?apps/web/src/lg/components/templates/TemplateEditor.tsx:468 'Governing law and courts' override inputs in the Sections pane | no automated test pi-legal-gc /workspace/pi-for-legal/lg/templates?t=<templateId> Set 'Governing law override' = 'DIFC law', Save sections, Preview then downloaded .docx says DIFC law instead of the entity's governing law |
| Desc: governing law and courts come from the entity by default | Governing law and courts come from the entity by default. | Implemented | apps/api/src/lg/services/lg-templates.ts:234 raw = entity?.values[k] for governingLaw/courts when no overrideapps/api/src/lg/services/lg-entities.ts:41 governingLawEn/Ar, courtsEn/Ar by language | generation.test.ts generates v01… (expects 'Governed by the Federal laws of the UAE.')pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Download v01: governing law clause carries the entity register value |
| Desc: Arabic templates (RTL, table headings in the template's language, blocked for entities with incomplete Arabic fields) | Arabic templates. Field detection, conditional sections and locked sections work the same way, with right-to-left text. Rates tables use the template's language for column headings. An Arabic template can't be used for an entity until its Arabic fields in R-03 are complete. | Implemented | apps/api/src/lg/services/lg-docx.ts:410 tableXml: bidi/rtl runs and <w:bidiVisual/> for AR; NA paragraph gets <w:bidi/> (488)apps/api/src/lg/services/lg-templates.ts:242 table columns replaced by the GC's per-field `columns` (set in the template's language)apps/api/src/lg/services/lg-generation.ts:386 generateContract: AR + entity incomplete then GC alert email + 409 'The Arabic template can't be used for this entity yet'apps/web/src/lg/components/templates/TemplateEditor.tsx:152 'Column headings in the template's language' | generation.test.ts an Arabic template can't be used for an entity without its Arabic fieldsAPI POST /api/workspace/pi-for-legal/portal/lg/generation/<draftId>/generate (language AR, entity with missing Arabic fields) 409 mentioning the missing Arabic details; GC gets a REGISTER_ALERT email |
| AC8 | Given a contract type, then at most one English and one Arabic template are Active at the same time. | Implemented | apps/api/src/lg/services/lg-templates.ts:476 activateTemplate archives every other ACTIVE template with the same contractTypeId + language (any group), then settleSingleActive() (493-503) resolves racesapps/api/src/lg/services/lg-templates.ts:310 activeTemplatesFor returns at most one EN and one AR | templates.test.ts a change to an Active template creates a new version; one Active per type and languagepi-legal-gc /workspace/pi-for-legal/lg/templates Activate v2 then v1 of the same type/language flips to archived; Contract types view shows one 'EN template' chip |
| AC9 | Given the GC runs a preview, then a test contract is generated and isn't saved to any request. | Implemented | apps/api/src/lg/services/lg-templates.ts:526 previewTemplate fills sample answers, renders, returns the buffer , no LgGeneration/LgRequest/LgDocument writeapps/api/src/lg/routes/templates.ts:209 POST /lg/templates/:id/preview streams the .docxapps/web/src/lg/components/templates/TemplatePreviewDialog.tsx:35 GC answers as a requester would; 'Test contract downloaded. It isn't saved anywhere' | templates.test.ts previews a test contract without saving it (lgGeneration count stays 0)pi-legal-gc /workspace/pi-for-legal/lg/templates?t=<templateId> Preview then Generate test contract downloads PREVIEW_… .docx; My requests / Work show no new request |
| Desc: status Draft/Active/Archived; only Active templates offered to requesters | Status: Draft, Active or Archived. Only Active templates are offered to requesters. | Implemented | apps/api/src/lg/services/lg-templates.ts:311 activeTemplatesFor: where status = 'ACTIVE'apps/api/src/lg/services/lg-generation.ts:379 generateContract re-checks the draft's template is still ACTIVE, else the current Active one, else 409 | generation.test.ts offers only Active templates; none then no generationAPI GET /api/workspace/pi-for-legal/portal/lg/generation/options/<contractTypeId> 200 with languages [] for a type whose templates are Draft/Archived |
| AC10 | Given a new version, then contracts already generated keep the version they used. | Implemented | apps/api/prisma/schema.prisma:5122 LgGeneration { templateId, templateVersion, answers } , the exact LgTemplate row (one row per version, @@unique(groupId, version))apps/api/src/lg/services/lg-generation.ts:442 buildV01 loads the template row by gen.templateId (the version used), never the latestapps/api/src/lg/services/lg-templates.ts:371 newVersion() creates a new LgTemplate row; the old row is never mutated | generation.test.ts v01 keeps the entity details it was generated with, even after the register changes (byte-identical re-download)pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation 'Template: <name> · v1' stays v1 after the GC activates v2; Download v01 unchanged |
| Desc: a new Word file or a change to any field or section creates a new version; earlier versions kept | A new Word file or a change to any field or section creates a new version. Earlier versions are kept, and each generated contract records the version it used. Deliberate narrowing (documented only in the lg-templates.ts header, not in DESIGN.md): a never-activated, never-used Draft is edited in place rather than spawning a version per edit. Once a version has been Active or used, every change creates a new version as the PRD says. | Minor difference | apps/api/src/lg/services/lg-templates.ts:432 replaceTemplateFile always creates a new versionapps/api/src/lg/services/lg-templates.ts:362 editableInPlace(): a latest Draft that was never Active and never used is edited IN PLACE (no new version); any other version then newVersion() (429, 467)apps/web/src/lg/components/templates/TemplateEditor.tsx:527 UI text: 'A new Word file or a change to an Active or used version creates a new version' | templates.test.ts configures fields and sections… (newVersion === false while setting up) / a change to an Active template creates a new versionAPI PATCH /api/workspace/pi-for-legal/portal/lg/templates/<neverActivatedDraftId> { name } 200 { newVersion: false } (same id); PATCH on an Active template then { newVersion: true, version: n+1 } |
| AC11 | Given a template that has been used, then it can be archived but not deleted. | Implemented | apps/api/src/lg/services/lg-templates.ts:514 deleteTemplate: isTemplateUsed (LgGeneration count + non-draft LgRequest.templateId) or usedCount>0 then DELETE_BLOCKED audit + 409apps/api/src/lg/services/lg-templates.ts:505 archiveTemplate always allowedapps/web/src/lg/components/templates/TemplateEditor.tsx:276 delete button only when !used && usedCount === 0 | templates.test.ts deletes a never-used template; a used one can only be archivedAPI DELETE /api/workspace/pi-for-legal/portal/lg/templates/<usedTemplateId> 409 'This template has been used, so it can only be archived' |
| AC12 | Given the GC adds a contract type or flags it "Ask customs clearance", then intake uses it without a code change. | Implemented | apps/api/src/lg/services/lg-templates.ts:557 upsertContractType: add/edit side, category, name, askCustoms, active (audited)apps/api/src/lg/routes/templates.ts:106 GET/POST /lg/templates/contract-types, PATCH /contract-types/:idapps/api/src/lg/services/lg-intake.ts:145 resolveCtx reads askCustoms from the DB row then customsFlagged drives the intake customs questionpackages/shared/src/legalModules.ts:204 customsQ 'Does this require customs clearance?' showIf { key: 'contractType', customsFlagged: true }apps/web/src/lg/components/templates/ContractTypesPanel.tsx:48 Add form with 'Ask customs clearance'; per-row Customs / Active switches (92-97) | templates.test.ts keeps the contract type list, with "Ask customs clearance" (new type visible in /reference for a requester)pi-legal-gc then pi-legal-requester /workspace/pi-for-legal/lg/templates?view=types then /workspace/pi-for-legal/lg/new GC adds 'Other · Lab · Lab Pact' with Customs on then requester's intake lists it and asks 'Does this require customs clearance?' |
| AC13 | Given any user other than the GC, then they can't open or change the template library. Read access is wider than the PRD's literal 'can't open': team leads and the IT admin can view (not change). Recorded as a decision to confirm with Legal. | By decision | apps/api/src/lg/routes/templates.ts:86 router.use(requireSettingsViewer, requireGcToChange): GC, team leads and the IT admin may GET (and preview); every write needs the GCapps/api/src/lg/middleware/lg-auth.ts:141 requireGcToChange passes GET/HEAD and /preview, else requireGc; canViewSettings = isGc || team lead || isItAdmin (line 95)docs/pi-for-legal/DESIGN.md:120 Decision: 'Who manages settings , R-02 says the GC configures; R-19 AC9 says IT manage settings. Built per R-02: the GC edits, team leads and the IT admin view.'apps/web/src/lg/pages/LgTemplatesPage.tsx:106 canView = me.canViewSettings; viewOnly = !isGc (editor wrapped in <fieldset disabled>) | templates.test.ts only the GC changes it; team leads and IT view it (R-02 AC2); other lawyers don't see it (lawyer 403, itadmin GET 200, itadmin POST 403)API GET /api/workspace/pi-for-legal/portal/lg/templates team lead + IT admin 200 read-only (POST then 403); requester / non-lead lawyer 403 |
| Desc: every change is logged | Only the GC can open, add, edit, activate, archive or delete templates. Every change is logged. | Implemented | apps/api/src/lg/services/lg-templates.ts:357 lgAudit CREATE on upload; EDIT per field (424-426); CREATE per new version (384); status EDIT on activate/archive (480-483, 510); DELETE / DELETE_BLOCKED (518-522); ContractType CREATE/EDIT (573, 581)apps/api/src/lg/routes/templates.ts:227 DOWNLOAD audited | templates.test.ts deletes a never-used template… (audit actions CREATE, EDIT, DELETE, DELETE_BLOCKED for entity Template)pi-legal-gc /workspace/pi-for-legal/lg/admin/audit Entity 'Template' / 'ContractType' rows after any change |
| As | Call | HTTP | Response |
|---|---|---|---|
| gc | DELETE /templates/d90c8132-723c-4d04-99c5-179826f5a6f4 | 409 | This template has been used, so it can only be archived expected: 4xx: a used template can only be archived |
| counsel | GET /templates | 200 | data returned expected: 403: only the GC opens the template library |
| counsel | GET /templates | 200 | data returned expected: PRD: non-GC cannot open the library |
| counsel | POST /templates/d90c8132-723c-4d04-99c5-179826f5a6f4/archive | 403 | Only the General Counsel can do that expected: 403 |
| req | GET /templates | 403 | You can't view the legal settings expected: 403/404 |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Desc: choosing the template , side, category, type (R-07); customs asked if flagged | The requester answers "Are we the supplier, the customer, or other?", then picks the category and contract type (R-07). Customs clearance is asked if the type is flagged. | Implemented | apps/web/src/lg/components/intake/AnswerInput.tsx:331 contract_type answer: side then category then typeapps/web/src/lg/components/intake/Conversation.tsx:505 1.0 handoff: Active template then 'Generate the contract' (navigates to /lg/new?generate=<id>)apps/web/src/lg/components/generation/GenerationFlow.tsx:117 'customs' step added when contractType.askCustomsapps/api/src/lg/services/lg-generation.ts:374 generateContract refuses while customs is unanswered on a flagged type | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new Choose Contracts › Generate a contract (1.0) then side/category/type; a flagged type (e.g. Supplier · Courier · International) asks 'Does this require customs clearance?' |
| AC1 | Given an Active template for the chosen type, then the system uses it and asks only its configured fields. | Implemented | apps/api/src/lg/services/lg-generation.ts:223 templateQuestions(): only source === 'QUESTION' fields, condition met, not in a dropped section, in field order with the GC's wording (label = question || placeholder)apps/api/src/lg/services/lg-generation.ts:130 draft stores templateId/templateVersion of the Active templateapps/web/src/lg/components/generation/GenerationFlow.tsx:119 one step per state.questions entry | generation.test.ts asks only the template's questions and blocks generation until mandatory ones are answered (questions === ['purpose'])API GET /api/workspace/pi-for-legal/portal/lg/generation/<draftId> 200; data.questions = only the template's QUESTION fields |
| AC2 | Given both an Active English and an Active Arabic template, then the requester chooses the language before the questions start. | Implemented | apps/api/src/lg/services/lg-generation.ts:107 createGenerationDraft: language auto-set only when a single Active language exists; otherwise null until chosenapps/api/src/lg/services/lg-generation.ts:165 PATCH language switches templateId/templateVersion and arabic flagapps/web/src/lg/components/generation/GenerationFlow.tsx:116 'language' is the first step when state.languages.length > 1 | generation.test.ts an Arabic template can't be used… (languages === ['EN','AR'] then PATCH language AR)pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<NDA typeId> First prompt: 'Both an English and an Arabic template exist… Which language?' |
| AC3 | Given no Active template, then the requester is offered New contract drafting. | Implemented | apps/api/src/lg/services/lg-generation.ts:103 409 'There's no Active 7X template for this contract type. Raise a New contract drafting request instead'apps/web/src/lg/components/generation/GenerationFlow.tsx:170 error state shows a 'New contract drafting' button then /lg/new?type=1.2apps/web/src/lg/components/intake/Conversation.tsx:511 intake handoff without templateOffer: 'Shall I raise it as New contract drafting?' (patch typeCode 1.2, keeps contractType + customs) | generation.test.ts offers only Active templates; none then no generation (409 /New contract drafting/)pi-legal-requester /workspace/pi-for-legal/lg/new Pick a type with no Active template (e.g. Other · MOU · Binding) then assistant offers 'Yes, New contract drafting' |
| Desc: only the template's fields in the GC's order and wording; the conversation stays in English | Only the template's fields are asked (R-23), in the GC's order and wording. The conversation stays in English. | Implemented | apps/api/src/lg/services/lg-templates.ts:92 fieldsOf() sorts by orderapps/web/src/lg/components/generation/GenerationFlow.tsx:189 all assistant prompts are English; Arabic only applies to answer inputs (dir=rtl) for AR templates | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<typeId> Questions appear in the configured order with the GC's wording and help text; prompts remain English even for the Arabic template |
| AC4 | Given a mandatory template field, then the contract can't be generated until it's answered. | Implemented | apps/api/src/lg/services/lg-generation.ts:393 generateContract validates every template question (validateValue: required, number/min/max, date, options, pattern) then 400apps/api/src/lg/services/lg-generation.ts:411 second guard: plan.missingRequired then 'Answer: …' | generation.test.ts asks only the template's questions and blocks generation until mandatory ones are answered (400 /purpose/)API POST /api/workspace/pi-for-legal/portal/lg/generation/<draftId>/generate (mandatory question blank) 400 '"<question>" is required' |
| AC5 | Given the selected 7X entity, then its details, governing law, courts and default signatory are filled from R-03 in the template's language, without being asked. | Implemented | apps/api/src/lg/services/lg-generation.ts:386 entityTemplateData(r.entityId, lang) snapshot; passed as entityValues to planRender (410)apps/api/src/lg/services/lg-templates.ts:230 ENTITY source keys legalName/shortName/address/licenceNumber/governingLaw/courts/signatoryName/signatoryTitleapps/api/src/lg/services/lg-generation.ts:349 commonFor(): requester details (name, department), title, BU filled from the request | generation.test.ts generates v01… ('Between Lab Group Company PJSC and Acme Trading LLC', governing law filled) / Arabic entity text 'بين شركة المختبر ش.م.ع'pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<typeId> No question about entity name/law/courts/signatory; downloaded v01 carries them |
| AC6 | Given no counterparty details, then the contract still generates, with the placeholders kept in yellow. | Implemented | apps/api/src/lg/services/lg-templates.ts:237 COUNTERPARTY value null then formatValue null then placeholder kept + yellow (lg-docx.ts:436)apps/web/src/lg/components/generation/GenerationFlow.tsx:414 Counterparty step: Skip | templates.test.ts fills values, keeps yellow for missing optionals (counterparty_name null then '[Counterparty Name]' highlighted)pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<typeId> Skip counterparty then Generate works; file name uses 'Internal'; placeholders yellow in Word |
| AC7 | Given an Arabic template, then counterparty values are extracted or typed in Arabic. | Implemented | apps/api/src/lg/services/lg-generation.ts:313 extractCounterpartyFromLicence(file, lang): AI prompt 'Language for name and address: Arabic (copy the Arabic text exactly)' (334); OCR first for scans (316-320); deterministic fallback regexes incl. Arabic labelsapps/api/src/lg/routes/generation.ts:126 POST /:id/licence passes the draft's languageapps/web/src/lg/components/generation/GenerationFlow.tsx:388 AR: 'Give the counterparty's name and address in Arabic'; inputs dir=rtl | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<NDA typeId> (language Arabic) Counterparty step says to give details in Arabic; 'Read a trade licence' with a bilingual licence fills Arabic name/address |
| Desc: preview summary with edit, then Generate | The requester sees a summary of all answers and can edit any of them, then clicks Generate. | Implemented | apps/web/src/lg/components/generation/GenerationFlow.tsx:306 review step: definition list of every step with an Edit link, then 'Generate contract' | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new?generate=<typeId> 'Here's everything for your contract' summary with Edit per row |
| AC8 | Given Generate, then the contract keeps the template's formatting, has the generation date as the effective date, gets a contract reference number and is named per R-16. | Implemented | apps/api/src/lg/services/lg-docx.ts:1 fills word/document.xml in place (values land in the placeholder's first run, keeping its rPr); numbering/styles untouchedapps/api/src/lg/services/lg-generation.ts:399 contractRef = nextContractRef(entity shortName, contractRefFormat setting); effectiveDate = new Date() (400); SYSTEM effectiveDate field formatted as dateapps/api/src/lg/services/lg-generation.ts:424 lgFileName(namingConvention, { date, entity, counterparty || 'Internal', docType 'Contract', version 'v01', initials 'SS' }, '.docx')packages/shared/src/legalModules.ts:1060 lgFileName(): initials null then 'SS' | generation.test.ts generates v01 with a contract reference and the SS name… (contractRef /^LAB-CTR-\d{4}-0001$/, fileName /LABAcmeTradingLLCContractv01_SS\.docx$/)pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Contract reference e.g. EPGL-CTR-2026-00NN; file name <yyyymmdd>_<Entity>_<Counterparty>_Contract_v01_SS.docx; effective date = today in the Word |
| Desc: downloaded as Word (and PDF where the template allows) | …downloaded as Word (and PDF where the template allows). | Implemented | apps/api/src/lg/services/lg-generation.ts:454 buildV01Pdf: 409 unless template.allowPdf; docxToPdf via Gotenberg or LibreOffice (lg-pdf.ts:60), 501 when neither is installedapps/api/src/lg/routes/generation.ts:154 GET /:id/download?format=pdfapps/web/src/lg/components/templates/TemplateEditor.tsx:458 GC 'PDF download' switch per templatedocs/pi-for-legal/DESIGN.md:128 Deployment need: LibreOffice or GOTENBERG_URL on the API host | generation.test.ts PDF only where the template allows it (409 then 501 when conversion disabled; canDownloadPdf true)pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation 'PDF' button appears only when the GC allowed it; returns a PDF (or a clear 'PDF conversion isn't available on this server' if LibreOffice is absent) |
| AC9 | Given a generated contract, then the file isn't stored, and v01 can be recreated from the template version and answers. | Implemented | apps/api/src/lg/services/lg-generation.ts:401 GenSnapshot { answers, counterparty, common, entityId, entity (register values at generation), effectiveDate, contractRef } saved on LgGeneration; no LgDocument is writtenapps/api/src/lg/services/lg-generation.ts:442 buildV01 re-renders from gen.templateId + snapshot on every download | generation.test.ts generates v01… (lgDocument count 0; two downloads identical)generation.test.ts v01 keeps the entity details it was generated with, even after the register changespi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/documents No v01 document row; Generation tab 'Download v01' regenerates it |
| AC10 | Given generation fails twice, then the reason is shown, the requester and the GC are notified, and nothing is saved. | Implemented | apps/api/src/lg/services/lg-generation.ts:405 render loop attempts < 2; on a second failure notifyGenerationFailure (GENERATION_FAILED email to requester + GC, 361-365) then 500 'The contract couldn't be generated (<reason>). Nothing was saved…'; LgGeneration/contractRef/status writes happen only after success (428-436)packages/shared/src/legalModules.ts:1120 GENERATION_FAILED event: recipients 'Requester and GC' | no automated test API POST /api/workspace/pi-for-legal/portal/lg/generation/<draftId>/generate (template whose fileData was corrupted via DB) 500 with the reason; LgOutboundEmail GENERATION_FAILED to requester + GC; request still DRAFT |
| Desc: Sent to counterparty; reminded every 3 days | The requester sends the contract to the counterparty and clicks "Sent to counterparty" (With counterparty). They're reminded every 3 days. | Implemented | apps/api/src/lg/services/lg-generation.ts:463 markSentToCounterparty then moveStatus WITH_COUNTERPARTY, lastReminderAtapps/api/src/lg/services/lg-generation-timers.ts:21 COUNTERPARTY_REMINDER every waitingReminderDays (3) while WITH_COUNTERPARTY; idempotent via lastReminderAtapps/web/src/lg/request/tabs/LgGenerationTab.tsx:144 'Sent to counterparty' button | generation.test.ts reminds the requester every 3 days while with the counterpartyAPI POST /api/workspace/pi-for-legal/portal/lg/jobs/run { now: <+4 days> } 200 counts counterpartyReminders ≥ 1; Mailbox › Outbox shows COUNTERPARTY_REMINDER |
| AC11 | Given a returned Word file with no change to locked sections, then the request moves to approval (if required) and then signature, with no lawyer review. | Implemented | apps/api/src/lg/services/lg-generation.ts:546 upload then RETURNED; NO_CHANGE leaves it there with actions canSendForApproval (needs approvalRequired) / readyForSignature (297-307)apps/api/src/lg/services/lg-generation.ts:581 sendGeneratedForApproval then startApproval(requester as actor)apps/api/src/lg/routes/signature.ts:45 requester of a GENERATION request may send for signatureapps/api/src/lg/services/lg-generation-gate.ts:16 generationComparedClean: latest LgComparison must be NO_CHANGE on every approval/signature path (approvals.ts:273, esign.ts:194/334) | generation.test.ts no change to locked sections then Returned, ready for approval or signaturesignature.test.ts a generated contract goes to approval or signature only after a clean comparison; redlines stay with legal (F-12, F-02)pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Upload the unchanged v01 then 'No change to the locked clauses'; 'Send for approval' or 'Go to signature' appears; no lawyer assigned |
| AC12 | Given a returned file with a tracked change or text change inside a locked section, then the request converts to a Contract review. | Implemented | apps/api/src/lg/services/lg-compare.ts:102 docx: per locked section hasTrackedChanges(heading..bodyEnd) then TRACKED_CHANGE; else bodyMatches() on normalised text then CHANGEDapps/api/src/lg/services/lg-docx.ts:352 hasTrackedChanges: w:ins | w:del | w:moveFrom | w:moveTo (comments do not match)apps/api/src/lg/services/lg-generation.ts:561 CHANGED then convertToContractReview(reason names the sections) | generation.test.ts a tracked change in a locked section converts to a Contract review with the same referencetemplates.test.ts finds sections and spots tracked changespi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Upload a v01 with a tracked edit in a locked clause then 'A locked clause changed. The request is now a Contract review'; header shows type 1.1, same LGL reference, a lawyer assigned |
| Desc: Word preferred and asked first; formatting-only differences ignored; comments alone don't count | Word is preferred and asked for first. Text-based PDF, scanned PDF and image files are also accepted. Formatting-only differences are ignored. Comments alone don't [count]. | Implemented | apps/web/src/lg/request/tabs/LgGenerationTab.tsx:127 'Upload their version when it comes back. Word is best'; accept .docx,.pdf,.png,.jpg (155); PDF then toast 'Word is preferred' (161)apps/api/src/lg/services/lg-docx.ts:305 normalizeText strips formatting/quotes/dashes/whitespace/diacritics; only w:t text is comparedapps/api/src/lg/services/lg-compare.ts:68 bodyMatches: a blank optional [placeholder] filled in by the counterparty is not a change | contracts-gaps.test.ts treats a filled-in optional placeholder as no change, a real edit as a changepi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Upload v01 with only bold/colour changes or a Word comment on a locked clause then 'No change' |
| AC13 | Given a text-based PDF, then its text is compared, and conversion-only differences are ignored. | Implemented | apps/api/src/lg/services/lg-compare.ts:114 pdf: pdf-parse text (≥40 chars) then compareText(PDF_TEXT)apps/api/src/lg/services/lg-compare.ts:242 compareText: stripPageFurniture (page numbers, running headers), wordTokens with pdf hyphenation join (lg-docx.ts:307), line-start numbering stripped (144-157), Arabic visual-order variant (245), both edges anchored (206-240) | contracts-gaps.test.ts ignores numbering, page numbers and running headers in PDF/OCR textcontracts-gaps.test.ts keeps every number that is wording, and anchors both edges of a locked clause (PDF/OCR text)pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Upload v01 saved as PDF then comparison row 'PDF text compared · No change'; change '30 days' then 'changed' |
| AC14 | Given a scanned file, then text recognition runs first, and the comparison runs only if the text is read with enough confidence. | Implemented | apps/api/src/lg/services/lg-ocr.ts:44 recognizeText: model vision (aiComplete toolKey lg-ocr with the file attached); null when no model, confidence below MEDIUM, <15 words or >3% [illegible] (72-76)apps/api/src/lg/services/lg-compare.ts:122 scanned PDF (no text layer) / images then recognizeText then compareText(OCR) else FAILED with 'Upload the Word version or a text PDF'docs/pi-for-legal/DESIGN.md:102 Text recognition: scanned PDFs and images read by the model's vision | contracts-gaps.test.ts an image that can't be recognised fails with the PRD wording (no model in tests)generation.test.ts an unreadable scan fails the comparison; Send to legal converts with a reasonpi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Upload a clear scan (PNG/scanned PDF) with the model configured then 'Text recognition · No change'; a blurred scan then Comparison failed with the 'upload the Word version or a clearer file' reason |
| AC15 | Given a comparison fails twice, then the status is Comparison failed and the request can't go to approval or signature. | Implemented | apps/api/src/lg/services/lg-compare.ts:263 compareAndRecord: a thrown (system) error is retried once; second failure then FAILED 'A system error stopped the comparison' (systemError). Non-system failures (unreadable/low confidence/section not found) are deterministic and fail on the first passapps/api/src/lg/services/lg-generation.ts:565 FAILED then moveStatus COMPARISON_FAILED; GC emailed COMPARISON_ERROR after 2 system errors (568-574)apps/api/src/lg/services/lg-generation-gate.ts:22 assertGenerationCompared blocks startApproval, DocuSign, wet ink; sendGeneratedForApproval also 409 (lg-generation.ts:583)apps/api/src/lg/services/lg-generation-timers.ts:32 COMPARISON_FAILED_REMINDER every 3 days | generation.test.ts an unreadable scan fails the comparison; Send to legal converts with a reason (status COMPARISON_FAILED, /approval then 409)API POST /api/workspace/pi-for-legal/portal/lg/generation/<id>/approval (after a failed comparison) 409 'The comparison isn't confirmed…'; Approval & signature tab shows startBlockedReason |
| AC16 | Given "Ask legal for help" or "Send to legal", then the request converts to a Contract review with the same reference. | Implemented | apps/api/src/lg/services/lg-generation.ts:470 convertToContractReview: allowed in LG_CONVERTIBLE (GENERATED, WITH_COUNTERPARTY, RETURNED, COMPARISON_FAILED), reason required, same row/reference: path CORE, typeCode 1.1, status SUBMITTED, convertedFromGeneration, conversionReason, status event, audit, thread EVENT, routeAndAssignpackages/shared/src/legalModules.ts:870 LG_CONVERTIBLEapps/web/src/lg/request/tabs/LgGenerationTab.tsx:179 'Ask legal for help' / 'Send to legal' (at Comparison failed) dialog with reason | generation.test.ts an unreadable scan fails the comparison; Send to legal converts with a reason (empty reason 400; typeCode 1.1, ASSIGNED)pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation 'Ask legal for help' then reason then request header shows 1.1 Contract review, same reference, Generation tab banner 'Converted to a Contract review' |
| AC17 | Given an Arabic generated contract converts, then Arabic support is set to Yes and it routes to an Arabic-speaking lawyer. | Implemented | apps/api/src/lg/services/lg-generation.ts:477 isArabic = gen.language === 'AR' then arabic: true, arabicAuto: true on conversion (486)apps/api/src/lg/services/lg-routing.ts:81 routeAndAssign: r.arabic then candidates filtered to arabicSpeaker profiles | no automated test pi-legal-requester then pi-legal-gc /workspace/pi-for-legal/lg/requests/<ref>/overview After converting an Arabic generation: 'Arabic support: Yes' and the assigned lawyer is an Arabic speaker (Settings › People) |
| Desc: conversion keeps reference and history, gets a lawyer and the Contract review SLA; lawyer links SharePoint and stored files move | The request continues as type 1.1 in the Commercial queue with the same reference and history (R-13), and gets a lawyer and the Contract review SLA (R-17). The lawyer links a SharePoint folder, and the stored files move there (R-16). | Implemented | apps/api/src/lg/services/lg-generation.ts:483 queueKey from the 1.1 request type, scriptSnapshot replaced; routeAndAssign applies SLAapps/api/src/lg/services/lg-documents.ts:113 selfService = path === 'GENERATION' then after conversion the path is CORE so documents follow the normal SharePoint rulesapps/api/src/lg/routes/requests.ts:395 POST /lg/requests/:id/sharepoint links the folder and files held documents (fileRequestDocuments) | generation.test.ts a tracked change in a locked section converts… (slaDueAt truthy, assignedLawyerId set)pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/overview Converted request shows SLA due date, assignee, History with the generation events; 'Link a folder' moves the returned version |
| AC18 | Given any comparison, then a comparison report is saved. | Implemented | apps/api/src/lg/services/lg-compare.ts:279 LgComparison row per comparison: fileName, fileType, method (WORD|PDF_TEXT|OCR), result, reason, details, attemptsapps/api/prisma/schema.prisma:5135 model LgComparisonapps/web/src/lg/request/tabs/LgGenerationTab.tsx:206 'Returned versions and comparisons' list with method/result/reason and per-section chips | generation.test.ts an unreadable scan fails the comparison… (lgComparison count === 1)pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Each upload adds a row: file, 'Word compared / PDF text compared / Text recognition', result and reason |
| Desc: storage in the system only; executed contract then register entry; request records template/answers/returns/comparisons | Returned versions, comparison reports and the executed copy are stored in the system only (R-16). The executed contract creates a contract register entry (R-27). The request records the template name, language and version, every answer, each returned version and each comparison result. | Implemented | apps/api/src/lg/services/lg-documents.ts:120 folderUrl null for self-service then storage SYSTEM; initials 'SS'apps/api/src/lg/services/lg-esign.ts:444 completeWithExecutedCopy: GENERATION path then createContractFromRequest (register entry)apps/api/src/lg/services/lg-generation.ts:253 generationState returns template {name, version, language}, values, counterparty, comparisons, documents | no automated test pi-legal-requester /workspace/pi-for-legal/lg/requests/<ref>/generation Template name · vN, Language, Answers, Returned versions and comparisons; after signature Registers › Contracts has the entry |
| Desc: template usage (generated, converted, time to signature) feeds R-30 | Template usage (contracts generated, how many converted, time to signature) feeds R-30. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:427 generated/converted counts, perTemplate {generated, converted, days to completion from generatedAt} on the GC dashboardapps/web/src/lg/pages/LgTemplatesPage.tsx:158 'Contracts generated' stat (sum of usedCount) | no automated test pi-legal-gc /workspace/pi-for-legal/lg/dashboard Self-service generation block: generated, converted, time to signature per template |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given any user other than the GC, then they can't open or change the playbook library. PRD says lawyers don't open the library; team leads (who are lawyers) and the IT admin can view it read-only. Recorded as a decision to confirm. | By decision | apps/api/src/lg/routes/playbooks.ts:56 router.use(requireSettingsViewer, requireGcToChange): GC + team leads + IT admin read; only the GC writesapps/api/src/lg/middleware/lg-auth.ts:141 requireGcToChangedocs/pi-for-legal/DESIGN.md:120 Decision 'Who manages settings': GC edits, team leads and the IT admin viewapps/web/src/lg/pages/LgPlaybooksPage.tsx:49 canView = canViewSettings; viewOnly = !isGc; lawyers see 'The playbook library is the General Counsel's'apps/api/src/lg/services/lg-playbooks.ts:286 activePlaybookChoices() for the review picker returns names only , lawyers never open clauses outside review results | reviews.test.ts is the GC's to change; team leads and IT view it (R-02 AC2); other lawyers don't see it (lawyer 403, lead GET 200 / POST 403)API GET /api/workspace/pi-for-legal/portal/lg/playbooks team lead 200 read-only (POST 403); a non-lead lawyer or requester 403 |
| AC2 | Given a contract type and side, then at most one playbook version is Active. | Implemented | apps/api/src/lg/services/lg-playbooks.ts:234 publish archives every other ACTIVE playbook with the same contractTypeId (null = general), then settles races (244-251)apps/api/src/lg/services/lg-playbooks.ts:173 side derived from the contract type (one type ⇒ one side) | reviews.test.ts drafts, refuses to publish an incomplete playbook, publishes, and keeps one Active per typepi-legal-gc /workspace/pi-for-legal/lg/playbooks Publish Draft v2 of a playbook then v1 shows archived; publishing a second playbook for the same type archives the first |
| AC3 | Given a playbook clause, then it holds a preferred position, optional fallbacks, a red line, guidance, model wording and a risk level if missing. | Implemented | apps/api/src/lg/services/lg-playbooks.ts:31 LgPlaybookClause { key, name, why, keywords, preferred{guidance,wording,wordingAr}, fallbacks[], redLine{guidance,triggers}, riskIfMissing }apps/api/src/lg/services/lg-playbooks.ts:94 validateForPublish: name, preferred guidance or wording, red line guidance requiredapps/web/src/lg/components/review/ClauseEditor.tsx:58 editor: name, why, risk if missing, keywords, red line + triggers, preferred, ordered fallbacks with Arabic model wording | reviews.test.ts drafts, refuses to publish an incomplete playbook… (publish of {name:'Liability'} then 400 /red line/)pi-legal-gc /workspace/pi-for-legal/lg/playbooks?id=<playbookId> Expand a clause: all fields present; Publish refuses while a red line is empty |
| Desc: clauses with a risk level are flagged when missing; playbooks in English apply to EN and AR contracts | Risk level if missing: Low, Medium or High. Clauses with a risk level are flagged when missing. Playbooks are written in English and apply to contracts in English and Arabic. | Implemented | apps/api/src/lg/services/lg-review.ts:304 MISSING with no riskIfMissing then not flagged (skipped)apps/api/src/lg/services/lg-review.ts:344 Arabic documents reviewed against the English playbook; suggested wording swapped to Arabic | reviews.test.ts runs on an uploaded version… (Data protection MISSING/HIGH flagged; Notices has no risk level)pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review A clause with 'Not flagged' risk that is absent from the document produces no finding |
| AC4 | Given a Draft playbook, then it isn't used in any review until it's Active. | Implemented | apps/api/src/lg/services/lg-playbooks.ts:277 activePlaybookFor: status 'ACTIVE' onlyapps/api/src/lg/services/lg-review.ts:414 an explicitly chosen playbook must be ACTIVE ('Choose an Active playbook')apps/api/src/lg/services/lg-playbooks.ts:287 review picker lists ACTIVE playbooks only | reviews.test.ts reports Not run with the reason… (NDA type with no Active playbook then NOT_RUN 'No Active playbook')API POST /api/workspace/pi-for-legal/portal/lg/reviews/<requestId> { documentId, playbookId: <draftId> } 400 'Choose an Active playbook' |
| AC5 | Given the GC publishes a change, then a new version is created and earlier versions are kept. | Implemented | apps/api/src/lg/services/lg-playbooks.ts:188 Active/Archived versions can't be edited (409)apps/api/src/lg/services/lg-playbooks.ts:211 newVersion(): Draft copy with version+1 in the same groupId; publish (228) activates it and archives the previous , rows are never deleted on publishapps/api/prisma/schema.prisma:5172 LgReview.playbookId + playbookVersion record the version used | reviews.test.ts drafts… (PATCH on Active then 409; new-version then v2 DRAFT)pi-legal-gc /workspace/pi-for-legal/lg/playbooks?id=<activeId> 'New version' then Draft v2; Publish then v2 active, v1 archived; version chips list both |
| AC6 | Given a contract type and side with no playbook, then the general playbook applies. | Implemented | apps/api/src/lg/services/lg-playbooks.ts:277 activePlaybookFor: own Active playbook else Active general (contractTypeId null)apps/api/src/lg/services/lg-review.ts:415 runReview uses activePlaybookFor(contractTypeOf(request))apps/web/src/lg/pages/LgPlaybooksPage.tsx:147 'General playbook (types without their own)' option | no automated test pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Run review on a type with no own playbook: dialog pre-selects the general playbook ('picked for this contract type'); result header shows it |
| AC7 | Given a playbook that has been used, then it can be archived but not deleted. | Implemented | apps/api/src/lg/services/lg-playbooks.ts:265 remove(): usedCount>0 or any LgReview referencing it then DELETE_BLOCKED audit + 409apps/api/src/lg/services/lg-review.ts:472 usedCount incremented on every completed reviewapps/api/src/lg/services/lg-playbooks.ts:255 archive() always allowed | reviews.test.ts a used playbook can be archived but not deletedAPI DELETE /api/workspace/pi-for-legal/portal/lg/playbooks/<usedId> 409 'This playbook has been used in a review, so it can only be archived' |
| AC8 | Given a position with Arabic model wording, then Arabic redlines use that wording. | Implemented | apps/api/src/lg/services/lg-review.ts:350 AR document: preferred.wordingAr then suggestedWording (source PLAYBOOK_AR), no translationapps/api/src/lg/services/lg-review-redline.ts:71 redline text for AR: fb.wordingAr || AI translation || English; preferred: c.preferred.wordingAr first (75-77)apps/web/src/lg/components/review/ClauseEditor.tsx:51 'Arabic model wording (optional, used instead of a translation)' | reviews.test.ts reports Not run… and Arabic documents get Arabic wording flagged Verify (Data protection then PLAYBOOK_AR, 'البيانات')pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review (Arabic document) Finding shows 'Suggested wording · GC Arabic model wording'; generated redline inserts that Arabic text |
| Desc: build on screen or import/export Word/Excel in the GC's format; the system starts with no playbooks | Playbooks can be built on screen, or imported from and exported to Word or Excel in the GC's format. The system starts with no playbooks. | Implemented | apps/api/src/lg/services/lg-playbook-io.ts:28 exportPlaybookXlsx / importPlaybookXlsx (51), exportPlaybookDocx (94) / importPlaybookDocx (121): lossless round tripapps/api/src/lg/routes/playbooks.ts:72 POST /lg/playbooks/import, GET /:id/export?format=xlsx|docxapps/web/src/lg/pages/LgPlaybooksPage.tsx:329 Import dialog; Export to Excel/Word in the More menu (219-220); empty state 'The system starts with none'apps/api/src/lg/services/lg-playbook-seed.ts:72 DEMO ONLY: the pi-for-legal seed creates NDA, Services and general playbooks (ensureDemoPlaybooks); a fresh workspace has none | reviews.test.ts exports and imports Excel and Word in the same formatpi-legal-gc /workspace/pi-for-legal/lg/playbooks Export to Excel then re-import the file then new Draft with the same clauses |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | GET /playbooks | 200 | data returned expected: 403 |
| gc | DELETE /playbooks/3552213f-38cd-42f3-9d2c-3c398611bc5e | 409 | This playbook has been used in a review, so it can only be archived expected: 4xx: a used playbook can only be archived |
| counsel | POST /playbooks/3552213f-38cd-42f3-9d2c-3c398611bc5e/publish | 403 | Only the General Counsel can do that expected: 403 |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a Contracts request with an uploaded version, when the lawyer clicks "Run review", then each playbook clause shows its position found, risk level, confidence, extract and guidance. | Implemented | apps/api/src/lg/services/lg-review.ts:406 runReview: CONTRACTS + REVIEWABLE_TYPES (1.1,1.2,1.3,1.5,1.6), document on the request, playbook auto/explicit then execute()apps/api/src/lg/services/lg-review.ts:290 buildFindings: per clause position, risk (riskFor), confidence + reason, extract/location, guidance, suggested wording; AI (analyse 253) with deterministic heuristicReview fallback (172)apps/web/src/lg/request/tabs/LgReviewTab.tsx:135 Run dialog (document version + playbook)apps/web/src/lg/components/review/FindingCard.tsx:74 chips + extract/location/guidance/suggested wording | reviews.test.ts runs on an uploaded version and places every playbook clausepi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Run review then each playbook clause as a card with Position / Risk / Confidence chips, extract with location, playbook guidance |
| Desc: playbook picked from contract type and side; lawyer can choose another; results saved per document version with playbook version; legal only (confidential then GC) | The system picks the playbook from the contract type and side. The lawyer can choose another. Results are saved against that document version, with the playbook version used. Only legal can see them (confidential requests: the GC only). | Implemented | apps/api/src/lg/routes/reviews.ts:95 GET /:requestId returns defaultPlaybookId (activePlaybookFor) + Active choicesapps/api/src/lg/services/lg-review.ts:417 LgReview { documentId, playbookId, playbookVersion }apps/api/src/lg/routes/reviews.ts:49 load(): !isLegal || !canSeeInternal || (confidential && !isGc) then 404 | reviews.test.ts is legal-only; acting needs the assigned lawyer, lead or GCAPI GET /api/workspace/pi-for-legal/portal/lg/reviews/<confidentialRequestId> 404 for a lawyer, 200 for pi-legal-gc |
| Desc: positions incl. Not in playbook; risk mapping Low/Medium/High; missing takes the playbook level | Position found: Preferred, Fallback (which one), Beyond fallback, Red line, Missing, or Not in playbook. Risk level: Low = a fallback; Medium = beyond the fallbacks but within the red line; High = the red line is crossed. Missing clauses take the risk level set in the playbook. | Implemented | apps/api/src/lg/services/lg-review.ts:44 LgPosition incl. NOT_IN_PLAYBOOK; fallbackIndex keptapps/api/src/lg/services/lg-review.ts:104 riskFor: FALLBACKthenLOW, BEYOND_FALLBACKthenMEDIUM, RED_LINEthenHIGH, MISSINGthenclause.riskIfMissingapps/api/src/lg/services/lg-review.ts:334 notInPlaybook extras from the AI become NOT_IN_PLAYBOOK findings | reviews.test.ts runs on an uploaded version… (FALLBACK/LOW, RED_LINE/HIGH, MISSING/HIGH, BEYOND_FALLBACK)pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Position chip reads 'Fallback 1', 'Red line', 'Missing' etc. with the matching risk chip |
| AC2 | Given a finding, then risk and confidence are shown as separate labels, and Low confidence shows "Verify". | Implemented | apps/api/src/lg/services/lg-review.ts:320 confidenceReason always set below HIGH; verify = confidence === 'LOW'apps/web/src/lg/components/review/ReviewChips.tsx:16 RiskChip and ConfidenceChip are separate; ConfidenceChip adds a 'Verify' chip when verifyapps/web/src/lg/components/review/FindingCard.tsx:86 one-line confidence reason under the chips | reviews.test.ts runs on an uploaded version… (confidence LOW, verify true on the fallback finding)pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Risk chip + Confidence chip side by side; Low confidence shows the 'Verify' chip and a reason line |
| Desc: header summary; High risk first, Verify first within level; filters by risk, confidence and Verify only | The header summarizes findings by risk and confidence. Findings are listed High risk first, Verify first within each level, with filters by risk, confidence and "Verify only". | Implemented | apps/api/src/lg/services/lg-review.ts:97 sortFindings: risk HIGHthenMEDIUMthenLOWthennone, then verify first, then nameapps/api/src/lg/services/lg-review.ts:550 summarise(): counts by risk, confidence, verify, redLineOpen, deltaapps/web/src/lg/request/tabs/LgReviewTab.tsx:276 StatStrip (High/Medium/Low/Verify/Red lines open), confidence counts (285-290), Risk + Confidence segmented filters and 'Verify only' (301-312) | reviews.test.ts runs on an uploaded version… (findings[0].risk === 'HIGH')pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Stat strip, High-risk cards first, filters narrow the list ('N of M') |
| AC3 | Given an Arabic document, then findings are in English and suggested wording is in Arabic. AI-translated wording always shows "Verify". | Implemented | apps/api/src/lg/services/lg-review.ts:220 prompt: location/confidenceReason/titles in English, extracts in the document's languageapps/api/src/lg/services/lg-review.ts:344 AR: GC Arabic wording then PLAYBOOK_AR; else translate() then AI_TRANSLATION and f.verify = true (366) even when the translation is unavailable (note shown)apps/web/src/lg/components/review/FindingCard.tsx:106 'Suggested wording · AI translation, verify before use' | reviews.test.ts reports Not run… and Arabic documents get Arabic wording flagged Verify (language AR; liability finding verify=true with 'translation unavailable' note)pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review (Arabic .docx) Header 'Arabic document. Findings in English, wording in Arabic'; translated wording carries Verify |
| AC4 | Given a review, then the document version and playbook version used are recorded. | Implemented | apps/api/prisma/schema.prisma:5172 LgReview { documentId, playbookId, playbookVersion, status, findings, source, attempts, redlineDocumentIds, baseReviewId }apps/api/src/lg/services/lg-review.ts:563 reviewView returns document {fileName, versionLabel} and playbook {name, version} | reviews.test.ts runs on an uploaded version… (res.data.playbook.name === 'Services playbook')pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Header line '<file> (v01) · <playbook> v1 · <lawyer> · <time>' |
| AC5 | Given the review fails twice or isn't run, then the reason is shown and the request's status and SLA are unaffected. | Implemented | apps/api/src/lg/services/lg-review.ts:442 execute(): NOT_RUN 'No Active playbook' / 'Unsupported file type' / 'Language not supported'; FAILED 'File not readable'; analysis loop attempt < 2 then FAILED 'The review failed twice (…). Retry, or continue manually' + REVIEW_FAILED email to the lawyer (481-497); no moveStatus/SLA call anywhere in the serviceapps/api/src/lg/services/lg-review.ts:428 retryReview for FAILED/NOT_RUNapps/web/src/lg/request/tabs/LgReviewTab.tsx:249 non-completed state shows status, reason, 'The request's status and SLA are not affected', Retry | reviews.test.ts runs on an uploaded version… (status and slaDueAt unchanged after the review)reviews.test.ts reports Not run with the reason… (NOT_RUN 'No Active playbook', 'Unsupported file type', FAILED 'File not readable')pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Run on an .xlsx then 'Review not run · Unsupported file type'; Overview status/SLA unchanged |
| AC6 | Given a red-line hit, then the lawyer must accept (with a reason), redline or escalate to the GC. Until every red-line hit has a decision, the request can't be completed. | Implemented | apps/api/src/lg/services/lg-review.ts:611 RED_LINE accepts only ACCEPTED (note required) / REDLINE / ESCALATED; ESCALATED opens a GC consult via createConsult (619-637)apps/api/src/lg/services/lg-lifecycle.ts:203 assertCompletable + assertCanCompleteWithFinalReply + assertRedLinesDecided (272): any RED_LINE finding without decision (newest review per clause) blocks Complete and signatureapps/web/src/lg/request/tabs/LgReviewTab.tsx:395 RedLineDialog: Redline / Accept (reason required) / Escalate to the GC | reviews.test.ts blocks completion until every red-line hit has a decisioncore.test.ts refuses signature while a consult is open or a red line is undecided (signing completes the request)API POST /api/workspace/pi-for-legal/portal/lg/requests/<id>/status { to: 'COMPLETED' } 409 'Every red-line finding from the AI review needs a decision (accept, redline or escalate)' |
| Desc: lawyer marks any finding Accepted / Dismissed / Edited with a note; every decision and reason logged | The lawyer can mark any finding Accepted, Dismissed or Edited, with a note. Every decision and reason is logged. | Implemented | apps/api/src/lg/services/lg-review.ts:614 non-red-line: ACCEPTED | DISMISSED | EDITED (editedWording required); decidedBy/decidedAt; lgAudit REVIEW with old/new decision + note (646-649)apps/web/src/lg/components/review/FindingCard.tsx:119 Accept / Dismiss / Edit wording buttons with note | reviews.test.ts blocks completion… (EDITED without wording 400; audit REVIEW rows ≥ 2)pi-legal-gc /workspace/pi-for-legal/lg/requests/<ref>/history Audit rows 'Review · finding:<clause>' with the decision and note |
| AC7 | Given the lawyer ticks findings and chooses the wording for each, then the Word redline shows exactly those changes as tracked changes and nothing else. | Implemented | apps/api/src/lg/services/lg-review-redline.ts:45 generateRedline: only the ticked findings become RedlineChange items; wording PREFERRED / FALLBACK[i] / OWNapps/api/src/lg/services/lg-redline.ts:283 applyRedline: word-level diff mapped onto the original runs, w:del/w:ins with w:author = lawyer name (297); untouched runs/fields/bookmarks byte-identical; whole-paragraph rebuild only as a warned fallback (356-371)apps/web/src/lg/request/tabs/LgReviewTab.tsx:353 'N findings ticked for the redline' bar then Generate redline (download) | reviews.test.ts writes a redline with only the ticked changes as tracked changes, internal comments stripped (untouched red line clause remains, author = lawyer)contracts-gaps.test.ts changes only the selected words; other runs, fields and footnote references stay byte-identicalcontracts-gaps.test.ts keeps each changed slice in its own run's formatting across run boundariespi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Tick one finding, choose 'Preferred' then downloaded .docx opens in Word with a single tracked change in the lawyer's name |
| Desc: missing clauses inserted at a confirmed location; saved as next version linked to the review; regenerate with another selection; nothing sent automatically | For missing clauses, the lawyer can insert the playbook wording at a suggested location they confirm. The system produces a Word document… saved as the next version (R-16) and linked to the review. The lawyer can generate the redline again with a different selection. Each version is kept. Nothing is sent to the counterparty automatically. | Implemented | apps/api/src/lg/services/lg-review.ts:153 suggestInsertAfter(): similar paragraph, else before the signature block, else end; AI insertAfter used when valid (325-327)apps/api/src/lg/services/lg-review-redline.ts:80 MISSING requires insertAfter confirmed; saveVersion via storeDocument (116-118); redlineDocumentIds appended per generation (120-123)apps/api/src/lg/services/lg-redline.ts:316 inserted as a tracked new paragraph after the chosen index (-1 = start)apps/web/src/lg/components/review/FindingCard.tsx:204 'Insert after' picker pre-set to the suggestion, lawyer confirms/changes | reviews.test.ts writes a redline… (missing Data protection inserted after ¶6; redlineDocumentIds length 1)contracts-gaps.test.ts suggests a place before the signature block when nothing similar existspi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Tick a Missing finding then 'Suggested: after ¶n. Confirm or choose another place'; Redlines section lists each generated version (v02, v03…); Documents tab shows them; no email to any counterparty |
| AC8 | Given a comment marked internal, then it's removed from the version prepared for sending. | Implemented | apps/api/src/lg/services/lg-review-redline.ts:92 comment: sel.commentInternal ? null : comment , internal comments never reach applyRedline; kept only on the finding (85-86)apps/api/src/lg/services/lg-redline.ts:391 counterparty comments written to word/comments.xmlapps/web/src/lg/components/review/FindingCard.tsx:225 comment + 'Internal: removed before sending' switch | reviews.test.ts writes a redline… internal comments stripped (comments.xml has the counterparty comment, not 'INTERNAL')pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Add an internal comment and a counterparty comment then downloaded redline shows only the counterparty comment in Word's review pane |
| Desc: files , Word and text PDF; scanned then OCR else 'File not readable'; redlines need Word, PDF converted first with a warning | Files. Word and text-based PDF. Scanned PDFs go through text recognition first; if unreadable, the review fails with "File not readable". Redlines need Word: a PDF is converted first, with a warning that formatting may change. | Implemented | apps/api/src/lg/services/lg-review-text.ts:80 readForReview: docx paragraphs; pdf-parse text; no text layer then recognizeText (OCR) else UNREADABLE 'File not readable…'; images then OCR; else UNSUPPORTEDapps/api/src/lg/services/lg-review-redline.ts:101 non-docx source then paragraphsToDocx with warning 'The PDF was converted to Word first. Formatting may differ' / OCR variant | reviews.test.ts reports Not run with the reason… (png without a model then FAILED /File not readable/)pi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Review a PDF version then Generate redline then toast warning 'The PDF was converted to Word first…' |
| AC9 | Given a review on a later version, then the results show resolved, new and still-open findings. | Implemented | apps/api/src/lg/services/lg-review.ts:505 previousVersionReview: latest completed review of an earlier document of the same docType with the same playbook groupapps/api/src/lg/services/lg-review.ts:528 applyDelta: delta NEW / STILL_OPEN / RESOLVED per clause; vanished issues added as RESOLVED; baseReviewId storedapps/web/src/lg/request/tabs/LgReviewTab.tsx:295 'Since v01 (<file>): N resolved · N new · N still open'; DeltaChip per finding | reviews.test.ts shows resolved, new and still-open findings on a later versionpi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref>/review Run on v02 then header 'Since v01…' and Resolved / New / Still open chips on findings |
| AC10 | Given a user outside the legal team, then they can't see review results or redlines. | Implemented | apps/api/src/lg/routes/reviews.ts:53 every /lg/reviews route 404s for non-legal / no-internal-access / confidential non-GCapps/api/src/lg/services/lg-documents.ts:279 internalOnlyDocIds: review redlineDocumentIds hidden from the requester's document list/download until a lawyer attaches one to a replyapps/api/src/lg/services/lg-generation.ts:265 generation state filters redline docs out of the requester's viewapps/web/src/lg/request/LgRequestPage.tsx:49 'AI review' tab only when canSeeInternal | reviews.test.ts is legal-only; acting needs the assigned lawyer, lead or GC (requester 404, itadmin 404)reviews.test.ts writes a redline… (requester cannot list or download the redline; lawyer can)API GET /api/workspace/pi-for-legal/portal/lg/reviews/<requestId> 404; Documents tab for the requester omits '(redline).docx' versions |
| As | Call | HTTP | Response |
|---|---|---|---|
| req | GET /reviews/9d9eeddd-9579-4c3c-bcdd-0b5ad6d385c1 | 404 | Request not found expected: 403/404: outside legal cannot see review results |
| counsel | GET /reviews/9d9eeddd-9579-4c3c-bcdd-0b5ad6d385c1 | 200 | data returned expected: 200 saved reviews with document + playbook version |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a request reaches EXECUTED, then an entry is created with fields prefilled: from the answers for generated contracts, or by AI for the lawyer to confirm. | Implemented | apps/api/src/lg/services/lg-esign.ts:444 completeWithExecutedCopy then createContractFromRequest(executedDocumentId) for generated / Contracts / Employmentapps/api/src/lg/services/lg-contracts-register.ts:183 generated: prefill from LgGeneration answers, confirmedAt set; lawyer-handled: aiPrefill(executed copy text) via aiComplete 'lg-contract-prefill' with fallback to request fields, prefillSource ai|request, confirmedAt null (196-230) + email to the lawyer to confirm (245-252)apps/api/src/lg/routes/registers.ts:807 POST /registers/contracts/:id/confirm (lawyer of the contract or GC)apps/web/src/lg/components/registers/ContractsView.tsx:253 'These fields were read by AI from the executed copy… Check them, then confirm' + 'To confirm' chip and filter | registers.test.ts creates an entry when a request is executed, prefilled from its answersregisters.test.ts lawyer-handled entries wait for the lawyer to confirm; courts come from the entity (G-05, G-16)pi-legal-counsel /workspace/pi-for-legal/lg/registers/contracts?filter=toConfirm after a simulated signing, the new entry shows the prefilled dates/value with a 'To confirm' chip and a Confirm button; a generated contract's entry is already confirmed |
| AC2 | Given a lawyer uploads an offline-signed contract, then they can create an entry manually. | Implemented | apps/api/src/lg/routes/registers.ts:755 POST /registers/contracts requires executedCopy (stored EXECUTED by the convention), allocates a contract ref, source OFFLINE; POST /contracts/prefill (746) reads the fields with AI firstapps/web/src/lg/components/registers/ContractsView.tsx:68 'Add a contract signed outside the LMS' dialog: executed copy first, AI prefill, lawyer confirms the fields | registers.test.ts expiry alerts go to the owner and lawyer; the owner can raise a linked 1.3pi-legal-counsel /workspace/pi-for-legal/lg/registers/contracts 'Add contract' then upload a PDF, fields prefilled, save then new row with a reference and the executed copy downloadable |
| AC3 | Given an entry with an expiry date or notice deadline, then the business owner and lawyer are alerted 90, 60 and 30 days before. | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:141 contracts: expiry and noticeDeadline thresholds LG_ALERTS.contractExpiry [90,60,30], idempotent per date, one REGISTER_ALERT to ownerUserId + lawyerId with a link to the entrypackages/shared/src/legalModules.ts:1028 contractExpiry: [90, 60, 30] | registers.test.ts expiry alerts go to the owner and lawyer; the owner can raise a linked 1.3API POST /api/workspace/pi-for-legal/portal/lg/jobs/run body {} contractAlerts ≥ 1 for an entry expiring within 90 days; Outbox 'Legal register alert: Contract … expires on …' to the owner and the lawyer |
| AC4 | Given an alert, then the business owner can raise a linked 1.3 request. | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:161 alert text 'To amend, renew or terminate it, raise a linked request from the register' with linkPath to the entryapps/api/src/lg/routes/registers.ts:815 POST /contracts/:id/raise-request (owner or legal) then /lg/new?type=1.3&contract=<id>; intake prefills contractRef and linkedContractId (lg-intake.ts:149, 570)apps/web/src/lg/components/registers/ContractsView.tsx:241 'Amend, renew or terminate' button for the owner / legal | registers.test.ts expiry alerts go to the owner and lawyer; the owner can raise a linked 1.3pi-legal-requester /workspace/pi-for-legal/lg/registers/contracts?id=<ownedContractId> the owner sees 'Amend, renew or terminate' then lands on /lg/new?type=1.3&contract=… with the contract preselected |
| AC5 | Given an amendment, renewal or termination is executed, then it's linked to the original entry and the status updates. | Implemented | apps/api/src/lg/services/lg-contracts-register.ts:124 1.3: Termination then TERMINATED; Amendment then value/expiry/notice updated from the executed amendment; Renewal then new entry, original SUPERSEDED; linkedRequestIds updated, auditedapps/api/src/lg/services/lg-lifecycle.ts:189 a 1.3 that completes without signature still applies via applyLinkedContractOnCompletion | registers.test.ts creates an entry when a request is executed, prefilled from its answersregisters.test.ts a 1.3 completed without signature updates the original; an amendment moves its dates (G-06)pi-legal-counsel /workspace/pi-for-legal/lg/registers/contracts?id=<originalId> after completing a 1.3 Termination raised on it, the entry's status is Terminated and the request is listed under 'Amendments, renewals and terminations raised under 1.3' |
| AC6 | Given a business user, then they see only entries they own or requested. | Implemented | apps/api/src/lg/services/lg-registers.ts:151 contractVisibilityWhere: non-legal then ownerUserId = me OR requestId in my requests; legal then non-confidential OR own; GC then allapps/api/src/lg/routes/registers.ts:672 applied on the list, and on detail/download via visibleContract (329) | registers.test.ts creates an entry when a request is executed, prefilled from its answersAPI GET /api/workspace/pi-for-legal/portal/lg/registers/contracts/<contractId-not-owned> 404; GET /lg/registers/contracts returns only rows where owner = me or requested by me |
| Desc: Fields | Fields. Contract reference; entity; counterparty; contract type and side; business unit; business owner (defaults to the requester); lawyer; value and currency; effective and expiry dates; auto-renewal; notice period and notice deadline (calculated); governing law and courts; language; link to the executed copy; linked requests. | Implemented | apps/api/prisma/schema.prisma:5196 LgContract has every listed field (contractRef, entityId, counterpartyName, contractTypeId, side, businessUnitId, ownerUserId, lawyerId, value, currency, effectiveDate, expiryDate, autoRenewal, noticePeriodDays, noticeDeadline, governingLaw, courts, language, executedDocumentId, linkedRequestIds)apps/api/src/lg/services/lg-contracts-register.ts:218 ownerUserId defaults to requesterId; noticeDeadline = expiry − notice days (45-48, 226) | registers.test.ts expiry alerts go to the owner and lawyer; the owner can raise a linked 1.3pi-legal-counsel /workspace/pi-for-legal/lg/registers/contracts?id=<id> detail sheet lists all fields incl. calculated notice deadline, executed copy download and linked requests |
| Desc: Statuses Active then Expired, Terminated or Superseded; 'Expiring' flag within 90 days | Statuses. Active then Expired, Terminated or Superseded. Flag: 'Expiring' within 90 days (R-13). | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:116 Active past expiry (not auto-renewing) then EXPIRED automatically; auto-renewing roll forward (124-140)apps/api/src/lg/services/lg-contracts-register.ts:134 TERMINATED on an executed termination; SUPERSEDED on renewal (165)apps/api/src/lg/services/lg-registers.ts:65 contractFlags.expiring = Active and 0-90 days left; ContractsView.tsx:216 'Expiring' chip; ?flag=expiring filter (registers.ts:682) | registers.test.ts auto-renewing contracts roll forward past expiry (G-17)pi-legal-counsel /workspace/pi-for-legal/lg/registers/contracts?flag=expiring rows with an 'Expiring' chip (expiry within 90 days); status column shows Active / Expired / Terminated / Superseded |
| Desc: The GC or the lawyer can change the business owner | The GC or the lawyer can change the business owner, for example when someone leaves. | Implemented | apps/api/src/lg/routes/registers.ts:793 POST /contracts/:id/owner , GC or the contract's lawyer only (403 otherwise), auditedapps/web/src/lg/components/registers/ContractsView.tsx:245 'Change owner' dialog ('Alerts go to the new owner') | registers.test.ts the executed copy downloads from the register; only the GC or the contract lawyer changes the owner (G-18, G-19)API POST /api/workspace/pi-for-legal/portal/lg/registers/contracts/<id>/owner body {"ownerUserId":"<uuid>"} 403; the same call as pi-legal-gc returns 200 with the new ownerUserId |
| Desc: Access follows R-19 , lawyers see all non-confidential entries | Access. Follows R-19: lawyers see all non-confidential entries; business users see entries they own or requested. | Implemented | apps/api/src/lg/services/lg-registers.ts:158 legal: confidential:false OR lawyerId = me OR own; confidential entries only to the GC and the handling lawyer | registers.test.ts creates an entry when a request is executed, prefilled from its answerspi-legal-litigation /workspace/pi-for-legal/lg/registers/contracts Khalifa (Disputes) sees every non-confidential contract but not the confidential Employment one that Adeeb (GC) sees |
| As | Call | HTTP | Response |
|---|---|---|---|
| req | GET /registers/contracts | 200 | data returned expected: 200: business users see entries they own or requested |
| counsel | GET /registers/contracts | 200 | data returned expected: 200 |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a Disputes request, or an Employment request in With authority, when the lawyer clicks Open case, then a case record is created and the request moves to Case opened. | Implemented | apps/api/src/lg/services/lg-cases.ts:46 canOpenCaseFrom: DISPUTES from UNDER_REVIEW/WITH_EXTERNAL_COUNSEL, EMPLOYMENT only from WITH_AUTHORITYapps/api/src/lg/services/lg-cases.ts:117 openCase moves the request to CASE_OPENED through moveStatus BEFORE creating the LgCase (move refused then nothing created)apps/api/src/lg/services/lg-cases.ts:120 LgCase created with requestId (unique then keeps the request reference), levels[0] = first instanceapps/api/src/lg/routes/cases.ts:203 POST /lg/cases/:requestId/open, zod caseBody, requireActpackages/shared/src/legalModules.ts:796 status table: WITH_AUTHORITYthenCASE_OPENED for EMPLOYMENT; 828-829 UNDER_REVIEW / WITH_EXTERNAL_COUNSELthenCASE_OPENED for Disputesapps/web/src/lg/request/tabs/LgCaseTab.tsx:62 'Open case' button on the Case tab when canOpen | cases.test.ts opens a case from a dispute under review; only those who act cancases.test.ts employment cases only from With authoritypi-legal-litigation /workspace/pi-for-legal/lg/requests/<disputes ref>/case 'Open case' then dialog (case number, court) then request header shows status Case opened, same reference |
| AC2 | Given a case, then hearings, deadlines, judgments, appeals, counsel fees, claim and exposure amounts can be recorded. | Implemented | apps/api/src/lg/services/lg-cases.ts:183 upsertDated: add/edit hearings (date, purpose, outcome, nextSteps) and deadlines (date, description, done)apps/api/src/lg/services/lg-cases.ts:226 recordJudgment: date, outcome, amount, currency; needs the judgment document; then JUDGEMENTapps/api/src/lg/services/lg-cases.ts:259 appeal(): new level on the same case then CASE_OPENEDapps/api/src/lg/services/lg-cases.ts:159 updateCase: claimAmount, currency, counterclaim, exposure, exposureAmount, externalCounsel (fees)apps/api/src/lg/routes/cases.ts:40 counsel schema: firm, lawyerName, contacts, engagementDate, feeArrangement, feesAgreed, feesInvoicedapps/web/src/lg/request/tabs/LgCaseTab.tsx:142 Hearings / Deadlines sections with Add, Edit, Remove; 156 Levels and judgments; 175 Execution; 184-227 dialogs | cases.test.ts records hearings and reminds the lawyer 7 days and 1 day before, once eachcases.test.ts judgment then appeal (new level) then judgment then executionpi-legal-litigation /workspace/pi-for-legal/lg/requests/<ref>/case Add hearing, Add deadline, Record judgment (needs a file), Appeal, Execution, Edit case (claim/exposure/counsel fees) all save and appear in the tab |
| AC3 | Given a hearing or deadline, then the lawyer is reminded 7 days and 1 day before. | Implemented | apps/api/src/lg/services/lg-case-reminders.ts:18 runCaseReminders: for every open case, each hearing/deadline not done; windows LG_ALERTS.hearingpackages/shared/src/legalModules.ts:1030 LG_ALERTS.hearing = [7, 1]apps/api/src/lg/services/lg-case-reminders.ts:46 lgEmail HEARING_REMINDER to request.assignedLawyerId; remindersSent marker makes it idempotent; a changed date resets (lg-cases.ts:198)apps/api/src/lg/services/lg-jobs.ts:9 hourly scheduler runs runCaseReminders under an advisory lock | cases.test.ts records hearings and reminds the lawyer 7 days and 1 day before, once eachcases.test.ts no hearing reminders once the request is closed (G-14)API POST /api/lg/jobs/run (as pi-legal-gc) with a hearing dated 7 days ahead, then open /workspace/pi-for-legal/lg/mailbox › Sent 200; a HEARING_REMINDER email to the assigned lawyer appears once; a second run sends nothing |
| AC4 | Given an appeal, then it's added as a new level on the same case. | Implemented | apps/api/src/lg/services/lg-cases.ts:259 appeal(): validates level (Appeal/Cassation), moveStatus then CASE_OPENED with reason 'Appeal · level'apps/api/src/lg/services/lg-cases.ts:265 levels[] appended {level, caseNumber, court, openedAt}; case.level/caseNumber/court updated on the SAME LgCase rowpackages/shared/src/legalModules.ts:833 JUDGEMENTthenCASE_OPENED labelled 'Appeal'apps/web/src/lg/request/tabs/LgCaseTab.tsx:83 Appeal button only while status is JUDGEMENT; 205 level select excludes First instance | cases.test.ts judgment then appeal (new level) then judgment then executionpi-legal-litigation /workspace/pi-for-legal/lg/requests/<ref>/case after Record judgment, click Appeal then 'Levels and judgments' lists two levels, status back to Case opened, same case id |
| AC5 | Given a case is closed, then the outcome, final amounts and a closing note are required. | Implemented | apps/api/src/lg/services/lg-cases.ts:304 closeCase refuses without outcome / numeric finalAmount / closingNote (400); then moveStatus CLOSED_COMPLETED (fromCase) which also needs the final replyapps/api/src/lg/routes/cases.ts:282 POST /close zod: outcome min 1, finalAmount number, closingNote min 1, optional settlementapps/web/src/lg/request/tabs/LgCaseTab.tsx:215 'Close case (completed)' dialog with required outcome, final amount, closing note | cases.test.ts closing needs outcome, final amount, closing note and a final replyAPI POST /api/lg/cases/<requestId>/close {outcome:'Paid', finalAmount:1000, closingNote:''} 400 'A closing note is required'; with all three and a Final reply posted then 200 and status Closed (completed) |
| AC6 | Given any user, then case access follows R-19. | Implemented | apps/api/src/lg/routes/cases.ts:84 visibleCases: case list filtered by visibleRequestWhere(actor) in the databaseapps/api/src/lg/routes/cases.ts:182 GET /:requestId via loadRequestForActor (404 when not visible; approver-only then 404)apps/api/src/lg/routes/cases.ts:197 actable(): every write needs requireAct (assigned lawyer, queue team lead, GC)apps/api/src/lg/services/lg-access.ts:118 confidential: only GC, requester, copy, GC-added consults, approvers for their stepapps/api/src/lg/services/lg-access.ts:136 lawyers: canView all non-confidential, canAct = assigned || leadsapps/api/src/lg/services/lg-access.ts:156 visibleRequestWhere: requester/cc/lawyers(non-confidential)/GC | cases.test.ts requester and copy view; other lawyers view; outsiders get nothingcases.test.ts opens a case from a dispute under review; only those who act canAPI PATCH /api/lg/cases/<requestId> {court:'x'} as pi-legal-requester 403; GET same path as requester then 200 with canAct:false; as a non-involved business user then 404 |
| Desc: Case record fields (number, court, level, parties, counsel + fees, claim/counterclaim, exposure, hearings, deadlines, judgments, levels, execution) | Case record: case number; court or authority; level; parties and roles; external counsel (engagement date, fee arrangement, fees invoiced); claim amount and currency; counterclaim; exposure assessment and amount; hearings; deadlines; judgments; appeals; execution. | Implemented | apps/api/prisma/schema.prisma:5238 model LgCase: caseNumber, court, level, parties, externalCounsel, settlement, claimAmount, currency, counterclaim, exposure, exposureAmount, hearings, deadlines, judgments, levels, execution, outcome, finalAmount, closingNoteapps/api/src/lg/services/lg-cases.ts:25 LgHearing {date, purpose, outcome, nextSteps}; LgDeadline; LgJudgment {date, level, outcome, amount, currency, documentId}; LgCounsel {engagementDate, feeArrangement, feesInvoiced}; LgExecution {recovered, paid}packages/shared/src/legalModules.ts:1148 LG_CASE_LEVELS = First instance / Appeal / Cassation; LG_EXPOSURE = Probable / Possible / Remoteapps/web/src/lg/request/tabs/LgCaseTab.tsx:92 Facts strip: Claim, Counterclaim, Exposure, Parties, External counsel, Engaged, Fee arrangement, Fees invoiced | cases.test.ts judgment then appeal (new level) then judgment then executionv1-gaps.test.ts external counsel contact details are kept and validatedpi-legal-litigation /workspace/pi-for-legal/lg/requests/<ref>/case every field group above is visible and editable on the Case tab |
| Desc: Documents in the request's SharePoint folder (R-16) | Documents in the request's SharePoint folder (R-16). | Implemented | apps/api/src/lg/services/lg-cases.ts:241 the judgment file is stored with storeDocument(docType 'Judgment') on the request then named by convention, SHAREPOINT storage when the folder is linkedapps/web/src/lg/request/tabs/LgCaseTab.tsx:166 'judgment in Documents' pointer; the case shares the request's Documents tab (apps/web/src/lg/request/tabs/LgDocumentsTab.tsx)apps/api/src/lg/services/lg-lifecycle.ts:97 folder gate: a Disputes request cannot reach Case opened without a linked SharePoint folder | cases.test.ts judgment then appeal (new level) then judgment then executionpi-legal-litigation /workspace/pi-for-legal/lg/requests/<ref>/documents the Judgment document appears under the request's folder with the convention name |
| Desc: Execution amounts recovered or paid | Execution: amounts recovered or paid. | Implemented | apps/api/src/lg/services/lg-cases.ts:272 recordExecution: JUDGEMENT then EXECUTION then stores {recovered, paid, notes}; refused before a judgmentapps/api/src/lg/routes/cases.ts:272 POST /:requestId/executionapps/web/src/lg/request/tabs/LgCaseTab.tsx:210 Execution dialog | cases.test.ts judgment then appeal (new level) then judgment then executionAPI POST /api/lg/cases/<requestId>/execution {paid: 200000} 200 and status Execution; 409 'Execution follows a judgment' when no judgment yet |
| Desc: Cases list for the legal team | (implied) lawyers need a list of cases with next hearing/deadline, exposure and fees, exportable. | Implemented | apps/api/src/lg/routes/cases.ts:127 GET /lg/cases paged + X-Total-Count, scoped by visibleRequestWhere; /summary totals per currency; /export xlsx auditedapps/web/src/lg/pages/LgCasesPage.tsx:63 Cases page: Open/Closed/All, search, StatStrip, Export, Load more | cases.test.ts pages with a total, totals every matching case, and exports open and closed cases (H-G5, H-G15)pi-legal-gc /workspace/pi-for-legal/lg/cases list with next hearing, exposure, fees; Export downloads legal-cases-<date>.xlsx |
| As | Call | HTTP | Response |
|---|---|---|---|
| req | GET /cases/07da3720-1f46-4704-9fec-9a76bd9f1fe9 | 404 | Request not found expected: 404 (not the requester of that case) |
| lit | GET /cases/07da3720-1f46-4704-9fec-9a76bd9f1fe9 | 200 | data returned expected: 200 case record: hearings, deadlines, counsel, exposure |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given an IP request moves to With IP agent / office, then an IP record is created and linked to it. | Implemented | apps/api/src/lg/routes/requests.ts:256 status route: after the move to WITH_IP_AGENT then createIpFromRequest (try/catch, advisory , a failure never blocks the move)apps/api/src/lg/services/lg-ip.ts:19 createIpFromRequest: 5.1 'New' filing then one LgIpRecord per jurisdiction (answers.jurisdictions), linkedRequestIds=[request], request.linkedIpId set, lawyerId = assigned lawyer, audited CREATEapps/api/src/lg/services/lg-ip.ts:42 a request already linked (raised from an alert) or a renewal/opposition/infringement links to the existing right instead of creating a duplicate | registers.test.ts With IP agent creates a linked record; only IP lawyers and the GC editregisters.test.ts IP: one record per jurisdiction; renewals link to the existing right; alerts go to the responsible lawyer (G-07, G-08, G-10)API POST /api/lg/requests/<5.1 request id>/status {to:'WITH_IP_AGENT', documentId:<filing receipt>} 200; then GET /api/lg/registers/ip?q=<mark> lists a FILED record per jurisdiction with the request in linkedRequests |
| AC2 | Given a renewal date, then the IP lawyer and the GC are alerted 6, 3 and 1 months before, and the Renewal due flag shows. | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:167 IP renewals loop: windows LG_ALERTS.ipRenewalMonths [6,3,1] (legalModules.ts:1029), alertsSent marker per windowapps/api/src/lg/services/lg-register-alerts.ts:180 toUserIds = responsible lawyerId (else the IP queue) + GC; email links to /lg/registers/ip?id=apps/api/src/lg/services/lg-registers.ts:84 ipFlags.renewalDue when live status and renewalDate ≤ 6 months awayapps/web/src/lg/components/registers/IpView.tsx:137 'Renewal due' chip in the list and the detail (175), days-left text; Alerts filter 'Renewal due' (122) | registers.test.ts With IP agent creates a linked record; only IP lawyers and the GC editregisters.test.ts IP: one record per jurisdiction; renewals link to the existing right; alerts go to the responsible lawyer (G-07, G-08, G-10)pi-legal-gc /workspace/pi-for-legal/lg/registers/ip set a renewal date within 6 months on a record then 'Renewal due' chip; POST /api/lg/jobs/run then REGISTER_ALERT email to the responsible lawyer and the GC in Mailbox › Sent |
| AC3 | Given a user who isn't an IP-queue lawyer or the GC, then they can view records but not edit them. | Implemented | apps/api/src/lg/services/lg-registers.ts:21 canEdit('ip'): GC, else legal member of queue 'IP'apps/api/src/lg/routes/registers.ts:881 POST /ip and PATCH /ip/:id then forbidEdit 403 'Only IP-queue lawyers and the General Counsel can create or edit IP records'apps/api/src/lg/routes/registers.ts:57 handle(): any legal user (lawyer or GC) can GET; non-legal then 404apps/web/src/lg/components/registers/IpView.tsx:69 canEdit = isGc || queues includes 'IP' gates New record / Edit / Import buttons | registers.test.ts With IP agent creates a linked record; only IP lawyers and the GC editAPI PATCH /api/lg/registers/ip/<id> {status:'REGISTERED'} as pi-legal-counsel (Commercial) 403; GET /api/lg/registers/ip/<id> as the same user then 200 with canEdit:false |
| AC4 | Given an infringement request, then the lawyer can link it to the affected record. | Implemented | apps/api/src/lg/routes/registers.ts:903 POST /ip/:id/link-request {requestId|reference}: IP requests only; adds to linkedRequestIds and sets request.linkedIpId; auditedapps/api/src/lg/services/lg-ip.ts:24 5.2 infringement moving to With IP agent auto-links to the same mark in the same jurisdiction/entity (46-55); nothing created when the right isn't on the register (57)apps/web/src/lg/components/registers/IpView.tsx:91 'Link request' input on the record detail | registers.test.ts IP: one record per jurisdiction; renewals link to the existing right; alerts go to the responsible lawyer (G-07, G-08, G-10)pi-legal-gc /workspace/pi-for-legal/lg/registers/ip › open a record enter a 5.2 request reference in 'Link request' then it appears under Linked requests; the request's overview shows the linked record |
| AC5 | Given a status change, then it's logged, and records can't be deleted. | Implemented | apps/api/src/lg/routes/registers.ts:898 PATCH: lgAuditDiff('Ip', …, IP_FIELDS) logs every changed field incl. status with old/new valuesapps/api/src/lg/services/lg-ip.ts:38 automatic OPPOSED status change audited with old/newapps/api/src/lg/routes/registers.ts:321 commonRoutes DELETE /ip/:id then 405 'Register records are never deleted. Change the status instead.' + DELETE_BLOCKED auditapps/api/src/lg/routes/registers.ts:874 historyFor('ip') returned with the record; VIEW audited (876) | registers.test.ts shows the group structure and never deletesnfr.test.ts is append-only in the database; old views age out under retention onlyAPI DELETE /api/lg/registers/ip/<id> as pi-legal-gc 405; PATCH status then GET /ip/<id>.history shows the status change with actor and time |
| Desc: One record per right per jurisdiction: trademarks, patents, designs, domain names | Scope. One record per right per jurisdiction: trademarks, patents, designs and domain names. | Implemented | packages/shared/src/legalModules.ts:1020 LG_IP_TYPES = Trademark, Patent, Design, Domain nameapps/api/prisma/schema.prisma:5285 LgIpRecord: ipType, title, jurisdiction … one row per right per jurisdictionapps/api/src/lg/services/lg-ip.ts:62 one row per jurisdiction listed in the request answers | registers.test.ts IP: one record per jurisdiction; renewals link to the existing right; alerts go to the responsible lawyer (G-07, G-08, G-10)pi-legal-gc /workspace/pi-for-legal/lg/registers/ip New IP record offers the four types; a mark filed in UAE; KSA shows two rows |
| Desc: Fields (owner entity, BU, type, mark/title/domain, logo, classes, goods/services, jurisdiction, filing/registration no. and dates, agent, status, renewal date, linked requests, documents) | Fields. Owner entity and business unit; type; mark, title or domain, and logo image; classes and goods and services; jurisdiction; filing number and date; registration number and date; agent or registrar; status; renewal date; linked requests and documents. | Implemented | apps/api/src/lg/routes/registers.ts:143 ipSchema: entityId, businessUnitId, ipType, title, logoDocumentId, classes, goodsServices, jurisdiction, filingNumber, filingDate, registrationNumber, registrationDate, agent, status, renewalDate, lawyerIdapps/api/src/lg/routes/registers.ts:870 GET /ip/:id returns documents (documentsFor 'IP'), history, linkedRequestsapps/web/src/lg/components/registers/IpView.tsx:51 IpLogo renders the logo from the record's documents; 75-81 logo upload sets logoDocumentId | registers.test.ts With IP agent creates a linked record; only IP lawyers and the GC editpi-legal-gc /workspace/pi-for-legal/lg/registers/ip › record all fields present in the edit sheet; logo upload shows the image; Documents and Linked requests sections |
| Desc: IP-queue lawyers can add records manually | Records … IP-queue lawyers can also add records manually. | Implemented | apps/api/src/lg/routes/registers.ts:881 POST /ip (canEdit) creates a record, audited CREATEapps/web/src/lg/components/registers/IpView.tsx:126 'New IP record' button for IP lawyers / GC | no automated test API POST /api/lg/registers/ip {ipType:'Trademark', title:'X', jurisdiction:'UAE'} as an IP-queue lawyer 201 |
| Desc: Import existing records from Excel at launch; export the register | Existing records can be imported from Excel at launch, and the register can be exported. | Implemented | apps/api/src/lg/routes/registers.ts:342 commonRoutes(router,'ip', …) then GET /ip/export (xlsx, audited) and POST /ip/import {content, apply} with preview-then-apply (271-285)apps/api/src/lg/services/lg-register-io.ts:119 IP_COLS column spec (type required, options LG_IP_TYPES); sheet 'IP portfolio' (136); applyImport maps to lgIpRecord (410)apps/web/src/lg/components/registers/IpView.tsx:125 ImportExportButtons kind='ip' | registers.test.ts exports a workbook that imports back as updates, with a preview firstnfr.test.ts imports 1,000 contracts in under 10 seconds, with references allocatedpi-legal-gc /workspace/pi-for-legal/lg/registers/ip Export downloads ip-register-<date>.xlsx; Import of that file previews rows then applies |
| Desc: Statuses Filed, Published, Opposed, Registered, Expired, Abandoned, Cancelled; flag Renewal due | Statuses. Filed, Published, Opposed, Registered, Expired, Abandoned, Cancelled. Flag: Renewal due. | Implemented | packages/shared/src/legalModules.ts:1021 LG_IP_STATUSES exactly the seven; labels at 1022apps/api/src/lg/services/lg-registers.ts:84 renewalDue flag (not for EXPIRED/ABANDONED/CANCELLED) | registers.test.ts With IP agent creates a linked record; only IP lawyers and the GC editpi-legal-gc /workspace/pi-for-legal/lg/registers/ip Status filter lists the seven statuses; Alerts filter 'Renewal due' |
| Desc: From an alert the lawyer can raise a linked IP request | From an alert, the lawyer can raise a linked IP request. | Implemented | apps/api/src/lg/services/lg-register-alerts.ts:181 alert email text and link to the recordapps/api/src/lg/routes/registers.ts:918 POST /ip/:id/raise-request then /lg/new?type=5.1&ip=<id>apps/web/src/lg/components/registers/IpView.tsx:179 'Raise renewal request' button when renewalDueapps/api/src/lg/services/lg-ip.ts:42 on With IP agent the draft's linkedIpId links back to the same record | registers.test.ts IP: one record per jurisdiction; renewals link to the existing right; alerts go to the responsible lawyer (G-07, G-08, G-10)pi-legal-gc /workspace/pi-for-legal/lg/registers/ip › record with Renewal due 'Raise renewal request' opens the 5.1 intake prefilled; after submission the record's Linked requests shows it |
| Desc: Portfolio view filters by BU, entity, jurisdiction, class, type, status | Portfolio view. Filter by business unit, entity, jurisdiction, class, type and status. | Implemented | apps/api/src/lg/routes/registers.ts:838 GET /ip query: businessUnitId, entityId, jurisdiction, classes, ipType, status, q, flag=renewalDue; paged with X-Total-Countapps/web/src/lg/components/registers/IpView.tsx:105 search, Type, Status, Entity, Business unit, Jurisdiction, Class, Alerts filters | nfr.test.ts document search and the contract and IP registers page with a totalpi-legal-counsel /workspace/pi-for-legal/lg/registers/ip each filter narrows the list; 'Showing N of M · Load more' |
| Desc: Access , IP lawyers and GC edit, all lawyers view, never deleted, every change logged | Access. IP-queue lawyers and the GC can edit. All lawyers can view. Records are never deleted, and every change is logged. | Implemented | apps/api/src/lg/services/lg-registers.ts:21 canEditapps/api/src/lg/routes/registers.ts:57 legal-only viewapps/api/src/lg/routes/registers.ts:321 delete refused 405apps/api/src/lg/routes/registers.ts:898 lgAuditDiff on every edit | registers.test.ts With IP agent creates a linked record; only IP lawyers and the GC editAPI GET /api/lg/registers/ip as pi-legal-requester 404 (not legal); as any lawyer 200 |
| As | Call | HTTP | Response |
|---|---|---|---|
| counsel | GET /registers/ip | 200 | data returned expected: 200 |
| counsel | POST /registers/ip{"type": "TRADEMARK", "title": "x"} | 403 | Only IP-queue lawyers and the General Counsel can create or edit IP records expected: 403: only IP-queue lawyers and the GC edit |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| AC1 | Given a user opens the dashboard, then they see the view for their role, limited by R-19. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:47 allowedViews: gc / team_lead (leadQueues) / lawyer / businessapps/api/src/lg/routes/dashboard.ts:27 parse(): default = highest allowed view; a view outside allowedViews then 403apps/api/src/lg/services/lg-dashboard.ts:88 scopeWhere: gc all; team_lead own queues; lawyer assigned + open consults; business requester/ccapps/api/src/lg/services/lg-dashboard.ts:248 listable(): confidential rows only for GC, the assigned lawyer or the requesterapps/web/src/lg/pages/LgDashboardPage.tsx:112 Segmented view switcher only when more than one view is allowed | dashboard.test.ts business users see their own requests and what waits on themdashboard.test.ts lawyers see their open, overdue and waiting work, consults and hearingsdashboard.test.ts team leads count confidential requests but never list themdashboard.test.ts the GC sees the metrics; filters change themAPI GET /api/lg/dashboard?view=gc as pi-legal-requester 403 'You can't open that dashboard view'; without ?view then view:'business' |
| AC2 | Given any filter, then all figures update to match. The success-criteria figures for abandoned drafts/drop-off and filing compliance ignore the BU/entity/type/queue/lawyer filters (filing ignores the period too). Everything else follows the filters. | Minor difference | apps/api/src/lg/services/lg-dashboard.ts:71 filterWhere: period (submittedAt), businessUnitId, entityId, typeCode, queueKey, lawyerId applied to flow and snapshot queries (242-245)apps/api/src/lg/services/lg-dashboard.ts:290 consults, 352 queue panel, 414 register counts (regWhere), 534 send-back quarters all take the filtersapps/api/src/lg/services/lg-dashboard.ts:548 drafts.abandoned / draftsStarted / draftsSubmitted: workspace-wide (period only), ignore BU/entity/type/queue/lawyerapps/api/src/lg/services/lg-dashboard.ts:556 filing compliance docsMeant/docsFiled: no filter at all (whole workspace, all time)apps/web/src/lg/pages/LgDashboardPage.tsx:88 Period, Business unit, Entity, Type, Queue, Lawyer selects; BarList clicks set filters (243-246) | dashboard.test.ts the GC sees the metrics; filters change themdashboard.test.ts filters reach consults, the queue panel and the register counts (G-11)pi-legal-gc /workspace/pi-for-legal/lg/dashboard change Type or Lawyer then KPI strip, volumes, SLA, litigation all change; note the Success-criteria 'Documents filed by convention' and 'Drafts untouched' tiles do not |
| AC3 | Given a team lead, then confidential requests are counted in totals but not listed. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:361 queue open / confidentialOpen counts include confidential requests; per-lawyer counts too (368-371)apps/api/src/lg/services/lg-dashboard.ts:380 breached rows filtered by listable(); upcoming hearing titles then 'Confidential' (301)apps/api/src/lg/services/lg-dashboard.ts:254 totals.confidential count in the stripapps/web/src/lg/pages/LgDashboardPage.tsx:203 'N confidential' badge per queue; 228 note 'counted, never listed' | dashboard.test.ts team leads count confidential requests but never list thempi-legal-counsel /workspace/pi-for-legal/lg/dashboard (Team lead view) Queue workload shows '· 1 confidential' in the Commercial count while no confidential title appears anywhere on the page or in the export |
| AC4 | Given the GC, then they see time to first response, replies per request, SLA breaches, ageing by bucket, send-backs per request, self-service generation metrics, AI review metrics and litigation exposure. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:747 timeToFirstResponseDays (business days assignmentthenResponse, 440), repliesPerRequest (748), sendBacksPerRequest (749)apps/api/src/lg/services/lg-dashboard.ts:215 slaSummary met/breached/metLate/openBreached/metPct then base.slaapps/api/src/lg/services/lg-dashboard.ts:395 ageingByBucket (legal) + selfServiceAgeing; included in the GC payload via teamLead (786)apps/api/src/lg/services/lg-dashboard.ts:756 generation: generated, converted, conversionRate, avgDaysToSignature, byTemplateapps/api/src/lg/services/lg-dashboard.ts:765 aiReview: reviews, findings, decisions, redLine, byRiskapps/api/src/lg/services/lg-dashboard.ts:785 litigation: openCases, exposure by band and currency, counselFees, case rowsapps/web/src/lg/pages/LgDashboardPage.tsx:249 Metric tiles; 255 Self-service generation; 280 AI review; 295 Litigation exposure; 175 SLA; 176 ageing | dashboard.test.ts the GC sees the metrics; filters change themdashboard.test.ts contract risk, approvals and litigation per currency for the GC (G-12, G-21)pi-legal-gc /workspace/pi-for-legal/lg/dashboard GC view shows Time to first response, Replies per request (send-backs in hint), SLA performance, 'Where open requests are waiting' buckets, Self-service generation, AI review, Litigation exposure |
| AC5 | Given any dashboard view, then it can be exported to Excel. | Implemented | apps/api/src/lg/routes/dashboard.ts:59 GET /lg/dashboard/export?view=… builds the same view and streams .xlsx; EXPORT auditedapps/api/src/lg/services/lg-dashboard.ts:812 exportDashboardXlsx: Summary, Open by status, Weekly volume + per-view sheets (business, lawyer, Workload/Queues/Ageing, GC metrics, Success criteria, Exposure, Open cases, Withdrawals, Deviations…)apps/web/src/lg/pages/LgDashboardPage.tsx:139 'Export to Excel' button for the active view | dashboard.test.ts every view exports to Excel; the GC gets the monthly reportv1-gaps.test.ts every breakdown is in the GC Excel exportpi-legal-requester /workspace/pi-for-legal/lg/dashboard Export to Excel downloads legal-dashboard-business-<date>.xlsx with My requests / Waiting on me / Contracts expiring sheets |
| Desc: Business user dashboard , their requests and status, what's waiting on them, contracts nearing expiry | Business user: Their requests and status; what's waiting on them; their contracts nearing expiry. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:258 business view: mine (live), waitingOnMe (statuses awaiting requester/business/confirmation), contractsExpiring ≤ 90 days owned/requested/linkedapps/web/src/lg/pages/LgDashboardPage.tsx:147 Waiting on you / Your requests / Your contracts nearing expiry panels | dashboard.test.ts business users see their own requests and what waits on thempi-legal-requester /workspace/pi-for-legal/lg/dashboard three panels; a Completed request awaiting confirmation sits under Waiting on you |
| Desc: Lawyer dashboard , my open, due and overdue; consults; waiting on others; upcoming hearings and deadlines | Lawyer: My open requests, due and overdue; consults; waiting on others; upcoming hearings and deadlines. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:286 lawyer: open, dueSoon, overdue, consults (open, assigned to me), waitingOnOthers (non-LEGAL ageing bucket), upcoming hearings/deadlines next 30 daysapps/web/src/lg/pages/LgDashboardPage.tsx:425 LawyerPanels: Overdue, My open requests, Waiting on others, Consults for me, Register entries to confirm, Hearings and deadlines | dashboard.test.ts lawyers see their open, overdue and waiting work, consults and hearingspi-legal-litigation /workspace/pi-for-legal/lg/dashboard (Lawyer view) Hearings and deadlines panel lists the next 30 days from open cases |
| Desc: Team lead dashboard , queue workload per lawyer incl. consults; SLA met/breached; ageing by bucket; out-of-office cover | Team lead: Queue workload per lawyer (including consults); SLA met and breached; ageing by bucket; out-of-office cover. 'Out-of-office cover' shows only the OOO flag and until-date per lawyer; the covering delegate (LgProfile.delegateUserId) is not named on the dashboard. | Minor difference | apps/api/src/lg/services/lg-dashboard.ts:355 workload per queue: open, confidentialOpen, unassigned, per-lawyer open/consults/overdue/outOfOffice/oooUntil, breached rowsapps/api/src/lg/services/lg-dashboard.ts:395 ageing by bucket (legal) and self-service ageing; closed-in-period ageing (397-416)apps/api/src/lg/services/lg-dashboard.ts:251 base.sla (met/breached) on every viewapps/web/src/lg/pages/LgDashboardPage.tsx:196 Queue workload panel; 211 plane icon 'Out of office' per lawyer | dashboard.test.ts team leads count confidential requests but never list thempi-legal-counsel /workspace/pi-for-legal/lg/dashboard (Team lead) Queue workload lists each lawyer with open + consults, overdue, an out-of-office marker; SLA performance and ageing panels |
| Desc: GC dashboard , everything above across all queues plus GC metrics | GC: Everything above across all queues, plus the GC metrics below. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:89 scopeWhere gc = no restrictionapps/api/src/lg/services/lg-dashboard.ts:339 scopeQueues = every queue for the GCapps/api/src/lg/services/lg-dashboard.ts:786 GC payload returns lawyer + teamLead + gc sectionsapps/web/src/lg/pages/LgDashboardPage.tsx:172 team-lead panels rendered for the GC too; 237 GC panels; 380 own work | dashboard.test.ts the GC sees the metrics; filters change thempi-legal-gc /workspace/pi-for-legal/lg/dashboard all queues in Queue workload, plus the GC metric panels |
| Desc: GC metric , volumes by business unit, entity, type and lawyer | Volumes by business unit, entity, type and lawyer. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:741 gc.volumes.byBusinessUnit/byEntity/byType/byLawyerapps/web/src/lg/pages/LgDashboardPage.tsx:243 four Volume panels, click-to-filter | dashboard.test.ts the GC sees the metrics; filters change thempi-legal-gc /workspace/pi-for-legal/lg/dashboard Volume by business unit / entity / type / lawyer |
| Desc: GC metric , SLA met % and breaches | SLA met % and breaches. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:215 slaSummary metPct, met, breached, metLate, openBreachedapps/web/src/lg/pages/LgDashboardPage.tsx:175 SlaMeter | dashboard.test.ts the GC sees the metrics; filters change thempi-legal-gc /workspace/pi-for-legal/lg/dashboard SLA performance meter with met/breached counts |
| Desc: GC metric , time to first response | Time to first response. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:440 firstResponse = business days from assignedAt to slaMetAt (the Response-tagged reply)apps/api/src/lg/services/lg-dashboard.ts:747 timeToFirstResponseDays | no automated test pi-legal-gc /workspace/pi-for-legal/lg/dashboard 'Time to first response' tile, hint 'assignment then Response' |
| Desc: GC metric , replies per request | Replies per request. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:441 REPLY thread entries grouped per requestapps/api/src/lg/services/lg-dashboard.ts:748 repliesPerRequest over lawyer-handled requests | no automated test pi-legal-gc /workspace/pi-for-legal/lg/dashboard 'Replies per request' tile |
| Desc: GC metric , confidential requests assigned while the GC is out of office | Confidential requests assigned while the GC is out of office. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:473 whileAway = confidential requests stamped assignedWhileGcOoo at routingapps/api/src/lg/services/lg-dashboard.ts:750 confidentialWhileGcOoo + rowsapps/web/src/lg/pages/LgDashboardPage.tsx:252 tile; 372 panel listing them | dashboard.test.ts confidential requests routed while the GC was away are counted from the routing stamp (G-20)pi-legal-gc /workspace/pi-for-legal/lg/dashboard 'Confidential while GC away' tile and the panel listing those requests |
| Desc: GC metric , ageing by bucket | Ageing by bucket. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:395 ageingByBucket over open lawyer-handled requests; selfServiceAgeing separate (R-17)apps/web/src/lg/pages/LgDashboardPage.tsx:176 'Where open requests are waiting' panel | timers.test.ts (ageing tests in timers/lifecycle suites)pi-legal-gc /workspace/pi-for-legal/lg/dashboard ageing buckets in business days |
| Desc: GC metric , send-backs per request | Send-backs per request. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:442 SEND_BACK rounds grouped per requestapps/api/src/lg/services/lg-dashboard.ts:749 sendBacksPerRequestapps/web/src/lg/pages/LgDashboardPage.tsx:250 shown as the hint of 'Replies per request' | no automated test pi-legal-gc /workspace/pi-for-legal/lg/dashboard 'send-backs per request: N' under Replies per request; also 'Send-back and feedback rounds' panel (532) |
| Desc: GC metric , approval and signature cycle times | Approval and signature cycle times. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:753 approvalCycleDays (round startthenend) and signatureCycleDays (envelope sentthencompleted) in business daysapps/api/src/lg/services/lg-dashboard.ts:780 approvals block: openRounds, avgOpenAgeDays, cycleDays, outcomes, byApproverapps/web/src/lg/pages/LgDashboardPage.tsx:251 'Approval cycle' tile with signature cycle hint; 350 Approvals panel | dashboard.test.ts contract risk, approvals and litigation per currency for the GC (G-12, G-21)pi-legal-gc /workspace/pi-for-legal/lg/dashboard Approval cycle tile and Approvals panel |
| Desc: GC metric , self-service generation (contracts generated, conversion rate, time to signature) | Self-service generation (contracts generated, conversion rate, time to signature). | Implemented | apps/api/src/lg/services/lg-dashboard.ts:462 generated / converted / genSigned days; per-template rowsapps/api/src/lg/services/lg-dashboard.ts:756 gc.generationapps/web/src/lg/pages/LgDashboardPage.tsx:255 Self-service generation panel: generated, converted, conversion rate, to signature | no automated test pi-legal-gc /workspace/pi-for-legal/lg/dashboard Self-service generation panel |
| Desc: GC metric , AI review findings accepted vs dismissed, and red-line decisions | AI review findings accepted vs dismissed, and red-line decisions. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:448 decisions{ACCEPTED/DISMISSED/EDITED/UNDECIDED…} and redLine{…} per findingapps/api/src/lg/services/lg-dashboard.ts:765 gc.aiReviewapps/web/src/lg/pages/LgDashboardPage.tsx:280 AI review panel with decision bars | no automated test pi-legal-gc /workspace/pi-for-legal/lg/dashboard AI review panel: findings by decision, red-line decisions |
| Desc: GC metric , register alerts (contracts, POA, licences, IP) | Register alerts (contracts, POA, licences, IP). | Implemented | apps/api/src/lg/services/lg-dashboard.ts:414 counts: contracts ≤90d/notice, POAs ≤60d, licences ≤90d, IP renewals ≤6m (entity/BU filtered)apps/api/src/lg/services/lg-dashboard.ts:766 gc.registerAlertsapps/web/src/lg/pages/LgDashboardPage.tsx:286 Register alerts panel with links to each register | dashboard.test.ts filters reach consults, the queue panel and the register counts (G-11)pi-legal-gc /workspace/pi-for-legal/lg/dashboard Register alerts panel |
| Desc: GC metric , litigation exposure and counsel fees | Litigation exposure and counsel fees. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:426 exposure by Probable/Possible/Remote per currency; counselFeesByCurrency (feesInvoiced)apps/api/src/lg/services/lg-dashboard.ts:785 gc.litigationapps/web/src/lg/pages/LgDashboardPage.tsx:295 Litigation exposure panel: total exposure, counsel fees, case rows | dashboard.test.ts the GC sees the metrics; filters change themdashboard.test.ts contract risk, approvals and litigation per currency for the GC (G-12, G-21)pi-legal-gc /workspace/pi-for-legal/lg/dashboard Litigation exposure panel; 'All cases' link to /lg/cases |
| Desc: Filters by period, business unit, entity, type, queue and lawyer | Using the dashboards. Filters by period, business unit, entity, type, queue and lawyer. | Implemented | apps/api/src/lg/routes/dashboard.ts:37 query from/to/businessUnitId/entityId/typeCode/queueKey/lawyerId (lawyer filter only for legal users)apps/web/src/lg/pages/LgDashboardPage.tsx:88 six filter controls | dashboard.test.ts the GC sees the metrics; filters change thempi-legal-gc /workspace/pi-for-legal/lg/dashboard Period, Business unit, Entity, Type, Queue, Lawyer selects |
| Desc: Monthly legal function report and Power BI dataset (beyond R-30, serves the DoD) | (DoD) GC can produce a monthly legal function report; dashboards exportable to Excel/Power BI. | Implemented | apps/api/src/lg/routes/dashboard.ts:72 GET /monthly-report?month (GC) then monthlyReportXlsx (Cover, Backlog at month end, Requests this month, Cases, Register changes, Contract risk, Approvals by approver)apps/api/src/lg/routes/dashboard.ts:85 GET /dataset.csv|.xlsx flat R-19-scoped table for Power BI 'Get data then Web'docs/pi-for-legal/DESIGN.md:119 decision recorded: Power BI via dataset endpointapps/web/src/lg/pages/LgDashboardPage.tsx:127 Monthly report button; 132 Dataset menu | dashboard.test.ts the monthly report has a cover, month-end backlog, cases and register changes (G-22)dashboard.test.ts a flat dataset for Excel or Power BI, scoped by R-19 (G-15)pi-legal-gc /workspace/pi-for-legal/lg/dashboard 'Monthly report' downloads legal-monthly-report-<YYYY-MM>.xlsx; Dataset then Excel/CSV |
| As | Call | HTTP | Response |
|---|---|---|---|
| gc | GET /dashboard/export | 200 | {"_raw": "\u2026"} expected: 200 xlsx |
| gc | GET /dashboard/monthly-report?month=2026-11 | 200 | {"_raw": "\u2026"} expected: 200 xlsx (monthly legal function report) |
| req | GET /dashboard | 200 | data returned expected: 200 business-user view only |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Sign-in, roles and user profiles | Access for users outside 7X (counterparties, external counsel); managing Entra ID groups inside the LMS. | Implemented | apps/api/src/lg/middleware/lg-auth.ts:4 actor comes from the workspace bridge (membership already proven); Legal roles from LgProfile , no external/guest pathapps/api/src/lg/services/integrations/directory.ts:173 Entra groups are only READ and mapped to roles/queues (entraGroups state); no group management calls | no automated test API GET /api/lg/me without a workspace membership 401/404 , there is no external-user sign-in |
| Administration and configuration | Changing roles or Entra ID groups (IT does this at the GC's request). Built beyond the exclusion: the GC can change Legal roles inside the LMS (Settings › People) instead of asking IT. Harmless locally, but it contradicts the PRD's 'IT does this'. Confirm with Legal/IT or make the role toggles read-only when directory sync is on. Configurable in Legal settings Settings, People and roles: the GC chooses whether to use this; with directory sync on, roles come from Entra groups. | Minor difference | apps/api/src/lg/services/lg-admin.ts:481 personPatchSchema lets the GC set isLawyer / isGc / isItAdmin directly in the LMSapps/api/src/lg/routes/admin.ts:154 PATCH /lg/admin/people/:userId (requireGc)docs/pi-for-legal/DESIGN.md:101 Entra groups then roles/queues sync when LG_DIRECTORY_SYNC=1 (the PRD path) | no automated test pi-legal-gc /workspace/pi-for-legal/lg/admin (People) role toggles are editable by the GC |
| Legal entity register | Filing with authorities from the LMS. | Implemented | apps/api/src/lg/services/lg-entities.ts:1 register CRUD, alerts, template data only; no authority filing integration (no 'e-filing' hits in lg/) | no automated test |
| POA register | Notarization and attestation steps with third parties. | Implemented | apps/api/src/lg/services/lg-poas.ts:1 POA register records, authority search, expiry/renewal/revocation; no notarization workflowdocs/pi-for-legal/DESIGN.md:122 notarization handled manually in Corporate (R-13 B) | no automated test |
| Conversational request intake | Legal advice from the assistant. | Implemented | apps/api/src/lg/services/lg-intake-ai.ts:150 system prompt: 'You never give legal advice'; 77 an advice question is routed to type 6.1 | no automated test pi-legal-requester /workspace/pi-for-legal/lg/new type 'Can I terminate my supplier without notice?' then the assistant proposes a General request (6.1), gives no answer |
| Email intake | Requests from external senders; capturing emails from outside 7X automatically. | Implemented | apps/api/src/lg/services/lg-mailbox.ts:15 Outside 7X: nothing created or captured, no reply; forwarded to the GC's triage inbox (internalDomains setting, 159) | no automated test pi-legal-gc /workspace/pi-for-legal/lg/mailbox simulate an email from someone@gmail.com then outcome TRIAGE, no request created |
| Intake script - Corporate | Filing with authorities from the LMS. | Implemented | apps/api/src/lg/services/lg-status-moves.ts:58 With authority captures the authority name/date/document only | no automated test |
| Intake script - Disputes | Court e-filing. | Implemented | apps/api/src/lg/services/lg-cases.ts:1 case record only; no court system integration (grep 'e-filing' then none) | no automated test |
| Intake script - Employment | HR case management outside legal. | Implemented | packages/shared/src/legalModules.ts:796 Employment flow: With authority then Case opened only; no HR module | no automated test |
| Intake script - Intellectual Property | Filing with IP offices from the LMS. | Implemented | apps/api/src/lg/services/lg-ip.ts:71 'filing date is entered by the lawyer when the office confirms it' , no IP office integration | no automated test |
| Intake script - General | Answers given by the assistant itself. | Implemented | apps/api/src/lg/services/lg-intake-ai.ts:7 never gives legal advice: a legal question is routed to 6.1 | no automated test |
| Request lifecycle and status model | Statuses configurable by users; changes need a release. | Implemented | packages/shared/src/legalModules.ts:710 LG_STATUSES and the transition table are code constantsapps/api/src/lg/routes/admin.ts:8 admin routes: settings, types, categories, queues, business units, holidays, emails, people, audit , no statuses | no automated test |
| Document management | Migrating existing SharePoint files into the new structure. | Implemented | apps/api/src/lg/services/integrations/sharepoint.ts:1 creates/links folders and files new documents only; no migration job | no automated test |
| SLAs, ageing and escalation | Pausing the SLA clock. | Implemented | apps/api/src/lg/services/lg-sla.ts:5 'The clock never pauses; time waiting on others is…' reported through ageing instead | no automated test |
| Send-back and business feedback | Chat or messaging in Microsoft Teams; correcting intake answers by email. | Implemented | apps/api/src/lg/services/lg-mailbox.ts:51 email replies are captured to the thread (CAPTURED); answers are never rewritten from email (no 'answers' handling in lg-mailbox.ts)apps/api/src/lg/services/integrations/sharepoint.ts:46 the only 'teams' string in lg/ is a SharePoint URL segment | no automated test |
| Confidentiality, access and audit trail | Access for external users, such as counterparties and external counsel. | Implemented | apps/api/src/lg/services/lg-access.ts:89 requestAccess knows only workspace actors: requester, cc, consult, approver, lawyer, GC | no automated test |
| Approvals | Approvals in Microsoft Teams; recording approvals given outside the LMS; approvals by people outside 7X. | Implemented | apps/api/src/lg/routes/approvals.ts:1 decisions are POSTed by signed-in workspace users; approver ids resolve through userNames (workspace people)docs/pi-for-legal/DESIGN.md:103 approval emails carry buttons that open My approvals , sign-in still required | no automated test |
| E-signature (DocuSign) | UAE PASS and other e-signature providers; notarization. | Implemented | apps/api/src/lg/services/lg-docusign.ts:1 single DocuSign adapter (+ mock); no UAE PASS (grep then none) | no automated test |
| Notifications | In-app notifications; Microsoft Teams messages. | Implemented | apps/api/src/lg/services/lg-notify.ts:1 email only (lgEmail); no in-app notification store or bell in apps/web/src/lg (grep then none) | no automated test |
| Contract template library | Writing template content. The GC provides the Word templates. | Implemented | apps/api/src/lg/routes/templates.ts:86 GC uploads/edits template files (requireGcToChange); the system detects fields, it does not author clauses | no automated test |
| Contract generation from 7X templates | Sending contracts to counterparties from the LMS (requester sends them); storing the generated file. | Implemented | apps/api/src/lg/services/lg-generation.ts:463 markSentToCounterparty only records that the requester sent itapps/api/src/lg/services/lg-generation.ts:538 'v01 is the generated file (not stored), so stored returns start at v02' | no automated test |
| Playbook library | Writing playbook content; playbooks for non-contract requests; separate Arabic playbooks. | Implemented | apps/api/src/lg/routes/playbooks.ts:56 GC builds/imports playbooks (requireGcToChange)apps/api/src/lg/services/lg-review.ts:5 review applies to contract types 1.1-1.6 only; Arabic handled by model wording on the same playbook (16-17) | no automated test |
| AI playbook review and selective redline | Automatic reviews; AI review of non-contract requests; other languages; sending redlines to the counterparty automatically. | Implemented | apps/api/src/lg/routes/reviews.ts:120 a review starts only on POST /reviews/:requestId by the lawyerapps/api/src/lg/services/lg-review.ts:455 language UNKNOWN then NOT_RUN 'Language not supported'apps/api/src/lg/routes/reviews.ts:176 redline is generated and downloaded; no send-to-counterparty call | no automated test |
| Contract register | Bulk migration of legacy contracts; tracking obligations and milestones within contracts. | Implemented | apps/api/prisma/schema.prisma:5196 LgContract carries dates, value, parties, owner, flags , no obligation/milestone tables (grep then none)apps/api/src/lg/services/lg-register-io.ts:135 Excel import exists for launch records; no migration tooling | no automated test |
| Case management | Court e-filing integration; processing external counsel invoices (fees are recorded only). | Implemented | apps/api/src/lg/routes/cases.ts:49 feesAgreed / feesInvoiced are plain numbers on the counsel block; no invoice workflow | no automated test |
| IP portfolio register | Copyright works and IP licences; integration with IP office or registrar systems. | Implemented | packages/shared/src/legalModules.ts:1020 LG_IP_TYPES has only Trademark, Patent, Design, Domain nameapps/api/src/lg/services/lg-ip.ts:71 no office integration | no automated test |
| Reporting and dashboards | Power BI or other external BI tools; scheduled report emails. Built beyond the exclusion: a monthly 'report ready' email to the GC (headline figures + link). It serves the DoD monthly-report line; confirm Legal is happy with it or drop the email and keep the on-demand download. Configurable in Legal settings Profile, Emails: the monthly report-ready email is an FYI email that each user can switch off. | Minor difference | docs/pi-for-legal/DESIGN.md:119 Power BI: recorded decision , no connector, only a flat dataset endpoint Power BI can pull (deferred-by-design)apps/api/src/lg/services/lg-monthly-report.ts:23 runMonthlyReport emails the GC once a month that the report is ready (a scheduled report email)apps/api/src/lg/services/lg-jobs.ts:19 scheduled from the hourly timers | no automated test |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Performance: page load < 2 s | Page load time: < 2 seconds Operational, not code: no load-time measurement in the repo (no Lighthouse/perf budget in CI). | Operational | apps/web/src/App.tsx:154 Legal pages are lazy-loaded routesapps/api/src/lg/routes/cases.ts:129 lists are paged in the database (cases, registers, work list) | no automated test |
| Performance: API < 500 ms | API response time: < 500ms for standard operations Operational, not code: no latency assertion or APM alert in the repo; App Insights (apps/api/src/apm.ts) can report it once the connection string is set. | Operational | apps/api/src/lg/services/lg-dashboard.ts:108 inChunks slices id lists (5,000) for the heavy dashboard queriesapps/api/prisma/schema.prisma:5266 @@index on hot columns (39 indexes in the Lg section) | no automated test |
| Performance: bulk < 10 s for 1,000 records | Bulk operations: < 10 seconds for up to 1,000 records | Implemented | apps/api/src/lg/services/lg-register-io.ts:410 applyImport batches create/update per register | nfr.test.ts imports 1,000 contracts in under 10 seconds, with references allocatedAPI POST /api/lg/registers/contracts/import {content:<1,000-row xlsx>, apply:true} 200 within 10 s |
| Scalability: 100 concurrent users | Support minimum 100 concurrent users Operational, not code: no load test in the repo. | Operational | apps/api/src/lg/middleware/lg-rate-limit.ts:1 per-user budgets only on expensive endpoints; ordinary work unlimited | no automated test |
| Scalability: horizontal scaling | Horizontal scaling capability for future growth Stateless API apart from the in-memory rate-limit buckets (documented); file bytes stay in Postgres unless SharePoint is live. | Minor difference | apps/api/src/lg/services/lg-jobs.ts:9 timers run under a DB advisory lock so one instance runs themapps/api/src/lg/services/lg-usage.ts:7 AI budget counter is a DB row (instance-safe)docs/pi-for-legal/DESIGN.md:107 rate limits are in memory per instance , N instances allow N× the short-window limits | no automated test |
| Scalability: database designed for efficient query patterns | Database designed for efficient query patterns at scale | Implemented | apps/api/prisma/schema.prisma:5266 @@index([closedAt]) on LgCase; @@index([status, renewalDate]) on LgIpRecord (5311); 39 indexes across Lg modelsapps/api/src/lg/routes/cases.ts:83 filtering and paging in the database, X-Total-Countapps/api/src/lg/services/lg-refs.ts:1 LgCounter reference allocation | nfr.test.ts pages with true totals and server-side counts; export has every matchnfr.test.ts stay unique when many are taken at once |
| Availability: 99.5% uptime | Target uptime: 99.5% SLA Operational, not code (Azure Web Apps). The readiness endpoint is there for the load balancer. | Operational | apps/api/src/app.ts:103 /api/health liveness and /api/health/ready readiness (503 names the failing DB) | no automated test |
| Availability: automated health checks and monitoring | Automated health checks and monitoring | Implemented | apps/api/src/app.ts:103 GET /api/healthapps/api/src/app.ts:109 GET /api/health/ready checks both databases with a 3 s timeoutapps/api/src/apm.ts:1 Azure Application Insights via OpenTelemetry, on when APPLICATIONINSIGHTS_CONNECTION_STRING is set | no automated test API GET /api/health/ready 200 {checks: {main: ok, workspace: ok}} |
| Availability: graceful degradation | Graceful degradation for non-critical service failures | Implemented | apps/api/src/lg/services/lg-intake-ai.ts:9 every AI function degrades to a deterministic fallback when no model / budget spentapps/api/src/lg/services/lg-usage.ts:48 AI budget gate then fallbackapps/api/src/lg/routes/requests.ts:257 IP register creation failure never blocks the status moveapps/api/src/apm.ts:17 APM failure logged and swallowedapps/api/src/lg/lib/simulators.ts:1 integrations fall back to simulators outside production | nfr.test.ts a daily AI ceiling per workspace, held in the database; past it the call falls back |
| Availability: backup and disaster recovery | Automated backup and disaster recovery procedures Operational, not code: Azure Postgres backups / DR runbook live outside the repo (pre-release backups were taken manually per the deploy notes). | Operational | docs/pi-for-legal/DESIGN.md:125 Deployment needs (not code): schema, triggers, rls.sql applied by hand | no automated test |
| Security: token-based authentication | Authentication: Industry-standard token-based authentication (JWT/OAuth 2.0) | Implemented | apps/api/src/middleware/auth.ts:44 Bearer token required; verifyToken (80)apps/api/src/lg/middleware/lg-auth.ts:4 Legal actor built on top of the workspace bridgedocs/pi-for-legal/DESIGN.md:101 Entra ID SSO via Graph when configured; localhost test sign-in otherwise | no automated test |
| Security: RBAC | Authorization: Role-based access control (RBAC) | Implemented | apps/api/src/lg/middleware/lg-auth.ts:45 isLegal/isGc/isLawyer/leadQueues/queues on the actor; requireGc, requireSettingsViewer, requireGcToChangeapps/api/src/lg/services/lg-access.ts:89 per-request access matrixapps/api/src/lg/services/lg-registers.ts:21 register edit rights per queue | core.test.ts confidential requests are invisible to other lawyers, team leads and IT |
| Security: encryption at rest and in transit | Data encryption at rest and in transit (TLS 1.2+) Operational, not code: TLS termination and disk encryption are Azure Web App / Azure Postgres settings. | Operational | apps/api/src/app.ts:74 helmet() security headers; CORS restricted to env.CORS_ORIGIN (78) | no automated test |
| Security: input validation | Input validation and sanitization on all endpoints | Implemented | apps/api/src/lg/lib/http.ts:1 parseBody(zod) then 400 with field messages; 98 parseBody calls across lg routesapps/api/src/app.ts:93 JSON body limits 75 MB signed-in / 1 MB anonymousapps/api/src/lg/lib/xlsx.ts:1 safeCell neutralises formula injection in exports | nfr.test.ts neutralise spreadsheet formulas in user text |
| Security: regular audits and penetration testing | Regular security audits and penetration testing Operational, not code: no pen-test report in the repo; /security-review skill exists but no scheduled audit. | Operational | apps/api/src/lg/lib/simulators.ts:1 simulators refused in production unless LG_SIMULATORS=1apps/api/src/lg/__tests__/nfr.test.ts:82 test: simulators off in production, legal-only when on | no automated test |
| Usability: WCAG 2.1 AA | WCAG 2.1 AA compliance No automated accessibility audit (axe/Lighthouse) or contrast check in the repo; compliance is asserted, not verified. | Minor difference | apps/web/src/lg/components/registers/RowNav.tsx:1 focusable rows, Enter/Space, visible focus ring, MobileListapps/web/src/lg/components/registers/IpView.tsx:119 aria-label on filter inputs; 146 aria attributes across apps/web/src/lg | no automated test |
| Usability: responsive design | Responsive design (mobile, tablet, desktop) | Implemented | apps/web/src/lg/components/registers/RowNav.tsx:6 MobileList stacks register rows below smapps/web/src/lg/pages/LgDashboardPage.tsx:126 sm:block / lg:col-span-2 breakpoints (331 responsive class uses in lg/) | no automated test pi-legal-gc /workspace/pi-for-legal/lg/registers/ip at 375 px width cards instead of a sideways-scrolling table |
| Usability: consistent UI/UX patterns | Consistent UI/UX patterns across all modules | Implemented | docs/pi-for-legal/DESIGN.md:3 UI follows apps/web/DESIGN.md: PageHeader / SectionBar / StatStrip, brand blue onlyapps/web/src/lg/pages/LgCasesPage.tsx:15 StatStrip, Segmented, PagedFooter shared kit | no automated test |
| Usability: keyboard navigation | Support for keyboard navigation | Implemented | apps/web/src/lg/components/registers/RowNav.tsx:4 rowOpen(): focusable, Enter/Space, focus ringapps/web/src/lg/request/tabs/LgCaseTab.tsx:263 native checkboxes/buttons with aria-labels | no automated test |
| Usability: meaningful error messages and loading states | Meaningful error messages and loading states | Implemented | apps/api/src/lg/services/lg-cases.ts:108 plain-language LgMoveError messages ('An employment case can be opened only while the request is With authority')apps/api/src/middleware/request-context.ts:10 every error body carries requestIdapps/web/src/lg/pages/LgDashboardPage.tsx:145 StatStrip loading; 383 loading/empty/error usages in lg/ | no automated test |
| Maintainability: structured logging with correlation IDs | Structured logging with correlation IDs | Implemented | apps/api/src/middleware/request-context.ts:1 x-request-id accepted/generated, echoed, in AsyncLocalStorage, stamped on every log line and error bodyapps/api/src/utils/logger.ts:23 JSON log lines | no automated test |
| Maintainability: APM | Application performance monitoring (APM) | Implemented | apps/api/src/apm.ts:1 Application Insights distro; requests, dependencies, exceptions; env-gated | no automated test |
| Maintainability: documented API (OpenAPI/Swagger) | Documented API endpoints (OpenAPI/Swagger) | Implemented | apps/api/src/lg/openapi.ts:1 OpenAPI 3.1 generated from the live router treeapps/api/src/app.ts:141 GET /api/lg/openapi.json; HTML reference page lists PI Legal (381) | no automated test API GET /api/lg/openapi.json 200 OpenAPI document listing /cases, /registers/ip, /dashboard |
| Maintainability: CI/CD with staged deployments | Automated CI/CD pipeline with staged deployments | Implemented | .github/workflows/workspace-suites.yml:19 Legal/IT/Strategy suites job.github/workflows/staging_app-7xil-pi-stg.yml:35 staging deploy needs workspace-suites.github/workflows/main_app-7xil-pi-prod.yml:23 prod deploy needs workspace-suites | no automated test |
| Compliance: data retention policies | Data retention policies aligned with organizational requirements | Implemented | apps/api/src/lg/services/lg-usage.ts:70 runLgRetention: view audit, triage emails, outbound bodies per GC-set windows (default 7 years)apps/api/src/lg/services/lg-jobs.ts:36 runs once a day from the timersapps/web/src/lg/components/admin/ConfigSections.tsx:469 GC edits the windows in Legal settings | nfr.test.ts audit views and sent-email bodies are kept 7 years by default; the audit floor holds against env and settingnfr.test.ts retention runs daily from the timers with the windows the GC set, once a day |
| Compliance: audit trail for all critical operations | Audit trail for all critical operations | Implemented | apps/api/src/lg/services/lg-audit.ts:1 lgAudit / lgAuditDiff on every write, view, download, exportapps/api/prisma/workspace/rls.sql:127 LgAuditEvent append-only triggerapps/api/src/lg/routes/admin.ts:18 GET /audit + /audit/export for the GC | nfr.test.ts is append-only in the database; old views age out under retention onlycases.test.ts closing needs outcome, final amount, closing note and a final reply |
| Compliance: GDPR / data privacy | GDPR/data privacy compliance where applicable | Implemented | apps/api/src/lg/__tests__/nfr.test.ts:162 privacy export includes Legal data; erasure anonymises the person and keeps the matter | nfr.test.ts export includes Legal data; erasure anonymises the person and keeps the matter |
| Compliance: regular compliance reviews | Regular compliance reviews Operational, not code: no recurring review schedule. | Operational | docs/pi-for-legal/DESIGN.md:98 PRD gap audits and re-audits recorded (one-off, 2026-11-09) | no automated test |
| As | Call | HTTP | Response |
|---|---|---|---|
| gc | GET /api/lg/openapi.json | 200 | {"openapi": "3.1.0", "info": "\u2026", "servers": "\u2026", "security": [{"bearer": []}]} expected: 200 OpenAPI 3.1 |
| gc | GET /api/health | 200 | {"status": "ok", "timestamp": "2026-11-24T13:22:16.609Z"} expected: 200 |
| req | GET /requests | 200 | data returned expected: |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Adoption rate | Share of legal requests raised through the system (portal or email) rather than informal channels. Target 90% within 3 months. Only the numerator is measurable: the system cannot see informal requests, so the 90% share needs an outside count of matters handled off-system. | Minor difference | apps/api/src/lg/services/lg-dashboard.ts:522 successCriteria.byChannel (Portal vs Email) and emailSharePct (567)apps/web/src/lg/pages/LgDashboardPage.tsx:519 'Requests by email · portal' tile | dashboard.test.ts measures the PRD success criteria (H-G15) and counts every entry waiting for confirmation (G-05)pi-legal-gc /workspace/pi-for-legal/lg/dashboard › Success criteria requests by channel |
| SLA compliance | Share of requests completed within their SLA. Target 75% after the first 3 months. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:215 slaSummary.metPct over the periodapps/api/src/lg/services/lg-monthly-report.ts:44 monthly email headline 'SLA met N%' | dashboard.test.ts the GC sees the metrics; filters change thempi-legal-gc /workspace/pi-for-legal/lg/dashboard SLA performance meter, period filter = first 3 months |
| Send-back reduction | 30% fewer send-backs in the second quarter after launch than in the first. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:531 sendBacksByQuarter (last 4 quarters: requests, sendBacks, perRequest) and sendBackChangePctapps/web/src/lg/pages/LgDashboardPage.tsx:522 'Send-backs per request, quarter on quarter (target −30%)' | dashboard.test.ts measures the PRD success criteria (H-G15) and counts every entry waiting for confirmation (G-05)pi-legal-gc /workspace/pi-for-legal/lg/dashboard › Success criteria quarter-on-quarter change |
| Approvals captured | 100% of approvals recorded in the system with approver, date and decision. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:524 approvalsCaptured: signed contracts (envelope COMPLETED or EXECUTED copy) with an APPROVED round then pctapps/web/src/lg/pages/LgDashboardPage.tsx:520 'Signed with a recorded approval (target 100%)' | dashboard.test.ts measures the PRD success criteria (H-G15) and counts every entry waiting for confirmation (G-05)pi-legal-gc /workspace/pi-for-legal/lg/dashboard › Success criteria signed-with-approval % |
| Filing compliance | 90% of documents saved with the correct name and in the correct SharePoint folder. | Implemented | apps/api/src/lg/services/lg-dashboard.ts:556 filing: documents of lawyer-handled requests with storage SHAREPOINT (and sharepointItemId when SharePoint is live) / all such documentsapps/api/src/lg/services/lg-documents.ts:170 every stored document is named by the conventionapps/web/src/lg/pages/LgDashboardPage.tsx:521 'Documents filed by convention (target 90%)' | dashboard.test.ts a past month's report gives cases and exposure as at month end and marks today's snapshots (G-22)pi-legal-gc /workspace/pi-for-legal/lg/dashboard › Success criteria filing % |
| Item | Requirement (PRD v15) | Verdict | Where in the code | Test and proof |
|---|---|---|---|---|
| Functional: all MUST requirements live in production and used for real matters | All MUST requirements are live in production and used by the legal team for real matters Operational: per the release notes the Legal pack is on prod behind the Settings › PI products 'Coming soon' lock and not yet used for real matters. | Operational | docs/pi-for-legal/DESIGN.md:125 Deployment needs (not code): schema, trigger, rls.sql, Graph/DocuSign credentials | no automated test |
| Functional: all SHOULD requirements live or scheduled | All SHOULD requirements are either live or have a scheduled release date Operational: R-28/29/30 are Must Have; a release schedule for anything deferred lives outside the repo. | Operational | docs/pi-for-legal/DESIGN.md:98 gap audits closed ~180 items | no automated test |
| Functional: GC configures request types, SLAs, approval matrix, playbooks, naming convention, signatories and holidays without a code release | GC can configure request types, SLAs, approval matrix, playbooks, naming convention, signatories and holidays without a code release | Implemented | apps/api/src/lg/routes/admin.ts:11 POST/PATCH /types (scripts, SLA days , lg-admin.ts:209), /holidays (15), /settings (8: namingConvention, urgentSlaDays, tenderScopeSla, escalation…), naming-preview (10)apps/api/src/lg/routes/approvals.ts:208 approval matrix rules: POST/PATCH/DELETE /rules (requireGc)apps/api/src/lg/routes/playbooks.ts:56 playbooks GC-managedapps/api/prisma/schema.prisma:4731 entity signatories (signatoryNameEn/Ar, title, user) on the GC-edited entity register | admin.test.ts (admin suite)config.test.ts (config suite)pi-legal-gc /workspace/pi-for-legal/lg/admin Types, SLAs, Approval matrix, Playbooks, Naming, Holidays sections editable; a lawyer/IT admin sees them read-only |
| Operational: SLA clock, ageing by location and escalation rules running against live data | SLA clock, ageing by location, and escalation rules are running against live data | Implemented | apps/api/src/lg/services/lg-request-timers.ts:1 SLA breach alert to the lawyer, repeat every 3 business days, team lead at 5 past due; reminders per statusapps/api/src/lg/services/lg-jobs.ts:9 hourly across every Legal workspace under an advisory lockapps/api/src/lg/services/lg-dashboard.ts:395 ageing by bucket (where the time sits) | timers.test.ts (timers suite)API POST /api/lg/jobs/run 200 with per-area counts (requests, registers, approvals, generation, cases, monthly, retention) |
| Operational: confidential access rules passed a security review with IT incl. search, email and reporting | Confidential access rules have passed a security review with IT, including search, email and reporting surfaces Operational: the rules are enforced and tested on all three surfaces, but no IT security sign-off is recorded. | Operational | apps/api/src/lg/routes/documents.ts:51 document search scoped by visibleRequestWhereapps/api/src/lg/services/lg-notify.ts:73 no attachments on confidential emails; action labels only (151)apps/api/src/lg/services/lg-dashboard.ts:248 dashboard listable() + team-lead counting ruleapps/api/src/lg/services/lg-access.ts:118 confidential access matrix | core.test.ts confidential requests are invisible to other lawyers, team leads and ITdashboard.test.ts team leads count confidential requests but never list themdashboard.test.ts a flat dataset for Excel or Power BI, scoped by R-19 (G-15) |
| Operational: SharePoint folder structure and auto-naming applied to 100% of new matters | SharePoint folder structure and auto-naming convention are applied to 100% of new matters | Implemented | apps/api/src/lg/services/lg-lifecycle.ts:97 a lawyer-handled request cannot move past In progress / Under review without a linked SharePoint folderapps/api/src/lg/services/lg-documents.ts:170 every stored document named from the namingConvention settingapps/api/src/lg/services/lg-dashboard.ts:556 filing compliance % on the GC dashboard | core.test.ts records who, when and why; enforces the folder and final-reply gatesnfr.test.ts an existing folder must sit under the Legal SharePoint sitepi-legal-counsel /workspace/pi-for-legal/lg/requests/<ref> status move past In progress refused until 'Link folder'; uploaded files carry the convention name |
| Reporting: dashboards for workload, SLA, demand, ageing, contract risk, approvals and cases live and exportable to Excel/Power BI | Dashboards for workload, SLA performance, demand, ageing, contract risk, approvals and cases are live and exportable to Excel/Power BI | Implemented | apps/api/src/lg/services/lg-dashboard.ts:355 workloadapps/api/src/lg/services/lg-dashboard.ts:215 SLAapps/api/src/lg/services/lg-dashboard.ts:733 demand by department/requester + volumesapps/api/src/lg/services/lg-dashboard.ts:395 ageingapps/api/src/lg/services/lg-dashboard.ts:767 contractRiskapps/api/src/lg/services/lg-dashboard.ts:780 approvalsapps/api/src/lg/services/lg-dashboard.ts:718 cases breakdown + litigationapps/api/src/lg/routes/dashboard.ts:59 Excel exportapps/api/src/lg/routes/dashboard.ts:85 dataset for Power BIdocs/pi-for-legal/DESIGN.md:119 Power BI decision | dashboard.test.ts every view exports to Excel; the GC gets the monthly reportv1-gaps.test.ts every breakdown is in the GC Excel exportpi-legal-gc /workspace/pi-for-legal/lg/dashboard all seven areas on screen; Export to Excel; Dataset then CSV for Power BI |
| Reporting: GC produces a monthly legal function report without manual compilation | GC can produce a monthly legal function report from the system without manual compilation | Implemented | apps/api/src/lg/routes/dashboard.ts:72 GET /lg/dashboard/monthly-report?month=YYYY-MM (GC)apps/api/src/lg/services/lg-dashboard.ts:944 monthlyReportXlsx: Cover, Backlog at month end, Requests this month, Cases, Register changes, Contract risk, Approvals by approverapps/api/src/lg/services/lg-monthly-report.ts:23 monthly 'report ready' email with headline figures | dashboard.test.ts the monthly report has a cover, month-end backlog, cases and register changes (G-22)dashboard.test.ts the GC is emailed the monthly report once a monthpi-legal-gc /workspace/pi-for-legal/lg/dashboard pick a month then Monthly report downloads the workbook; a team lead gets 403 |
| As | Call | HTTP | Response |
|---|---|---|---|
| gc | GET /dashboard/dataset.csv | 200 | {"_raw": "\u00ef\u00bb\u00bfReference,Title,Type,Category,Queue,Status,Open,Urgent,Confidential,Entity,Business unit,Lawyer,Submitted,Assigned,SLA due,SLA met,S expected: 200 text/csv |
Generated 24 November 2026 from the audit files, the API proof log, the test log, the feedback round on PI and the screenshot set of this verification run.