# Models 與業務邏輯層

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

# RMS Legacy 專案 — Models 與共用 Helper 深讀報告

範圍：`E:/rms-old/rms/app/Models`（22 個 model）、`E:/rms-old/rms/app/Helpers.php`、以及順藤摸瓜找到的實質共用 helper `E:/rms-old/rms/app/NumericOptionService.php`（所有 magic number 的源頭，必須納入本報告才能解釋 type 19/22/5）。

---

## 1. 逐一 Model 清單

### 1.1 Agenda（`app/Models/Agenda.php`，21 行）
- **Traits/Interfaces**：`HasFactory`, `InteractsWithMedia`, `\OwenIt\Auditing\Auditable`；implements `HasMedia`, `Auditable`（Agenda.php:11-13）
- **$fillable**：`year`, `property_id`（Agenda.php:15）
- **Relationships**：`property()` belongsTo Property（Agenda.php:17-20）
- **無 $casts、無 constants**。implements HasMedia 但未註冊任何 media collection。

### 1.2 BankAccount（`app/Models/BankAccount.php`，22 行）
- **Traits**：`HasFactory`, Auditable（BankAccount.php:9-11）
- **$fillable**：`name`, `bank_name`, `bank_account_name`, `bank_account_number`, `bank_company_code`, `bank_account_code`, `company_account_code`（BankAccount.php:13-21）
- **零 relationships** — 但 DebitNote 與 Lease 都以 `bank_id` belongsTo 它（DebitNote.php:102-105、Lease.php:141-144），反向關聯缺失。

### 1.3 Company（`app/Models/Company.php`，30 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable；implements HasMedia, Auditable（Company.php:11-13）
- **$fillable**：`type`, `name`, `code`, `account_id`, `account_type`, `attention`, `location`, `fax`, `tel`, `email`, `bank_name`, `account_name`, `account_number`（Company.php:15-29）
- **零 relationships**（Property/Lease belongsTo 它，反向缺失）。`type`、`account_type` 無任何選項定義，是自由文字。

### 1.4 DebitNote（`app/Models/DebitNote.php`，106 行）— 業務核心
- **Traits**：HasFactory, InteractsWithMedia, Auditable（DebitNote.php:12-14）
- **$fillable**（DebitNote.php:16-29）：`property_id`, `start_date`, `end_date`, `user_id`, `due_date`, `date_of_auto_send`, `bank_name`, `account_name`, `account_number`, `debit_note_number`, `lease_id`, `unit_id`, `bank_id`, `is_checked`
- **無 $casts** — `start_date`/`end_date`/`due_date` 全是裸字串；金額計算全靠 PHP `round(x, 2)` 處理 float（DebitNote.php:67,81,83,90）。
- **Relationships**：`property()`, `lease()`, `user()`, `debit_note_fees()`（hasMany 帶 `orderBy('sort_order')`，DebitNote.php:46-49）, `transactions()`, `unit()`, `company_receipt()`（belongsTo BankAccount via `bank_id`，DebitNote.php:102-105 — 名稱誤導，其實是銀行帳戶不是 receipt）。
- **業務邏輯 method（全部應在 service 層）**：
  - `calculateTotalExpected()` / `calculateTotalActual()` / `calculateOutstanding()`（DebitNote.php:56-68）— 每呼叫一次就打一次 DB `sum()`。
  - `calculateRemaining($update = false)`（DebitNote.php:69-84）— **model 內硬編 magic number**：`where('type', '!=', 19)`（19 = Overdue）、`where('type', '!=', 5)`（5 = Late Interest Charges）；還用 `withCount` + `DB::raw('SUM(amount)')` 的 hack 子查詢（DebitNote.php:76-78）。`$update` 參數從未被使用。
  - `calculateOutstandingNoOverdue()`（DebitNote.php:86-91）— 名不副實：只回傳「非 overdue 費用總額」，根本沒扣已付款。
  - `calculateOverduePaid()`（DebitNote.php:93-96）— 直接 static 查另一個 model `TransactionItem::where('ref_id', $this->id)`，跨 model 硬繫結，且沒有過濾 type，與方法名稱（OverduePaid）不符。
- **Denormalized snapshot 欄位**：`bank_name`/`account_name`/`account_number` 是從 Lease 複製來的，與 `bank_id` 指向 BankAccount 並存，快照與參照混用。

### 1.5 DebitNoteFee（`app/Models/DebitNoteFee.php`，34 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（DebitNoteFee.php:11-13）
- **$fillable**：`property_id`, `remark`, `debit_note_id`, `amount`, `start_date`, `end_date`, `type`, `sort_order`, `ref_id`, `transaction_id`（DebitNoteFee.php:16）— `type` 是 0–23 的 magic int（見第 2 節）；`ref_id` 指向另一張 DebitNote（overdue 轉結機制）；`transaction_id` 在 fillable 卻沒有對應 relationship。
- **`protected $dates = ['date'];`**（DebitNoteFee.php:18）— **Laravel 10 已移除 `$dates` 屬性**（composer.json:14 確認 `laravel/framework: ^10.0`），這行是無效死碼，且 `date` 欄位根本不在 fillable。
- **Relationships**：`debitNote()`, `refDebitNote()`（belongsTo DebitNote via `ref_id`，DebitNoteFee.php:25-28）, `property()`。

### 1.6 Deposit（`app/Models/Deposit.php`，91 行）
- **Traits**：HasFactory, InteractsWithMedia；implements HasMedia — **沒有 Auditable**（Deposit.php:10-12），與其他財務 model 不一致。
- **$fillable**：`user_id`, `amount`, `allocated_amount`, `remaining_amount`, `status`, `reference_number`, `deposit_date`, `remarks`（Deposit.php:14-23）— `allocated_amount`/`remaining_amount` 是可被 mass-assign 的衍生欄位，危險。
- **$casts**：三個金額 `decimal:2`、`deposit_date` date（Deposit.php:25-32）— 是少數有正確 casts 的 model（新一代程式碼風格明顯不同，應是後期接手者所寫）。
- **Relationships**：`tenant()`（belongsTo User via user_id）、`allocations()`（hasMany DepositAllocation）、`debitNotes()`（hasManyThrough，Deposit.php:53-63）。
- **業務邏輯**：`recalculateStatus()`（Deposit.php:68-82）— 在 model 內重算 `allocated_amount`/`remaining_amount` 並**硬編狀態字串** `'fully_used'` / `'partially_used'` / `'active'`（Deposit.php:73-79），無 enum、無常數。
- **Media**：`registerMediaCollections()` 註冊 `deposit_pdf` singleFile（Deposit.php:87-90）。

