# DB Schema 與資料模型

> 舊系統 (E:\rms-old\rms) 深度研究 — 2026-07-22 由多 agent 分析產生，高嚴重度發現經獨立 agent 反證查核。

# RMS Legacy 專案 DB Schema 重建與設計品質評估報告

範圍：`E:/rms-old/rms/database/migrations`（54 個檔案全數細讀）、`database/seeders`（僅 1 個 `DatabaseSeeder.php`）、`database/factories`（僅 1 個 `UserFactory.php`），並交叉比對 `app/Models/*`、`app/Http/Controllers/*`、`app/NumericOptionService.php`、`lang/*` 以還原「migration 沒寫、但實際 DB 一定存在」的欄位。

---

## 0. 最重要的整體結論：migrations 已無法重現實際 schema（schema drift）

這套 migrations **從零跑起必定失敗**，而且大量實際使用中的欄位「不存在於任何 migration」。實際生產 DB 是靠手動 ALTER TABLE 演化出來的，migrations 只是部分歷史紀錄。證據：

1. **`properties` 建表就會爆**：`2023_03_18_150915_create_properties_table.php:30-31` 連續兩行宣告同名欄位 `air_conditioning_fee`，MySQL 會直接回 duplicate column error。
2. **對「不存在的欄位」建 FK、且引用「尚未建立的 table」**：
   - `2024_03_28_095835_add_fields_to_leases_table.php:17-19,22`：對 `leases.company_id / unit_id / bank_id / renew_by_lease_id` 下 `$table->foreign(...)`，但這四個欄位**從未在任何 migration 中被 add column**；且引用的 `companies`（2024_04_19 才建）、`units`（2024_05_06）、`bank_accounts`（2024_07_24）當時都還不存在。
   - `2024_04_02_081928_add_fields_to_properties.php:15`：對不存在的 `properties.company_id` 建 FK（`companies` 尚未建）；之後 `2024_04_19_103925_create_companies_table.php:31-34` 又「再一次」新增同一個 `company_id` 欄位＋FK — 證明前一支 migration 在實機上從未成功執行或被跳過。
   - `2024_04_10_044533_create_debit_notes_table.php:23,27`：對不存在的 `debit_notes.unit_id / bank_id` 建 FK。
   - `2024_04_24_112306_create_meter_readings_table.php:17`：對不存在的 `meter_readings.unit_id` 建 FK。
   - `2024_05_06_105403_create_transactions_table.php:20`：對不存在的 `transactions.ref_id` 建自我參照 FK。
3. **down() 洩露了實際 DB 的手動欄位**：`2024_03_28_095835_add_fields_to_leases_table.php:36-42` 的 down() 會 drop `due_date`、`date_of_auto_send`、`debit_note_number` — 這些欄位 up() 根本沒建，代表它們是直接在 DB 手動加的。
4. **只存在於程式碼、不存在於任何 migration 的欄位**（實際 DB 必有，否則功能會炸）：
   - `leases.rent_exclusive_options`（`app/Models/Lease.php:81-89` mutator 直接寫入該欄位；`app/Http/Controllers/LeaseController.php:206,395` 實際儲存）
   - `leases.due_date / date_of_auto_send / debit_note_number / bank_name / account_name / account_number / company_id / unit_id / bank_id / renew_by_lease_id`（`app/Models/Lease.php:16-37` fillable；`LeaseController.php:209` 實寫 `renew_by_lease_id`）
   - `transaction_items.fee_id / property_id`（`app/Models/TransactionItem.php:19`；`app/Http/Controllers/BulkTransactionController.php:108,341,462` 實寫）
   - `transactions.ref_id`（`app/Models/Transaction.php:32-35` relation）
   - `meter_readings.reading_date / reading / amount`（`app/Models/MeterReading.php:15-28`）
   - `companies.email`（`app/Models/Company.php:25`）
   - `debit_notes.start_date / end_date`（`app/Models/DebitNote.php:17` fillable，疑似 DB 有）

**Revamp 影響**：舊 DB 的真實 schema 必須用 `SHOW CREATE TABLE` / schema dump 從生產環境取得，不能信任 migrations。資料遷移計劃須以生產 DB 為準。

---

## 1. 最終 Schema 逐表清單

> 標記說明：〔drift〕= 不在任何 migration、由程式碼證實存在的欄位。金額欄位型別以粗體標出。

### 1.1 Domain Tables（18 張）

#### `properties`（2023_03_18_150915；修改：2024_04_09_025431、2024_04_19_103925、2026_03_12_000002、2026_03_31_remove）
| column | type | nullable | default |
|---|---|---|---|
| id | bigint PK auto | no | |
| region | varchar | yes | |
| area | varchar | yes | |
| location | varchar | no | |
| purchase_price | **double** | yes | 0 |
| year_of_purchase | **double**（年份存 double！） | yes | 0 |
| sale_price | **double** | yes | 0 |
| light_boxs（拼字錯誤） | **double** | yes | 0 |
| light_box_rentals | **double** | yes | 0 |
| intentional_rent | **double** | yes | 0 |
| management_fee | **double** | yes | 0 |
| air_conditioning_fee | **double**（migration 重複宣告兩次） | yes | 0 |
| managements | json | yes | |
| amenities | json | yes | |
| company_id | ubigint，FK→companies ON DELETE SET NULL | yes | |
| created_at / updated_at | timestamp | yes | |

- 已移除欄位：`type`（2026_03_12_000002 搬到 leases）、`property_category`（2026_03_31 搬到 leases）。
- Index/unique：無任何業務 unique（如 location）。

#### `units`（2024_05_06_161254；修改：2026_03_12_000003、2026_03_12_000004）
| column | type | nullable | default |
|---|---|---|---|
| id | bigint PK | no | |
| property_id | ubigint，FK→properties CASCADE | no | |
| name | varchar | no | |
| purchase_price | **double** | yes | 0 |
| year_of_purchase | integer（properties 卻是 double，型別不一致） | yes | 0 |
| sale_price | **double** | yes | 0 |
| sale_date | date | yes | |
| status | **enum('active','sold','pending')** | no | 'active' |
| unit_management_fees | **double** | yes | 0 |
| location | text | yes | |
| area | double（properties.area 卻是 varchar） | yes | 0 |
| timestamps | | | |

#### `leases`（2024_03_28_044520；修改：2024_03_28_095835、2025_01_16、2025_01_23、2026_03_12_000001、2026_03_31）
| column | type | nullable | default |
|---|---|---|---|
| id | bigint PK | no | |
| ref | varchar | yes | |
| deposit_month_count | integer | no | 2（業務規則寫死在 default） |
| property_id | ubigint，FK→properties CASCADE | no | |
| start_date / end_date | date | no | |
| type | varchar | yes | |
| property_category | varchar | yes | |
| lease_number | varchar UNIQUE | yes | |
| user_id | ubigint，FK→users CASCADE | yes | |
| water_formula / gas_formula / electricity_formula | varchar | yes | |
| amenities | json | yes | |
| is_all_link_collection | **varchar**（boolean 存字串 '0'/'1'） | no | '0' |
| rent_free_period | json | yes | |
| timestamps | | | |
| company_id〔drift，FK 宣告於 095835:17〕 | ubigint | yes | |
| unit_id〔drift，095835:18〕 | ubigint | yes | |
| bank_id〔drift，095835:19〕 | ubigint | yes | |
| renew_by_lease_id〔drift，095835:22，自我參照〕 | ubigint | yes | |
| due_date / date_of_auto_send / debit_note_number / bank_name / account_name / account_number〔drift〕 | — | yes | |
| rent_exclusive_options〔drift，JSON 字串〕 | text/json | yes | |

