# Dolibarr Module: doccontrol (Document Control / QMS Light)

## GOAL

Build a lightweight Document Control (QMS-style) module inside Dolibarr to manage controlled documents, versioning, approvals, and traceability, integrated with manufacturing (products, MO, workstations).

---

## SCOPE (MVP - ETAP 1)

Implement a minimal but usable Document Control system:

* Document registry
* Categories
* Versioning
* File storage (PDF/DOCX)
* Status control (Draft / In Review / Approved / Obsolete)
* Approval workflow (basic)
* Version history
* Permissions
* Links to Dolibarr objects (product, workstation, MO)
* Simple dashboard

DO NOT implement:

* CAPA
* NCR
* Audits
* Training matrix
* Complex workflows

---

## MODULE INFO

* Name: doccontrol
* Technical name: modDocControl
* Folder: htdocs/custom/doccontrol/
* Rights class: doccontrol
* Main menu: QMS / Document Control

---

## DIRECTORY STRUCTURE

htdocs/custom/doccontrol/

* class/
  * document.class.php
  * documentversion.class.php
* core/modules/
  * modDocControl.class.php
* sql/
  * install.sql
* css/
  * doccontrol.css
* js/
  * document.js
* pages/
  * index.php
  * document_list.php
  * document_card.php
  * document_version_add.php
  * document_approve.php
* ajax/
  * upload_version.php

---

## DATABASE SCHEMA

### TABLE: llx_doccontrol_document

* rowid (PK)
* ref (varchar 50)
* title (varchar 255)
* category_id (int)
* description (text)
* current_version (varchar 20)
* status (varchar 20) // Draft, InReview, Approved, Obsolete
* review_date (date)
* entity (int)
* fk_user_creat (int)
* fk_user_modif (int)
* tms (timestamp)

---

### TABLE: llx_doccontrol_document_version

* rowid (PK)
* fk_document (int)
* version_label (varchar 20)
* file_path (varchar 255)
* change_summary (text)
* status (varchar 20) // Draft, Approved, Obsolete
* approved_by (int)
* approved_at (datetime)
* effective_date (date)
* fk_user_creat (int)
* tms (timestamp)

---

### TABLE: llx_doccontrol_ack

* rowid (PK)
* fk_document (int)
* fk_version (int)
* fk_user (int)
* acknowledged_at (datetime)
* status (varchar 20)

---

### TABLE: llx_doccontrol_link

* rowid (PK)
* fk_document (int)
* link_type (varchar 50) // product, workstation, mo, project
* link_id (int)

---

### TABLE: llx_doccontrol_category

* rowid (PK)
* label (varchar 255)
* entity (int)

---

## CORE LOGIC

### VERSIONING

* Each document has multiple versions
* Only ONE version can be:
  * status = Approved
  * current_version = version_label
* New upload = new version record
* Old versions stay (no delete)

---

### STATUS FLOW

Document:

* Draft → InReview → Approved → Obsolete

Version:

* Draft → Approved → Obsolete

---

### APPROVAL FLOW (MVP)

* User uploads version → status = Draft
* Reviewer validates → status = InReview
* Approver confirms → status = Approved
* System updates document.current_version

---

### FILE STORAGE

Use Dolibarr document storage pattern:

* documents/doccontrol/{document_ref}/v{version}/file.pdf

NO external storage.

---

### PERMISSIONS

Define rights:

* read
* write
* approve
* delete

Hide buttons if no permission.

---

## UI / PAGES

### 1. Dashboard (index.php)

* Total documents
* Approved vs Draft
* Documents to review (review_date < today)
* Latest updated documents

---

### 2. Document List (document_list.php)

Table:

* Ref
* Title
* Category
* Current Version
* Status
* Review Date
* Linked Object
* Actions

---

### 3. Document Card (document_card.php)

Sections:

* Header (ref, title, status)
* Current version (download)
* Version history (table)
* Upload new version
* Approve button
* Linked objects (product / workstation / MO)

---

### 4. Add Version (document_version_add.php)

* File upload
* Version label (manual or auto increment)
* Change summary

---

### 5. Approve (document_approve.php)

* Approve version
* Set effective_date
* Set as current version

---

## LINKING LOGIC

Allow linking document to:

* Product (llx_product)
* Workstation (llx_workstation_workstation)
* MO (llx_mrp_mo)
* Project

Store in llx_doccontrol_link.

---

## INTEGRATION USE CASES

* Work instruction linked to workstation
* Product spec linked to FG/SF
* Setup sheet linked to machine
* Process doc linked to MO

---

## MINIMUM UI RULES

* Follow Dolibarr standard UI
* NO absolute positioning
* Use standard tables and classes
* Buttons aligned with Dolibarr style

---

## CSS

All custom CSS: css/doccontrol.css
DO NOT override global Dolibarr styles.

---

## JS

js/document.js:

* handle upload
* handle version refresh
* handle simple validation

---

## SECURITY

* Check permissions on every action
* Validate file upload
* No direct file access without rights

---

## DOCUMENT TYPES (ETAP 2)

### Overview

Introduce a `doc_type` field to `llx_doccontrol_document` to distinguish
structured document types with dedicated UI and extra fields.

