# Module: Operations & Deliveries (operations)

## Purpose
Covers the surgical lifecycle of the OB/GYN clinic: operation booking via a daily waiting list, the detailed operative note (anesthesia, incision, surgical team, intra-operative drugs with pharmacy receipt integration), brief operation logs attached to the infertility sheet, daily operations/deliveries reports, pregnancy-termination report, hospital transfer letters, and per-patient pathology/histopathology results.

## Controllers & Views (file paths)
- `/home/amrtechogate/public_html/obgy/core/controllers/operations.php` — operations daily report (joins `operations` + `infertilitysheet`), operation waiting list (`op_wait_list`), 4D waiting list (`op_4d_list`, not assigned), `sendToVisits` (creates `visits` row with `detections` id 36 hardcoded).
- `/home/amrtechogate/public_html/obgy/core/controllers/operativedetails.php` — operative note CRUD (`operativedetails`, `operativedetailsdrugs`), cascading lookups (`anasthesa`→`generalanasthesa`, `jncision`→`midlinejncision`), pharmacy receipt integration (`recepittmp`, `receiptdrugs`).
- `/home/amrtechogate/public_html/obgy/core/controllers/Deliveries.php` — deliveries report from `awifep` + `registeration` (place via `place2`), `wifeobst`, `wifemodeofd`.
- `/home/amrtechogate/public_html/obgy/core/controllers/termination.php` — termination report querying `phobstetric.obstermination` joined to `patients`.
- Supporting: `/home/amrtechogate/public_html/obgy/core/controllers/instruction.php` (uses `hospitalnames` for hospital transfer letters), `/home/amrtechogate/public_html/obgy/core/controllers/investigation.php` (manages `pathology` rows), `/home/amrtechogate/public_html/obgy/core/controllers/infertilitysheet.php` and `ancsheet.php` / `Completesreport.php` / `sh.php` (read `operations` by `infertilitysheetid`), `visits.php`/`index.php` (use `detections` as the fee catalog).
- Views: `/home/amrtechogate/public_html/obgy/core/views/obgy/operation/` (waitinglist.html, listdiv.html, listdivfut.html, four_d.html, listdiv_4d.html, listdivfut_4d.html), `/home/amrtechogate/public_html/obgy/core/views/obgy/operativedetails/` (show.html, showdata.html, anasthesa.html, jncision.html, editmodel.html, newrowUS.html), `/home/amrtechogate/public_html/obgy/core/views/obgy/reports2/` (operations*.html, deliveries*.html), `/home/amrtechogate/public_html/obgy/core/views/obgy/reports/termination*.html`, JS: `/home/amrtechogate/public_html/obgy/core/views/obgy/_assets/custom/operativedetails.js`.

## Tables

### operation (lookup)
Catalog of surgical procedure names. Used by waiting list (reads `title`) and operative note (reads `name`) — the two columns are used interchangeably by different screens.
- `id` int(11) PK AI
- `title` varchar(191) NULL
- `del` varchar(191) NULL (soft delete; queries use both `del is null` and `del = 0`)
- `name` varchar(191) NULL
No seed rows in the dump. Referenced by: `op_wait_list.operation` (CSV), `operations.operation` (CSV), `operativedetails.operationid`.

### operationids (legacy, unused)
- `id` int(11) PK AI
- `doctorid` int(11) NOT NULL
- `assistantid` int(11) NOT NULL
- `operationid` int(11) NOT NULL
No reference anywhere in `core/`, `board/`, `screen/`, `pharmacy/` code. Inferred legacy link table (doctor/assistant per operation) superseded by `operativedetails` staff CSV columns. Candidate for dropping.

### operations (transactional)
Brief operation log attached to the infertility sheet (shown inside infertility sheet and in the daily operations report).
- `id` int(11) unsigned PK AI
- `infertilitysheetid` int(11) unsigned NULL -> infertilitysheet.id
- `operation` varchar(191) NULL — CSV of operation.id values (resolved with `id in (0$data->operation)`)
- `date` varchar(191) NULL — stored as 'Y/m/d' string
- `place` varchar(191) NULL -> place.id
- `histopath` varchar(191) NULL — CSV of histopath.id values
- `cost` varchar(191) NULL — money as string
- `note` varchar(191) NULL
Rows are created/edited inline from infertility sheet views via generic `Add()` AJAX (table/id/col/value).