#### `lease_units`（pivot，2026_03_09_000000）— 後期唯一設計正確的 pivot
- id PK、lease_id FK→leases CASCADE、unit_id FK→units CASCADE、timestamps、**UNIQUE(lease_id, unit_id)**。
- 問題：與舊的 `leases.unit_id` 單欄關聯**並存**（`app/Models/Lease.php:111-119` 同時有 `unit()` 和 `units()`），`lease_master_fees.unit_id` 又是第三條路。

#### `companies`（2024_04_19_103925）
- id PK；name、code、account_id、account_type、attention、location、fax、tel、bank_name、account_name、account_number 全部 varchar nullable；type varchar default '0'（數字字串 enum）；timestamps；email〔drift〕。
- `code` 無 unique；銀行資料與 `bank_accounts` 表重複。

#### `bank_accounts`（2024_07_24_114949）
- id PK；name、bank_name、bank_account_number、bank_company_code、bank_account_code、company_account_code 全 varchar nullable；timestamps。無任何 FK / unique。

#### `debit_notes`（2024_04_10_044533；修改：2026_04_16_000000）
| column | type | nullable | default |
|---|---|---|---|
| id | bigint PK | no | |
| debit_note_number | varchar UNIQUE | yes | |
| property_id | ubigint，FK→properties CASCADE | no | |
| user_id | ubigint，FK→users CASCADE | yes | |
| lease_id | ubigint，FK→leases CASCADE | no | |
| outstanding_balance | **double** | no | 0 |
| is_checked | boolean（lang 顯示為「Grace has checked」） | no | 0 |
| due_date / date_of_auto_send | date | yes | |
| bank_name / account_name / account_number | varchar（由 lease/bank_accounts 反正規化複製） | yes | |
| remark | varchar | yes | |
| status | **varchar 存數字狀態機 0–6** | no | '0' |
| sms_sent / email_sent | **varchar 存數字 0/1/2** | no | '0' |
| timestamps | | | |
| unit_id / bank_id〔drift，FK 宣告於 :23,:27〕 | ubigint | yes | |

- status 語意寫死在 `app/NumericOptionService.php:12-21`：0 Pending / 1 Approved / 2 Under Review / 3 Complete / 4 Rejected / 5 Overdue / 6 Overpaid；狀態轉移散落 `DebitNoteController.php:790,808,827-839,884`。

#### `debit_note_fees`（2024_04_10_044925；修改：2026_04_21_000010）
- id PK；property_id ubigint FK→properties CASCADE；**type varchar（存數字 fee code 0–23，見第 5 節）**；remark varchar nullable；**amount double**；start_date/end_date date nullable；sort_order int nullable；debit_note_id FK→debit_notes CASCADE；**ref_id ubigint NOT NULL FK→debit_notes CASCADE**（指向「來源 DN」，命名完全看不出）；transaction_id ubigint nullable FK→transactions CASCADE（2026_04_21 補）；timestamps。

#### `lease_master_fees`（2024_04_22_160736；修改：2026_03_13_000000）
- id PK；**type varchar（同一套數字 fee code）**；**amount double**；start_date/end_date date nullable；sort_order int nullable；lease_id FK→leases CASCADE；unit_id ubigint nullable FK→units CASCADE；remark varchar **NOT NULL**（其他表都是 nullable，不一致）；counting_per_month int nullable default 0；timestamps。

#### `transactions`（2024_05_06_105403；修改：2026_03_27、2026_04_16_000001、2026_04_17_000002、2026_04_20_000005、2026_04_21_000009）
| column | type | nullable | default |
|---|---|---|---|
| id | bigint PK | no | |
| debit_note_id | ubigint，FK→debit_notes CASCADE | no | |
| allocation_id | ubigint，FK→receipt_allocations CASCADE | yes | |
| deposit_allocation_id | ubigint，FK→deposit_allocations CASCADE | yes | |
| lease_id | ubigint，FK→leases CASCADE | no | |
| type | **varchar 存數字 code（22=Paid）** | no | |
| description | varchar | no | |
| cheque_no | text | yes | |
| payment_method | varchar | no | 'cash'（與 settlement_method_id 功能重疊） |
| bank_account_number | varchar | yes | |
| settlement_method_id | ubigint，FK→settlement_methods SET NULL | yes | |
| amount | **double** | no | |
| transaction_date | datetime | no | |
| sent_at | timestamp | yes | |
| remark | text | yes | |
| timestamps | | | |
| ref_id〔drift，自我參照 FK 宣告於 create:20〕 | ubigint | yes | |

#### `transaction_items`（2024_05_07_180708）
- id PK；transaction_id FK→transactions CASCADE；**type varchar（數字 code）**；remark varchar nullable；**amount double**；start_date/end_date date nullable；sort_order int nullable；**ref_id ubigint NOT NULL FK→debit_notes CASCADE**（又一個指向 debit_notes 的 ref_id）；timestamps；fee_id〔drift→debit_note_fees〕、property_id〔drift〕。

#### `tenant_receipts`（2026_04_16_000002；修改：2026_04_17_000001）
- id PK；user_id ubigint FK→users CASCADE + index；transaction_date date；**amount decimal(12,2)**；**status enum('pending','approved','rejected') default 'pending'** + index；settlement_method_id ubigint nullable FK→settlement_methods **RESTRICT** + index；cheque_no varchar nullable；timestamps。
- 注意：收據掛在 user 上，與 lease/property 無關聯 — 租客身分 = 登入帳號。

#### `settlement_methods`（2026_04_17_000000）— 全專案唯一的 lookup table 正例
- id PK；code varchar UNIQUE；name varchar；chinese_name varchar nullable；description varchar nullable；requires_cheque_no boolean default false；is_active boolean default true + index；sort_order int default 0 + index；timestamps。
- 但**沒有 seeder**，生產資料靠手 key（`DatabaseSeeder.php` 完全沒碰它）。

#### `receipt_allocations`（2026_04_17_000003）
- id PK；tenant_receipt_id FK→tenant_receipts CASCADE；user_id FK→users CASCADE；**receipt_amount / allocated_amount(default 0) / remaining_amount 均 decimal(12,2)**；settlement_method_code varchar nullable（**存 code 字串副本而非 FK**，與 tenant_receipts.settlement_method_id 並存）；cheque_no varchar nullable；status varchar default 'draft'（draft/confirmed/completed 只寫在註解 :25）；notes text nullable；timestamps。

