# 財務模組 Controllers（金流）

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

# RMS 財務金流 Controllers 深度分析報告（revamp 證據蒐集）

分析範圍：`E:/rms-old/rms/app/Http/Controllers/` 下 8 個財務相關 controller、`app/Http/Requests`、`app/Exports`（含 Sheets）、`app/Imports`、`app/Services/EmailService.php`、`app/Mail`、`load_font.php`，以及必要的支援類別 `app/NumericOptionService.php`、`app/Models/DebitNote.php`（計算方法）、PDF blade 模板與 routes。

---

## 1. 完整金流敘述

### 1.1 型別代碼的唯一真相來源：NumericOptionService（PHP 陣列，非 DB）

整條金流的 fee type / status code 全部定義在 `app/NumericOptionService.php` 的硬編碼 PHP 陣列，**不在資料庫**：

- `debitNoteMasterFeeOptions`（`app/NumericOptionService.php:23-48`）：`0=Rental, 1=Management Fee, 2=Rates, 3=Government Rent, 4=Stamp Duty, 5=Late Interest Charges, 6=Water, 7=Electricity, 8=Gas, 9=Rental Deposit, 10=Management Fee Deposit, 11=Rates & Rent Deposit, 12-14=Adj 各類 Deposit, 15=Rent free period, 16=Late Interest charges(One-Time waiver), 17=Rent concession, 18=R&M, 19=Overdue, 20=CHQ DEP, 21=Balance, 22=Paid, 23=Deposit`
- DN 狀態 `debitNoteApprovalOptions`（`NumericOptionService.php:12-21`）：`0=Pending, 1=Approved, 2=Under Review, 3=Complete, 4=Rejected, 5=Overdue, 6=Overpaid`（7=Cleared 被註解掉但程式裡仍殘留對 7 的引用，如 `DebitNoteController.php:176` 註解、`734`）
- ERP 會計科目對照 `debitNoteFeeOptionsERPCode`（`NumericOptionService.php:75-96`）：如 `0 => ['account_code'=>'7120-01-0000','amt'=>'CR']`，整份會計科目表寫死在 PHP。
- email 發送狀態 `sendOptions`（`NumericOptionService.php:7-11`）：`0=Pending, 1=Fail, 2=Sent`。

### 1.2 Lease master fees → DN 產生（手動）

- 入口 `DebitNoteController::create()`（`DebitNoteController.php:151-460`，單一 method 約 310 行）。
  - 讀取 `$lease->lease_master_fees()`，以 `counting_per_month` 決定收費週期：`0`=一次性（押金類，只在第一張 DN 收，`:402-403`）、`1`=每月（rental/management fee 用下個月起算，`:393-395`）、`n`=每 n 個月（`monthsSinceStart % counting_per_month == 0`，`:406-407`）。
  - 按日拆分計費：`$amount = round($leaseFee->amount * $actualDays / $totalDays, 2)`（`:437`）。
  - **Overdue 帶入**：從上一張 DN 的 type 19 fee 追出未清 DN（`:178-180`），計算 `overdue_amount = fees(type!=19) - 已付(type!=5) - late_paid`（`:199-200`），塞成新 DN 的 type 19 fee。
  - **遲繳利息（type 5）**：以 `total * 0.02 * days / daysInMonth`（月息 2% 按日拆，`:261, :294, :345`）產生 late fee 列，邏輯極度糾結（`use_previous_end_date_to_start_date`、`_2` 變數副本、先 push 再 `array_pop` 的補丁式修正 `:281-285, :311-315, :362-366`）。
- `store()`（`:462-582`）：以「同一 lease 同一 `date_of_auto_send` 年月只能有一張」防重（`:483-492`）；`DebitNote::create($request->all())` 直接 mass assignment（`:507`）；DN 號碼 = `company_code + '-' + str_pad(id, 8, '0')`（`:508`）；銀行資料從 `lease->company_receipt` **快照複製**到 DN 欄位（`:502-504`）；逐筆寫 `DebitNoteFee` 後呼叫 `PdfController::generateDebitNote()`（`:562`），最後把之前狀態 0/1/2/4 的 DN 全部 `complete()`（`:565-568`）。

### 1.3 Cron/API 自動開 DN 與 SMS 提醒

- `GET /auto-create-debit-note` → `DebitNoteController::autoCreate()`（route 在 `routes/web.php:58`，**無 auth middleware**），驗證方式是 `$request->key !== env('APP_NAME')`（`DebitNoteController.php:982`）——用 APP_NAME 當 secret token。
- **關鍵：`autoCreate()` 內有 `dd('wait all done');`（`DebitNoteController.php:992`），整個自動開 DN 流程在 log 完數量後直接中斷，實際上是死程式**。其後 `:996-1243` 是把 `create()`+`store()` 邏輯整段複製貼上的第二份實作（且細節不一致，如 `:1113` 的 `addMonthsNoOverflow($leaseFee->counting_per_month)` 比 `:417` 少了 `-1`；`date_of_auto_send` 被覆寫為「下個月 28 號」`:1156`）。
- `GET /auto-alert-debit-note` → `autoAlert()`（`:1249-1270`）：找明天到期、狀態 1 的 DN，**實際發 SMS 的程式碼被註解掉**（`:1262-1263`），只剩 Log。
- 另有 `EmailService::sendDebitNoteTask()`（`EmailService.php:148-294`）批次寄 DN email（`date_of_auto_send <= now` 且未寄出），內含**第四份** overdue/late-fee 計算複本。

### 1.4 Tenant receipt 上傳 → receipt allocation → transactions（新流程）

- 租客/管理員在 `TenantReceiptController::store()`（`TenantReceiptController.php:90-121`）上傳付款證明（金額、日期、`settlement_method_id`、cheque_no、附件走 `public/tmp/uploads` 暫存再轉 medialibrary），狀態字串 `pending/approved/rejected`（`:150` 寫死在 validate）。
- 審批後走 `BulkTransactionController`：`selectTenant()`（`BulkTransactionController.php:31`）→ `selectReceipt()`（`:44`）→ `allocateReceipt($receiptId)`（`:156-190`）建立/重用 `ReceiptAllocation`（draft）→ `storeAllocation()`（`:195-371`）核心：
  - 逐列建 `ReceiptAllocationItem`；type 19（Overdue）逐筆分配、其他 fee 合併為一列「Current Month」（`:225-281`）。
  - 每張 DN 建一筆 `Transaction`（`RE-` 前綴 8 位數號碼，`:326`）與多筆 `TransactionItem`（grouped 列 type fallback 為 22 `Paid`，`:339`）。
  - 產生收據 PDF（`:352`）、以 `calculateOutstanding()` 重算 DN outstanding（`:355`）、allocation 標記 completed（`:360`）。
  - `deleteAllocation()`（`:376-416`）反向刪除 transaction/items/allocation items 並重算 outstanding。