### 1.7 DepositAllocation（`app/Models/DepositAllocation.php`，51 行）
- **Traits**：只有 HasFactory（無 Auditable — 財務分配紀錄竟不留審計）。
- **$fillable**：`deposit_id`, `transaction_id`, `debit_note_id`, `allocated_amount`, `allocated_date`, `remarks`（DepositAllocation.php:12-19）
- **$casts**：`allocated_amount` decimal:2、`allocated_date` date（DepositAllocation.php:21-26）
- **Relationships**：`deposit()`, `transaction()`, `debitNote()`（DepositAllocation.php:31-50）。乾淨的 join model。

### 1.8 Lease（`app/Models/Lease.php`，161 行）— hardcode 重災區
- **Traits**：HasFactory, InteractsWithMedia, Auditable（Lease.php:12-14）
- **$fillable**（Lease.php:16-37）：`lease_number`, `property_id`, `start_date`, `end_date`, `type`, `user_id`, `due_date`, `date_of_auto_send`, `bank_name`, `account_name`, `account_number`, `debit_note_number`, `unit_id`, `company_id`, `bank_id`, `water_formula`, `gas_formula`, `electricity_formula`, `is_all_link_collection`, `rent_free_period`, `renew_by_lease_id`, `ref`, `deposit_month_count`, `property_category`
  - `water_formula`/`gas_formula`/`electricity_formula`：**每張租約存自由文字計費公式字串**，在 MeterReadingController.php:328-336 取出使用 — 公式即資料，無驗證、無版本。
  - `renew_by_lease_id` 在 fillable 卻**沒有對應 relationship method**（續租鏈無法用 ORM 走訪）。
  - `due_date`/`date_of_auto_send`/`debit_note_number`/`bank_name`... 與 DebitNote.php:19-24 完全重複 — Lease 身兼「DN 產生範本」，欄位語意混雜。
- **無 $casts**（日期、boolean `is_all_link_collection` 全裸）。
- **Class constants（全 hardcode，見第 2 節）**：`RENT_EXCLUSIVE_OPTIONS`（Lease.php:40-48）、`RENT_EXCLUSIVE_OPTIONS_TRACKING`（Lease.php:50-54）、`PROPERTY_CATEGORIES_OPTIONS`（Lease.php:56-60，含客戶人名「JOYCE租予公司」）、`TYPES_OPTIONS`（Lease.php:62-79）。
- **手工 JSON accessors/mutators**：`setRentExclusiveOptionsAttribute`/`getRentExclusiveOptionsAttribute`、`setRentFreePeriodAttribute`/`getRentFreePeriodAttribute`（Lease.php:81-99）— 手寫 `json_encode`/`json_decode` 而非 `$casts = ['x' => 'array']`，且 getter 回傳 `Collection`，型別不對稱。
- **Relationships**：`property()`, `user()`, `unit()`（單數 belongsTo）**與** `units()`（belongsToMany via `lease_units` pivot，Lease.php:111-119）**並存** — 一租約單 unit 與多 unit 兩套 schema 同時存在；`debit_notes()`, `lease_master_fees()`（orderBy sort_order，行尾有雙分號 `;;`，Lease.php:128）, `transactions()`, `company()`, `company_receipt()`（belongsTo BankAccount via bank_id）。
- **翻譯 hack**：`getTranslatedTypeAttribute()`（Lease.php:149-160）詳見第 4 節。

### 1.9 LeaseMasterFee（`app/Models/LeaseMasterFee.php`，26 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（LeaseMasterFee.php:11-13）
- **$fillable**：`lease_id`, `unit_id`, `amount`, `start_date`, `end_date`, `type`, `counting_per_month`, `sort_order`, `remark`（LeaseMasterFee.php:15）— `type` 同樣是 NumericOptionService 的 magic int。
- **Relationships**：`lease()`, `unit()`。無 casts。

### 1.10 MaintenanceRequest（`app/Models/MaintenanceRequest.php`，50 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（MaintenanceRequest.php:11-13）
- **$fillable**：`property_id`, `unit_id`, `user_id`, `description`, `request_date`, `resolved_date`, `priority`, `title`, `start_date`, `end_date`, `amount`, `approval_status`, `is_hidden`（MaintenanceRequest.php:15-29）— `priority` 與 `approval_status` 無任何選項定義（散落在 controller/view）。
- **Relationships**：`property()`, `user()`, `unit()`, `maintenanceTasks()`。無 casts（`is_hidden` 連 boolean cast 都沒有）。

### 1.11 MaintenanceTask（`app/Models/MaintenanceTask.php`，34 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（MaintenanceTask.php:11-13）
- **$fillable**：`maintenance_request_id`, `assigned_to`, `scheduled_date`, `status`, `due_date`, `priority`, `title`（MaintenanceTask.php:15-23）— `status`/`priority` 同樣無定義。
- **Relationships**：`maintenanceRequest()`, `assignedTo()`（belongsTo User via `assigned_to`）。

### 1.12 Message（`app/Models/Message.php`，32 行）
- **Traits**：只有 Auditable（連 HasFactory 都沒有）。
- **$fillable**：`sender_id`, `receiver_id`, `message`（Message.php:13-15）— sender/receiver **無 relationship methods**。
- **`protected $dates`**（Message.php:17-20）— Laravel 10 無效死碼。
- **嚴重 accessor 問題**（Message.php:22-30）：
  - `getCreatedAtAttribute` 把 `created_at` 全域覆寫成 `isoFormat('YYYY-MM-D')` 顯示字串 — 之後任何程式讀 `$message->created_at` 拿到的都是格式化字串，排序、序列化、比較全部被污染。
  - `getUpdatedAtAttribute` **copy-paste bug**：讀的是 `$this->attributes['created_at']` 而非 `updated_at`（Message.php:29），且 `format('H:i:s A')` 24 小時制混用 AM/PM。顯示格式化屬 view 層職責。

### 1.13 MeterReading（`app/Models/MeterReading.php`，39 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（MeterReading.php:11-13）
- **$fillable**：`property_id`, `unit_id`, `reading_date`, `reading_start`, `reading_end`, `meter_type`, `reading`, `amount`, `start_date`, `end_date`, `remark`, `is_hidden`（MeterReading.php:15-28）— `meter_type` 是 magic int 0/1/2（水/電/煤，定義在 NumericOptionService.php:98-102），而**同一組公用事業在 fee type 裡卻是 6/7/8**（NumericOptionService.php:57-59），MeterReadingController.php:325-341 有一段 switch 專門做 6→0、7→1、8→2 的換算 — 同一概念兩套編號。
- **Relationships**：`property()`, `unit()`。無 casts。