#### `receipt_allocation_items`（2026_04_17_000004）
- id PK；receipt_allocation_id FK CASCADE；debit_note_id FK→debit_notes CASCADE；debit_note_fee_id nullable FK→debit_note_fees SET NULL；outstanding_amount / allocated_amount **decimal(12,2)**；**fee_type varchar 存英文字面值 'Overdue'/'Current Month'**（:23 註解；`BulkTransactionController.php:274` 實寫）— 與數字 fee code 是**第三種** fee type 表示法；start_date/end_date date **NOT NULL**；timestamps。

#### `deposits`（2026_04_20_000006）
- id PK；user_id FK→users CASCADE + index；amount / allocated_amount(default 0) / remaining_amount **decimal(12,2)**；**status enum('draft','active','partially_used','fully_used','refunded') default 'draft'** + index；reference_number varchar nullable UNIQUE（格式 DEP-00000001 只寫在註解 :21）；deposit_date date + index；remarks text nullable（其他表叫 remark，命名不一致）；timestamps。

#### `deposit_allocations`（2026_04_20_000007）
- id PK；deposit_id FK→deposits CASCADE + index；transaction_id nullable FK→transactions SET NULL；debit_note_id FK→debit_notes CASCADE + index；allocated_amount decimal(12,2)；allocated_date date + index；remarks text nullable；timestamps。

#### `meter_readings`（2024_04_24_112306；修改：2026_03_20_000000）
- id PK；property_id FK→properties CASCADE；**meter_type varchar 存 '0'/'1'/'2'**（0 水 1 電 2 煤，對照 `NumericOptionService.php:98-102`；`MeterReadingController.php:492,512,532` 直接寫死字串比對）；reading_start / reading_end **decimal(8,2)**（上限 999,999.99，電錶讀數可能溢位）；start_date/end_date date nullable；remark varchar NOT NULL；is_hidden boolean default false；timestamps；unit_id〔drift〕、reading_date / reading / amount〔drift〕。

#### `maintenance_requests`（2024_04_09_033656；修改：2026_03_20_000001、2026_03_20_000002）
- id PK；property_id FK→properties CASCADE（:27 對 FK builder 呼叫 `->nullable()` 是無效寫法）；unit_id foreignId nullable FK→units CASCADE；user_id nullable FK→users CASCADE；description text；**status varchar default '0'（數字字串）**；request_date timestamp useCurrent；resolved_date timestamp nullable；title varchar；start_date/end_date date nullable；amount decimal(12,2) nullable；approval_status varchar default 'pending'（**同表兩種 status 風格：數字字串 + 英文字串**）；priority varchar default '0'；is_hidden boolean default false；timestamps。`due_date` 已被 2026_03_20_000001:19 移除。

#### `maintenance_tasks`（2024_04_09_033701）
- id PK；maintenance_request_id FK→maintenance_requests CASCADE；assigned_to nullable FK→users CASCADE；scheduled_date timestamp nullable；status varchar default '0'；title varchar；priority varchar default '0'；due_date timestamp nullable；timestamps。

#### `messages`（2024_06_12_173205）
- id PK；sender_id / receiver_id FK→users（無 onDelete 行為）；message text；read boolean default 0（`read` 是準保留字風格差）；timestamps。無 (receiver_id, read) 複合 index。

#### `agendas`（2024_07_16_113726）
- id PK；year **varchar**；property_id foreignId FK→properties CASCADE；timestamps。

### 1.2 Framework / Package Tables（12 張）
- `users`（2014_10_12_000000 + 2024_04_02_082220）：id、name、email UNIQUE、email_verified_at、password、remember_token、timestamps；phone varchar nullable、id_number varchar UNIQUE nullable、**company_ids json NOT NULL**（`User.php:51` cast array、`User.php:54-57` 用 `whereIn` 手動模擬多對多 — 該用 pivot）。
- `password_reset_tokens`（2014_10_12_100000）：email PK、token、created_at。
- `failed_jobs`（2019_08_19_000000）：標準。**注意：沒有 `jobs` 表** — queue 若用 database driver 會炸，代表 queue 是 sync（cron 寄信全同步）。
- `personal_access_tokens`（2019_12_14_000001）：標準 Sanctum。
- spatie/permission 5 張（2023_03_18_135550）：permissions、roles、model_has_permissions、model_has_roles、role_has_permissions；標準套件 schema，UNIQUE(name, guard_name)。
- `media`（2024_03_26_051019）：標準 spatie/medialibrary，morphs(model)。
- `audits`（2024_08_21_105102）：owen-it/laravel-auditing 標準表；old_values/new_values 為 **text**（非 json，無法用 JSON 查詢）；morphs(auditable) + user morph index。幾乎所有 domain model 都掛 `\OwenIt\Auditing\Auditable`（如 `Transaction.php:11-13`、`Lease.php:12-14`），此表會無限成長且無清理 migration。
- 沒有 sessions / cache / jobs / notifications 表。

---

## 2. Domain ER Diagram（mermaid）

```mermaid
erDiagram
    companies ||--o{ properties : "company_id (set null)"
    properties ||--o{ units : "property_id (cascade)"
    properties ||--o{ leases : "property_id (cascade)"
    properties ||--o{ debit_notes : "property_id (cascade)"
    properties ||--o{ debit_note_fees : "property_id (cascade)"
    properties ||--o{ meter_readings : "property_id (cascade)"
    properties ||--o{ maintenance_requests : "property_id (cascade)"
    properties ||--o{ agendas : "property_id (cascade)"

    users ||--o{ leases : "user_id (tenant)"
    users ||--o{ debit_notes : "user_id"
    users ||--o{ maintenance_requests : "user_id"
    users ||--o{ maintenance_tasks : "assigned_to"
    users ||--o{ messages : "sender_id / receiver_id"
    users ||--o{ tenant_receipts : "user_id (cascade)"
    users ||--o{ deposits : "user_id (cascade)"
    users ||--o{ receipt_allocations : "user_id (cascade)"

    leases ||--o{ lease_units : "lease_id (cascade)"
    units ||--o{ lease_units : "unit_id (cascade, UNIQUE pair)"
    leases ||--o{ lease_master_fees : "lease_id (cascade)"
    units ||--o{ lease_master_fees : "unit_id (nullable)"
    leases ||--o{ debit_notes : "lease_id (cascade)"
    leases ||--o{ transactions : "lease_id (cascade)"
    leases ||--o| leases : "renew_by_lease_id (drift)"
    bank_accounts ||--o{ leases : "bank_id (drift)"
    bank_accounts ||--o{ debit_notes : "bank_id (drift)"
    companies ||--o{ leases : "company_id (drift)"
    units ||--o{ leases : "unit_id (drift, legacy)"
    units ||--o{ debit_notes : "unit_id (drift)"
    units ||--o{ meter_readings : "unit_id (drift)"
    units ||--o{ maintenance_requests : "unit_id (nullable)"

    debit_notes ||--o{ debit_note_fees : "debit_note_id (cascade)"
    debit_notes ||--o{ debit_note_fees : "ref_id = 來源DN (cascade)"
    debit_notes ||--o{ transactions : "debit_note_id (cascade)"
    debit_notes ||--o{ transaction_items : "ref_id (cascade)"
    transactions ||--o{ transaction_items : "transaction_id (cascade)"
    transactions ||--o{ debit_note_fees : "transaction_id (nullable)"
    transactions ||--o| transactions : "ref_id (drift)"
    debit_note_fees ||--o{ transaction_items : "fee_id (drift)"

    maintenance_requests ||--o{ maintenance_tasks : "maintenance_request_id (cascade)"

    settlement_methods ||--o{ tenant_receipts : "settlement_method_id (restrict)"
    settlement_methods ||--o{ transactions : "settlement_method_id (set null)"
    tenant_receipts ||--o{ receipt_allocations : "tenant_receipt_id (cascade)"
    receipt_allocations ||--o{ receipt_allocation_items : "receipt_allocation_id (cascade)"
    debit_notes ||--o{ receipt_allocation_items : "debit_note_id (cascade)"
    debit_note_fees ||--o{ receipt_allocation_items : "debit_note_fee_id (set null)"
    receipt_allocations ||--o{ transactions : "allocation_id (cascade)"

    deposits ||--o{ deposit_allocations : "deposit_id (cascade)"
    debit_notes ||--o{ deposit_allocations : "debit_note_id (cascade)"
    transactions ||--o{ deposit_allocations : "transaction_id (set null)"
    deposit_allocations ||--o{ transactions : "deposit_allocation_id (cascade)"
```