- 已付金額判定 `calculatePaidAmount()`（`:421-435`）：用 `$item->ref_id == $fee->ref_id && $item->type != 22` 比對——一般 fee 的 ref_id 是 null，null==null 全部互相匹配，是以「巧合」運作的脆弱設計。

### 1.5 舊流程：TransactionController 直接對 DN 收款

- `TransactionController::create()`（`TransactionController.php:45-155`）雙模式：帶 `lease_id` 建「Balance」交易（`B-` 前綴）；帶 `debit_note_id` 則列出 type 19 未清項 + 一列 type 22（Paid）代表本期應收（`:118` `$type = 22`，`:136` 金額 = outstanding - overdue + paid 調整）。
- `store()`（`:157-285`）：建 `Transaction`（`RE-`）+ `TransactionItem`；支援用 lease 餘額抵扣——產生一筆負數 `B-` 交易（`:261-269`）。**Transaction 資料表同時當收據（debit_note_id）與 lease 錢包（lease_id）用，schema 語意重載**。
- `destroy()`（`:500-532`）：刪收據時把關聯 balance 加回（再建一筆 `B-` 正數交易）。
- `sendReceipt()`（`:534-587`）寄收據 email，`-R0001` 版本號規則與 DN 相同。

### 1.6 Deposit → deposit allocation

- `DepositController::store()`（`DepositController.php:96-140`）：建 `Deposit`（`DEP-` 8 位數 reference），狀態字串 `draft`→`active` 寫死（`:113, :120`）。
- `storeAllocation()`（`:329-423`）：驗餘額後建 `DepositAllocation`，同步 1) 更新 deposit 的 allocated/remaining（`:360-363`）、2) 建 `Transaction`（先塞 `DEP-` 號再改成 `RE-`，`:368, :376`——同一筆連存兩次）、3) 建 type 23 `TransactionItem`（`:381-388`）、4) 在 DN 上加一筆**負數** type 23 `DebitNoteFee`（`:391-400`，sort_order 寫死 999）、5) 手動遞減 `outstanding_balance`（`:403`，與其他流程用 `calculateOutstanding()` 重算的方式不一致）。
- `revokeAllocation()`（`:240-288`）：反向刪 transaction/items/type 23 fee，**手動加回** outstanding（`:267`）。

### 1.7 Settlement method

- 唯一做對的部分：`settlement_methods` 是 DB 資料表，`SettlementMethodController`（113 行）是乾淨的 CRUD，`code/name/chinese_name/requires_cheque_no/is_active/sort_order` 全可配置。`TenantReceipt`、`Transaction` 都以 `settlement_method_id` FK 關聯。revamp 時「fee types、DN status」應仿照此模式落 DB。

### 1.8 Outstanding 的計算

- `DebitNote::calculateOutstanding()`（`app/Models/DebitNote.php:65-68`）= `sum(debit_note_fees.amount) - sum(transactions.amount)`；`calculateRemaining()`（`:69-84`）另一套排除 type 19/5 的演算法。同一個「欠多少錢」概念有兩種算法 + DepositController 的手動加減，三者並存。
- DN 完成/逾期/溢繳狀態機在 `DebitNoteController::complete()`（`:818-849`）：outstanding>0 → 5(Overdue)；<0 → 6(Overpaid) 並呼叫 `complete_overdue()`（`:851-862`）把溢繳金額轉成 lease 餘額交易；=0 但有遲付 → 5。注意 `:823` 的 guard `!(status != 1 || status != 2 || status != 4)` 是恆假的邏輯錯誤（永遠不會擋），任何狀態都能被 complete。

---

## 2. 各 controller LOC 與職責膨脹

| Controller | LOC | 膨脹評估 |
|---|---|---|
| `DebitNoteController.php` | 1,271 | 極肥。`create()` 一個 method 310 行（`:151-460`）；`autoCreate()` 又複製了 create+store 共約 270 行（`:979-1246`）；同時負責 CRUD、審批狀態機、餘額回沖、email、SMS、media、cron endpoint |
| `TransactionController.php` | 588 | 肥。`show()` 與 `edit()` 幾乎相同的 preset_input 組裝各約 60 行（`:287-337` vs `:339-405`） |
| `BulkTransactionController.php` | 504 | 中肥。`getDNsToAllocate()`（`:85-151`）與 `getDNsData()`（`:440-503`）在**同檔內**幾乎完全重複 |
| `DepositController.php` | 424 | 中。allocation 的複式記帳邏輯全部內嵌 controller |
| `PdfController.php` | 389 | PDF controller 內嵌 overdue/late-fee 商業計算（`:37-96`, `:149-206`）；`previewPdf()` 內 `:100` return 之後 `:102-104` 是死碼 |
| `EmailService.php` | 310 | 名為 EmailService，實際混雜 email、SMS gateway、Firebase/app push、DN overdue 計算複本（`:164-221`） |
| `TenantReceiptController.php` | 224 | 尚可，但 `sendRejectionSMS(User $user, $receiptId)`（`:208`）宣告兩參數、呼叫處 `:180` 只傳一個 → **一觸發 reject 即 ArgumentCountError fatal**；`destroy()` 清的 media collection 名 `TenantReceipt_attachments`（`:195`）與 store 用的 `attachments`（`:112`）不一致 |
| `ReportController.php` | 117 | 薄，但只是把計算推給 Export classes |
| `SettlementMethodController.php` | 113 | 乾淨 CRUD，可作範本 |