### 1.14 Property（`app/Models/Property.php`，159 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（Property.php:12-14）
- **$casts**：`managements => 'array'`（Property.php:41-43）— 但同檔的 `amenities` 卻用手寫 JSON accessor（Property.php:125-133），同一個 model 兩種 JSON 處理方式。
- **$fillable**（Property.php:45-64）：`name`, `company_name`, `company_location`, `company_fax`, `company_tel`, `location`, `company_id`, `region`, `area`, `intentional_rent`, `purchase_price`, `year_of_purchase`, `sale_price`, `light_boxs`, `light_box_rentals`, `management_fee`, `air_conditioning_fee`, `managements` — `company_name`/`company_location`/`company_fax`/`company_tel` 與 `company_id` 並存（又是快照+參照混用）。欄位說明是中文註解塊（Property.php:21-40）而非 schema 文件。
- **Class constants**：`REGIONS_OPTIONS` 28 個香港地區（Property.php:65-94）、`MANAGEMENT_TYPES_OPTIONS`（Property.php:96-100）、`AMENITIES_OPTIONS` 19 項（Property.php:102-123）。
- **致命設計**：`region` 欄位存的是 **REGIONS_OPTIONS 的陣列索引**（properties/create.blade.php:57-60 `<option value="{{ $index }}">`；讀取端 `Property::REGIONS_OPTIONS[$property->region]`，PropertiesWithUnitsExport.php:54、TenantRentSheet.php:117）— 在常數陣列中間插入或重排任何一項，全部既有物業的地區資料立即錯位損毀。
- **Relationships**：`leases()`, `debit_notes()`, `company()`, `units()`, `agendas()`（Property.php:135-158）。

### 1.15 ReceiptAllocation（`app/Models/ReceiptAllocation.php`，73 行）
- **Traits**：只有 HasFactory（無 Auditable）。
- **$fillable**：`tenant_receipt_id`, `user_id`, `receipt_amount`, `allocated_amount`, `remaining_amount`, `settlement_method_code`, `cheque_no`, `status`, `notes`（ReceiptAllocation.php:12-22）— 注意 `settlement_method_code` 存 code 字串，而 TenantReceipt 存 `settlement_method_id`，同一概念兩種外鍵形態。
- **$casts**：三個金額 decimal:2（ReceiptAllocation.php:24-28）。
- **Relationships**：`tenantReceipt()`, `user()`, `items()`。
- **Query scopes**：`scopeDraft`/`scopeConfirmed`/`scopeCompleted`（ReceiptAllocation.php:47-60）— 狀態字串 `'draft'`/`'confirmed'`/`'completed'` 硬編，無 enum。
- **業務 method**：`calculateRemaining()`、`updateRemaining()`（ReceiptAllocation.php:63-72）— 後者在 model 內直接 `$this->save()`，副作用藏在 model。

### 1.16 ReceiptAllocationItem（`app/Models/ReceiptAllocationItem.php`，51 行）
- **Traits**：HasFactory。
- **$fillable**：`receipt_allocation_id`, `debit_note_id`, `debit_note_fee_id`, `outstanding_amount`, `allocated_amount`, `fee_type`, `start_date`, `end_date`（ReceiptAllocationItem.php:12-21）— `fee_type` 在這裡存的是**字串**（BulkTransactionController.php:274 存 `'Overdue'` 或 `'Current Month'`），與 DebitNoteFee 的 int type 又是另一套。
- **$casts**：金額 decimal:2、日期 date（ReceiptAllocationItem.php:23-28）。
- **Relationships**：`allocation()`, `debitNote()`, `debitNoteFee()`。Method：`getRemainingAmount()`（ReceiptAllocationItem.php:47-50）。

### 1.17 SettlementMethod（`app/Models/SettlementMethod.php`，55 行）
- **Traits**：HasFactory（無 Auditable）。
- **$fillable**：`code`, `name`, `chinese_name`, `description`, `requires_cheque_no`, `is_active`, `sort_order`（SettlementMethod.php:12-20）— **全專案唯一做對方向的 model**：選項存 DB、有 `is_active`、有 `sort_order`，是 revamp 時所有 option list 應效法的樣板。但 `chinese_name` 欄位式雙語是第三種 i18n 手法（見第 4 節）。
- **$casts**：兩個 boolean（SettlementMethod.php:22-25）。
- **Static methods**：`getActive()`、`getSelectOptions()`（SettlementMethod.php:30-46）— `getSelectOptions()` 的 pluck 給下拉選單用，presentation 邏輯進了 model，但屬輕微。
- **Relationships**：`tenantReceipts()`。

### 1.18 TenantReceipt（`app/Models/TenantReceipt.php`，62 行）
- **Traits**：HasFactory, InteractsWithMedia；implements HasMedia — **無 Auditable**（TenantReceipt.php:10-13）。
- **$fillable**：`user_id`, `transaction_date`, `amount`, `status`, `settlement_method_id`, `cheque_no`（TenantReceipt.php:15-22）— `status` 值無定義。
- **$casts**：`transaction_date` date、`amount` decimal:2（TenantReceipt.php:24-27）。
- **Relationships**：`user()`, `settlementMethod()`, `allocations()`。
- **Media**：collection 名稱 `'TenantReceipt'`（大寫駝峰，與其他 collection 如 `deposit_pdf`/`receipt_pdf` 命名不一致，TenantReceipt.php:58-61）。

### 1.19 Transaction（`app/Models/Transaction.php`，47 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（Transaction.php:11-13）
- **$fillable**（Transaction.php:15）：**`'debit_note_id '` 帶尾隨空格** — 這使 `debit_note_id` 實際上不可 mass-assign。開發者沒修 bug 而是繞過：BulkTransactionController.php:324-325 註解寫明 "Set debit_note_id after creation to avoid mass assignment issues" 然後手動賦值。同時 `ref_id`、`transaction_number`、`allocation_id`、`type` 都不在 fillable（BulkTransactionController.php:321 傳入的 `allocation_id` 會被 Laravel 靜默丟棄）。`payment_method` 與 `settlement_method_id` 並存（新舊兩代付款方式欄位）。
- **無 $casts**（金額、日期全裸）。
- **Relationships**：`debit_note()`, `settlementMethod()`, **`transactions()`**（Transaction.php:27-30 — 名稱嚴重誤導，實際是 hasMany **TransactionItem**）, `ref_transaction()`（self belongsTo via ref_id，Transaction.php:32-35）。
- **Method**：`getReceiptPdf()`（Transaction.php:37-46）— media URL 取得邏輯，`sizeof()` + `->last() ?? ''` 的防禦式寫法，應交給 medialibrary API。

### 1.20 TransactionItem（`app/Models/TransactionItem.php`，36 行）
- **Traits**：HasFactory, InteractsWithMedia, Auditable（TransactionItem.php:11-13）；顯式 `$table = 'transaction_items'`（TransactionItem.php:15，其實符合慣例，多餘）。
- **$fillable**：`transaction_id`, `property_id`, `remark`, `amount`, `start_date`, `end_date`, `type`, `sort_order`, `ref_id`, `fee_id`（TransactionItem.php:17-20）— `type` 是 magic int（19=Overdue、22=Paid、5=Late Interest）；`ref_id` 指向 DebitNote、`fee_id` 指向 DebitNoteFee，欄位命名毫無自明性。
- **Relationships**：`transaction()`, `refDebitNote()`（via ref_id）, `refDebitNoteFee()`（via fee_id）。