---

## 3. Schema 設計問題清單（重點）

### 金額型別（high）
- 2024 年建的所有財務表用 **double**：`debit_notes.outstanding_balance`（create_debit_notes:28）、`debit_note_fees.amount`（create_debit_note_fees:19）、`lease_master_fees.amount`（create_lease_master_fees:17）、`transactions.amount`（create_transactions:24）、`transaction_items.amount`（create_transaction_items:19）、properties/units 各價格欄。程式已被迫到處 `round(...,2)` 補救（`app/Models/DebitNote.php:67,81,83,90`）。
- 2026 年新表改用 `decimal(12,2)`（tenant_receipts、receipt_allocations、deposits 等）— **同一系統兩套金額型別**，對帳時 float 誤差會現形。

### Enum / 狀態儲存混亂（high）
同一系統存在四種狀態表示法：
1. varchar 存數字字串：`debit_notes.status` '0'-'6'、`sms_sent/email_sent` '0'-'2'、`maintenance_requests.status/priority` '0'、`companies.type` '0'、`leases.is_all_link_collection` '0'/'1'、`meter_readings.meter_type` '0'/'1'/'2'。
2. 原生 MySQL enum：`units.status`（2026_03_12_000003:19）、`tenant_receipts.status`（:21）、`deposits.status`（:20）— 新增狀態要 ALTER TABLE。
3. varchar 存英文字：`maintenance_requests.approval_status` 'pending'、`receipt_allocations.status` 'draft'、`transactions.payment_method` 'cash'。
4. varchar 存翻譯字面值：`receipt_allocation_items.fee_type` 'Overdue'/'Current Month'。
數字語意全部只存在 `app/NumericOptionService.php`（PHP 陣列），DB 完全無自我描述能力。

### JSON / serialized columns（high）
- `users.company_ids` json NOT NULL（2024_04_02_082220:17）— 多對多塞 JSON，無 FK、無法 join，`User.php:54-57` 用 `whereIn` 手撈。
- `properties.managements` json、`properties.amenities` json、`leases.amenities` json、`leases.rent_free_period` json、`leases.rent_exclusive_options`〔drift〕— 後兩者甚至是 model 手動 `json_encode`（`Lease.php:81-99`），非 Eloquent cast。`rent_exclusive_options` 內容還承載計費開關語意（`MeterReadingController.php:490-530` 判斷 'Water charges tracking' 等字串）。

### FK / 完整性（high）
- 上述 6 處「FK 宣告在不存在的欄位上」意味著實際 DB 中 `leases.company_id/unit_id/bank_id/renew_by_lease_id`、`debit_notes.unit_id/bank_id`、`meter_readings.unit_id`、`transactions.ref_id`、`transaction_items.fee_id/property_id` **極可能完全沒有 FK constraint 也沒有 index**。
- `messages.sender_id/receiver_id` 無 onDelete 規則（刪 user 會被 RESTRICT 卡死）。
- 財務鏈全部 `onDelete('cascade')`：刪一筆 lease → 連鎖刪 debit_notes → transactions → transaction_items → receipt_allocation_items/deposit_allocations（部分）→ **財務歷史整串蒸發**，且全系統無 soft delete。對租務/會計系統是嚴重風險。

### 缺 unique constraint（medium）
- `companies.code`、`bank_accounts.bank_account_number`、`agendas(year, property_id)`、`meter_readings(property_id, unit_id, meter_type, start_date)` 皆無 unique。
- `debit_note_fees` / `transaction_items` 的 `ref_id` NOT NULL 且 FK 指向 `debit_notes` — 名稱含糊（ref = 來源 DN），與 `transactions.ref_id`（指向 transactions）同名不同義。

### 向後相容的 nullable / ad-hoc 加欄位痕跡（medium）
- 幾乎所有後加欄位一律 `nullable()->after(...)`：`leases.ref`、`leases.property_category`、`transactions.bank_account_number`、`settlement_method_id` 等 — 舊資料無 backfill。
- 欄位在表間搬家：`type` 從 properties 搬到 leases（2026_03_12_000001/000002，內含 raw SQL data migration :24-28）、`property_category` 同樣搬家（2026_03_31 兩支）— 顯示 domain 模型（property vs lease 的屬性歸屬）一直未定。
- `maintenance_requests` 三次改版（建表、2026_03_20_000001 換掉 due_date、000002 加 unit_id/is_hidden）。
- `transactions` 被 6 支 migration 疊加：payment_method（字串）與 settlement_method_id（FK）**兩套付款方式並存**；allocation_id 與 deposit_allocation_id 兩條回填鏈。

### 命名不一致（low–medium）
- remark / remarks / notes 三種；is_hidden vs read；`light_boxs` 拼錯；`getdDebitNoteFee`（NumericOptionService.php:119）拼錯；console command `EmailForDebitNotePening`（Pending 拼錯）；`Lease::company_receipt()` 實際回傳 BankAccount（`Lease.php:141-144`）；`transaction_items` 的 relation 叫 `transactions()`（`Transaction.php:27-30`）。
- `properties.area` varchar vs `units.area` double；`properties.year_of_purchase` double vs `units.year_of_purchase` integer；`transactions.transaction_date` datetime vs `tenant_receipts.transaction_date` date。

### audits 表用法（medium）
- 幾乎所有 model（含高頻寫入的 Transaction、DebitNote、TransactionItem）都開審計；`audits.old_values/new_values` 是 text 非 json；無 partition / 清理策略。revamp 應改為 event-sourced 或有保留期限的審計方案。