### operativedetails (transactional, core)
Full operative note per patient.
- `id` int(11) PK AI
- `operationid` int(11) NOT NULL -> operation.id
- `date` date NOT NULL
- `timestart` time, `timeend` time
- `indication` varchar(255)
- `anasthesaid` int(11) -> anasthesa.id
- `generalid` int(11) -> generalanasthesa.id
- `anasthetstsid` varchar(255) — CSV of awusers.user_id (anesthetist doctors, role_id=4 specialid=1)
- `assistantid` varchar(255) — CSV of awusers.user_id (assistant doctors, role_id=6 specialid=2)
- `complication` longtext
- `jncisionid` int(11) -> jncision.id (incision type lookup, not assigned to this module)
- `midlineid` int(11) -> midlinejncision.id (incision subtype, cascades from jncision)
- `peritonealwash` int(1) default 0
- `exdetails`, `opsteps`, `layers`, `drains`, `suture` varchar(255)
- `bloodtransfusion` int(1) default 0
- `complications` varchar(255)
- `recommendation` longtext
- `patientid` int(11) NOT NULL -> patients.id
- `del` int(11) unsigned NULL (soft delete)
- `anasthetsts2id` varchar(255) — CSV awusers (second anesthetist team, role_id=4 specialid=3)
- `assistant2id` varchar(255) — CSV awusers (second assistant team, role_id=6 specialid=4)
Empty row is auto-created when the showdata screen opens; fields are saved one-by-one via AJAX `update()`.

### operativedetailsdrugs (transactional)
Intra-operative drugs grid; integrates with pharmacy billing.
- `id` int(11) PK AI
- `operationid` int(11) NOT NULL -> operativedetails.id
- `drugid` varchar(255) -> drugs.id (-1 = unselected)
- `drugtype` varchar(255), `drugdos` varchar(255), `drugname` varchar(255)
- `doctorid` varchar(255) -> awusers.user_id (session user)
- `deleted` int(11) default 0
- `recepittmpid` int(11) default 0 -> recepittmp.id (pharmacy temp receipt; new receipt opened if status=1 i.e. already cashed)
- `recepitdrugid` int(11) default 0 -> receiptdrugs.id

### op_wait_list (transactional)
Surgical booking / waiting list.
- `id` int(11) PK AI
- `patientid` int(11) default 0 -> patients.id
- `opdate` date NULL
- `operation` varchar(255) — CSV of operation.id values
- `place` int(11) NULL -> place.id
- `notes` text
- `deleted` int(11) default 0
- `user_id` int(11) default 0 -> awusers.user_id
- `createdate` datetime
Listed grouped by day (Arabic day names) over a date range, or future bookings per patient; edit/update/soft-delete supported. Table charset is latin1 with utf8mb4 columns (inconsistent).

### anasthesa (lookup)
Anesthesia main types.
- `id` int(11) PK AI, `name` varchar(255) NOT NULL, `del` int(11) NOT NULL
No seed rows in the dump (user-maintained at runtime via "add new item" AJAX).

### generalanasthesa (lookup, child)
Anesthesia subtypes, cascading dropdown under anasthesa.
- `id` int(11) PK AI, `name` varchar(255), `del` int(11), `anasthesaid` int(11) -> anasthesa.id
No seed rows.

### hospitalnames (lookup)
Hospitals for transfer/admission letters (instruction.php `printtransfer`).
- `id` int(11) unsigned PK AI, `name` varchar(191) NULL
No seed rows. Selected hospital id is used to render the printed letter; not persisted on a transactional row (selection-only usage in current code).

### histopath (lookup)
Histopathology findings catalog.
- `id` int(11) unsigned PK AI, `title` varchar(191) NULL, `del` tinyint(1) unsigned NULL
No seed rows. Referenced as CSV ids from `operations.histopath`.

### pathology (transactional)
Per-patient pathology results, managed from investigation.php (auto-creates an empty row if patient has none).
- `id` int(11) unsigned PK AI
- `sdate` date NULL
- `patientid` varchar(191) NULL -> patients.id (varchar, type mismatch)
- `del` int(11) unsigned NULL
- `cytology` varchar(191) NULL
- `histopathology` text NULL
- `doctorid` int(11) unsigned NULL -> awusers.user_id