### 1.21 Unit（`app/Models/Unit.php`，67 行）
- **Traits**：HasFactory, Auditable（Unit.php:9-11，無 media）。
- **$fillable**：`name`, `property_id`, `location`, `area`, `purchase_price`, `year_of_purchase`, `sale_price`, `sale_date`, `status`, `unit_management_fees`（Unit.php:13-24）
- **$casts**：`sale_date` date（Unit.php:26-28）。
- **Constants**：`STATUS_OPTIONS = ['active'=>'Active','pending'=>'Pending','sold'=>'Sold']`（Unit.php:30-34）— 這個至少 key 是穩定字串，屬最輕微的 hardcode。
- **Relationships**：`property()`, `leases()`（belongsToMany via lease_units）。
- **業務 methods**：`hasActiveLease()` / `getActiveLease()`（Unit.php:49-66）— 兩段幾乎相同的查詢複製貼上，用 `date('Y-m-d')` 直接取系統時間（不可測試、無時區考量），「active lease」的定義（start<=today<=end）散落於 model。

### 1.22 User（`app/Models/User.php`，73 行）
- **Traits**：`HasApiTokens`, `HasFactory`, `Notifiable`, **`HasRoles`**（spatie/permission）, Auditable（User.php:15）
- **$fillable**：`name`, `email`, `phone`, `company_name`, `attention`, `tel`, `password`, `company_ids`, `id_number`（User.php:22-32）— `phone` 與 `tel` 並存；`password` 可 mass-assign 又無 `hashed` cast（Laravel 10 已支援）。
- **$hidden**：`password`, `remember_token`（User.php:39-42）
- **$casts**：`email_verified_at` datetime、**`company_ids` => array**（User.php:49-52）— 多對多關係用 JSON int 陣列存，**無外鍵、無 pivot table**。
- **偽 relationship**：`companies()`（User.php:54-57）直接 `Company::whereIn('id', $this->company_ids ?? [])->get()` — 回傳 Collection 而非 Relation，不能 eager load、不能 query chain，每次呼叫都打 DB。
- **Relationships**：`tenantReceipts()`, `deposits()`, `leases()`。
- User 同時身兼 admin/staff/tenant（角色由 spatie 管），tenant 專屬欄位（company_name、id_number）直接掛在 users 表。

---

## 2. Magic Number 總表（源頭：`app/NumericOptionService.php`）

`Helpers.php` 是空的，**實質的共用 helper 是 `app/NumericOptionService.php`（133 行）**——全系統費用類型、狀態碼的唯一對照表，硬編在 PHP class property 裡：

| 定義 | 位置 | 內容 |
|---|---|---|
| `$sendOptions` | NumericOptionService.php:7-11 | 0=Pending, 1=Fail, 2=Sent（DN 寄送狀態，**連 CSS class 都硬編在裡面**） |
| `$debitNoteApprovalOptions` | NumericOptionService.php:12-21 | 0=Pending, 1=Approved, 2=Under Review, 3=Complete, 4=Rejected, 5=Overdue, 6=Overpaid（+CSS class） |
| `$debitNoteMasterFeeOptions` | NumericOptionService.php:23-48 | **0–23 共 24 種費用類型**：0=Rental, 1=Management Fee, 5=Late Interest Charges, 6=Water, 7=Electricity, 8=Gas, **19=Overdue**, 20=CHQ DEP, 21=Balance, **22=Paid**, 23=Deposit |
| `$debitNoteFeeOptions` | NumericOptionService.php:50-73 | 上表的子集（註解掉 5/19/20），同一組編號兩份清單要人手同步 |
| `$debitNoteFeeOptionsERPCode` | NumericOptionService.php:75-96 | **每種費用對應的 ERP 會計科目代碼**（'7120-01-0000' 等）與 DR/CR 方向，硬編在 PHP |
| `$meterReadingOptions` | NumericOptionService.php:98-102 | 0=Water, 1=Electricity, 2=Gas — 與 fee type 的 6/7/8 是**同一概念的第二套編號**，MeterReadingController.php:325-341 專門寫 switch 換算 |

這些 magic number 滲透進 model 層：DebitNote.php:71-77（19、5）、controller 層（TransactionController.php:87,118,130 的 22；DebitNoteController.php:221,1037、PdfController.php:65,175、EmailService.php:190 的 19）、甚至 method 名稱有 typo：`getdDebitNoteFee()`（NumericOptionService.php:119）。

git commit 提到的「transaction type 22 (paid)」即 NumericOptionService.php:46 的 `22 => 'Paid'`——「已付」不是一個布林欄位或狀態機，而是一筆 type=22 的 TransactionItem 資料列，overdue 結轉則是 type=19 的資料列，這是整個帳務資料模型最深的技術債。

---

## 3. 業務邏輯放錯層（model 層做了 service 層的事）

1. **DebitNote 的整套結欠計算引擎**（DebitNote.php:56-96）：五個 calculate* method 包含 overdue 轉結、late interest 排除、balance 沖銷等核心帳務規則，直接混用 magic number 與跨 model static 查詢（`TransactionItem::where(...)`，DebitNote.php:73-74,95），每呼叫一次打多次 DB。revamp 應抽出為 BillingService/LedgerService，且結欠應由不可變的 ledger entries 推導。
2. **Deposit::recalculateStatus()**（Deposit.php:68-82）：狀態機轉移邏輯 + 衍生欄位重算寫在 model，狀態字串 inline 硬編，呼叫方還要記得自己 save。
3. **ReceiptAllocation::updateRemaining()**（ReceiptAllocation.php:68-72）：model method 內含 `$this->save()` 副作用。
4. **Unit::hasActiveLease()/getActiveLease()**（Unit.php:49-66）：「有效租約」的業務定義用 `date('Y-m-d')` 寫死在 model，兩個 method 查詢邏輯複製貼上。
5. **SettlementMethod::getSelectOptions()**（SettlementMethod.php:41-46）：下拉選單格式化（presentation）寫成 model static method。
6. **Message 的顯示格式化 accessors**（Message.php:22-30）：view 層職責寫進 model，且直接覆寫框架的 created_at/updated_at，全域污染。
7. **Transaction::getReceiptPdf()**（Transaction.php:37-46）：media URL 解析邏輯。
8. **User::companies()**（User.php:54-57）：以 query 偽裝 relationship，掩蓋了 schema 缺失（無 pivot table）。

---