### 重複邏輯段落（overdue + 2% 遲繳利息計算，共 6+ 份複本）
1. `DebitNoteController.php:189-377`（create）
2. `DebitNoteController.php:1017-1081`（autoCreate，簡化版、行為不一致）
3. `PdfController.php:37-96`（previewPdf）
4. `PdfController.php:149-206`（generateDebitNote）
5. `EmailService.php:164-221`（sendDebitNoteTask）
6. `resources/views/pdf/debt_note.blade.php:310-327`（**blade 模板內再算一次** transaction_amount）
7. 「已付金額」判定：`TransactionController.php:82-108`、`BulkTransactionController.php:421-435`、`DebitNote::calculateRemaining()`（`app/Models/DebitNote.php:69-84`）三種寫法並存。

其他重複：`-R0001` PDF 版本號規則出現在 `DebitNoteController.php:901-908`、`TransactionController.php:545-563`、`PdfController.php:210-217, :287-303`、`EmailService.php:225-232`；media 從 `tmp/uploads` 搬移的樣板碼在 6 個以上位置。

---

## 3. 交易安全（DB transaction）

全專案 `app/` 只有兩個 controller 用 `DB::beginTransaction`：
- `BulkTransactionController.php:206, :379`
- `DepositController.php:106, :183, :222, :243, :337`

**完全沒有包 transaction 的高風險多步驟寫入：**
1. `DebitNoteController::store()`（`:462-582`）：DN → DN number 二次 save → 多筆 DebitNoteFee → media 搬移 → outstanding 重算 → PDF → 迴圈 complete 舊 DN（每個 complete 可能再建 balance transaction）。中途失敗會留下號碼未編/費用不齊的 DN。
2. `DebitNoteController::update()`（`:631-724`）：先 `whereNotIn` **刪除** fee 再重建（`:666`），中途失敗 = 費用資料遺失。
3. `DebitNoteController::destroy()`（`:726-780`）：建回沖 balance transaction 後才 delete DN，失敗會多出憑空餘額。
4. `DebitNoteController::complete()/complete_overdue()`（`:818-862`）：改狀態 + 建 overpaid balance transaction 兩步無原子性；且 `complete()` 被 `store()` 迴圈呼叫，重複觸發可能重複建立溢繳餘額。
5. `TransactionController::store()`（`:157-285`）：Transaction → items → 負數 balance transaction → outstanding 重算，共 4 類寫入無包裹；`:214` create 後 `:270` 才 save 號碼。
6. `TransactionController::update()`（`:406-497`）與 `destroy()`（`:500-532`）：同樣是「刪 items→重建→回沖餘額」裸奔。
7. `TenantReceiptController::store()`（`:90-121`）：receipt + media 兩步。
8. 另外即使有包 transaction 的：`DepositController::storeAllocation()` 把 PDF 產生放在 transaction 內（`:407-413`），`BulkTransactionController::storeAllocation()` 亦然（`:352`）——長 IO 佔住 DB 交易；`DepositController::revokeAllocation()` 在 tx 內呼叫 `generateDebitNote`（`:277`）。

**併發問題**：所有 outstanding_balance 更新皆為「讀-算-寫」，無鎖、無 optimistic locking；`DepositController` 手動 `+=`/`-=`（`:267, :360-361, :403`）與其他處 `calculateOutstanding()` 重算並存，兩個管理員同時操作同一 DN 必然產生錯帳。

---

## 4. Hardcode 清單（詳見 structured findings）

重點摘要：
- **Transaction/fee type codes 0-23** 全部寫死（意義見 §1.1）；散落引用：type 19 於 `DebitNoteController.php:178,204,221,231…`、type 5 於 `:191,263,296,342`、type 22 於 `TransactionController.php:87,118,130`、`BulkTransactionController.php:339,429`、type 23 於 `DepositController.php:257,383,393`、type 0/1/2 於 `TenantRentSheet.php:83,95,101`。
- **2% 月遲繳利率**：`DebitNoteController.php:261,294,345,1051`、`PdfController.php:183`、`EmailService.php:198`，並以字串 `'*2%*'` 直接拼進 remark（`DebitNoteController.php:266,299,347` 等）——費率改動要改 6+ 處加一堆字串。
- **到期日規則**：`startOfMonth()->addMonth()->addDays(9)`（下月 10 號）寫死於 `DebitNoteController.php:172,1007`；autoCreate 的 `date_of_auto_send` 寫死下月 28 號（`:1156`）。
- **銀行/公司資料**：DN 建立時從 `lease->company_receipt` 快照 `bank_name/account_name/account_number` 到 DN 欄位（`DebitNoteController.php:502-504,1168-1170`）；寄件人 `info@wesleymarketplace.com`、cc `property@e-inv.link, rental@e-inv.link`、admin_user_id=11 寫死於 `config/services.php:36-43`。
- **外部服務**：SMS gateway `http://143.89.41.83/report/api/sms.php`（`EmailService.php:300`，HTTP 明文）；推播伺服器 `http://125.215.175.143:8080` + **API key 明碼**（`EmailService.php:27,91`）；被註解的 Firebase private key 仍留在原始碼（`EmailService.php:28-32`）；香港區碼 `'852'` 寫死（`TenantReceiptController.php:216`）。
- **Cron 認證**：`env('APP_NAME')` 當 secret（`DebitNoteController.php:982,1252`），route 無 auth（`routes/web.php:58-60`）；config 快取後 `env()` 回 null，`null !== null` 為 false，**等於無密碼放行**。
- **人名/staff code**：`wongkwu`、`CKLONG`、Grace 出現在（註解的）推播程式（`DebitNoteController.php:117,813,967`）。
- **PDF 模板**：遠端簽名圖 `https://property.e-inv.link/storage/images/signature.png`（`receipt.blade.php:163`、`deposit.blade.php:163`）——PDF 內容綁死某一環境網域；付款指示、`Remarks : Cheque deposit (Not valid until cheque is cleared)`（`receipt.blade.php:303`）等英文條款寫死；Google Fonts `@import`（`debt_note.blade.php:9`）配合 `setIsRemoteEnabled(true)` 每次產 PDF 都外連；deposit PDF 抬頭寫死 `DEPOSIT MANAGEMENT SYSTEM`（`deposit.blade.php:167`）。
- **報表**：sheet 名 `'JOYCE租予公司'/'JOYCE外面租客'/'公司物業收租'`（`TenantRentReportExport.php:81-83`，客戶人名寫進程式）；`"放租中"` 中文字串比對決定儲存格底色（`TenantRentSheet.php:274,282,290`），與 `__('report.For Rent')` 翻譯脫鉤，換語系即失效；儲存格座標/顏色 `FF518dd5`、`F1=SUM(...)` 寫死（`TransactionsPerMonthSheet.php:132-134`）。
- **單號格式**：`str_pad(id, 8, '0')` 配 `B-`/`RE-`/`DEP-`/`company_code-` 前綴散落 `DebitNoteController.php:508,746,757,857`、`TransactionController.php:178,215,263,505`、`DepositController.php:119,368,376`、`BulkTransactionController.php:326`。
- **日期格式**：`Y-m-d`、`d-M-Y`（`debt_note.blade.php:175`）、`d/m/Y`（`:286`）混用無集中定義。
- **檔案上傳暫存**：`public_path('tmp/uploads/')` 魔法路徑 + `explode('_', $file, 2)[1]` 檔名解析散落 10+ 處（如 `DebitNoteController.php:543-546`、`TransactionController.php:459-463`、`TenantReceiptController.php:108-115`）。