### detections (lookup, shared with Visits module)
Visit/service fee catalog (title + price). In this module used by `operations.php::sendToVisits()` which hardcodes detection id 36 (4D scan fee) when pushing a 4D-list patient into today's `visits` queue.
- `id` int(11) PK AI, `title` varchar(100) NOT NULL, `detectionval` float NOT NULL, `del` int(11) unsigned NULL
No seed rows in the dump.

### place (lookup)
Operation places (used by waiting list and `operations.place`).
- `id` int(11) unsigned PK AI, `title` varchar(191) NULL, `del` int(11) unsigned NULL
No seed rows.

### place2 (lookup)
Delivery places — structural duplicate of `place`. Referenced from `registeration.place2` in the Deliveries report.
- `id` int(11) unsigned PK AI, `title` varchar(191) NULL, `del` varchar(191) NULL
No seed rows.

### Related (not assigned but seeded) — clinical vocabulary for operative note
- `jncision` (incision types, seeds: midline, transverse, paramedian + soft-deleted junk test rows 'sss','www', etc.)
- `midlinejncision` (incision subtypes, seeds: upper, lower, pfnnestiel [Pfannenstiel], joel cohen, RT, 1-T ... keyed by `jncisionid`)

## Relationships (explicit list)
- operations.infertilitysheetid -> infertilitysheet.id
- operations.operation (CSV) -> operation.id
- operations.histopath (CSV) -> histopath.id
- operations.place -> place.id
- operativedetails.patientid -> patients.id
- operativedetails.operationid -> operation.id
- operativedetails.anasthesaid -> anasthesa.id
- operativedetails.generalid -> generalanasthesa.id
- operativedetails.jncisionid -> jncision.id ; operativedetails.midlineid -> midlinejncision.id
- operativedetails.anasthetstsid / anasthetsts2id / assistantid / assistant2id (CSV) -> awusers.user_id
- generalanasthesa.anasthesaid -> anasthesa.id
- operativedetailsdrugs.operationid -> operativedetails.id
- operativedetailsdrugs.drugid -> drugs.id ; operativedetailsdrugs.doctorid -> awusers.user_id
- operativedetailsdrugs.recepittmpid -> recepittmp.id ; operativedetailsdrugs.recepitdrugid -> receiptdrugs.id
- op_wait_list.patientid -> patients.id ; op_wait_list.place -> place.id ; op_wait_list.operation (CSV) -> operation.id ; op_wait_list.user_id -> awusers.user_id
- pathology.patientid -> patients.id ; pathology.doctorid -> awusers.user_id
- registeration.place2 -> place2.id (deliveries report path: awifep -> registeration -> place2)
- visits.detectionid -> detections.id (sendToVisits uses id 36 hardcoded)
- operationids.doctorid/assistantid -> awusers.user_id ; operationids.operationid -> operation.id (inferred; table unused)