Supported types (MVP):

| Code | Label |
|------|-------|
| `GENERIC` | Generic document (default, current behaviour) |
| `MFG_METHOD` | Manufacturing Method |
| `WORK_INSTR` | Manual Work Instruction |
| `SA_FILE` | Business Document / SA File |

---

### DB change: add doc_type to llx_doccontrol_document

```sql
ALTER TABLE llx_doccontrol_document
  ADD COLUMN doc_type VARCHAR(30) NOT NULL DEFAULT 'GENERIC' AFTER category_id;
```

---

### MANUFACTURING METHOD (MFG_METHOD)

Purpose: describe how to manufacture a product — process steps, parameters, tooling.

#### Extra fields (stored in llx_doccontrol_document_meta — new table)

| Field | Type | Description |
|-------|------|-------------|
| fk_document | int | FK to llx_doccontrol_document |
| fk_product | int | Linked finished/semi-finished product |
| fk_workstation | int | Primary workstation |
| cycle_time_sec | int | Cycle time in seconds |
| process_steps | text | JSON array of steps [{rank, description, ws, tool}] |
| tooling_notes | text | Free text tooling requirements |

#### UI additions

* `pages/mfg_method_card.php` — dedicated card with steps editor
* Document list shows: Product, Workstation, Cycle time columns when filtered by type
* Link to MO: show linked MFG_METHOD on MO card (future integration)

---

### MANUAL WORK INSTRUCTION (WORK_INSTR)

Purpose: step-by-step operator instructions for a specific operation at a workstation.

#### Extra fields (also in llx_doccontrol_document_meta)

| Field | Type | Description |
|-------|------|-------------|
| fk_document | int | FK to llx_doccontrol_document |
| fk_workstation | int | Target workstation |
| fk_product | int | Product this instruction applies to (optional) |
| op_rank | smallint | Operation rank (position in routing) |
| safety_notes | text | Safety / PPE requirements |
| quality_checks | text | Inline quality check points (JSON array) |
| estimated_time_min | int | Estimated time per unit in minutes |

#### UI additions

* `pages/work_instr_card.php` — dedicated card with steps + quality checks
* Step editor: rank, description, image upload per step
* Print-friendly view: `pages/work_instr_print.php` (Bootstrap-free, clean A4 layout)

---

### NEW TABLE: llx_doccontrol_document_meta

```sql
CREATE TABLE IF NOT EXISTS llx_doccontrol_document_meta (
  rowid               INT NOT NULL AUTO_INCREMENT,
  fk_document         INT NOT NULL,
  fk_product          INT DEFAULT NULL,
  fk_workstation      INT DEFAULT NULL,
  fk_societe          INT DEFAULT NULL,
  op_rank             SMALLINT DEFAULT NULL,
  cycle_time_sec      INT DEFAULT NULL,
  estimated_time_min  INT DEFAULT NULL,
  contract_number     VARCHAR(100) DEFAULT NULL,
  counterparty_ref    VARCHAR(100) DEFAULT NULL,
  valid_from          DATE DEFAULT NULL,
  valid_until         DATE DEFAULT NULL,
  process_steps       LONGTEXT DEFAULT NULL,
  quality_checks      LONGTEXT DEFAULT NULL,
  tooling_notes       TEXT DEFAULT NULL,
  safety_notes        TEXT DEFAULT NULL,
  sa_notes            TEXT DEFAULT NULL,
  PRIMARY KEY (rowid),
  UNIQUE KEY uniq_doc (fk_document)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```

---

### MENU additions (ETAP 2)

Under Doc Control left menu:

* **Manufacturing Methods** → `pages/document_list.php?type=MFG_METHOD`
* **Work Instructions**     → `pages/document_list.php?type=WORK_INSTR`

Document list already filters by `doc_type` when `?type=` param is set.

---

### SQL migration file

`sql/alter_add_doc_type.sql` — run once, safe (IF NOT EXISTS / column check).

---

### BUSINESS DOCUMENT / SA FILE (SA_FILE)

Purpose: store and version-control business documents such as Sales Agreements,
Customer Specifications, NDAs, Quality Plans, MSA/PPAP documents, and other
contractual or customer-facing files.

#### Extra fields (also in llx_doccontrol_document_meta)

| Field | Type | Description |
|-------|------|-------------|
| fk_document | int | FK to llx_doccontrol_document |
| fk_societe | int | Linked customer / supplier (llx_societe) |
| fk_product | int | Related product (optional) |
| contract_number | varchar(100) | Customer contract / PO number |
| valid_from | date | Agreement valid from |
| valid_until | date | Agreement expiry date |
| counterparty_ref | varchar(100) | Customer's own document reference |
| sa_notes | text | Internal notes |

#### UI additions

* `pages/sa_file_card.php` — dedicated card with contract details panel
* Document list shows: Customer, Contract No., Valid Until columns when filtered by type
* Alert on dashboard: SA files expiring within 30 days
* Link to Dolibarr third-party (societe) card

#### Menu entry (ETAP 2)

* **SA Files / Business Docs** → `pages/document_list.php?type=SA_FILE`

---

