## Approval Step Creation and Management System – Full Revision Plan

---

### 🎯 Objective

Add an **Approval Step Configuration** feature to the *Inbound, Outbound,* and *Rental Registration* screens,
and expand the existing “Approval Management” and “Approval History” menus into a unified, fully functional approval workflow.

Both **backend and frontend modifications are permitted** as needed,
but all changes must be designed and deployed carefully to **avoid any side effects** and ensure **system stability**.

---

## 1. Core Principles

* Existing **data structures, responses, and UI** may be changed if necessary.
  However, every change must be **controlled and validated** to ensure compatibility and prevent unintended side effects.
* Prefer **append-only** design, but allow structural refactoring when the current design causes inefficiency or redundancy.
* Every change must include **test coverage, rollback strategy, and observability** before release.
* Draft approvals must persist across browser sessions so submitters can resume from Approval Management, and pending transactions remain hidden from the primary lists until final approval.

---

## 2. Approval Step Logic and Workflow

1. **Approval Flow**

   * The **submitter** is automatically set as the logged-in user (not editable).
   * **Intermediate approvers** must be other users (the submitter cannot approve their own request).
   * Up to **98 approval steps** can be added dynamically.
   * **Final approver** is mandatory and always visible.
   * **Admins** (highest privilege users) can designate themselves as the final approver.

2. **Status Transitions**

   * SUBMIT → IN_PROGRESS → APPROVED / REJECTED / RECALLED
   * Rejection immediately terminates the process.
   * The submitter can **recall** a request only if the **first approver** has not acted yet.
   * Recalled requests can be **edited and resubmitted (RESUBMIT)**.
   * All state transitions must be logged in an **Audit Table** with timestamp, actor, and action.

3. **User Roles & Permissions**

   * Each approver can approve/reject only their assigned step.
   * Earlier steps are visible for reference but cannot be modified.
   * Notes or memos visibility follows permission tiers (own, higher-level, or approvers only).
   * Submitters and approvers who have already completed their step retain read access; future-step approvers (including the final approver before their turn) cannot see the document in lists or detail views and receive a `403` when attempting access.
   * **terabits (Super Admin)** can view all approvals and logs but cannot modify them.

---

## 3. Frontend Revision Plan

1. **UI Additions**

   * Add an **Approval Step Configuration** section (or modal) to the existing Inbound / Outbound / Rental registration forms.
   * Default fields:

     * Submitter (auto-filled, read-only)
     * Final Approver (search/dropdown input)
   * Intermediate approvers added dynamically via **“+ Add Approver”** button (max 98).
   * Each row displays: Order, Approver, Role, Delete(X).
   * Include **Template Selector** to load previously saved approval configurations.
   * On save, send both registration data and approval configuration together.
   * Draft submissions must be saved server-side and restorable from the Approval Management menu even after the browser window is closed.
    * Persist drafts through `/approval-drafts` (`GET /approval-drafts?requester_id=<user>`, `POST /approval-drafts`, `POST /approval-drafts/{id}/restore`) so the client can resume unfinished configurations across devices.
    * The draft payload mirrors the final submission contract (title, summary, note, `transaction_id`, optional `template_id`, `steps[]`) and accepts an optional `session_key` that lets browsers overwrite the current draft without creating duplicates.
    * Drafts expire automatically; pass `include_expired=true` when the recovery UI needs to surface recently expired drafts for troubleshooting.

2. **Approval Management Menu**

   * Show user-created approval templates with step summaries (e.g., “1: Team Lead → 2: Director → Final: Executive”).
   * Allow template creation, modification, and deletion.
   * During submission, a user can choose a template to auto-populate steps.
   * Provide `Draft`/`Pending` filters so submitters can reopen saved approvals while restricting visibility for future-step approvers.

3. **Approval History Menu**

   * Display list of submitted approvals with current state, responsible approver, and timestamp.
   * In detail view, show all steps with status, timestamp, and memo timeline.
   * If eligible, show **Recall** button; after recall, allow **Resubmit**.
   * **terabits (Super Admin)** can view all approvals globally (read-only).
   * Enforce visibility so only the submitter and already-acting approvers can open pending documents; final approvers gain access only when their step is activated.