**Requests 層**：`app/Http/Requests` 只有 `ProfileUpdateRequest.php` 與 `Auth/LoginRequest.php`——**所有財務端點都沒有 FormRequest**，驗證內嵌 controller，且大量 `Model::create($request->all())` mass assignment（`DebitNoteController.php:507,662`、`TransactionController.php:177,214,426`）。

---

## 5. ReportController 計算邏輯與可重用性

- `ReportController`（117 行）本身幾乎沒有計算：`getFilteredDebitNoteData()`（`ReportController.php:79-116`）只做 property/lease/year 過濾後 `->get()` 全撈；`getFilteredTenantRentData()`（`:67-78`）只撈 Property。
- **真正的報表計算在 Export/Sheet classes**：
  - `TransactionsPerMonthSheet::collection()`（`app/Exports/Sheets/TransactionsPerMonthSheet.php:43-87`）：把全年 DN 集合在 PHP 端逐月 filter（`:54-56`，同一集合被 12 個 sheet 各 filter 一次），三層巢狀迴圈逐 DN → transaction → item 取數，`$debit_note->transactions()->latest()->get()` 在迴圈內執行——嚴重 N+1；「是否計息」判斷 `outstanding_balance > 0 || 有遲付` 內嵌在 row 組裝（`:74`）。
  - `TenantRentSheet::collection()`（`TenantRentSheet.php:42-208`）：每 unit 在迴圈內查 active lease 與 type 0/1/2 master fee（N+1）；6 個月到期提醒 `DateInterval('P6M')` 寫死（`:113,173`）；`headings()` 23 欄 vs 資料列 21 欄，欄位錯位（`:210-238` vs `:116-141`）。
- **可重用性：低。** 計算與 PhpSpreadsheet 樣式碼（凍結窗格、顏色、SUM 公式）綁死在同一 class；月租/欠款彙總無獨立 service 或 query object，UI 頁面（filter view）與 Excel 匯出各自組資料。revamp 應把「應收/實收/欠款 per lease per month」做成獨立查詢層，報表與畫面共用。

---

## 6. PDF 產生方式與 load_font.php

- 使用 `barryvdh/laravel-dompdf`（`PdfController.php:5` 注入 `Barryvdh\DomPDF\PDF`）。產出流程：`View::share('data', $model)`（全域共享而非傳參，`PdfController.php:232,309,365`）→ `loadView('pdf.debt_note'|'pdf.receipt'|'pdf.deposit')` → `$pdf->output()` 存成 medialibrary media（collection `debit_note_pdf`/`transaction_receipt_pdf`/`deposit_pdf`），重寄時以 `-R0001` 尾碼疊版本。
- **危險選項**：`setIsPhpEnabled(true)`（`PdfController.php:119,121,314,370`——允許模板內嵌 PHP，dompdf 已知 RCE 面向）、`setIsRemoteEnabled(true)` + SSL `verify_peer=false`（`:315-321,371-377`）以便抓遠端簽名圖與 Google Fonts——每次產 PDF 都做外部 HTTP 請求，離線/網路抖動即產出破圖 PDF。
- **`load_font.php`（專案根目錄，202 行）**：dompdf 官方 CLI 字型安裝工具的複製品，把 `$fontDir` 指到 `storage/fonts`（`load_font.php:10`，相對路徑，依 CWD 而定）。作用：把 TTF/OTF（此處為中文字型）複製進 `storage/fonts` 並用 php-font-lib 產生 `.ufm` metrics、寫入 font lookup table——這是 dompdf 能渲染中文（SimHei、Noto Sans TC，見 `storage/fonts/` 內容）的前提。
- **問題**：(1) 手動 CLI 步驟，部署新環境漏跑就變豆腐字，無任何文件化；(2) `storage/fonts` 裡同時存在大量 hash 命名的 `noto_sans_tc_*.ttf`，代表 runtime 也在靠 remoteEnabled 下載 Google Fonts 並快取——字型來源雙軌不可控；(3) 工具檔放在專案根目錄而非 artisan command，與 vendor 內建版本重複；(4) blade 用 `@import url('https://fonts.googleapis.com/...')`（`debt_note.blade.php:9`）宣告字型、CSS class 名叫 `.chinese` 手動套用，中文覆蓋範圍靠人肉保證。
- 其他：`previewPdf()` 內 `:100` `return view(...)` 之後 `:102-104` 為不可達死碼；`generateDebitNote()` 會**永久改寫共享模型屬性再存檔**風險（`$debit_note->property->location .= ...` `:229`，靠不 save 僥倖不落地）；catch 的是 `ValidationException`（`:262,330,384`）但流程中根本不會拋這型別，等於沒有錯誤處理。

---

## 7. Revamp 重點建議（依證據）

1. **Fee type / DN status / 費率 / 到期日規則全部落 DB**，仿 `settlement_methods` 模式（唯一已做對的先例）。
2. **金流寫入抽出到 domain service**（如 `BillingService`/`AllocationService`），單一 overdue+利息演算法、單一「已付」判定，全部以 `DB::transaction` + 行鎖包裹；outstanding 改為 ledger 推導而非可變欄位。
3. **廢除 Transaction 表的雙重語意**（收據 vs lease 錢包），改為明確的 ledger entries。
4. PDF 改為離線資產（本地字型、本地簽名圖）、關閉 isPhpEnabled/isRemoteEnabled；字型安裝改 artisan command。
5. 報表查詢層獨立於 Excel 匯出，消除 N+1。
6. cron endpoints 改 artisan schedule + 正式 token/簽名驗證。