### ETAP 2 checklist (updated)

- [ ] Add `doc_type` column to `llx_doccontrol_document`
- [ ] Create `llx_doccontrol_document_meta` table
- [ ] Update `document_list.php` to filter by type + show type-specific columns
- [ ] Create `mfg_method_card.php`
- [ ] Create `work_instr_card.php`
- [ ] Create `work_instr_print.php` (A4 print view)
- [ ] Create `sa_file_card.php` (contract details + customer link)
- [ ] Add menu entries for Manufacturing Methods + Work Instructions + SA Files
- [ ] Steps editor JS (sortable rank, add/remove rows)
- [ ] Image upload per step (store in doccontrol/{ref}/steps/)
- [ ] Link Work Instruction to Workstation routing (op_rank)
- [ ] Show linked Work Instruction on Workstation card (future)
- [ ] Dashboard alert: SA files expiring within 30 days
- [ ] Link SA file to Dolibarr third-party (societe) card (future)
- [ ] R&U acknowledgement UI — operator confirms reading Work Instruction (`pages/ack_list.php`)
- [ ] R&U pending list — show who has NOT confirmed per document/version
- [ ] Scheduled review notifications — create `llx_actioncomm` task when `review_date` < today+30

---

## INSTALL LOGIC

In modDocControl.class.php:

* use $this->_load_tables('/doccontrol/sql/')
* follow same pattern as modPlanning

---

## ETAP 3 (Future)

### R&U Acknowledgement (Read & Understood)

Operator confirms they have read a Work Instruction before starting work.

* `pages/ack_list.php` — list all documents pending acknowledgement for current user
* `pages/ack_confirm.php` — single-click confirmation page (also usable on tablet)
* Dashboard widget: "X documents awaiting your acknowledgement"
* Manager view: per-document ack matrix (user rows × version column)
* Table `llx_doccontrol_ack` already defined — only UI needed

---

### Scheduled Review Notifications

Automatic reminder when `review_date` is approaching.

* Cron job / trigger: scan `llx_doccontrol_document` where `review_date BETWEEN today AND today+30`
* Create `llx_actioncomm` task assigned to `fk_user_modif` (document owner)
* Subject: "Document {ref} is due for review on {review_date}"
* Optional: e-mail via Dolibarr mail system
* Dashboard alert: list of overdue + upcoming reviews

---

### Master Document Index (MDI) export

Single PDF/CSV export of all Approved documents — required for ISO 9001 / IATF 16949 audits.

* Columns: Ref, Title, Type, Version, Status, Review date, Owner
* Export button on document list page
* PDF via Dolibarr PDF generation or simple HTML print stylesheet

---

### ISO / IATF Clause Tagging

Tag each document with one or more ISO/IATF 16949 clause numbers.

* New table `llx_doccontrol_clause`: rowid, fk_document, clause (varchar 20), norm (varchar 20)
* Filter documents by clause in document list
* Clause → documents cross-reference view (useful during audits)

---

### Change Request (ECR — Engineering Change Request)

Formal request to change a document before uploading a new version.

* New table `llx_doccontrol_ecr`: rowid, fk_document, requested_by, description, status, approved_by, approved_at
* Status flow: Open → InReview → Approved / Rejected
* ECR list linked from document card
* Only after ECR approved → allow new version upload

---

### Document Package / PPAP Bundle

Group documents into a named package for customer submission.

* New table `llx_doccontrol_package`: rowid, label, fk_societe, status, sent_at
* New table `llx_doccontrol_package_item`: rowid, fk_package, fk_document, fk_version
* Package card: add/remove documents, set customer, mark as sent
* Link to SA_FILE for contract context

---

### QR Code on Work Instruction Print

Operator scans QR to verify they have the current approved version.

* QR encodes URL: `doccontrol/pages/check_version.php?ref=WI-045`
* Page shows: current approved version + effective date
* If operator's printed version differs → warning shown

---

### Controlled Copy Log

Register of physical printed copies (who has it, where, which version).

* New table `llx_doccontrol_copy`: rowid, fk_document, fk_version, copy_no, holder, location, issued_at, returned_at
* On new version approval → show list of outstanding copies to recall

---

### NCR Link (Non-Conformance)

Link a non-conformance record to the document that was violated or needs updating.

* Extend `llx_doccontrol_link` with `link_type = 'ncr'`
* Or dedicated join table when NCR module exists
* Document card shows: "Referenced in X NCRs"

---

## ETAP 3 checklist

- [ ] R&U acknowledgement pages (`ack_list.php`, `ack_confirm.php`)
- [ ] R&U manager matrix view
- [ ] Dashboard widget: pending acknowledgements
- [ ] Cron/trigger for review date notifications
- [ ] MDI export (PDF + CSV)
- [ ] ISO/IATF clause tagging + filter
- [ ] ECR module (change requests)
- [ ] Document package / PPAP bundle
- [ ] QR code on Work Instruction print
- [ ] Controlled copy log
- [ ] NCR link

---

## GIT (when implementing)

```
git add -A
git commit -m "feat(doccontrol): initial MVP Document Control module with versioning, approval flow and Dolibarr integration"
```