### 收款/押金域掛錯聚合根（medium–high）
- `tenant_receipts.user_id`、`deposits.user_id` 直接掛 users，未關聯 lease/unit/property；同一租客多份租約時無法歸屬。`receipt_allocations` 同時複製 `receipt_amount`、`settlement_method_code`、`cheque_no`（tenant_receipts 已有），且 `allocated_amount/remaining_amount` 為存量欄位靠應用層 `recalculateStatus()`（`Deposit.php:68-82`）維護，無 DB 層保證。

---

## 4. Seeders / 預設資料 hardcode

- `database/seeders/DatabaseSeeder.php` 是唯一 seeder：
  - :19-24 寫死 4 個 role 權限（role-list/create/edit/delete）。
  - :37-41 寫死 admin 使用者 **'Prevail Ejimadu' / test@example.com / password 'password'**（外判開發者留下的帳號）。
  - :43-49 寫死 'Admin' role 並給全部權限。
- 其餘 35 個業務權限**不在 seeder 而在 migration**：`2024_04_08_043418_add_custom_permissions_to_permissions_table.php:12-47`（user-list…finance-report），down() 是空的（:51-56）不可回滾；權限清單 = schema 版本的一部分，新增權限要新 migration。
- `settlement_methods` 有表**沒有 seed**：生產環境的結算方式資料是手 key 的，環境重建即遺失。
- `database/factories/UserFactory.php` 為 Laravel 樣板（:24 寫死 bcrypt hash，屬正常樣板），無任何 domain factory — 代表沒有可用的測試資料建置能力。

---

## 5. Magic number 追查結果

### transactions.type = 22 (paid) 的來源
語意唯一定義處是 **`app/NumericOptionService.php:23-48`** 的 `$debitNoteMasterFeeOptions` PHP 陣列 — fee/transaction 的 `type` 欄位（DB 型別 varchar）存的是這個陣列的 **index**：
```
0 Rental, 1 Management Fee, 2 Rates, 3 Government Rent, 4 Stamp Duty,
5 Late Interest Charges, 6 Water, 7 Electricity, 8 Gas,
9-11 各類 Deposit, 12-14 Adj Deposit, 15 Rent free period,
16 Late Interest (One-Time waiver), 17 Rent concession, 18 R&M,
19 Overdue, 20 CHQ DEP, 21 Balance, 22 Paid, 23 Deposit
```
- 這套 taxonomy **把「費用種類」(0-18,23) 與「行項角色/狀態」(19 Overdue、21 Balance、22 Paid) 混進同一個 id space**。
- 實際使用：`TransactionController.php:118`（`$type = 22;` 產生付款彙總列）、:87/:130（`type != 22` / `== 22` 判斷）；`BulkTransactionController.php:339,429,464,470,496`（19=Overdue 拆列、22=彙總付款列，:496 `'type_id' => 22`）；`DebitNote.php:71-77`（`type != 19`、`type == 5` 直接寫死於欠款計算公式）。
- 另有 ERP 會計科目對照寫死在 `NumericOptionService.php:75-96`（`debitNoteFeeOptionsERPCode`，如 '7120-01-0000' CR/DR）— 會計整合規則 hardcode 在 PHP。
- 顯示層再經 `lang/en/dn.php` / `lang/zh/dn.php` 以英文字面值為 key 翻譯 — 數字 → 英文 label → 翻譯，三層間接。

### debit_note_fees / lease_master_fees 的 fee type 儲存方式
- 兩表的 `type` 欄位皆為 `$table->string('type')`（create_debit_note_fees:17、create_lease_master_fees:16），**存數字字串**，語意同上表。DB 無 fee_types lookup table、無 FK、無 CHECK。
- 新表 `receipt_allocation_items.fee_type` 又改存英文字面值 'Overdue'/'Current Month'（migration :23 註解、`BulkTransactionController.php:274`）— 同一概念第三種表示法。
- `meter_readings.meter_type` 同 pattern：varchar 存 '0'/'1'/'2'（`NumericOptionService.php:98-102`；`MeterReadingController.php:492,512,532` 寫死比對）。

### 其他寫死的業務常數（revamp 需資料化）
- `app/Models/Lease.php:40-79`：RENT_EXCLUSIVE_OPTIONS、RENT_EXCLUSIVE_OPTIONS_TRACKING、**PROPERTY_CATEGORIES_OPTIONS（'JOYCE租予公司'、'JOYCE外面租客'、'公司物業收租' — 業主個人名字寫進程式碼）**、TYPES_OPTIONS（14 種物業類型）；:151-157 中文 type 對照表（'住宅'、'寫字樓'、'倉'…）。
- `app/Models/Property.php:65-123`：REGIONS_OPTIONS（28 個香港地區）、MANAGEMENT_TYPES_OPTIONS、AMENITIES_OPTIONS。
- `lang/en/dn.php:80`：**'Grace has checked'** — `debit_notes.is_checked` 欄位的 UI 語意綁定特定員工姓名。

---

## 6. 對 revamp 的核心建議（schema 層）

1. **以生產 DB dump 為 schema 唯一真相**重建資料字典，migrations 只能當歷史參考。
2. 金額一律 `decimal(12,2)`（或 minor units bigint）；讀數欄位放大精度。
3. 建立 `fee_types`、`transaction_types`（或拆開 line-item role）、`meter_types`、`statuses` 等 lookup tables 或 PHP enum + DB CHECK，消滅 NumericOptionService；ERP 科目對照移入 DB 設定表。
4. 租客/收據/押金掛到 lease（或 tenancy）聚合根，而非 user 帳號；`users.company_ids` 改 pivot。
5. 財務紀錄禁止 cascade delete，改 soft delete + 不可變 ledger（transactions append-only）。
6. 統一 unit 關聯為 `lease_units` pivot 一條路；移除 `leases.unit_id` 與反正規化銀行欄位。
7. 所有預設角色/權限/結算方式改為 idempotent seeders，與 schema migration 分離。

## Hardcode 發現（16 項）