## Business Workflows (traced from code)
1. **Operation booking**: `operations.php?ac=waiting_list` lists places + operations lookups; `addInList` inserts `op_wait_list` (patientid, opdate, CSV operation ids, place, notes, user_id, createdate). `reloadOpVisits`/`listVisits` render day-grouped lists (Arabic day names via `getDayNameFnAr`); `editvisit`/`updatevisit` edit; `del` sets `deleted=1`; `addnewrecord` adds new lookup rows (e.g. new place/operation) inline.
2. **Operative note**: `operativedetails.php?ac=showdata&patientid=X` auto-creates an empty `operativedetails` row, then every field saves via AJAX `update()` (table/col/value). Cascades: choosing `anasthesaid` loads `generalanasthesa` children (`loadanasthesa`); choosing `jncisionid` loads `midlinejncision` (`loadjncision`). Staff pickers query `awusers` with hardcoded role/special ids (4/1, 6/2, 4/3, 6/4) and store CSV user ids. New lookup values can be added inline (`addselect`, `addanasthesa`, `addanasthesachild`, `addjncision`, `addjncisionchild`).
3. **Intra-op drugs + pharmacy**: `drawRow` inserts an `operativedetailsdrugs` placeholder; selecting a drug in `update()` creates/reuses a `recepittmp` (status 0 = open, 1 = cashed -> open a new one) and a `receiptdrugs` line, so the pharmacy module can dispense/bill. `delodrug` soft-deletes the drug row and trashes the receipt line if not yet cashed.
4. **Operations report**: `operations.php` index/search/showprint join `operations` LEFT JOIN `infertilitysheet` to resolve `patientid`, expand CSV operation/histopath ids, and load `place`; also lists `hysteroscopy(infertility)` and `laparoscopy(infertility)` rows. Note: index uses tables `hysteroscopy`/`laparoscopy` while search/print use `hysteroscopyinfertility`/`laparoscopyinfertility` (inconsistency).
5. **Deliveries report**: `Deliveries.php` reads `awifep` (delivery record per pregnancy, antenatal module) for today/range, resolves patient via `infertilitysheet`, mode of delivery (`wifemodeofd`), obstetric outcomes (`wifeobst` CSV), and the latest `registeration` row to show `place2`, `origin`, `type`; search + print variants.
6. **Termination report**: `termination.php` lists `phobstericterminate` types, then `search` runs raw SQL on `phobstetric` filtered by `obstermination = <termtype>` joined to `patients` (in instruction.php logic: 1 = SVD, 2 = CS).
7. **Hospital transfer letter**: `instruction.php` transfer screen lists `hospitalnames` + `operationinstructions`; `printtransfer` computes obstetric formula (G = phobstetric count + pno + ab + ectopic + vmodel + 1; P = SVD + CS + pno), gestational weeks from `mainantenental.lmp`, and prints the letter with the selected hospital name.
8. **Pathology results**: `investigation.php` auto-creates a `pathology` row per patient if none exists; rows hold sdate, cytology, histopathology free text, doctorid; listed newest-first with doctor name resolved from `awusers`.
9. **4D list → visit**: `sendToVisits` loads `detections` id 36 and inserts a `visits` row (fee = detectionval, queue order = max(enterordered)+1) — cross-module write into the Visits/Finance module.

## ERP Migration Notes
**Proposed Laravel models/tables:**
- `Procedure` (merge `operation.title`/`name` into one `name` column; replaces `operation`)
- `SurgicalBooking` (replaces `op_wait_list`) + pivot `surgical_booking_procedure`
- `OperativeNote` (replaces `operativedetails`) with proper FKs, `datetime` start/end
- `operative_note_staff` pivot (note_id, user_id, role enum: anesthetist/assistant, team enum) replacing the 4 CSV columns
- `OperativeNoteDrug` (replaces `operativedetailsdrugs`); link to pharmacy via a `PrescriptionService` + domain events instead of inline receipt logic
- `InfertilityOperation` (replaces `operations`) + pivots `infertility_operation_procedure`, `infertility_operation_histopath_finding`; `date` as DATE, `cost` as DECIMAL
- `AnesthesiaType` / `AnesthesiaSubtype` (replaces `anasthesa`/`generalanasthesa`, FK subtype->type)
- `IncisionType` / `IncisionSubtype` (migrate `jncision`/`midlinejncision`, purge soft-deleted junk seeds)
- `Hospital` (replaces `hospitalnames`); persist hospital_id on a new `TransferLetter` model instead of print-only usage
- `HistopathologyFinding` (replaces `histopath`)
- `PathologyResult` (replaces `pathology`; `patientid` varchar -> unsignedBigInteger FK)
- `Location` single table with `type` enum (operation/delivery) merging `place` + `place2` (and sibling `copyplace`, `laparplace` from neighboring modules)
- `ServiceType` (the `detections` fee catalog) belongs to the Visits/Finance module; reference by configurable setting instead of hardcoded id 36

**Normalize / drop:**
- Drop `operationids` (no code references; verify production row count first).
- Replace all CSV multi-value columns with pivot tables.
- Unify soft deletes (`del` null/0/1 vs `deleted` 0/1) into Laravel `deleted_at`.
- Replace auto-create-empty-row + per-field AJAX with draft/final status or single validated FormRequest submission.
- Parameterize all queries (current code concatenates `patientid`, `parentid`, `termtype` into SQL — injection risk).
- Move hardcoded role/special ids for surgical team pickers into configuration or a staff-specialty table.
- Termination semantics (`obstermination`: 1=SVD, 2=CS, ...) should become a `delivery_modes` enum/lookup shared with the obstetric history module.
