# 會計模組設計（Accounting）

> 狀態：已與使用者確認（2026-08-26）

## 目標

新增會計頁，按月份管理以**宿舍**為中心的租金支出、工人租金收入、其他開支／收入，並可產生宿舍報告、月結報告、年報（網頁預覽＋Excel）。

## 業務規則（已確認）

1. **已定居工人**＝有分配宿舍（`workers.dormitory_id` 不為空）。
2. **宿舍租金**＝公司支出；宿舍可設預設 `monthly_rent`，每月帳目可改。
3. **工人租金**＝收入；工人可設預設 `monthly_rent`，每月帳目可改。
4. **其他開支／收入**：自由項目 ＋ 預設類別（`accounting_categories`）。
5. **歸屬**：所有支出／收入跟**宿舍**，不按店鋪（Branch）。
6. **產生帳目**：進入月份可自動帶出 ＋「產生本月帳目」按鈕；已存在列不覆蓋已改金額。
7. **權限**：登入可新增／編輯；僅 admin 可刪（與現有模組一致）。
8. **報告**：宿舍報告、月結、年報；網頁預覽／列印 ＋ Excel。

## 架構（方案 B）

分表存放，報表再彙總。

### Schema 變更

**擴充既有表**

- `dormitories.monthly_rent` — decimal, nullable（預設宿舍月租支出）
- `workers.monthly_rent` — decimal, nullable（預設工人月租收入）

**新表**

- `accounting_categories`
  - `id`, `name`, `type` (`income`|`expense`), `is_active` (bool, default true), timestamps

- `dorm_rent_expenses`
  - `id`, `dormitory_id`, `year`, `month`, `amount`, `note` (nullable)
  - unique(`dormitory_id`, `year`, `month`)

- `worker_rent_incomes`
  - `id`, `worker_id`, `dormitory_id`（快照）, `year`, `month`, `amount`, `note` (nullable)
  - unique(`worker_id`, `year`, `month`)

- `other_entries`
  - `id`, `dormitory_id`, `category_id` (nullable), `year`, `month`
  - `type` (`income`|`expense`), `title`, `amount`, `note` (nullable)
  - timestamps

### Models

- `AccountingCategory`, `DormRentExpense`, `WorkerRentIncome`, `OtherEntry`
- `Dormitory` / `Worker` 增加 `monthly_rent` 與相關 hasMany

### Controllers（建議）

- `AccountingController` — 月度主頁、產生帳目、明細 CRUD
- `AccountingCategoryController` — 類別 CRUD
- `AccountingReportController` — 宿舍／月結／年報預覽與 Excel

宿舍／工人表單補上 `monthly_rent` 欄位（`DormitoryController`、`WorkerController` 與對應 Blade）。

## UI

- 側邊欄新增「會計」
- 主頁：年月切換、宿舍篩選、合計摘要、產生本月帳目、三區塊表格（宿舍支出／工人收入／其他）
- 行內或小表單編輯金額／備註；其他項目可新增
- 類別管理簡易 CRUD 頁
- 報告入口：宿舍報告／月結／年報 → 預覽頁 → 列印／Excel

## 產生本月帳目邏輯

1. 所有設有 `monthly_rent` 的宿舍 → 若該月尚無 `dorm_rent_expenses` 則建立。
2. 所有 `dormitory_id` 不空且設有 `monthly_rent` 的工人 → 若該月尚無 `worker_rent_incomes` 則建立（寫入當下 `dormitory_id` 快照）。
3. 已存在列跳過（不覆蓋金額）。

## 報告內容

| 報告 | 參數 | 內容 |
|------|------|------|
| 宿舍報告 | 宿舍 + 年月 | 該宿舍三類明細 + 小計 |
| 月結報告 | 年月 | 全部宿舍明細 + 總計 |
| 年報 | 年份 | 12 月彙總（收入／支出／結餘）+ 可選宿舍明細 |

輸出：Blade 預覽（列印友善）＋ Maatwebsite Excel export。

## 路由（草圖）

```
GET    /accounting?year=&month=&dormitory_id=
POST   /accounting/generate
PUT    /accounting/dorm-rent/{id}
DELETE /accounting/dorm-rent/{id}
PUT    /accounting/worker-rent/{id}
DELETE /accounting/worker-rent/{id}
POST   /accounting/other
PUT    /accounting/other/{id}
DELETE /accounting/other/{id}

Resource accounting-categories

GET /accounting/reports/dormitory
GET /accounting/reports/monthly
GET /accounting/reports/yearly
GET /accounting/reports/.../excel
```

## 非目標（YAGNI）

- 不按店鋪（Branch）歸帳或出報告
- 不做多幣別、審批流、會計期間鎖定
- 不引入 Vue/React；維持 Blade + Bootstrap