## 4. 翻譯（i18n）處理手法 — 三套並存

1. **`getTranslatedTypeAttribute` runtime 補丁**（Lease.php:149-160）：`leases.type` 欄位裡有**兩代資料並存** — 舊資料存中文（'住宅'、'寫字樓'、'倉'、'車庫'），新資料存英文 label（TYPES_OPTIONS，leases/create.blade.php:96-97 直接以顯示字串為 value）。accessor 用硬編 `$typeMap` 把中文舊值映到 lang key（'property.Residential' 等），對不上的直接丟進 `__()` 碰運氣。這是「以 accessor 掩蓋髒資料」的典型 hack。
2. **「label 即 lang key」串接**：view/export 用 `__('property.' . Property::REGIONS_OPTIONS[$property->region])`（properties/index.blade.php:111、PropertiesWithUnitsExport.php:54）、`__('lease.' . str_replace('/', '_', $typeOption))`（leases/create.blade.php:98）— 英文顯示 label 同時是資料值又是翻譯 key，改任何一個 label 會同時弄壞資料比對與翻譯查找。語言檔在 `lang/en`、`lang/zh`。
3. **DB 欄位式雙語**：SettlementMethod 的 `name` + `chinese_name`（SettlementMethod.php:15-16）。

revamp 建議統一為：lookup table 用穩定 code + translations 表（或 JSON translations 欄位，如 spatie/laravel-translatable），顯示層只憑 code 查翻譯。

---

## 5. Helpers.php

`E:/rms-old/rms/app/Helpers.php:1-14`：**整個檔案只有一個被完全註解掉的 `formatFileSize()`，實際內容為零**，卻仍掛在 composer.json:40 的 `autoload.files` 每個 request 都載入。用途：無。問題：死碼 + 無謂的 autoload 項目。revamp 直接刪除；真正的共用邏輯（NumericOptionService）如第 2 節所述另行處理。

---

## 6. 其他橫切面觀察

- **審計覆蓋不一致**：舊 model 全上 laravel-auditing，但新一代金流 model（Deposit、TenantReceipt、DepositAllocation、ReceiptAllocation、ReceiptAllocationItem、SettlementMethod）全部沒有 — 收款與押金分配反而是最需要 audit trail 的部分。
- **casts 風格斷層**：舊 model（DebitNote、Lease、Transaction、TransactionItem、LeaseMasterFee）完全沒有 casts，金額以 float + `round()` 處理；新 model 用 `decimal:2` — 兩代程式碼品質差異明顯，revamp 應全面以 integer cents 或 decimal 處理金額。
- **`$dates` 死碼**：DebitNoteFee.php:18、Message.php:17-20（Laravel 10 已移除該屬性）。
- **無 SoftDeletes**：22 個 model 無一使用軟刪除，財務資料可被硬刪（僅靠 audit 表補救）。
- **HasMedia 濫掛**：多數 model implements HasMedia 卻不註冊 collection（Agenda、DebitNoteFee、LeaseMasterFee、MaintenanceTask、TransactionItem 等）。
- **關係命名混亂**：snake_case（`debit_notes`、`company_receipt`）與 camelCase（`maintenanceTasks`、`settlementMethod`）混用；`Transaction::transactions()` 實為 items；`company_receipt()` 實為 bank account。

## Hardcode 發現（21 項）