| Severity | 位置 | 問題 | Revamp 建議 |
|---|---|---|---|
| 🔴 High | `app/NumericOptionService.php:23-48` | fee/transaction type 的完整 taxonomy（0=Rental…19=Overdue, 22=Paid, 23=Deposit）以 PHP 陣列 index 寫死，DB 的 debit_note_fees.type / lease_master_fees.type / transactions.type / transaction_items.type 皆以 varchar 存這些數字，無 lookup table、無 FK、無 CHECK；且費用種類與行項狀態（Overdue/Paid/Balance）混在同一 id space | revamp 時建立 fee_types lookup table（含 code、雙語名稱、會計屬性），行項角色（overdue/paid/balance）拆為獨立欄位或獨立概念；DB 層以 FK 約束 |
| 🔴 High | `app/NumericOptionService.php:75-96` | ERP 會計科目代碼（'7120-01-0000' 等）與 DR/CR 方向按 fee type index 寫死在 PHP | 會計科目對照移入 DB 設定表（fee_type ↔ account_code ↔ dr/cr），可由管理介面維護 |
| 🔴 High | `app/Http/Controllers/TransactionController.php:87,118,130 與 app/Http/Controllers/BulkTransactionController.php:339,429,464,496` | 交易付款彙總列直接寫死 type 22（Paid）、逾期列寫死 type 19（Overdue）於商業邏輯中 | 改用具名 enum/常數並將行項角色正規化為獨立欄位，杜絕 magic number 散落 |
| 🔴 High | `app/Models/DebitNote.php:71-77` | 欠款計算公式寫死 type != 19（Overdue）與 type == 5（Late Interest Charges）的 magic number | 計費/對帳規則抽成可配置的計算策略，type 判斷改用具名 enum |
| 🔴 High | `database/migrations/2024_04_08_043418_add_custom_permissions_to_permissions_table.php:12-47` | 35 個業務權限（user-list…finance-report）以資料寫入的形式放在 schema migration 內，down() 為空無法回滾；權限清單被鎖進 migration 歷史 | 權限清單改為 idempotent seeder（firstOrCreate）或 config 驅動的 sync command，與 schema migration 分離 |
| 🔴 High | `database/seeders/DatabaseSeeder.php:37-49` | 寫死外判開發者 admin 帳號 'Prevail Ejimadu' / test@example.com / 密碼 'password'，並建立擁有全部權限的 Admin role | admin 帳號由環境變數或安裝流程建立，禁止把明文預設密碼進版控 |
| 🔴 High | `app/Models/Lease.php:56-60` | PROPERTY_CATEGORIES_OPTIONS 寫死業主個人業務分類 'JOYCE租予公司'、'JOYCE外面租客'、'公司物業收租'（含真實人名 JOYCE） | 物業類別改為 DB lookup table 由使用者維護，避免個人名字與業務結構寫死在程式碼 |
| 🔴 High | `app/Models/Lease.php:40-54 及 app/Http/Controllers/MeterReadingController.php:490-530` | RENT_EXCLUSIVE_OPTIONS / *_TRACKING 以英文字面值寫死，且存入 leases.rent_exclusive_options JSON 欄位後，抄錶邏輯再以 in_array('Water charges tracking', ...) 字串比對驅動計費行為 | 租金不含項目與追蹤開關改為結構化設定表（lease_billing_options），以 boolean/FK 欄位取代 JSON 內的英文字串 |
| 🔴 High | `app/NumericOptionService.php:12-21 與 app/Http/Controllers/DebitNoteController.php:790-884` | debit_notes.status 數字狀態機（0 Pending…6 Overpaid）語意只存在 PHP 陣列，狀態轉移以 magic number 散落 controller | revamp 用具名狀態（enum/state machine library），DB 存可讀 code 並以 CHECK/lookup 約束 |
| 🟡 Medium | `app/Models/Property.php:65-123` | REGIONS_OPTIONS（28 個香港地區）、MANAGEMENT_TYPES_OPTIONS、AMENITIES_OPTIONS 全部寫死在 model 常數 | 地區/設施改 lookup table 或 config，支援新增與雙語 |
| 🟡 Medium | `app/Models/Lease.php:62-79,149-160` | TYPES_OPTIONS 物業類型清單與中文對照表（'住宅'→'property.Residential' 等）寫死；DB 內 leases.type 實際儲存中文字串 | 物業類型改 lookup table（code + 雙語名稱），DB 存 code 而非中文字面值 |
| 🟡 Medium | `lang/en/dn.php:80` | debit_notes.is_checked 欄位的 UI 文案寫死為 'Grace has checked'，把特定員工姓名綁進功能語意 | 改為通用的 reviewed_by user FK + reviewed_at，記錄實際覆核人 |
| 🟡 Medium | `database/migrations/2026_04_17_000000_create_settlement_methods_table.php + database/seeders/DatabaseSeeder.php` | settlement_methods 是正確的 lookup table 設計，但完全沒有 seeder，生產資料靠手動輸入；receipt_allocations.settlement_method_code 又以字串副本儲存而非 FK | 提供預設結算方式 seeder；allocation 端改存 settlement_method_id FK |
| 🟡 Medium | `app/NumericOptionService.php:98-102 與 app/Http/Controllers/MeterReadingController.php:492,512,532` | meter_readings.meter_type 以 varchar 存 '0'/'1'/'2'（水/電/煤），controller 寫死字串比對 | 改為 meter_types lookup table 或 PHP backed enum + DB CHECK |
| 🟡 Medium | `database/migrations/2026_04_16_000001_add_payment_method_to_transactions_table.php:15` | transactions.payment_method 以自由字串儲存且 default 'cash'，與後來的 settlement_method_id FK 並存為兩套付款方式表示法 | 統一為 settlement_method_id 一條路，移除字串欄位 |
| ⚪ Low | `database/migrations/2025_01_23_100922_add_deposit_month_count_to_leases_table.php:12` | 押金月數業務規則以 column default 2 寫死 | 預設值移至可配置的系統設定 |

## 設計問題（13 項）