## Hardcode 發現（20 項）

| Severity | 位置 | 問題 | Revamp 建議 |
|---|---|---|---|
| 🔴 High | `app/NumericOptionService.php:23-48` | 全部 fee/transaction type codes（0=Rental…5=Late Interest Charges…19=Overdue, 20=CHQ DEP, 21=Balance, 22=Paid, 23=Deposit）以 PHP 陣列寫死，DB 無對應表；所有金流計算以整數字面值散落引用（type 19: DebitNoteController.php:178,204; type 5: :191,263; type 22: TransactionController.php:87,118, BulkTransactionController.php:339,429; type 23: DepositController.php:257,383,393） | 建立 fee_types / transaction_types 資料表（code、name、雙語名稱、是否計息、是否 deposit 類、排序），以 Enum/const 引用取代魔法數字，type 行為（如 overdue、paid marker）用欄位 flag 表達 |
| 🔴 High | `app/NumericOptionService.php:12-21` | DN 狀態機 0=Pending,1=Approved,2=Under Review,3=Complete,4=Rejected,5=Overdue,6=Overpaid 寫死；7=Cleared 被註解但程式仍殘留引用（DebitNoteController.php:176,734 註解）；狀態判斷散落各 controller（DebitNoteController.php:786,804,823,829-841,869,883） | 改為 PHP 8.1 backed Enum + 明確 state machine（可用 spatie/laravel-model-states），Overdue/Overpaid 應為推導屬性而非持久化狀態 |
| 🔴 High | `DebitNoteController.php:261,294,345,1051 / PdfController.php:183 / EmailService.php:198` | 遲繳利息月利率 0.02（2%）寫死於 6+ 處，且以字串 '*2%*' 拼入 remark（DebitNoteController.php:266,299,347,1053）；改費率需同步改動計算與顯示字串多處 | 利率放 lease 或系統設定（per-lease late_interest_rate 欄位），remark 由計算結果格式化產生，計算集中於單一 service |
| 🔴 High | `DebitNoteController.php:982,1252 + routes/web.php:58-60` | cron API 以 $request->key !== env('APP_NAME') 驗證：APP_NAME 非機密；route 無 auth middleware；config:cache 後 env() 回 null 使 null!==null 為 false，等於無密碼放行 | 改用 artisan schedule 內部執行；若須 HTTP 觸發，用專用長隨機 token 存 config/secret manager 並以 hash_equals 比對 |
| 🔴 High | `app/Services/EmailService.php:27,91,300` | 推播伺服器 IP http://125.215.175.143:8080 與 64 字元 API key 明碼寫死；SMS gateway http://143.89.41.83/report/api/sms.php 明文 HTTP 寫死；:28-32 還留有被註解的 Firebase private key 全文 | 全部移入 .env/config，撤換已洩漏的 key，刪除註解中的 private key 並視為已外洩處理；SMS/push 抽象成 notification channel 介面 |
| 🔴 High | `resources/views/pdf/receipt.blade.php:163,303 / deposit.blade.php:163,167` | 收據 PDF 的簽名圖抓遠端 https://property.e-inv.link/storage/images/signature.png（綁死特定環境網域，且 PdfController.php:315-321 為此開 isRemoteEnabled + 關閉 SSL 驗證）；'Remarks : Cheque deposit (Not valid until cheque is cleared)' 無條件寫死；deposit 抬頭寫死 'DEPOSIT MANAGEMENT SYSTEM' | 簽名圖改本地檔案/base64 內嵌；備註依 settlement method 的 requires_cheque_no 條件輸出；抬頭取自公司資料；關閉 isRemoteEnabled/isPhpEnabled |
| 🔴 High | `DebitNoteController.php:172,1007,1156` | 帳期規則寫死：due_date = 月初+1月+9天（即下月10號）；autoCreate 的 date_of_auto_send 寫死下月 28 號 | payment terms（出帳日、到期日 offset）設為 lease 層級可配置欄位 |
| 🟡 Medium | `app/NumericOptionService.php:75-96` | ERP 會計科目對照表（account_code 如 7120-01-0000、DR/CR 方向）整份寫死在 PHP | 落 DB 設定表（fee_type ↔ account_code ↔ dr/cr），由財務人員維護 |
| 🟡 Medium | `config/services.php:36-43 + app/Mail/DebitNoteEmail.php:62-63 / ReceiptEmail.php:62-63` | 寄件人 info@wesleymarketplace.com、cc 名單 property@e-inv.link/rental@e-inv.link、admin_user_id=11、log_visible=[1,11] 寫死在 config（非 env） | 寄件人/CC 落 DB 系統設定或 .env；不要以硬編 user id 指定管理員，改用 role/permission 查詢 |
| 🟡 Medium | `DebitNoteController.php:502-504,1168-1170 + resources/views/pdf/debt_note.blade.php:455-472` | 銀行收款資料（bank_name/account_name/account_number）從 lease->company_receipt 快照複製進 DN 欄位；PDF 模板付款指示（crossed cheque 條款、銀行資訊區塊）為寫死英文文案 | 快照設計可保留（歷史正確性）但應結構化為 JSON snapshot + FK；付款指示文案落可編輯模板/設定，支援雙語 |
| 🟡 Medium | `resources/views/pdf/debt_note.blade.php:9 + load_font.php:10 + PdfController.php:314-321` | PDF 中文字型雙軌：blade @import Google Fonts（每次產 PDF 外連下載）+ load_font.php 手動 CLI 預裝 SimHei/Noto Sans TC 到 storage/fonts（相對路徑、無部署文件） | 字型檔納入 repo/部署產物，dompdf font_dir 指向版本控管目錄，安裝步驟做成 artisan command；移除 Google Fonts @import |
| 🟡 Medium | `app/Exports/TenantRentReportExport.php:81-83 + app/Exports/Sheets/TenantRentSheet.php:274,282,290` | 報表 sheet 名寫死客戶人名分類 'JOYCE租予公司'/'JOYCE外面租客'/'公司物業收租'（property_category 0/1/2 對照也隱含寫死）；儲存格底色判斷用中文字面值 "放租中" 比對，與 __('report.For Rent') 翻譯脫鉤，切 en 語系即失效 | property_category 落 DB 字典表（含顯示名稱），報表分組讀 DB；樣式判斷用資料旗標而非顯示字串 |
| 🟡 Medium | `DebitNoteController.php:508,746,757,857 / TransactionController.php:178,215,263,505 / DepositController.php:119,368,376 / BulkTransactionController.php:326` | 單號規則（B-/RE-/DEP-/company_code- + str_pad(id,8,'0')）散落 10+ 處字面拼接，且多處為 create 後再 save 的兩段式寫入 | 集中到 NumberSequence service（可配置前綴/位數/重置規則），與建檔同一 DB transaction 內產號 |
| 🟡 Medium | `TenantReceiptController.php:150 / DepositController.php:113,120 / BulkTransactionController.php:169-178,292,360` | receipt 狀態 'pending/approved/rejected'、deposit 狀態 'draft/active'、allocation 狀態 'draft/confirmed/completed' 皆為字串字面值散落 | backed Enum + DB enum/lookup，狀態轉移集中管理 |
| 🟡 Medium | `DebitNoteController.php:117,813,967` | 員工帳號/人名 wongkwu、CKLONG、Grace 寫死於（註解中的）推播通知程式，通知對象與業務流程耦合特定員工 | revamp 時以 role/permission 或可設定的通知群組取代具名帳號 |
| 🟡 Medium | `DebitNoteController.php:543-546,672-676 / TransactionController.php:459-463 / TenantReceiptController.php:108-115` | 上傳暫存路徑 public_path('tmp/uploads/') 與檔名解析 explode('_',$file,2)[1] 魔法約定重複 10+ 處；暫存檔在 public 目錄可被直接 URL 存取 | 抽成單一 MediaAttachService；暫存改 storage 非公開 disk |
| ⚪ Low | `TenantReceiptController.php:216 + EmailService.php:300` | 香港區碼 '852' 寫死於 SMS 呼叫；SMS 文案內嵌程式（DebitNoteController.php:1263 註解版含完整文案） | 區碼取自 user 資料，SMS 文案移入 lang 檔/通知模板 |
| ⚪ Low | `resources/views/pdf/debt_note.blade.php:175,286 / TransactionsPerMonthSheet.php:113` | 日期格式 d-M-Y、d/m/Y、Y-m-d 及 '年/月' 中文格式散落，無集中 formatter；DebitNoteController.php:183-186 還留有假日期測試碼（Carbon::setTestNow 註解） | 集中日期格式常數/formatter，支援 locale |
| ⚪ Low | `app/Exports/Sheets/TransactionsPerMonthSheet.php:132-134 + TenantRentSheet.php:253-254,276-301` | Excel 樣式/公式硬編：F1=SUM 公式、顏色 FF518dd5/FFFF0000、欄位範圍 A2:J2；TenantRentSheet headings() 23 欄 vs 資料列 21 欄錯位 | revamp 報表時以宣告式欄位定義（heading+getter+format）產生 sheet，欄數由同一定義驅動 |
| ⚪ Low | `DepositController.php:399 + BulkTransactionController.php:339` | deposit fee 的 sort_order 寫死 999『確保排最後』；grouped 列 type fallback 寫死 22 | 排序改由 fee 類型設定決定；fallback type 以常數/Enum 表達 |