| Severity | 位置 | 問題 | Revamp 建議 |
|---|---|---|---|
| 🔴 High | `app/NumericOptionService.php:23-48` | debitNoteMasterFeeOptions：24 種費用/交易類型以 magic int 0-23 硬編在 PHP property，含 19=Overdue、22=Paid（git commit 提到的 transaction type 22）、5=Late Interest Charges。全系統帳務語意繫於此陣列，DebitNoteFee.type、LeaseMasterFee.type、TransactionItem.type 皆存這些裸數字。 | 改為 fee_types DB lookup table（穩定 code、名稱、雙語翻譯、is_active、sort_order），行為性質（是否計入結欠、是否 overdue 結轉、是否代表已付）改為 table 上的 boolean/behavior 欄位或 PHP backed enum 承載行為，而非靠 int 比對。'Paid' 與 'Overdue' 根本不是費用類型，應改為正式的付款狀態機/ledger entry type。 |
| 🔴 High | `app/NumericOptionService.php:75-96` | debitNoteFeeOptionsERPCode：每種費用類型對應的 ERP 會計科目代碼（'7120-01-0000' 等）與 DR/CR 方向硬編在 PHP。會計科目異動須改 code 部署。 | 移入 fee_types lookup table 的 account_code / dr_cr 欄位（或獨立 gl_mappings 表），由後台維護。 |
| 🔴 High | `app/NumericOptionService.php:12-21` | debitNoteApprovalOptions：DN 審批/狀態碼 0-6（Pending/Approved/Under Review/Complete/Rejected/Overdue/Overpaid）硬編，且把 CSS class 名稱一併硬編在 PHP 資料結構內（presentation 混入 domain）。 | PHP backed enum（DebitNoteStatus）承載狀態機與轉移規則；CSS class 對照移到 view/前端層。Overdue/Overpaid 是衍生狀態，應由計算而非儲存。 |
| 🔴 High | `app/NumericOptionService.php:98-102 + app/Http/Controllers/MeterReadingController.php:325-341` | meterReadingOptions：水/電/煤編號 0/1/2，但同一組公用事業在費用類型裡是 6/7/8（NumericOptionService.php:57-59），controller 需寫 switch 做 6→0/7→1/8→2 換算 — 同一概念兩套 magic number。 | 統一為單一 utility_types lookup table 或 PHP enum（WATER/ELECTRICITY/GAS），fee type 以 FK 關聯 utility type，消滅換算層。 |
| 🔴 High | `app/Models/DebitNote.php:71-77` | calculateRemaining() 在 model 內硬編 where('type','!=',19)、where('type','!=',5)、where('type','=',5) 等 magic number，帳務核心規則（排除 overdue 結轉與遲息）以裸數字表達。 | 抽到 service 層並改用 enum/lookup 的具名行為欄位（如 excluded_from_outstanding）；同 magic number 亦散見 TransactionController.php:87,118,130（22）、DebitNoteController.php:221,1037、PdfController.php:65,175、EmailService.php:190（19）。 |
| 🔴 High | `app/Models/Property.php:65-94` | REGIONS_OPTIONS：28 個香港地區硬編為 PHP 常數陣列，且 properties.region 欄位儲存的是陣列索引（properties/create.blade.php:58 option value 為 $index；讀取端 Property::REGIONS_OPTIONS[$property->region]，見 app/Exports/PropertiesWithUnitsExport.php:54）。在陣列中段插入/刪除/重排任一地區即令全部既有資料錯位。 | 改為 districts DB lookup table（id 穩定、name_en/name_zh、sort_order），properties.region_id 為 FK；資料遷移時以索引對照表轉換。 |
| 🔴 High | `app/Models/Lease.php:40-54` | RENT_EXCLUSIVE_OPTIONS 與 RENT_EXCLUSIVE_OPTIONS_TRACKING：英文顯示 label（'Water charges tracking' 等）硬編且直接以字串存入 leases.rent_exclusive_options JSON，業務邏輯以 in_array('Water charges tracking', ...) 字串比對驅動抄錶計費（MeterReadingController.php:490,510,530）。改 label 即破壞計費行為。 | 改為穩定 code 的 lookup table + lease_fee_settings 關聯表，tracking 與否為 boolean 欄位；顯示文字走翻譯。 |
| 🔴 High | `app/Models/Lease.php:56-60` | PROPERTY_CATEGORIES_OPTIONS：硬編客戶專屬中文分類「JOYCE租予公司」「JOYCE外面租客」「公司物業收租」（含真實人名），leases.property_category 存陣列索引（leases/create.blade.php:107-109）。 | 改為使用者可維護的 categories lookup table；人名/公司名不應出現在程式碼。 |
| 🔴 High | `app/Models/Lease.php:62-79` | TYPES_OPTIONS：14 種物業類型硬編，leases.type 直接儲存英文顯示字串（leases/create.blade.php:96），同欄位又殘留舊中文值（'住宅'、'寫字樓'、'倉'、'車庫'），需靠 getTranslatedTypeAttribute 的硬編 typeMap 補救（Lease.php:151-157）— 一個欄位兩代資料格式。 | property_types lookup table（穩定 code + 雙語），遷移時把中文/英文舊值正規化為 FK；刪除 accessor 補丁。 |
| 🔴 High | `app/Models/Transaction.php:15` | $fillable 含尾隨空格的 'debit_note_id '，令該欄位實際不可 mass-assign；團隊以註解 'Set debit_note_id after creation to avoid mass assignment issues'（BulkTransactionController.php:324-325）繞過而非修正；ref_id/transaction_number/type/allocation_id 均不在 fillable，BulkTransactionController.php:321 傳入的 allocation_id 被靜默丟棄。 | revamp 時以明確的 DTO/service 建立交易，fillable 全面重審；此例證明衍生工程已在 bug 上疊 workaround，schema 與寫入路徑須重設計。 |
| 🔴 High | `app/Models/User.php:49-57` | company_ids 以 JSON int 陣列 cast 儲存 user-company 多對多關係，companies() 是回傳 Collection 的偽 relationship（無 FK 完整性、不能 eager load、每呼叫必打 DB）。 | 建 company_user pivot table + belongsToMany；revamp schema 必改。 |
| 🟡 Medium | `app/NumericOptionService.php:50-73` | debitNoteFeeOptions 是 debitNoteMasterFeeOptions 的手工維護子集（以註解排除 5/19/20），同一組編號兩份清單需人手同步，已出現漂移風險；method 名稱還有 typo getdDebitNoteFee (line 119)。 | 單一來源（lookup table）+ 以 flag（selectable_in_ui、is_system）過濾，不維護第二份清單。 |
| 🟡 Medium | `app/NumericOptionService.php:7-11` | sendOptions：DN 寄送狀態 0=Pending/1=Fail/2=Sent 硬編（含 CSS class）。 | PHP backed enum（SendStatus），CSS 移出。 |
| 🟡 Medium | `app/Models/Property.php:102-123` | AMENITIES_OPTIONS：19 項設施硬編，且儲存的是英文 label 字串本身的 JSON 陣列（Property.php:125-133 手寫 json_encode accessor），label 即資料值。 | amenities lookup table + property_amenity pivot；或至少以穩定 slug 儲存、翻譯另置。 |
| 🟡 Medium | `app/Models/Property.php:96-100` | MANAGEMENT_TYPES_OPTIONS（Management Office/Accounting/Engineering）硬編，managements JSON 欄位內以索引/label 參照。 | 併入 lookup table 或 PHP enum；managements 聯絡人結構改為獨立 property_contacts 表。 |
| 🟡 Medium | `app/Models/Deposit.php:73-79` | recalculateStatus() 內 inline 硬編狀態字串 'fully_used'/'partially_used'/'active'，無常數無 enum，其他層要比對只能重複硬編字串。 | PHP backed enum（DepositStatus）+ $casts enum cast；狀態轉移邏輯移到 service。 |
| 🟡 Medium | `app/Models/ReceiptAllocation.php:47-60` | scopeDraft/scopeConfirmed/scopeCompleted 硬編狀態字串 'draft'/'confirmed'/'completed'，且 ReceiptAllocationItem.fee_type 另存 'Overdue'/'Current Month' 顯示字串作資料（BulkTransactionController.php:274）。 | AllocationStatus PHP enum；fee_type 改存 FK/enum 而非顯示字串。 |
| 🟡 Medium | `app/Models/Lease.php:151-157` | getTranslatedTypeAttribute 內硬編中文→lang key 對照表（'住宅'=>'property.Residential' 等 5 項），為髒資料打 runtime 補丁。 | 資料遷移時一次過正規化 leases.type，刪除此 accessor；翻譯統一由 lookup table 的 translations 提供。 |
| 🟡 Medium | `app/Models/Lease.php:28-30` | water_formula/gas_formula/electricity_formula 以自由文字字串存每張租約的計費公式（LeaseController.php:167-169 僅驗證 nullable\|string），MeterReadingController.php:328-336 取出運算 — 公式無結構、無驗證、無版本。 | 改為結構化 tariff/formula 設定（rate、fixed charge、階梯式參數的 JSON schema 或關聯表），由 service 層以白名單運算，不存裸公式字串。 |
| ⚪ Low | `app/Models/Unit.php:30-34` | STATUS_OPTIONS：unit 狀態 active/pending/sold 硬編為常數陣列（key 為穩定字串，是最無害的一種）。 | PHP backed enum（UnitStatus）即可，毋須 DB table。 |
| ⚪ Low | `app/Helpers.php:1-14 + composer.json:40` | Helpers.php 整檔只剩被註解掉的 formatFileSize()，內容為零，卻仍掛在 composer autoload.files 每個 request 載入。 | 刪除檔案與 autoload 項目；共用邏輯改以具名 service/enum 提供。 |

## 設計問題（8 項）