| Severity | 範疇 | 問題 | 影響 | 建議 |
|---|---|---|---|---|
| 🔴 High | migrations 完整性 | migration 鏈從零執行必定失敗且與實際 DB 脫節：properties 建表重複宣告 air_conditioning_fee（2023_03_18_150915:30-31）；6 處對不存在欄位建 FK 並引用尚未建立的 table（2024_03_28_095835:17-22、2024_04_02_081928:15、2024_04_10_044533:23,27、2024_04_24_112306:17、2024_05_06_105403:20）；大量實際使用欄位（leases.rent_exclusive_options/due_date/company_id/unit_id/bank_id/renew_by_lease_id、transaction_items.fee_id/property_id、transactions.ref_id、meter_readings.unit_id 等）不存在於任何 migration | 無法重建環境、無法信任 schema 版本控制；資料遷移計劃無法以 migrations 為依據，必須從生產 DB dump 反推 | revamp 時以生產 SHOW CREATE TABLE 為唯一真相建立新 schema；新系統嚴格要求 migration 可從零重放並以 CI 驗證 |
| 🔴 High | 金額型別 | 2024 年所有財務表金額用 double（debit_notes.outstanding_balance、debit_note_fees.amount、lease_master_fees.amount、transactions.amount、transaction_items.amount、properties/units 價格欄），程式靠 round(...,2) 補救（app/Models/DebitNote.php:67-90）；2026 年新表改 decimal(12,2)，同系統兩套精度 | 浮點誤差導致對帳差額、outstanding balance 判斷（==0）不可靠；新舊表混算誤差放大 | 全面改 decimal(12,2) 或以整數 minor units 儲存；對帳邏輯用 bccomp 類精確比較 |
| 🔴 High | enum/狀態儲存 | 四種狀態表示法並存：varchar 存數字字串（debit_notes.status '0'-'6'、sms_sent/email_sent、maintenance_requests.status、companies.type、is_all_link_collection、meter_type）、原生 MySQL enum（units.status、tenant_receipts.status、deposits.status）、varchar 英文字（approval_status、receipt_allocations.status、payment_method）、varchar 翻譯字面值（receipt_allocation_items.fee_type 'Overdue'/'Current Month'）；數字語意僅存於 app/NumericOptionService.php | DB 無自我描述能力，跨表查詢/報表需硬編對照；新增狀態要改 PHP 或 ALTER TABLE；資料稽核困難 | 統一為 backed enum（DB 存可讀 code）＋ lookup table 或 CHECK constraint；一種概念一種表示法 |
| 🔴 High | 參照完整性與刪除策略 | 財務鏈全 cascade delete（leases→debit_notes→transactions→transaction_items、receipt/deposit allocation 亦多為 cascade），全系統無 soft delete；drift 欄位（leases.bank_id 等）在實際 DB 極可能無 FK 無 index；messages FK 無 onDelete 規則 | 刪除一筆 lease 或 debit note 會連鎖抹除全部財務歷史，違反租務/會計系統的稽核要求；孤兒資料與慢查詢風險 | 財務資料改 append-only + soft delete，FK 用 restrict；重建所有缺失的 FK 與 index |
| 🔴 High | 多對多與 JSON 濫用 | users.company_ids 以 json NOT NULL 存公司清單（2024_04_02_082220:17，User.php:54-57 手動 whereIn 模擬關聯）；properties.managements/amenities、leases.amenities/rent_free_period/rent_exclusive_options 均為 JSON，且 Lease model 以手動 json_encode 而非 cast（Lease.php:81-99） | 無法 join、無 FK 完整性、查詢需全表掃描；rent_exclusive_options 更承載計費開關語意，業務規則藏在 JSON 字串 | 多對多一律 pivot table；結構化業務設定改獨立表；僅真正無 schema 的附加資料才用 JSON |
| 🔴 High | lease-unit 關聯三軌並存 | leases.unit_id（drift 單欄）、lease_units pivot（2026_03_09，含 UNIQUE(lease_id,unit_id)）、lease_master_fees.unit_id（2026_03_13）三種 lease↔unit 關聯同時存在；Lease model 同時有 unit() 與 units()（Lease.php:111-119） | 同一租約的單位歸屬有兩個以上真相來源，計費（per-unit master fee）與租約單位可能不一致 | revamp 統一以 pivot（或 lease_lines）為唯一關聯，fee 掛在 pivot row 上 |
| 🟡 Medium | 收款/押金域聚合根 | tenant_receipts.user_id、deposits.user_id 直接掛 users 而非 lease/tenancy；receipt_allocations 重複儲存 receipt_amount/settlement_method_code/cheque_no（tenant_receipts 已有），settlement_method_code 存字串副本非 FK；allocated_amount/remaining_amount 為應用層維護的存量欄位（Deposit.php:68-82） | 同一租客多租約時收款無法正確歸屬；資料重複易失同步；存量欄位無 DB 保證可能與明細加總不符 | 收款/押金關聯到 lease（或 tenancy）；金額存量改由明細推導或以 DB 觸發/交易保證 |
| 🟡 Medium | 反正規化與重複欄位 | 銀行資訊在 companies、bank_accounts、debit_notes（bank_name/account_name/account_number）、leases（drift 同名欄）四處重複；transactions 同時有 payment_method 字串與 settlement_method_id FK；transactions.bank_account_number 又是一份副本 | 資料不一致風險高，更新銀行資料需多處同步；報表對不上 | 單一 bank_accounts 真相來源＋FK；歷史快照需求改用明確的 snapshot 欄位（標記為 immutable copy） |
| 🟡 Medium | 命名與型別一致性 | remark/remarks/notes 混用；ref_id 三種語意（debit_note_fees.ref_id→來源DN、transaction_items.ref_id→DN、transactions.ref_id→transaction）；light_boxs、EmailForDebitNotePening、getdDebitNoteFee 拼錯；company_receipt() 回傳 BankAccount；properties.area varchar vs units.area double；year_of_purchase double vs integer；agendas.year 存 varchar；transaction_date 一表 datetime 一表 date | 開發者認知負擔大、易寫錯 join/查詢；自動化工具（ORM、報表）難以推斷語意 | revamp 制定命名規約（外鍵一律 <entity>_id、註解欄統一、日期型別統一），ref 類欄位改具語意名稱如 source_debit_note_id |
| 🟡 Medium | audits 表 | 幾乎所有 domain model 掛 laravel-auditing（含高頻 Transaction/TransactionItem），audits.old_values/new_values 為 text 非 json，無保留期限與清理 migration，audits 無按 auditable 型別分區 | audits 成為最大且不可查詢的表，DB 膨脹、備份變慢；審計資料難以做結構化查詢 | 改 json 欄位＋保留策略（archive/partition），或事件溯源方案；僅對關鍵財務模型開審計 |
| 🟡 Medium | 索引 | 2024 年建的表除 FK 自動索引外幾乎無業務索引：debit_notes 無 (lease_id,status)、(date_of_auto_send,email_sent) 等排程掃描用索引（EmailService.php:150 的查詢全靠字串狀態欄）；messages 無 (receiver_id,read)；drift 欄位（無 FK）連索引都沒有 | cron 排程與列表頁隨資料量成長線性變慢 | revamp 依查詢模式設計覆蓋索引；狀態欄位型別修正後建複合索引 |
| 🟡 Medium | 測試資料能力 | factories 只有 Laravel 樣板 UserFactory，18 張 domain table 無任何 factory；seeder 無法建出可運作的示範資料集 | 無法寫可靠的自動化測試，revamp 遷移驗證缺乏基準資料生成工具 | 新系統為每個 aggregate 建 factory 與情境 seeder（demo/staging） |
| ⚪ Low | queue/基礎表缺失 | 只有 failed_jobs 而無 jobs 表，亦無 sessions/cache/notifications 表——排程寄信（EmailService）為同步執行 | 大量 DN 寄送時 cron 阻塞、失敗無重試機制 | 新系統採用 queue（database/redis）與 notification 基礎表 |

## 高嚴重度發現的獨立查證