## 設計問題（10 項）

| Severity | 範疇 | 問題 | 影響 | 建議 |
|---|---|---|---|---|
| 🔴 High | 金流一致性 / 交易安全 | 除 BulkTransactionController 與 DepositController 外，所有關鍵金流寫入（DebitNoteController store/update/destroy/complete/complete_overdue、TransactionController store/update/destroy、TenantReceiptController store）皆無 DB transaction 包裹；多步驟寫入（建 DN→編號→fees→media→PDF→complete 舊 DN→回沖 balance）任一步失敗即留下半套資料。outstanding_balance 為可變欄位，DepositController 手動 +=/-=（DepositController.php:267,360-361,403）與他處 calculateOutstanding() 重算並存，且全部是無鎖的讀-算-寫。 | 併發或中途失敗會直接產生錯帳（DN 少 fees、憑空餘額、outstanding 與明細不符），且無法事後對帳還原。 | revamp 採 ledger-first 設計：所有金額異動為不可變分錄，outstanding 由分錄推導；寫入集中於 domain service 並以 DB::transaction + 行級鎖包裹；PDF/email 移出交易改用 queued job。 |
| 🔴 High | 邏輯重複（overdue/遲繳利息計算） | 同一套「overdue 金額 + 2% 按日遲繳利息」演算法存在至少 6 份互不一致的複本：DebitNoteController.php:189-377（create）、:1017-1081（autoCreate，公式細節不同如 :1113 少 -1）、PdfController.php:37-96、:149-206、EmailService.php:164-221、debt_note.blade.php:310-327（模板內再算）；『已付金額』另有 3 種判定（TransactionController.php:82-108、BulkTransactionController.php:421-435、DebitNote::calculateRemaining）。 | 畫面、PDF、email、自動開單四個出口對同一張 DN 可能算出不同數字；任何規則修改需同步 6+ 處，遺漏即產生帳務分歧。 | 單一 BillingCalculator service 作為唯一計算來源，所有出口（UI/PDF/email/cron/報表）共用；以測試鎖定計息規則。 |
| 🔴 High | Fat controller / 死程式 | DebitNoteController 1,271 行，create() 單一 method 310 行、autoCreate() 複製 create+store 約 270 行且內含 dd('wait all done')（DebitNoteController.php:992）使 cron 自動開 DN 實際不可用；autoAlert 的 SMS 實際發送被註解（:1262-1263）；complete() 的狀態 guard !(status!=1\|\|status!=2\|\|status!=4) 恆假（:823）；PdfController::previewPdf return 後死碼（PdfController.php:102-104）；TenantReceiptController::sendRejectionSMS 參數不符必然 fatal（TenantReceiptController.php:180 vs :208）。 | 核心自動化（自動開單、到期提醒、收據駁回通知）處於壞死或半殘狀態，維護者無法從程式碼判斷哪些功能真正在運作。 | revamp 時以 use-case service + artisan command 重寫自動化流程，刪除死碼；controller 僅保留 HTTP 編排。 |
| 🔴 High | 資料模型語意重載 | transactions 資料表同時承載三種語意：DN 收據（debit_note_id + RE-）、lease 餘額錢包（lease_id + B-，正負數互抵，TransactionController.php:175-184,261-269）、deposit 分配產物（deposit_allocation_id，DepositController.php:366-378）；DebitNoteFee 亦被塞入負數 type 23 列代表押金抵扣（DepositController.php:391-400）。三套收款流程（TransactionController 舊流程、TenantReceipt→ReceiptAllocation→BulkTransaction 新流程、Deposit→DepositAllocation）並存且互相不知情。 | 同一筆錢可能同時被舊流程 balance 抵扣與新流程 allocation 分配；報表與 outstanding 計算必須用 type/ref_id 魔法過濾來區分語意，極易錯帳。 | 新 schema 明確分離：receipts（收款）、allocations（分配）、ledger_entries（分錄）、credit balance 獨立實體；一次 revamp 收斂為單一收款-分配流程。 |
| 🔴 High | PDF 產生安全與可靠性 | dompdf 開啟 isPhpEnabled（PdfController.php:119,121,314,370，dompdf 已知 RCE 面向）與 isRemoteEnabled + verify_peer=false（:315-321,371-377）；產 PDF 依賴外連 Google Fonts 與 property.e-inv.link 簽名圖；View::share 全域傳資料（:232,309,365）並直接改寫模型屬性（:226,229,293,304）；錯誤處理 catch ValidationException 型別根本不會發生（:262,330,384）；generateDebitNote 失敗 retry 一次後 return redirect（:245-259）但呼叫端是 service 流程，redirect 無意義。 | 安全面（isPhpEnabled + 可控 remark 進模板）、可靠性面（離線/外站失效即壞 PDF）、正確性面（PDF 版本 -R 規則多處複本不一致）皆有風險。 | revamp 改用受控的 PDF 服務（本地資產、關閉 php/remote）、以明確 DTO 傳入模板、產出走 queued job 並記錄失敗。 |
| 🟡 Medium | 驗證與 mass assignment | app/Http/Requests 僅有 ProfileUpdateRequest 與 LoginRequest，所有財務端點驗證內嵌 controller 且大量 Model::create($request->all())（DebitNoteController.php:507,662、TransactionController.php:177,214,426）；DebitNote status/amount 等欄位可否被表單覆寫完全取決於 $fillable。 | 驗證規則不可重用、無授權層；mass assignment 面向使金額/狀態欄位有被竄改風險。 | 每個寫入端點配 FormRequest（rules+authorize），改用 DTO/明確欄位白名單建模。 |
| 🟡 Medium | 報表架構 | ReportController 僅過濾後全撈（ReportController.php:79-116），計算全在 Export classes：TransactionsPerMonthSheet 對同一集合做 12 次 PHP 端月份 filter、迴圈內 ->transactions()->latest()->get() 造成嚴重 N+1（TransactionsPerMonthSheet.php:54-60）；TenantRentSheet 每 unit 迴圈內多次查 lease/master fee（TenantRentSheet.php:72-104）且 headings 與資料欄數錯位（:210-238 vs :116-141）；計算與 PhpSpreadsheet 樣式耦合，UI 頁與匯出各自組數。 | 資料量成長後匯出逾時；報表數字與畫面/DN 可能不一致；欄位錯位輸出錯誤報表。 | 建立獨立報表查詢層（SQL 聚合/read model），Excel 僅負責呈現；欄位以單一宣告式定義驅動 heading 與資料。 |
| 🟡 Medium | 通知/整合服務 | EmailService 混雜 email、SMS（明文 HTTP GET file_get_contents，EmailService.php:296-309）、自建推播（硬編 IP+API key，:27,91）、以及 DN 計算複本；Mail classes 同時實作 Laravel 9+ envelope/content 與舊式 build()（DebitNoteEmail.php:28-58 vs :60-86），attachments() 回空陣列、實際附件在 build() 內，雙軌並存。 | 通知管道無抽象、不可測試、密鑰外洩；Mailable 雙軌寫法使行為取決於框架版本細節。 | 拆分 NotificationService（channel 介面：mail/sms/push），統一用 Laravel notification 系統與現代 Mailable 寫法。 |
| 🟡 Medium | 權限與路由 | cron endpoints /auto-create-debit-note、/auto-alert-debit-note 註冊在 web routes 且無 auth（routes/web.php:58-60）；TransactionController 沿用 debit-note-* 權限（TransactionController.php:33-36）無自身權限粒度；DepositController 以 hasRole('Admin') 字串判斷（DepositController.php:36,297）與 spatie permission 檢查混用；TenantReceiptController index 以 hasRole('Admin') 決定可見範圍（TenantReceiptController.php:23）但 Super Admin 等其他角色行為未定義。 | 權限模型不一致，新角色加入時各金流頁面行為不可預期；公開 cron endpoint 可被掃描觸發。 | 統一以 permission（非 role 字串）+ policy 授權；排程改 artisan scheduler。 |
| ⚪ Low | 雙語/在地化 | 訊息以 __() 拼接組句（如 __('global.Debit Note') . __('global.created successfully')，DebitNoteController.php:574）在中英文語序下都不自然；報表以顯示字串（"放租中"）做邏輯判斷；SMS/通知文案硬編中文或英文（DebitNoteController.php:813,967）。 | 翻譯品質差且脆弱，新增語言需改程式。 | 使用帶佔位符的完整句 translation key；邏輯判斷一律用資料值不用顯示字串。 |

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