| Severity | 範疇 | 問題 | 影響 | 建議 |
|---|---|---|---|---|
| 🔴 High | 帳務核心資料模型 | 「已付」與「逾期」不是狀態欄位而是特殊 type 的資料列：付清以 type=22 的 TransactionItem 表達（TransactionController.php:118）、逾期結轉以 type=19 的 DebitNoteFee/TransactionItem 表達（DebitNoteController.php:221）；DebitNote 的結欠由五個 calculate* method 於 model 層即時彙總（DebitNote.php:56-96），混用 magic number、跨 model static 查詢（DebitNote.php:73-74,95）與 withCount+DB::raw hack（DebitNote.php:76-78）。 | 帳務正確性依賴散落各處的 int 比對，無單一事實來源；任何新費用類型或狀態都要改多處程式；報表/結欠計算難以驗證且效能差（每張 DN 多次 sum 查詢）。 | revamp 以正式 ledger 設計：不可變 ledger entries + 具名 entry type（enum/lookup）+ DN 狀態機；結欠為推導值由 service 計算並可快取。 |
| 🔴 High | Model 層承載業務邏輯 | 本應在 service 層的計算與流程寫在 model：DebitNote 五個 calculate*（DebitNote.php:56-96）、Deposit::recalculateStatus 狀態機（Deposit.php:68-82）、ReceiptAllocation::updateRemaining 內含 save() 副作用（ReceiptAllocation.php:68-72）、Unit::hasActiveLease/getActiveLease 以 date('Y-m-d') 寫死有效租約定義且複製貼上（Unit.php:49-66）、SettlementMethod::getSelectOptions 下拉格式化（SettlementMethod.php:41-46）、Transaction::getReceiptPdf media 解析（Transaction.php:37-46）。 | 邏輯不可測試、不可重用，controller/model/view 三層互相滲透；修改任一規則需全域搜尋。 | domain service + action class 分層；model 只保留 relationships、casts、簡單 accessor。 |
| 🔴 High | Schema：快照欄位與參照混用、欄位重複 | DebitNote 同時有 bank_name/account_name/account_number 與 bank_id（DebitNote.php:21-27）；Property 有 company_name/company_location/company_fax/company_tel 與 company_id 並存（Property.php:47-52）；Lease 複製了整組 DN 預設欄位 due_date/date_of_auto_send/debit_note_number/bank_*（Lease.php:19-24，與 DebitNote.php:19-24 重複）；Lease 同時有單數 unit_id 與 lease_units 多對多（Lease.php:111-119）；Transaction 有 payment_method 與 settlement_method_id 兩代欄位（Transaction.php:15）；ReceiptAllocation 用 settlement_method_code 而 TenantReceipt 用 settlement_method_id（ReceiptAllocation.php:18 vs TenantReceipt.php:20）。 | 同一事實多處儲存且無同步機制，新舊兩代 schema 並存，任何查詢都要猜哪個欄位是真相。 | revamp schema 明確區分 reference（FK）與 point-in-time snapshot（如 DN 開立時的收款帳戶快照，集中一個 JSON snapshot 欄位或歷史表）；淘汰重複欄位。 |
| 🔴 High | 審計與資料保護不一致 | 舊 model 全掛 laravel-auditing，但新一代金流 model 全部沒有：Deposit（Deposit.php:10-12）、TenantReceipt（TenantReceipt.php:10-13）、DepositAllocation、ReceiptAllocation、ReceiptAllocationItem、SettlementMethod；且 22 個 model 無一使用 SoftDeletes。 | 最敏感的收款/押金分配操作反而無審計軌跡；財務資料可被硬刪。 | revamp 統一審計策略（全財務表必審）+ 軟刪除或禁刪（以沖銷代替刪除）。 |
| 🟡 Medium | 型別與金額處理斷層 | 舊 model（DebitNote、Lease、Transaction、TransactionItem、LeaseMasterFee、MeterReading）完全沒有 $casts，金額以 float 運算靠 round(x,2) 補救（DebitNote.php:67,81,83）；新 model 用 decimal:2 cast（Deposit.php:25-32 等）。另有 Laravel 10 已移除的 $dates 死碼（DebitNoteFee.php:18、Message.php:17-20）。 | 浮點誤差風險散佈於帳務計算；同 codebase 兩套日期/金額慣例增加維護成本。 | 金額統一 integer cents 或 decimal cast + Money value object；日期一律 casts。 |
| 🟡 Medium | i18n 三套機制並存 | （1）getTranslatedTypeAttribute runtime 對照補丁（Lease.php:149-160）；（2）「顯示 label 即資料值又即 lang key」：__('property.'.REGIONS_OPTIONS[$region])（PropertiesWithUnitsExport.php:54）、__('lease.'.str_replace('/','_',$typeOption))（leases/create.blade.php:98）；（3）DB 欄位式雙語 name/chinese_name（SettlementMethod.php:15-16）。 | 改任何顯示文字都可能同時破壞資料比對與翻譯；新增語言需三處改法。 | 統一為 lookup table 穩定 code + 翻譯表（或 spatie/laravel-translatable JSON 欄位），顯示層只憑 code 取翻譯。 |
| 🟡 Medium | Relationship 完整性與命名 | Transaction::transactions() 實為 hasMany TransactionItem（Transaction.php:27-30）；DebitNote::company_receipt() 實為 BankAccount（DebitNote.php:102-105）；Lease.renew_by_lease_id 無 relationship（Lease.php:33）；Message 的 sender/receiver 無 relationship（Message.php:13-15）；BankAccount/Company 無任何反向關聯；命名 snake_case 與 camelCase 混用（debit_note_fees vs maintenanceTasks）。Message 更把 created_at/updated_at accessor 覆寫成格式化字串且 updated_at 誤讀 created_at（Message.php:22-30）。 | ORM 能力（eager load、關聯查詢）無法使用或誤導開發者；Message 時間戳全域污染導致排序/序列化錯誤。 | revamp 統一命名規範、補齊雙向關聯、禁止覆寫框架時間戳 accessor（格式化交給 view/resource 層）。 |
| 🟡 Medium | User 模型多重身分 | User 同時是 admin/staff/tenant（spatie HasRoles，User.php:15），tenant 專屬欄位 company_name/attention/tel/id_number 直接掛在 users 表（User.php:22-32），user-company 關係以 company_ids JSON 陣列儲存（User.php:49-57），phone 與 tel 欄位並存。 | 租客資料與登入帳號耦合，無法表達一租客多聯絡人、公司租客等結構；JSON 關聯無完整性。 | revamp 拆分 tenants（當事人/公司實體）與 users（登入帳號），以 pivot 表建立 user-company 關聯。 |

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