- ✅ 屬實 — **fee/transaction type 的完整 taxonomy（0=Rental…19=Overdue, 22=Paid, 23=Deposit）以 PHP 陣列 index 寫死，DB 的 debit_note_fees.type / lease_master_fees.type / transactions.type / transaction_items.type 皆以 varchar 存這些數字，無 lookup table、無 FK、無 CHECK；且費用種類與行項狀態（Overdue/Paid/Balance）混在同一 id space**（app/NumericOptionService.php:23-48）
  - 查證註記：Claim 核心全部屬實，僅一處子論述需修正。屬實部分：(1) fee/transaction type taxonomy 完整寫死在 app/NumericOptionService.php:23-48 的 $debitNoteMasterFeeOptions PHP 陣列（0=Rental…19=Overdue、20=CHQ DEP、21=Balance、22=Paid、23=Deposit），另有 50-73 行的 $debitNoteFeeOptions 與 75-96 行的 ERP code 對照，皆為 hardcode，三份陣列還需手動保持同步。(2) 四張表的 type 欄位在 migration 中皆為 $table->string('type')（即 varchar），全部 55 個 migration 中無 fee type lookup table、無 type 欄位的 FK、無 CHECK/enum 約束；唯一的輸入驗證僅為 'required\|numeric'（TransactionController.php:168），無白名單。(3) 數字碼確實存入 DB：debit_note_fees.type（DebitNoteController.php:526 寫入、DepositController.php:393 寫 23、多處 where('type',19) 查詢）、lease_master_fees.type（LeaseController.php:247 寫入，140-146 行以字串 '0'/'1'/'2' 比對，證明 varchar 存數字）、transaction_items.type（TransactionController.php:231/443、DepositController.php:383 寫 23，DebitNote.php:73-74 以 5/19 查詢，TransactionsPerMonthSheet.php:61 直接以 item type 索引 taxonomy 陣列）。(4) 費用種類與行項狀態確實混在同一 id space：19=Overdue、21=Balance、22=Paid 與 0-18 費用種類同陣列，且 19/22/23 實際被寫入同一批 type 欄位（type=19 為上期欠款行、type=22 為 Paid 行、type=23 為 Deposit 行）。需修正的子論述：transactions.type 欄位確為無約束 varchar NOT NULL，但 Transaction model 的 $fillable（app/Models/Transaction.php:15）不含 'type'，且全 app 找不到任何對 transactions.type 的寫入（無賦值、無 DB::table insert、無 factory/seeder）；程式中 $transaction->transactions->where('type',...) 全是透過名為 transactions() 的 hasMany 關聯查 transaction_items 表。因此「transactions.type 存這些數字」無程式碼證據，該欄位實為從未被應用程式寫入的死欄位（非嚴格模式 MySQL 下會落為空字串）——這不推翻 claim 的主旨（schema 無約束、taxonomy hardcode、id space 混用），反而是額外的 schema 債。
  - 證據：app/NumericOptionService.php:23-48（$debitNoteMasterFeeOptions：0=>'Rental'…19=>'Overdue',20=>'CHQ DEP',21=>'Balance',22=>'Paid',23=>'Deposit'）；database/migrations/2024_04_10_044925_create_debit_note_fees_table.php:17、2024_04_22_160736_create_lease_master_fees_table.php:16、2024_05_06_105403_create_transactions_table.php:21、2024_05_07_180708_create_transaction_items_table.php:17（皆為 $table->string('type')）；寫入數字碼：DebitNoteController.php:526 'type' => $debit_note_fee_data['type']、DepositController.php:383/393 'type' => 23、TransactionController.php:118 $type = 22、EmailService.php:190 'type' => 19；查詢混
- ✅ 屬實 — **ERP 會計科目代碼（'7120-01-0000' 等）與 DR/CR 方向按 fee type index 寫死在 PHP**（app/NumericOptionService.php:75-96）
  - 查證註記：Claim 屬實，無法推翻。E:\rms-old\rms\app\NumericOptionService.php 第 75-96 行確實存在 protected 屬性 $debitNoteFeeOptionsERPCode，以 fee type index（對應同檔第 50-73 行 $debitNoteFeeOptions 的索引：0=Rental、4=Stamp Duty、23=Deposit 等）為 key，硬編碼 ERP 會計科目代碼（account_code）與 DR/CR 方向（amt）。'7120-01-0000' 出現在 index 0（CR）、15（DR）、17（DR）。全庫 Grep 確認這些代碼字串（7120-01-0000、1410-01-0000、4070-01-0000、7100-99-0000、8180-99-0000）只存在於此 PHP 檔，無 config、env 或 DB seed 來源；bank_accounts 資料表雖有 account_code 欄位，但那是銀行帳戶用途，與 fee type ERP 對照無關。唯一保留意見：getter getdDebitNoteFeeERPCode()（第 124-127 行）在本 repo 內找不到任何呼叫端，此對照表可能是未被使用的死程式碼，但「硬編碼在 PHP」這一 claim 本身成立。
  - 證據：E:\rms-old\rms\app\NumericOptionService.php:75-96 — protected $debitNoteFeeOptionsERPCode = [ 0 => ['account_code' => '7120-01-0000', 'amt' => 'CR'], 1 => ['account_code' => '1410-01-0000', 'amt' => 'CR'], ... 4 => ['account_code' => '1410-01-0000', 'amt' => 'DR'], ... 15 => ['account_code' => '7120-01-0000', 'amt' => 'DR'], 18 => ['account_code' => '8180-99-0000', 'amt' => 'DR'], 23 => ['account_code' => '4070-01-0000', 'amt' => 'DR'] ]; getter 位於 :124-127 getdDebitNoteFeeERPCode()。
- ✅ 屬實 — **交易付款彙總列直接寫死 type 22（Paid）、逾期列寫死 type 19（Overdue）於商業邏輯中**（app/Http/Controllers/TransactionController.php:87,118,130 與 app/Http/Controllers/BulkTransactionController.php:339,429,464,496）
  - 查證註記：Claim 屬實。我親自打開兩個檔案逐行核對，所有指涉的行號均存在魔術數字 19/22 的硬編碼，且 app/NumericOptionService.php 第 43、46 行證實語意對應為 19 => 'Overdue'、22 => 'Paid'。細節：(1) TransactionController.php — 第 87 行以 `$transactionItem->type != 22` 判斷已付金額、第 118 行直接指派 `$type = 22;` 給彙總列、第 130 行以 `$transactionItem->type == 22` 累加 paid；另第 66 行也硬編碼 `where('type', 19)` 篩選逾期費用。(2) BulkTransactionController.php — 第 339 行 `'type' => $item->debitNoteFee?->type ?? 22`（分組列預設 22）、第 429 行 `$item->type != 22`、第 464 行逾期列寫死 `'type_id' => 19`（fee_type 'Overdue'）、第 496 行彙總列寫死 `'type_id' => 22`。唯一可挑剔處：第 496 行的 22 在 UI 標籤為 'Current Month' 而非 'Paid'，但依 NumericOptionService 定義 22 的正式語意確為 'Paid'，硬編碼於商業邏輯的核心主張無法推翻。這些數值散落於控制器且無常數/enum 引用，屬 hardcode 無誤。
  - 證據：TransactionController.php:87 `if ($transactionItem->ref_id == $ref_id && $transactionItem->type != 22)`；:118 `$type = 22;`；:130 `if ($transactionItem->type == 22)`；:66 `->where('type', 19)`。BulkTransactionController.php:339 `'type' => $item->debitNoteFee?->type ?? 22, // Use fee type or default to 22 for grouped rows`；:429 `if ($item->ref_id == $fee->ref_id && $item->type != 22)`；:463-464 `'fee_type' => 'Overdue', 'type_id' => 19,`；:495-496 `'fee_type' => 'Current Month', 'type_id' => 22,`。語意定義：app/NumericOptionService.php:43 `19 => 'Overdue',`、:46 `22 => 'Paid',`。