- ✅ 屬實 — **全部 fee/transaction type codes（0=Rental…5=Late Interest Charges…19=Overdue, 20=CHQ DEP, 21=Balance, 22=Paid, 23=Deposit）以 PHP 陣列寫死，DB 無對應表；所有金流計算以整數字面值散落引用（type 19: DebitNoteController.php:178,204; type 5: :191,263; type 22: TransactionController.php:87,118, BulkTransactionController.php:339,429; type 23: DepositController.php:257,383,393）**（app/NumericOptionService.php:23-48）
  - 查證註記：Claim 屬實，無法推翻。(1) E:/rms-old/rms/app/NumericOptionService.php 第 23-48 行的 $debitNoteMasterFeeOptions 確實以 PHP 陣列寫死全部 fee/transaction type codes，內容與 claim 完全一致（0=Rental、5=Late Interest Charges、19=Overdue、20=CHQ DEP、21=Balance、22=Paid、23=Deposit），同檔另有 $debitNoteFeeOptions（50-73 行）與 $debitNoteFeeOptionsERPCode（75-96 行）等重複寫死的變體。(2) DB 無對應表：檢查 database/migrations 全部 62 個 migration，不存在 fee_types / transaction_types 之類的 lookup table；debit_note_fees 與 transaction_items 兩張表的 type 欄位皆僅為 $table->string('type')（各自 migration 第 17 行），無外鍵約束。(3) 所有引用行號逐一開檔核實均正確：DebitNoteController.php:178 與 204 用整數 19、:191 與 263 用整數 5；TransactionController.php:87 與 118 用整數 22；BulkTransactionController.php:339 與 429 用整數 22；DepositController.php:257、383、393 用整數 23。實際上 claim 還低估了散落程度——DebitNoteController.php 另有 :196、:199、:200、:221、:231、:243、:251 等多處以字面值 5/19 直接比對或寫入。
  - 證據：NumericOptionService.php:23-48 `protected $debitNoteMasterFeeOptions = [0 => 'Rental', ... 5 => 'Late Interest Charges', ... 19 => 'Overdue', 20 => 'CHQ DEP', 21 => 'Balance', 22 => 'Paid', 23 => 'Deposit'];`；DebitNoteController.php:178 `->debit_note_fees->where('type', '=', 19)->pluck('ref_id')`、:191 `DebitNoteFee::where('type', '=', 5)`、:204 `$q->where('ref_id', '=', $overdue->id)->where('type', '=', 19)`、:263 `$type = 5;`；TransactionController.php:87 `if ($transactionItem->ref_id == $ref_id && $transactionItem->type != 22)`、:118 `$type = 22;`；BulkTransactionController.php:339 `'type' => $it
- ✅ 屬實 — **DN 狀態機 0=Pending,1=Approved,2=Under Review,3=Complete,4=Rejected,5=Overdue,6=Overpaid 寫死；7=Cleared 被註解但程式仍殘留引用（DebitNoteController.php:176,734 註解）；狀態判斷散落各 controller（DebitNoteController.php:786,804,823,829-841,869,883）**（app/NumericOptionService.php:12-21）
  - 查證註記：Claim 全部屬實。(1) NumericOptionService.php:12-21 的 $debitNoteApprovalOptions 硬編碼 0=Pending/1=Approved/2=Under Review/3=Complete/4=Rejected/5=Overdue/6=Overpaid，第 20 行 7=Cleared 被註解。(2) DebitNoteController.php:176（whereNotIn('status',[3,7]) 註解）與 734（status != 7 條件註解）確有殘留引用；另發現 claim 未列的第 771 行也有 `// $dn->status = 7;` 註解殘留。Grep 確認 "Cleared" 全 app 目錄僅存在於註解中，無活代碼引用。(3) 狀態判斷確實以硬編碼數字散落於 786/804/823/829-841/869/883 各處。附帶觀察（不影響 claim 成立）：823 行條件 !(status!=1 \|\| status!=2 \|\| status!=4) 恆為 false，是邏輯 bug。
  - 證據：E:\rms-old\rms\app\NumericOptionService.php:12-21（0-6 硬編碼，20 行 `// 7 => ['class' => 'status-success', 'text' => 'Cleared'],`）；E:\rms-old\rms\app\Http\Controllers\DebitNoteController.php:176 `// $overdues = DebitNote::...->whereNotIn('status', [3, 7])->get();`、734 `// if ($debit_note->status != 3 && ... && $debit_note->status != 7) {`、771 `// $dn->status = 7;`、786 `if ($debitNote->status != 2)`、804 `if ($debitNote->status != 0)`、823 `if (!($debitNote->status != 1 \|\| $debitNote->status != 2 \|\| $debitNote->status != 4))`、829-841 status=5/6/3 分支、869 與 883 `status == 1 \|\| == 2 \|\| == 4`