4. **Validation & Integration**

   * Validation must match the current frontend logic and framework conventions.
   * Reuse existing UI components (dropdowns, toasts, validation rules).
   * Enforce constraints:

     * No duplicate approvers
     * Submitter cannot self-approve
     * Final approver is mandatory
     * Default inventory lists surface only fully approved transactions; drafts and submitted items live in dedicated "Pending Approvals" views.

---

## 4. Backend Revision Plan

1. **Data Model**

   * Existing schemas and API responses **can be modified** when justified,
     but every change must maintain backward compatibility and prevent side effects.
   * Key entities (if not already present):

     * `approval_requests`: Approval request header
     * `approval_steps`: Per-step status tracking
     * `approval_templates`: Saved approval flow templates
     * `approval_template_steps`: Template step definitions
     * `approval_audits`: Activity and state transition logs

2. **Core Logic**

   * Enforce strict sequential flow between steps.
   * Each approval/rejection triggers a state change and audit log entry.
   * Recall allowed only if **step 1 approver** has not acted.
   * Resubmission allowed only from recalled/rejected states.
   * All transitions must be **atomic** and **transaction-safe**.

3. **API Design**

   * Existing endpoints may be extended with new parameters or response fields if needed.
   * Main APIs:

     * `POST /approval/submit`
     * `POST /approval/approve`
     * `POST /approval/reject`
     * `POST /approval/recall`
     * `POST /approval/resubmit`
     * `GET /approval/history`
     * `GET /approval/templates`
   * Responses should remain backward-compatible while exposing additional fields (e.g., `approvalStatus`, `currentStep`).

4. **Auditing and Monitoring**

   * Log all actions (create, submit, approve, reject, recall, resubmit) in `approval_audits`.
   * Each entry records user ID, timestamp, action type, and metadata.
   * Emit state-change events (e.g., Kafka or WebSocket) for real-time tracking.

---

## 5. Change Control and Stability

1. **Side-Effect Prevention**

   * Schema updates must include **pre-migration validation, backup, and rollback scripts**.
   * Deploy via **staging → production**, with feature toggles for controlled rollout.
   * Critical operations (approval/rejection) must be **idempotent** and transaction-safe.

2. **Consistency and Concurrency**

   * Prevent duplicate approvers or skipped steps.
   * Apply **optimistic locking/version control** for step updates.
   * Centralize all approval state changes in a single service (e.g., `ApprovalService`).

3. **Testing Criteria**

   * Existing modules (inbound/outbound/rental) must work with or without approval data.
   * Verify all state transitions: submit → approve → final approve, reject, recall, resubmit.
   * terabits can view all but not modify.
   * Audit log integrity check for every state transition.

---

## 6. Operations and Collaboration

* **Frontend and Backend may both be modified** if agreed upon during design review.

  * All changes must be documented and version-controlled.
  * Updated response specs must be reflected in OpenAPI/Swagger documentation.
* **Feature Toggles** must allow enabling/disabling approval features per environment.
* **Monitoring and Alerts:**

  * Track approval error rates, delays, and recall/resubmission frequency.

---

## 7. Deliverables

* **Frontend:**

  * `ApprovalStepUI` Component
  * `ApprovalTemplateManager`, `ApprovalHistoryViewer` Modules
* **Backend:**

  * `ApprovalController`, `ApprovalService`, `ApprovalAuditService`
  * Migration + Rollback Scripts
  * Updated OpenAPI Documentation
* **Task Plans:**

  * Backend 세부 작업 계획 — `../superport_api_v2/doc/approval_flow_backend_task_plan.md`
  * Frontend 세부 작업 계획 — `doc/approval_flow_frontend_task_plan.md`

---

## 8. Final Directive

* Backend and frontend **may be modified freely when necessary**,
  but every modification must be **safely designed to prevent side effects**.
* The approval system must support **real workflow tracking** — including
  role-based visibility, note sharing, audit logging, recall/resubmission,
  and seamless integration with existing registration processes.
* The guiding principles are:
  **Controlled Change**, **Traceability**, and **Operational Safety**.