- ✅ 屬實 — **debitNoteMasterFeeOptions：24 種費用/交易類型以 magic int 0-23 硬編在 PHP property，含 19=Overdue、22=Paid（git commit 提到的 transaction type 22）、5=Late Interest Charges。全系統帳務語意繫於此陣列，DebitNoteFee.type、LeaseMasterFee.type、TransactionItem.type 皆存這些裸數字。**（app/NumericOptionService.php:23-48）
  - 查證註記：Claim 屬實，且經多方交叉驗證無法推翻。(1) E:\rms-old\rms\app\NumericOptionService.php:23-48 的 $debitNoteMasterFeeOptions 確為 24 個連續整數鍵 0-23 的硬編陣列，其中 5='Late Interest Charges'（第29行）、19='Overdue'（第43行）、22='Paid'（第46行）。(2) 三個 model（DebitNoteFee.php:16、LeaseMasterFee.php:15、TransactionItem.php:19）的 fillable 皆含 'type'，且完全沒有 enum、cast 或常數定義；migration 2024_05_07_180708_create_transaction_items_table.php:17 定義 type 為 string 欄位，但實際存入的是這些裸數字。(3) 全系統以 magic int 直接讀寫：DebitNoteController.php:221/1037 與 PdfController.php:65/175 寫入 'type' => 19；DepositController.php:383/393 寫入 'type' => 23；EmailService.php:190/201 寫入 19 與 $type=5；DebitNoteController.php:263/296/342/1048 與 PdfController.php:76/186 設 $type=5（Late Interest）；TransactionController.php:130 比對 $transactionItem->type == 22；BulkTransactionController.php:274 比對 $fee->type == 19 ? 'Overdue'，:339 預設 ?? 22，:464/:496 寫 type_id 19/22。(4) git commit fbb31c5 訊息「on create transaction, add a type 22(paid) to group splited fee types as one type」證實 claim 中的 transaction type 22 出處。(5) blade（leases/create.blade.php:300-305）以陣列 index 作為 option value 直接存入 type，證實 UI 到 DB 全程使用裸數字。唯一細節補充：LeaseController.php:36 注入 lease 表單的其實是子集 getdDebitNoteFee()（$debitNoteFeeOptions，鍵有跳號、註解掉 5/19/20/22），但編號體系同一套，不影響 claim 成立。
  - 證據：app/NumericOptionService.php:23-48 `protected $debitNoteMasterFeeOptions = [ 0 => 'Rental', ... 5 => 'Late Interest Charges', ... 19 => 'Overdue', ... 22 => 'Paid', 23 => 'Deposit', ];`（鍵 0-23 共 24 項）。TransactionController.php:130 `if ($transactionItem->type == 22) {`；BulkTransactionController.php:274 `'fee_type' => $fee->type == 19 ? 'Overdue' : 'Current Month'`；DebitNoteController.php:221 `'type' => 19,`；EmailService.php:201 `$type = 5;`；DebitNoteFee.php:16 / LeaseMasterFee.php:15 / TransactionItem.php:19 fillable 皆含 'type' 且無 cast/enum；git commit fbb31c5 "add a type 22(paid) to group splite
- ✅ 屬實 — **debitNoteFeeOptionsERPCode：每種費用類型對應的 ERP 會計科目代碼（'7120-01-0000' 等）與 DR/CR 方向硬編在 PHP。會計科目異動須改 code 部署。**（app/NumericOptionService.php:75-96）
  - 查證註記：Claim 屬實。E:/rms-old/rms/app/NumericOptionService.php 第 75-96 行確實以 protected 屬性 $debitNoteFeeOptionsERPCode 將每種費用類型（key 對應 $debitNoteFeeOptions 的 0=Rental、1=Management Fee…23=Deposit）的 ERP 會計科目代碼與 DR/CR 方向硬編在 PHP 原始碼中，代碼包含 '7120-01-0000'、'1410-01-0000'、'7100-99-0000'、'4070-01-0000'、'8180-99-0000'。我嘗試推翻：全庫 grep 這些科目代碼字串，僅出現在此檔案，沒有任何 config、migration、seeder 或資料表提供同等對照（bank_accounts 表的 account_code 欄位是銀行帳戶代碼，與 ERP 科目對照無關），因此科目異動確實只能改 code 重新部署。附帶發現（不推翻 claim 但影響其嚴重性）：getter getdDebitNoteFeeERPCode()（第 124-127 行）在整個程式碼庫中沒有任何呼叫端（grep 'getdDebitNoteFeeERPCode' 與不分大小寫的 'ERPCode' 皆只命中此檔案），此對照表在目前快照中疑似為未被使用的 dead code，實際執行期影響可能為零。
  - 證據：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'], … 18 => ['account_code' => '8180-99-0000', 'amt' => 'DR'], 23 => ['account_code' => '4070-01-0000', 'amt' => 'DR'] ]; 以及 :124-127 getdDebitNoteFeeERPCode() 回傳該陣列。全庫 grep '7120-01-0000\|4070-01-0000\|8180-99-0000\|1410-01-0000\|7100-99-0000' 僅命中此檔；grep 'getdDebitNoteFeeERPCode' 無任何呼叫端。
- ✅ 屬實 — **debitNoteApprovalOptions：DN 審批/狀態碼 0-6（Pending/Approved/Under Review/Complete/Rejected/Overdue/Overpaid）硬編，且把 CSS class 名稱一併硬編在 PHP 資料結構內（presentation 混入 domain）。**（app/NumericOptionService.php:12-21）
  - 查證註記：Claim 屬實，無法推翻。E:\rms-old\rms\app\NumericOptionService.php 第 12-21 行的 protected $debitNoteApprovalOptions 確實以硬編碼定義狀態碼 0-6，文字依序為 Pending / Approved / Under Review / Complete / Rejected / Overdue / Overpaid（另有被註解掉的 7 => 'Cleared'），且每個項目都內嵌 'class' 鍵存放 CSS class 名稱（status-pending、status-approved、status-under-review、status-success、status-fail）。這些名稱確為 presentation 層的 CSS class：public/css/app.css 第 196-212 行定義了 .status-success/.status-pending/.status-fail/.status-approved/.status-under-review，而 resources/views/debit_notes/show.blade.php（第 36、379 行）直接以 $debitNoteApprovalOptions[$debit_note->status]['class'] 輸出到 HTML class 屬性。多個 Controller（DebitNoteController、LeaseController、TransactionController）透過 getDebitNoteApprovalOptions() 取得後傳入 view，證實 presentation 資訊（CSS class）混入 domain 資料結構的說法成立。
  - 證據：app/NumericOptionService.php:12-21 — protected $debitNoteApprovalOptions = [ 0 => ['class' => 'status-pending', 'text' => 'Pending'], 1 => ['class' => 'status-approved', 'text' => 'Approved'], 2 => ['class' => 'status-under-review', 'text' => 'Under Review'], 3 => ['class' => 'status-success', 'text' => 'Complete'], 4 => ['class' => 'status-fail', 'text' => 'Rejected'], 5 => ['class' => 'status-fail', 'text' => 'Overdue'], 6 => ['class' => 'status-success', 'text' => 'Overpaid'], // 7 => ['class' => 'status-success', 'text' => 'Cleared'], ];　佐證：public/css/app.css:196-212 定義對應 CSS class；resourc