- ✅ 屬實 — **遲繳利息月利率 0.02（2%）寫死於 6+ 處，且以字串 '*2%*' 拼入 remark（DebitNoteController.php:266,299,347,1053）；改費率需同步改動計算與顯示字串多處**（DebitNoteController.php:261,294,345,1051 / PdfController.php:183 / EmailService.php:198）
  - 查證註記：已親自開檔查證，claim 屬實且略為保守。月利率 0.02 的有效計算點共 6 處：DebitNoteController.php:261、294、345、1051（另有 260、293 兩行為註解掉的重複程式碼）、PdfController.php:183、EmailService.php:198，全部與遲繳費（late charge，type=5）計算相關，公式皆為 round(金額 * 0.02 * 天數 / daysInMonth, 2)。顯示字串 '*2%*' 拼入 remark 的位置：DebitNoteController.php:266、299、347、1053 與 claim 完全一致，另外 PdfController.php:79、189 及 EmailService.php:204 也各有一處（合計 7 處 remark 字串）。嘗試推翻「改費率需改多處」：搜尋 config 目錄找不到任何 late rate/interest 集中設定，計算與 remark 皆為字面常數，無單一來源可改。因此若要調整費率，確需同步修改至少 6 處計算式與 7 處顯示字串（共 13 處，含 2 處註解），claim 中「6+ 處」成立。唯一小出入：claim 未提及 PdfController.php:79 與 EmailService.php:204 也有 '*2%*' 字串，實際散佈範圍比 claim 描述更廣。
  - 證據：DebitNoteController.php:261 `$amount = round($total * 0.02 * $days / Carbon::parse($transaction_due->transaction_date)->daysInMonth, 2);`；266 `$' . round($total, 2) . '*2%*' . $days . '/'...`；294 `$amount_2 = round($total * 0.02 * $days_2 / ...)`；299 `'*2%*' . $days_2`；345 `$amount = round($total * 0.02 * $days / Carbon::parse($latest_debit_note->due_date)->daysInMonth, 2);`；347 `'*2%*' . $days`；1051 同 345 式；1053 `'*2%*' . $days`。PdfController.php:183 `$amount = round($overdue_amount * 0.02 * \Carbon\Carbon::now()->daysInMonth / ...)`；189 `'*2%*'`；79 `'*2%*'`。EmailService.php:198 `$amount = ro
