unify-settlement-sheet: HR's approved list and the department CSV preview share one settlement sheet (user decision 2026-10-29). Columns: 刷卡月份, 發放月份 (card month + 2), then the department preview format (部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例, 最終補助, 尾差調整) with a 部門合計 row per department. The approved list is one file with every finalized department plus a 全公司合計 row; Excel uses number cells with NT$ / % formats, CSV plain integers. The 薪資名目 column is dropped (always 其他獎金)
CI / build (push) Successful in 5m16s

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
pkgsp50777_楊舒諠
2026-10-29 17:37:23 +08:00
co-authored by Claude Opus 5.5
parent 48935fd91e
commit 2e6e8f9dce
20 changed files with 699 additions and 214 deletions
+2 -2
View File
@@ -199,7 +199,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- The audit action is `settlement.eligible_adjusted`.
- The quota block shows four stats: 計算人數|月上限|補助合計|超額 (no 「每人額度」, no 「可補助總額」; the admin detail keeps 每人額度 in its parameter snapshot). 補助合計 is the personal-cap total (`totalEligible`, live for an open trial; user decision 2026-10-20); 超額 = 補助合計 − cap and turns `text-danger` when it is > 0. The paid total appears only in the allocation table's total row. 「支付金額(當月合計)」 is the person's sum of approved cases.
- `AllocationTable` and the department CSV preview have a 「個人上限(50%)」 column (`settlement_allocations.personal_cap`; rows from before it are null and show 「—」).
- The department CSV preview (`department/settlement/export/route.ts`) follows the user's format (2026-10-22): 部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例 (final ÷ cap), 最終補助, 尾差調整, then a 「部門合計」 row. No 個人可補助 or 狀態 column; new applicants leave the calculated columns blank.
- The department CSV preview (`department/settlement/export/route.ts`) and the admin approved list share one settlement sheet (`unify-settlement-sheet`, user decision 2026-10-29): `SETTLEMENT_SHEET_COLUMNS` / `departmentSheetRows` / `sheetCells` in `src/lib/settlement-sheet.ts` — 刷卡月份, 發放月份 (card month + 2), 部門, 員工編號, 姓名, 平台, 實際支付金額, 個人可補助上限, 系統計算可補助/部門分配上限, 佔月上限/部門成員補助比例 (final ÷ cap), 最終補助, 尾差調整, then a 「部門合計」 row (format from the user, 2026-10-22). The preview uses `display` cells (NT$ text, same as the page); new applicants leave the calculated columns blank.
- The allocation table's 「占月上限」 column (page, admin detail, CSV) is final ÷ cap (`capShareBp`, computed at display time; 「—」 when the cap is 0). The stored `share_bp` is final ÷ cap too (not shown).
- Approved → pending settlement is time-based:
- `promoteApprovedToPendingSettlement` is idempotent. The `SYSTEM_ACTOR` transition `promote` runs it.
@@ -214,7 +214,7 @@ If Playwright's browser download fails (CDN returns 403 on this machine), set `P
- Every submit appends a `settlement_submissions` version. Versions are append-only; return info is written once.
- `finalizeSettlement` moves cases to `finalized` and notifies applicants (final amount, expected payout month = card month + 2, pay item 「其他獎金」). It creates no payout records.
- Multi-step settlement writes use `abortableTransaction` + `SettlementAbort` (`src/server/settlement/transaction.ts`), so a mid-way failure rolls everything back.
- 「匯出核定名單」 on `/admin/settlements` (`approvedPayoutRows`): for the selected card month, every finalized (or legacy `paid`) settlement's allocations with final > 0. Columns live in `PAYOUT_EXPORT_COLUMNS` (`src/lib/payouts.ts`, 7 columns, shared by Excel (exceljs) and CSV) and are documented in `docs/operations/payout-export.md` (a test keeps them in sync). Audit `payout.exported` (「匯出核定名單」).
- 「匯出核定名單」 on `/admin/settlements` (`approvedSheetRows` in `payouts.ts`): the same settlement sheet for every finalized (or legacy `paid`) department of the selected card month, sorted by name, each with all its members (including 0) and its 「部門合計」 row (from the stored `getSettlementView`), then one 「全公司合計」 row (share blank). `numeric` cells: Excel (exceljs) number cells formatted `"NT$"#,##0` / `0.00%`, totals bold; CSV plain integers. No 薪資名目 column (always 其他獎金). Columns are documented in `docs/operations/payout-export.md` (a test keeps them in sync). Audit `payout.exported` (「匯出核定名單」, `rows` = member rows).
- Legacy data from the removed payout management and settlement corrections: `paid` cases/settlements still show 「已發放」 and stay read-only; `payout_records` and `settlement_corrections` keep their rows and triggers (still in `BUSINESS_TABLES`) but nothing reads or writes them; their status/type enums, the `pay` transition action (timeline label only), the `payout.paid` notification type and the old audit actions stay only so old rows still display.
- Dialogs that need a reason use `ReasonDialog` (`src/components/ui/reason-dialog.tsx`).
+35 -12
View File
@@ -1,20 +1,43 @@
# 核定名單匯出欄位
# 月結明細表與核定名單匯出欄位
`/admin/settlements`(全公司月結)的「匯出 Excel」與「匯出 CSV」輸出相同欄位與順序(定義在 `src/lib/payouts.ts` 的 `PAYOUT_EXPORT_COLUMNS`,測試會比對本文件的表格與程式一致)。CSV 為 UTF-8(含 BOM),以 Excel 開啟中文不亂碼。
部門主管的「匯出預覽」(`/department/settlement`,CSV)與管理端的「匯出核定名單」(`/admin/settlements`,Excel 與 CSV)使用同一份月結明細表,欄位與順序相同(定義在 `src/lib/settlement-sheet.ts` 的 `SETTLEMENT_SHEET_COLUMNS`,測試會比對本文件的表格與程式一致)。CSV 為 UTF-8(含 BOM),以 Excel 開啟中文不亂碼。
名單是所選**刷卡月份**中,已最終核定(含移除發放管理前已標記發放)的部門月結裡,最終補助大於 0 的每位申請人。尚未最終核定的部門不會列入。系統不追蹤實際是否已發放,發放由薪資作業處理。
## 內容
- **部門主管匯出預覽**:自己部門所選刷卡月份的分配明細(提交前為試算),最後一列「部門合計」。
- **管理端核定名單**:所選**刷卡月份**中所有已最終核定(含移除發放管理前已標記發放)的部門,依部門名稱排列;每個部門列出月結裡的所有申請人(依員工編號,含最終補助為 0 的人),接著一列該部門的「部門合計」;最後一列「全公司合計」。尚未最終核定的部門不會列入。系統不追蹤實際是否已發放,發放由薪資作業處理。
- 合計列的「員工編號」留白,「姓名」為「部門合計」或「全公司合計」,篩選時可用這兩欄排除;Excel 的合計列為粗體。
- 補助一律以薪資名目「其他獎金」發放(表上不另列欄位)。
## 欄位
| 順序 | 欄位 | 內容 |
| ---- | ---- | ---- |
| 1 | 發放月份 | `YYYY/MM`,刷卡月份後第 2 個月,隨該月薪資發放 |
| 2 | 員工編號 | |
| 3 | 姓名 | |
| 4 | 部門 | 申請當時所屬部門(月結的部門) |
| 5 | 刷卡月份 | `YYYY/MM`,補助所屬的月結月份 |
| 6 | 補助金額 | 整數元數值(不含 NT$ 與千分位),一律為正數 |
| 7 | 薪資名目 | 固定「其他獎金」 |
| 1 | 刷卡月份 | `YYYY/MM`,補助所屬的月結月份 |
| 2 | 發放月份 | `YYYY/MM`,刷卡月份後第 2 個月,隨該月薪資發放(預覽為預計發放月份) |
| 3 | 部門 | 申請當時所屬部門(月結的部門);全公司合計留白 |
| 4 | 員工編號 | 合計列留白 |
| 5 | 姓名 | 合計列為「部門合計」/「全公司合計」 |
| 6 | 平台 | 該月核准案件的平台,以「、」分隔 |
| 7 | 實際支付金額 | 該月核准案件的台幣金額合計 |
| 8 | 個人可補助上限 | 支付金額 × 50%,逐筆無條件捨去後加總;舊月結沒有此值時為「—」(核定名單留白) |
| 9 | 系統計算可補助/部門分配上限 | 系統依規則計算的個人可補助(超額時為平分後的分配上限) |
| 10 | 佔月上限/部門成員補助比例 | 最終補助 ÷ 部門月上限;全公司合計留白(各部門月上限不同) |
| 11 | 最終補助 | 實際發放的補助金額 |
| 12 | 尾差調整 | 平分時分到的尾差元數(`+1`),沒有時留白 |
## 格式差異
| 匯出 | 金額 | 比例 |
| ---- | ---- | ---- |
| 部門主管匯出預覽(CSV) | `NT$1,276`(與頁面一致) | `4.73%` |
| 核定名單 CSV | 整數元 `1276`(不含 NT$ 與千分位) | `4.73%` |
| 核定名單 Excel | 數值儲存格,顯示為 `NT$1,276`,可直接加總 | 數值儲存格,顯示為 `4.73%` |
部門主管的預覽中,試算後才出現的申請人只填到個人可補助上限,其餘留白(等主管重新計算)。
## 欄位變更紀錄
- 2026/10(`add-settlement-corrections`):新增第 9–11 欄(項目類型、更正編號、原發放月份)。
- 2026/10/28(`remove-payout-management`):移除發放管理與月結更正。匯出改在全公司月結頁、依刷卡月份匯出,只保留第 1–7 欄;第 8–11 欄(發放狀態、項目類型、更正編號、原發放月份)移除。第 1–7 欄位置不變。
- 2026/10(`add-settlement-corrections`):發放名單新增第 9–11 欄(項目類型、更正編號、原發放月份)。
- 2026/10/28(`remove-payout-management`):移除發放管理與月結更正,核定名單改在全公司月結頁依刷卡月份匯出,只保留 7 欄(發放月份、員工編號、姓名、部門、刷卡月份、補助金額、薪資名目)。
- 2026/10/29(`unify-settlement-sheet`):核定名單改用與部門主管匯出預覽相同的 12 欄月結明細表(上表),加上部門合計與全公司合計列;「補助金額」改名為「最終補助」,「薪資名目」欄移除(固定其他獎金)。部門主管的預覽在最前面加上刷卡月份與發放月份。
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-29
@@ -0,0 +1,47 @@
## Context
- 部門主管「匯出預覽」:`department/settlement/export/route.ts` 直接組 10 欄 CSV,資料來自 `getSettlementView`(open 時為試算或即時預覽,提交後為存檔結果),金額為 `NT$1,276` 文字。
- HR「匯出核定名單」:`/admin/settlements/export` → `approvedPayoutRows`(只取最終補助 > 0 的分配)→ `PAYOUT_EXPORT_COLUMNS`(7 欄,`src/lib/payouts.ts`)→ CSV 或 exceljs Excel。
- 使用者決定(2026-10-29):兩邊用同一份表;HR 一份含全部已核定部門;Excel 數字+格式、CSV 純數字;只含已最終核定;刷卡月份、發放月份放最前面。
## Goals / Non-Goals
**Goals:**
- 欄位只定義一次,兩個匯出共用;部門主管與 HR 看到的欄位、順序、合計一致。
- HR 的表可直接用於薪資作業(數值可加總)。
**Non-Goals:**
- 不改月結計算或頁面上的分配表。
- 部門主管的匯出仍只有 CSV 預覽,不加 Excel。
- 不加「全公司」以外的跨月彙總。
## Decisions
### D1. 共用定義 `src/lib/settlement-sheet.ts`
- `SheetRow`:`{ kind: "member" | "department_total" | "company_total", chargeMonth, payoutMonth, departmentName, employeeNo, name, platforms, paidTotal, personalCap: number | null, systemEligible: number | null, shareBp: number | null, finalAmount: number | null, remainderAdjustment: number | null }`(null = 留白)。
- `SETTLEMENT_SHEET_COLUMNS`:12 欄的標題與取值,每欄標示類型 `text | money | share | adjustment`。
- 兩種輸出:
- `display`(部門預覽):money → `formatMoney`(`NT$1,276`),share → `formatShare`,adjustment → `+1`。
- `numeric`(HR):money → 整數;share → CSV 為 `formatShare` 文字(`77.39%`)、Excel 為小數(0.7739)配百分比格式;adjustment → 整數。
- `departmentSheetRows(view, month)`:由 `getSettlementView` 的結果組成員列+部門合計列(沿用目前預覽的規則:新申請人留白、合計列的個人上限用 `personalCapTotal`、比例 = 最終合計 ÷ 月上限)。部門預覽與 HR 都用它,確保合計一致。
- 合計列:員工編號留白、姓名欄放「部門合計」/「全公司合計」,刷卡與發放月份照填,部門欄:部門合計放部門名稱以便篩選,全公司合計留白。
### D2. 發放月份
用現有的發放月份規則(刷卡月份 + 2,`company-settlement`「發放月份規則」)。部門預覽也填,代表預計發放月份。
### D3. HR 資料來源
`approvedSheetRows(db, month)`:查該月 `finalized`/`paid` 的部門月結,依部門名稱(zh-Hant)排序,逐一呼叫 `getSettlementView` 取存檔結果(非 open 時不重算),用 `departmentSheetRows` 組列,最後加「全公司合計」(各金額欄加總,比例留白)。
- 列出月結中所有人(含 0 元),部門合計才和部門月結一致;薪資作業以「最終補助」為準。
- 原本 `approvedPayoutRows`/`PAYOUT_EXPORT_COLUMNS` 移除;操作紀錄沿用 `payout.exported`(`rows` 改記成員列數)。
### D4. Excel
沿用 exceljs,工作表名稱「核定名單 YYYY-MM」。金額欄 `numFmt = '"NT$"#,##0'`、比例欄 `0.00%`;合計列粗體。凍結標題列。
### D5. 「薪資名目」欄拿掉
使用者提供的格式沒有這欄;名目固定為「其他獎金」,寫在 `docs/operations/payout-export.md`。
## Risks / Trade-offs
- [薪資作業若已依舊 7 欄做匯入會壞] → 文件說明新欄位;正式站目前剛移除發放管理,影響有限。上線時提醒使用者。
- [合計列混在資料列中,篩選或樞紐分析要先排除] → 合計列的「姓名」欄固定為「部門合計」/「全公司合計」、員工編號留白,容易排除;Excel 合計列粗體。
- [每個部門呼叫一次 `getSettlementView`] → 部門數有限(數十個),可接受。
@@ -0,0 +1,34 @@
## Why
部門主管的「匯出預覽」已依使用者格式改好(2026-10-22),但 HR(管理端)匯出的核定名單仍是另一份 7 欄的表,兩邊對不起來。使用者決定(2026-10-29):HR 與部門主管都看同一種表,以部門預覽表為準,前面再加上「刷卡月份」「發放月份」。
## What Changes
- 共用一份「月結明細表」欄位定義,依序:刷卡月份、發放月份、部門、員工編號、姓名、平台、實際支付金額、個人可補助上限、系統計算可補助/部門分配上限、佔月上限/部門成員補助比例、最終補助、尾差調整。
- **部門主管「匯出預覽」**(CSV):改用這份欄位(多了最前面兩欄,其餘不變;發放月份為預計發放月份,刷卡月份 + 2)。金額維持 `NT$1,276` 格式,最後一列「部門合計」。
- **HR「匯出核定名單」**(全公司月結頁,Excel/CSV):**BREAKING** 欄位由原本 7 欄改為上面 12 欄。
- 同一份檔案含所選刷卡月份**所有已最終核定**(含舊資料已發放)的部門,依部門排列;每個部門的成員後面接該部門的「部門合計」列,檔案最後一列為「全公司合計」。
- 每個部門列出月結裡的所有人(含最終補助 0 元的人),部門合計才會和部門月結一致。
- 金額:Excel 儲存格是數字、顯示為 `NT$1,276`(比例顯示為百分比),可直接加總;CSV 為純數字(不含 NT$ 與千分位)。
- 拿掉「薪資名目」欄(固定為「其他獎金」,改寫在欄位說明文件)。
- 欄位說明文件 `docs/operations/payout-export.md` 改寫。
## Capabilities
### New Capabilities
(無)
### Modified Capabilities
- `department-settlement`:「重新計算與匯出預覽」的匯出欄位加上刷卡月份、發放月份。
- `company-settlement`:「匯出核定名單」改為與部門預覽相同的明細表,所有已核定部門整合在同一份,含部門合計與全公司合計。
## Impact
- 新增 `src/lib/settlement-sheet.ts`(欄位定義與列的組成,前後端共用)。
- `src/app/(app)/department/settlement/export/route.ts` 改用共用定義。
- `src/server/settlement/payouts.ts`:`approvedPayoutRows` 改為逐一取已核定部門的月結明細(沿用 `getSettlementView` 的存檔結果),`payoutCsv`/`payoutWorkbook` 改輸出新欄位與合計列。`src/lib/payouts.ts` 的舊 7 欄定義移除。
- `docs/operations/payout-export.md`、CLAUDE.md。
- 測試:`payouts` 相關單元測試、`company.test.ts`、e2e `company-settlement.spec.ts`、部門月結匯出的 e2e。
- 沒有資料庫 migration。薪資作業若有依舊 7 欄做的匯入,需要跟著調整。
@@ -0,0 +1,24 @@
## MODIFIED Requirements
### Requirement: 匯出核定名單
管理者 SHALL 能在全公司月結頁匯出所選刷卡月份的核定名單(Excel 與 CSV 兩種格式),格式為與部門主管匯出預覽相同的月結明細表。同一份檔案 SHALL 含該月所有已最終核定(含舊資料中已發放)的部門,依部門名稱排列;每個部門列出月結中的所有申請人(依員工編號,含最終補助為 0 的人),接著一列該部門的「部門合計」;檔案最後一列為「全公司合計」。欄位固定依序為:刷卡月份、發放月份、部門、員工編號、姓名、平台、實際支付金額、個人可補助上限、系統計算可補助/部門分配上限、佔月上限/部門成員補助比例(最終補助 ÷ 該部門月上限)、最終補助、尾差調整。Excel 的金額與比例 SHALL 為數值儲存格(金額顯示為 NT$ 與千分位、比例顯示為百分比);CSV 的金額 SHALL 為整數元(不含 NT$ 與千分位)。「全公司合計」的佔月上限比例留白。尚未最終核定的部門 MUST NOT 列入。只有管理者能匯出;每次匯出 SHALL 寫入操作紀錄。
#### Scenario: 匯出 2026/10 核定名單
- **WHEN** 2026/10 有 3 個部門已最終核定、2 個仍為已提交,管理者在全公司月結頁選 2026/10 並匯出 Excel
- **THEN** 檔案只含 3 個已核定部門,每個部門的成員後面接該部門的「部門合計」列,最後一列為「全公司合計」;每列刷卡月份為 2026/10、發放月份為 2026/12
#### Scenario: 合計與部門月結一致
- **WHEN** 研發部 2026/10 已核定,最終補助合計 NT$20,896、月上限 NT$27,000
- **THEN** 檔案中研發部的「部門合計」最終補助為 20896、佔月上限比例為 77.39%,與該部門月結的合計相同
#### Scenario: CSV 金額為純數字
- **WHEN** 管理者匯出 CSV,甲的實際支付金額為 NT$2,553
- **THEN** 甲那一列的實際支付金額為 2553
#### Scenario: 沒有已核定部門
- **WHEN** 所選月份沒有任何已最終核定的部門
- **THEN** 匯出按鈕停用並說明尚無已核定的部門
#### Scenario: 非管理者被拒
- **WHEN** 部門主管直接開啟匯出網址
- **THEN** 系統回應無權限,不回傳任何名單
@@ -0,0 +1,24 @@
## MODIFIED Requirements
### Requirement: 重新計算與匯出預覽
在月結提交前,主管 SHALL 能按「重新計算」以目前的審核通過案件與後台參數更新試算結果,並能匯出目前分配明細為 CSV 預覽檔。重新計算與匯出 MUST 記錄於操作紀錄。已有存下的試算時,頁面的支付金額(當月合計)SHALL 以目前審核通過的案件即時加總;目前資料與試算不一致(支付金額改變、申請人增減或月上限改變)時,頁面 SHALL 提示「審核結果已變動,支付金額已更新;請按「重新計算」更新個人可補助與最終補助」,並在變動的列標示「待重新計算」;新出現的申請人 SHALL 列出,其個人可補助與最終補助顯示「待重新計算」。預覽檔的欄位 SHALL 與管理端核定名單共用同一份月結明細表定義。
#### Scenario: 審核結果變動後重算
- **WHEN** 主管於提交前又核准一筆該月案件,接著按「重新計算」
- **THEN** 分配明細納入新案件並更新合計與超額判斷
#### Scenario: 匯出預覽
- **WHEN** 主管在 2026/10 的部門月結按「匯出預覽」
- **THEN** 下載 CSV,欄位依序為刷卡月份、發放月份、部門、員工編號、姓名、平台、實際支付金額、個人可補助上限、系統計算可補助/部門分配上限、佔月上限/部門成員補助比例(最終補助 ÷ 月上限)、最終補助、尾差調整;每列刷卡月份為 2026/10、發放月份為 2026/12;最後一列為「部門合計」,金額格式與頁面一致;試算後才出現的申請人只填到個人可補助上限,其餘留白
#### Scenario: 核准後支付金額自動更新並提示重新計算
- **WHEN** 已有試算,甲的支付金額為 NT$450,之後主管在部門審核又核准甲一筆 NT$150 的案件,再開啟部門月結頁
- **THEN** 甲的支付金額顯示 NT$600 並標示「待重新計算」,頁面上方提示需按「重新計算」,甲的個人可補助維持試算值
#### Scenario: 重新計算後提示消失
- **WHEN** 頁面顯示待重新計算的提示時,主管按「重新計算」
- **THEN** 提示與「待重新計算」標示消失,個人可補助與最終補助依目前資料更新
#### Scenario: 新出現的申請人
- **WHEN** 已有試算後,另一位原本沒有案件的同仁有案件被核准
- **THEN** 分配明細列出該同仁與其支付金額,個人可補助與最終補助顯示「待重新計算」
@@ -0,0 +1,24 @@
## 1. 共用明細表
- [x] 1.1 新增 `src/lib/settlement-sheet.ts`:`SheetRow`、`SETTLEMENT_SHEET_COLUMNS`(12 欄)、`sheetCells(row, mode)`(`display`/`numeric`)。單元測試:欄位順序、兩種模式的金額與比例格式、留白規則、合計列。
- [x] 1.2 `departmentSheetRows(view, month)`(放在 server 端,輸入 `getSettlementView` 的結果):成員列+部門合計列,發放月份 = 刷卡月份 + 2。單元測試:新申請人留白、合計與月結一致。
## 2. 部門主管匯出預覽
- [x] 2.1 `department/settlement/export/route.ts` 改用 `departmentSheetRows` + `display` 模式輸出 CSV(多了刷卡月份、發放月份兩欄)。
## 3. HR 匯出核定名單
- [x] 3.1 `src/server/settlement/payouts.ts`:`approvedSheetRows(db, month)`(已核定部門依名稱排序、各自部門合計、最後全公司合計),`payoutCsv`(純數字)與 `payoutWorkbook`(數值儲存格+NT$/百分比格式、合計列粗體、凍結標題列)改用共用欄位;移除 `src/lib/payouts.ts` 的舊 7 欄定義與 `approvedPayoutRows`。
- [x] 3.2 全公司月結頁的「匯出 Excel/CSV」停用判斷改用新資料來源(沒有已核定部門時停用)。
- [x] 3.3 單元測試(`company.test.ts` 或 `payouts` 測試):只含已核定部門、0 元成員也列出、部門合計與全公司合計正確、CSV 金額為純數字、Excel 儲存格為數值。
## 4. 文件
- [x] 4.1 改寫 `docs/operations/payout-export.md`(12 欄、合計列、Excel/CSV 差異、薪資名目固定為其他獎金),測試比對文件與欄位一致。
- [x] 4.2 CLAUDE.md:Department settlement 的 CSV 預覽與 Admin side 的核定名單描述改為共用明細表。
## 5. 驗證
- [x] 5.1 e2e:`company-settlement.spec.ts` 的匯出測試改檢查新標題、成員列、部門合計列與全公司合計列;部門月結匯出預覽的 e2e 檢查新標題與刷卡/發放月份。
- [x] 5.2 `npm run lint`、`format:check`、`typecheck`、`npm test` 與受影響的 e2e 全過。
@@ -2,13 +2,17 @@ import { auditContextFor } from "@/server/audit/action-context";
import { requireRouteAccess } from "@/server/auth/current-user";
import { getDb } from "@/server/db/client";
import {
approvedPayoutRows,
approvedSheetRows,
memberCount,
payoutCsv,
payoutWorkbook,
recordPayoutExport,
} from "@/server/settlement/payouts";
/** 匯出某刷卡月份已最終核定的名單:Excel(.xlsx)或 CSV(UTF-8 BOM),欄位固定,寫入操作紀錄。 */
/**
* 匯出某刷卡月份已最終核定的名單(與部門預覽相同的月結明細表,含部門合計與全公司合計):
* Excel(.xlsx)或 CSV(UTF-8 BOM),寫入操作紀錄。
*/
export async function GET(request: Request) {
const user = await requireRouteAccess("/admin/settlements/export");
const url = new URL(request.url);
@@ -16,8 +20,9 @@ export async function GET(request: Request) {
const format = url.searchParams.get("format") === "csv" ? "csv" : "xlsx";
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month)) return new Response("Not Found", { status: 404 });
const db = getDb();
const rows = approvedPayoutRows(db, month);
recordPayoutExport(db, await auditContextFor(user), { month, format, rows: rows.length });
const audit = await auditContextFor(user);
const rows = approvedSheetRows(db, month, audit.now);
recordPayoutExport(db, audit, { month, format, rows: memberCount(rows) });
const name = encodeURIComponent(`核定名單_${month}.${format}`);
const disposition = `attachment; filename="approved-${month}.${format}"; filename*=UTF-8''${name}`;
if (format === "csv") {
@@ -1,7 +1,6 @@
import { toCsv } from "@/lib/csv";
import { formatMoney, formatMonth } from "@/lib/format";
import { capShareBp } from "@/domain/settlement";
import { formatShare, personalCapTotal } from "@/lib/settlement";
import { formatMonth } from "@/lib/format";
import { SHEET_HEADERS, departmentSheetRows, sheetCells } from "@/lib/settlement-sheet";
import { auditContextFor } from "@/server/audit/action-context";
import { recordAudit } from "@/server/audit/record";
import { requireRouteAccess } from "@/server/auth/current-user";
@@ -13,16 +12,13 @@ import { getSettlementView, managesDepartment } from "@/server/settlement/servic
* 匯出目前分配明細為 CSV 預覽(UTF-8 BOM,Excel 可直接開啟)。正式匯出在管理端(change 10)。
* 只有該部門主管;匯出記錄於操作紀錄。
*/
/** 個人上限:舊月結沒有這個值時為「—」。 */
const capText = (cap: number | null) => (cap === null ? "—" : formatMoney(cap));
export async function GET(request: Request) {
const user = await requireRouteAccess("/department/settlement/export");
const url = new URL(request.url);
const departmentId = Number(url.searchParams.get("department"));
const month = url.searchParams.get("month") ?? "";
const db = getDb();
if (!/^\d{4}-\d{2}$/.test(month) || !managesDepartment(db, user, departmentId)) {
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month) || !managesDepartment(db, user, departmentId)) {
return new Response("Not Found", { status: 404 });
}
const audit = await auditContextFor(user);
@@ -37,47 +33,8 @@ export async function GET(request: Request) {
after: { departmentId, month, rows: v.allocations.length },
}),
);
// 欄位依使用者提供的匯出格式(2026-10-22)。「佔月上限/部門成員補助比例」= 最終補助 ÷ 部門月上限。
const dept = v.departmentName;
const rows = [
[
"部門",
"員工編號",
"姓名",
"平台",
"實際支付金額",
"個人可補助上限",
"系統計算可補助/部門分配上限",
"佔月上限/部門成員補助比例",
"最終補助",
"尾差調整",
],
...v.allocations.map((a) => [
dept,
a.employeeNo,
a.name,
a.platforms,
formatMoney(a.paidTotal),
capText(a.personalCap),
// 試算後才出現的申請人尚未計算:留白,等主管重新計算。
a.newApplicant ? "" : formatMoney(a.systemEligible),
a.newApplicant ? "" : formatShare(capShareBp(a.finalAmount, v.cap)),
a.newApplicant ? "" : formatMoney(a.finalAmount),
!a.newApplicant && a.remainderAdjustment > 0 ? `+${a.remainderAdjustment}` : "",
]),
[
"",
"",
"部門合計",
"",
formatMoney(v.allocations.reduce((s, a) => s + a.paidTotal, 0)),
capText(personalCapTotal(v.allocations)),
formatMoney(v.allocations.reduce((s, a) => s + a.systemEligible, 0)),
v.allocations.length > 0 ? formatShare(capShareBp(v.finalTotal, v.cap)) : "",
formatMoney(v.finalTotal),
"",
],
];
// 欄位與管理端核定名單共用(月結明細表,unify-settlement-sheet);金額格式與頁面一致。
const rows = [SHEET_HEADERS, ...departmentSheetRows(v).map((r) => sheetCells(r, "display"))];
const name = `部門月結預覽_${v.departmentName}_${formatMonth(month).replace("/", "-")}.csv`;
return new Response(toCsv(rows), {
headers: {
+6 -5
View File
@@ -1,5 +1,5 @@
import { Card, PageHeader } from "@/components/page-header";
import { PAYOUT_EXPORT_COLUMNS } from "@/lib/payouts";
import { SHEET_HEADERS } from "@/lib/settlement-sheet";
import { PAY_ITEM, REMAINDER_RULE_TEXT } from "@/lib/settlement";
import { requireRouteAccess } from "@/server/auth/current-user";
@@ -125,10 +125,11 @@ export default async function HelpPage() {
2 個月(例如 10 月刷卡於 12 月發放),薪資名目固定「{PAY_ITEM}」。
</li>
<li>
全公司月結頁可匯出所選月份已核定的名單(Excel 或
CSV),交給薪資作業發放,欄位固定為:
{PAYOUT_EXPORT_COLUMNS.map((c) => c.header).join("、")}
;補助金額為整數元數值。系統不追蹤實際發放結果。
全公司月結頁可匯出所選月份所有已核定部門的名單(Excel 或
CSV),交給薪資作業發放。表格與部長的匯出預覽相同,欄位為:
{SHEET_HEADERS.join("、")}
;每個部門後面有「部門合計」,最後一列為「全公司合計」。Excel 的金額可直接加總,CSV
的金額為整數元。系統不追蹤實際發放結果。
</li>
</ul>
</Card>
-16
View File
@@ -1,16 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { PAYOUT_EXPORT_COLUMNS } from "./payouts";
describe("發放名單匯出欄位文件", () => {
it("docs/operations/payout-export.md 的欄位表與 PAYOUT_EXPORT_COLUMNS 一致(名稱與順序)", () => {
const doc = readFileSync("docs/operations/payout-export.md", "utf8");
const documented = doc
.split("\n")
.map((line) => line.match(/^\|\s*(\d+)\s*\|\s*([^|]+?)\s*\|/))
.filter((m): m is RegExpMatchArray => m !== null)
.map((m) => [Number(m[1]), m[2]] as const);
expect(documented.map(([n]) => n)).toEqual(PAYOUT_EXPORT_COLUMNS.map((_, i) => i + 1));
expect(documented.map(([, name]) => name)).toEqual(PAYOUT_EXPORT_COLUMNS.map((c) => c.header));
});
});
-28
View File
@@ -1,28 +0,0 @@
import { formatMonth } from "./format";
// 核定名單匯出的固定欄位(company-settlement「匯出核定名單」):Excel 與 CSV 共用,調整只改這裡。
// 補助金額為整數元數值(不含 NT$ 與千分位),讓薪資作業直接使用。
// 欄位定義文件:docs/operations/payout-export.md(測試比對兩者一致)。新欄位只附加在最後。
export interface PayoutExportSource {
payoutMonth: string;
employeeNo: string;
name: string;
departmentName: string;
chargeMonth: string;
amount: number;
payItem: string;
}
export const PAYOUT_EXPORT_COLUMNS: readonly {
header: string;
value: (r: PayoutExportSource) => string | number;
}[] = [
{ header: "發放月份", value: (r) => formatMonth(r.payoutMonth) },
{ header: "員工編號", value: (r) => r.employeeNo },
{ header: "姓名", value: (r) => r.name },
{ header: "部門", value: (r) => r.departmentName },
{ header: "刷卡月份", value: (r) => formatMonth(r.chargeMonth) },
{ header: "補助金額", value: (r) => r.amount },
{ header: "薪資名目", value: (r) => r.payItem },
];
+192
View File
@@ -0,0 +1,192 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import {
SETTLEMENT_SHEET_COLUMNS,
SHEET_HEADERS,
companyTotalRow,
departmentSheetRows,
sheetCells,
type SheetSettlement,
} from "./settlement-sheet";
const member = (over: Partial<SheetSettlement["allocations"][number]> = {}) => ({
employeeNo: "E0001",
name: "甲",
platforms: "Claude、ChatGPT",
paidTotal: 2553,
personalCap: 1276,
systemEligible: 1276,
finalAmount: 1276,
remainderAdjustment: 0,
newApplicant: false,
...over,
});
const rnd: SheetSettlement = {
departmentName: "研發部",
month: "2026-12",
cap: 27000,
finalTotal: 1276 + 335,
allocations: [
member(),
member({
employeeNo: "E0002",
name: "乙",
platforms: "Gemini",
paidTotal: 671,
personalCap: 335,
systemEligible: 335,
finalAmount: 335,
remainderAdjustment: 1,
}),
],
};
describe("月結明細表欄位", () => {
it("欄位順序:刷卡月份、發放月份在最前面,其餘同部門預覽", () => {
expect(SHEET_HEADERS).toEqual([
"刷卡月份",
"發放月份",
"部門",
"員工編號",
"姓名",
"平台",
"實際支付金額",
"個人可補助上限",
"系統計算可補助/部門分配上限",
"佔月上限/部門成員補助比例",
"最終補助",
"尾差調整",
]);
});
it("docs/operations/payout-export.md 的欄位表與程式一致(名稱與順序)", () => {
const doc = readFileSync("docs/operations/payout-export.md", "utf8");
const documented = doc
.split("\n")
.map((line) => line.match(/^\|\s*(\d+)\s*\|\s*([^|]+?)\s*\|/))
.filter((m): m is RegExpMatchArray => m !== null)
.map((m) => [Number(m[1]), m[2]] as const);
expect(documented.map(([n]) => n)).toEqual(SETTLEMENT_SHEET_COLUMNS.map((_, i) => i + 1));
expect(documented.map(([, name]) => name)).toEqual(SHEET_HEADERS);
});
});
describe("departmentSheetRows", () => {
it("成員列+部門合計;發放月份為刷卡月份後第 2 個月(跨年);display 格式同頁面", () => {
const rows = departmentSheetRows(rnd);
expect(rows.map((r) => r.kind)).toEqual(["member", "member", "department_total"]);
expect(rows.map((r) => sheetCells(r, "display"))).toEqual([
[
"2026/12",
"2027/02",
"研發部",
"E0001",
"甲",
"Claude、ChatGPT",
"NT$2,553",
"NT$1,276",
"NT$1,276",
"4.73%",
"NT$1,276",
"",
],
[
"2026/12",
"2027/02",
"研發部",
"E0002",
"乙",
"Gemini",
"NT$671",
"NT$335",
"NT$335",
"1.24%",
"NT$335",
"+1",
],
[
"2026/12",
"2027/02",
"研發部",
"",
"部門合計",
"",
"NT$3,224",
"NT$1,611",
"NT$1,611",
"5.97%",
"NT$1,611",
"",
],
]);
});
it("numeric:金額與尾差為整數、比例為 bp,無資料留白", () => {
const [first, second] = departmentSheetRows(rnd);
expect(sheetCells(first, "numeric").slice(6)).toEqual([2553, 1276, 1276, 473, 1276, ""]);
expect(sheetCells(second, "numeric").at(-1)).toBe(1);
});
it("試算後才出現的申請人只填到個人上限;舊月結沒有個人上限時為「—」", () => {
const rows = departmentSheetRows({
...rnd,
allocations: [member({ newApplicant: true, remainderAdjustment: 1 })],
finalTotal: 0,
});
expect(sheetCells(rows[0], "display").slice(6)).toEqual([
"NT$2,553",
"NT$1,276",
"",
"",
"",
"",
]);
const legacy = departmentSheetRows({ ...rnd, allocations: [member({ personalCap: null })] });
expect(sheetCells(legacy[0], "display")[7]).toBe("—");
expect(sheetCells(legacy[1], "display")[7]).toBe("—");
expect(sheetCells(legacy[0], "numeric")[7]).toBe("");
});
it("月上限為 0 時比例為「—」", () => {
const rows = departmentSheetRows({ ...rnd, cap: 0 });
expect(sheetCells(rows[0], "display")[9]).toBe("—");
expect(sheetCells(rows[2], "display")[9]).toBe("—");
});
});
describe("companyTotalRow", () => {
it("加總各部門合計列,比例與部門留白", () => {
const design: SheetSettlement = {
departmentName: "設計部",
month: "2026-12",
cap: 1000,
finalTotal: 500,
allocations: [
member({
employeeNo: "E0003",
paidTotal: 1800,
personalCap: 900,
systemEligible: 500,
finalAmount: 500,
}),
],
};
const rows = [...departmentSheetRows(rnd), ...departmentSheetRows(design)];
const total = companyTotalRow("2026-12", rows);
expect(sheetCells(total, "numeric")).toEqual([
"2026/12",
"2027/02",
"",
"",
"全公司合計",
"",
3224 + 1800,
1611 + 900,
1611 + 500,
"",
1611 + 500,
"",
]);
});
});
+153
View File
@@ -0,0 +1,153 @@
import { capShareBp, payoutMonth } from "@/domain/settlement";
import { formatMoney, formatMonth } from "./format";
import { formatShare, personalCapTotal } from "./settlement";
// 月結明細表(unify-settlement-sheet):部門主管的「匯出預覽」與管理端的「匯出核定名單」共用的欄位。
// 欄位依使用者提供的格式(2026-10-22),前面加刷卡月份與發放月份(2026-10-29)。
// 欄位定義文件:docs/operations/payout-export.md(測試比對兩者一致)。
/** 儲存格值:數值;`undefined` 為留白;`null` 為無資料(顯示「—」,例如舊月結沒有個人上限)。 */
export type SheetValue = number | null | undefined;
export interface SheetRow {
kind: "member" | "department_total" | "company_total";
chargeMonth: string;
payoutMonth: string;
departmentName: string;
employeeNo: string;
name: string;
platforms: string;
paidTotal: SheetValue;
personalCap: SheetValue;
systemEligible: SheetValue;
shareBp: SheetValue;
finalAmount: SheetValue;
remainderAdjustment: SheetValue;
}
type ColumnType = "text" | "money" | "share" | "adjustment";
export const SETTLEMENT_SHEET_COLUMNS: readonly {
header: string;
type: ColumnType;
value: (r: SheetRow) => string | SheetValue;
}[] = [
{ header: "刷卡月份", type: "text", value: (r) => formatMonth(r.chargeMonth) },
{ header: "發放月份", type: "text", value: (r) => formatMonth(r.payoutMonth) },
{ header: "部門", type: "text", value: (r) => r.departmentName },
{ header: "員工編號", type: "text", value: (r) => r.employeeNo },
{ header: "姓名", type: "text", value: (r) => r.name },
{ header: "平台", type: "text", value: (r) => r.platforms },
{ header: "實際支付金額", type: "money", value: (r) => r.paidTotal },
{ header: "個人可補助上限", type: "money", value: (r) => r.personalCap },
{ header: "系統計算可補助/部門分配上限", type: "money", value: (r) => r.systemEligible },
{ header: "佔月上限/部門成員補助比例", type: "share", value: (r) => r.shareBp },
{ header: "最終補助", type: "money", value: (r) => r.finalAmount },
{ header: "尾差調整", type: "adjustment", value: (r) => r.remainderAdjustment },
];
export const SHEET_HEADERS = SETTLEMENT_SHEET_COLUMNS.map((c) => c.header);
/**
* 一列的儲存格。`display`(部門預覽 CSV):金額 `NT$1,276`、比例 `4.73%`、尾差 `+1`;
* `numeric`(核定名單):金額與尾差為整數、比例為 `bp`(Excel 再轉成百分比),無資料一律留白。
*/
export function sheetCells(row: SheetRow, mode: "display"): string[];
export function sheetCells(row: SheetRow, mode: "numeric"): (string | number)[];
export function sheetCells(row: SheetRow, mode: "display" | "numeric"): (string | number)[] {
return SETTLEMENT_SHEET_COLUMNS.map(({ type, value }) => {
const v = value(row);
if (typeof v === "string") return v;
if (v === undefined) return "";
if (mode === "numeric") return v ?? "";
if (type === "share") return formatShare(v);
if (type === "adjustment") return v === null ? "" : `+${v}`;
return v === null ? "—" : formatMoney(v);
});
}
/** 組明細表需要的月結資料(`getSettlementView` 的結果)。 */
export interface SheetSettlement {
departmentName: string;
month: string;
cap: number;
finalTotal: number;
allocations: readonly {
employeeNo: string;
name: string;
platforms: string;
paidTotal: number;
personalCap: number | null;
systemEligible: number;
finalAmount: number;
remainderAdjustment: number;
newApplicant: boolean;
}[];
}
/**
* 一個部門的明細:成員列+「部門合計」列。試算後才出現的申請人只填到個人上限,其餘留白;
* 佔月上限比例 = 最終補助 ÷ 部門月上限(月上限為 0 時為「—」)。
*/
export function departmentSheetRows(s: SheetSettlement): SheetRow[] {
const months = { chargeMonth: s.month, payoutMonth: payoutMonth(s.month) };
const members: SheetRow[] = s.allocations.map((a) => ({
kind: "member",
...months,
departmentName: s.departmentName,
employeeNo: a.employeeNo,
name: a.name,
platforms: a.platforms,
paidTotal: a.paidTotal,
personalCap: a.personalCap,
systemEligible: a.newApplicant ? undefined : a.systemEligible,
shareBp: a.newApplicant ? undefined : capShareBp(a.finalAmount, s.cap),
finalAmount: a.newApplicant ? undefined : a.finalAmount,
remainderAdjustment:
!a.newApplicant && a.remainderAdjustment > 0 ? a.remainderAdjustment : undefined,
}));
const total: SheetRow = {
kind: "department_total",
...months,
departmentName: s.departmentName,
employeeNo: "",
name: "部門合計",
platforms: "",
paidTotal: sum(s.allocations.map((a) => a.paidTotal)),
personalCap: personalCapTotal(s.allocations),
systemEligible: sum(s.allocations.map((a) => a.systemEligible)),
shareBp: s.allocations.length > 0 ? capShareBp(s.finalTotal, s.cap) : undefined,
finalAmount: s.finalTotal,
remainderAdjustment: undefined,
};
return [...members, total];
}
/** 「全公司合計」列:各部門合計列的金額加總,佔月上限比例留白(各部門月上限不同,不能相加)。 */
export function companyTotalRow(month: string, rows: readonly SheetRow[]): SheetRow {
const totals = rows.filter((r) => r.kind === "department_total");
const add = (pick: (r: SheetRow) => SheetValue): SheetValue => {
const values = totals.map(pick);
if (values.some((v) => v === null)) return null;
return sum(values.map((v) => v ?? 0));
};
return {
kind: "company_total",
chargeMonth: month,
payoutMonth: payoutMonth(month),
departmentName: "",
employeeNo: "",
name: "全公司合計",
platforms: "",
paidTotal: add((r) => r.paidTotal),
personalCap: add((r) => r.personalCap),
systemEligible: add((r) => r.systemEligible),
shareBp: undefined,
finalAmount: add((r) => r.finalAmount),
remainderAdjustment: undefined,
};
}
function sum(values: readonly number[]): number {
return values.reduce((s, v) => s + v, 0);
}
+44 -27
View File
@@ -36,7 +36,13 @@ import {
returnSettlement,
} from "./company";
import { SETTLEMENT_LOCKED_MESSAGE } from "./lock";
import { approvedPayoutRows, payoutCsv, payoutWorkbook, recordPayoutExport } from "./payouts";
import {
approvedSheetRows,
memberCount,
payoutCsv,
payoutWorkbook,
recordPayoutExport,
} from "./payouts";
import { SUBMITTED_RECALC_MESSAGE, recalculateSettlement, submitSettlement } from "./service";
const TZ = "Asia/Taipei";
@@ -465,55 +471,66 @@ describe("退回月結", () => {
});
describe("匯出核定名單", () => {
it("只含已最終核定(含舊的已發放)部門、最終補助大於 0 的人;發放月份為刷卡月份後第 2 個月", () => {
const now = new Date(DEC_05);
const names = (month = MONTH) =>
approvedSheetRows(t.db, month, now).map((r) => [r.kind, r.departmentName, r.name]);
it("只含已最終核定(含舊的已發放)部門:成員、部門合計、全公司合計;發放月份為刷卡月份後第 2 個月", () => {
submittedDesign();
expect(approvedPayoutRows(t.db, MONTH)).toEqual([]);
expect(approvedSheetRows(t.db, MONTH, now)).toEqual([]);
finalize();
expect(
approvedPayoutRows(t.db, MONTH).map((r) => [
r.payoutMonth,
r.employeeNo,
r.name,
r.departmentName,
r.chargeMonth,
r.amount,
r.payItem,
]),
).toEqual([
["2026-12", "E0001", "王小明", "設計部", "2026-10", 500, "其他獎金"],
["2026-12", "E0002", "同事", "設計部", "2026-10", 500, "其他獎金"],
const rows = approvedSheetRows(t.db, MONTH, now);
expect(names()).toEqual([
["member", "設計部", "王小明"],
["member", "設計部", "同事"],
["department_total", "設計部", "部門合計"],
["company_total", "", "全公司合計"],
]);
expect(rows.every((r) => r.chargeMonth === "2026-10" && r.payoutMonth === "2026-12")).toBe(
true,
);
expect(rows.map((r) => r.finalAmount)).toEqual([500, 500, 1000, 1000]);
expect(rows[2]).toMatchObject({ paidTotal: 5200, personalCap: 2600, shareBp: 10000 });
expect(rows[3]).toMatchObject({ paidTotal: 5200, personalCap: 2600, shareBp: undefined });
expect(memberCount(rows)).toBe(2);
t.db
.update(departmentSettlements)
.set({ status: "paid" })
.where(eq(departmentSettlements.id, settlement().id))
.run();
expect(approvedPayoutRows(t.db, MONTH)).toHaveLength(2);
expect(approvedPayoutRows(t.db, "2026-09")).toEqual([]);
expect(names()).toHaveLength(4);
expect(approvedSheetRows(t.db, "2026-09", now)).toEqual([]);
});
it("CSV 與 Excel 欄位順序固定、金額為整數數值;匯出寫入操作紀錄", async () => {
it("CSV 金額為整數、比例為百分比;Excel 為數值儲存格;匯出寫入操作紀錄", async () => {
submittedDesign();
finalize();
const rows = approvedPayoutRows(t.db, MONTH);
const header = "發放月份,員工編號,姓名,部門,刷卡月份,補助金額,薪資名目";
const rows = approvedSheetRows(t.db, MONTH, now);
const header =
"刷卡月份,發放月份,部門,員工編號,姓名,平台,實際支付金額,個人可補助上限,系統計算可補助/部門分配上限,佔月上限/部門成員補助比例,最終補助,尾差調整";
const csv = payoutCsv(rows);
expect(csv.charCodeAt(0)).toBe(0xfeff);
expect(csv.slice(1).trim().split("\r\n")).toEqual([
header,
"2026/12,E0001,王小明,設計部,2026/10,500,其他獎金",
"2026/12,E0002,同事,設計部,2026/10,500,其他獎金",
"2026/10,2026/12,設計部,E0001,王小明,ChatGPT,1800,900,500,50.00%,500,",
"2026/10,2026/12,設計部,E0002,同事,ChatGPT,3400,1700,500,50.00%,500,",
"2026/10,2026/12,設計部,,部門合計,,5200,2600,1000,100.00%,1000,",
"2026/10,2026/12,,,全公司合計,,5200,2600,1000,,1000,",
]);
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.load((await payoutWorkbook(MONTH, rows)) as unknown as ArrayBuffer);
const sheet = workbook.worksheets[0];
expect(sheet.getRow(1).values).toEqual([undefined, ...header.split(",")]);
expect(sheet.getRow(2).getCell(6).value).toBe(500);
expect(typeof sheet.getRow(3).getCell(6).value).toBe("number");
expect(sheet.getRow(3).getCell(3).value).toBe("同事");
expect(sheet.getRow(2).getCell(7).value).toBe(1800);
expect(sheet.getRow(2).getCell(10).value).toBe(0.5);
expect(sheet.getRow(2).getCell(11).value).toBe(500);
expect(sheet.getColumn(11).numFmt).toBe('"NT$"#,##0');
expect(sheet.getRow(4).getCell(5).value).toBe("部門合計");
expect(sheet.getRow(4).font?.bold).toBe(true);
expect(sheet.getRow(5).getCell(11).value).toBe(1000);
recordPayoutExport(t.db, at(DEC_05), { month: MONTH, format: "xlsx", rows: rows.length });
recordPayoutExport(t.db, at(DEC_05), { month: MONTH, format: "xlsx", rows: memberCount(rows) });
expect(expectAudit(t.db, "payout.exported").after).toEqual({
month: MONTH,
format: "xlsx",
+69 -58
View File
@@ -1,87 +1,98 @@
import ExcelJS from "exceljs";
import { and, eq, gt, inArray } from "drizzle-orm";
import { payoutMonth } from "@/domain/settlement";
import { and, eq, inArray } from "drizzle-orm";
import { toCsv } from "@/lib/csv";
import { PAYOUT_EXPORT_COLUMNS, type PayoutExportSource } from "@/lib/payouts";
import { PAY_ITEM } from "@/lib/settlement";
import {
SETTLEMENT_SHEET_COLUMNS,
SHEET_HEADERS,
companyTotalRow,
departmentSheetRows,
sheetCells,
type SheetRow,
} from "@/lib/settlement-sheet";
import { recordAudit, type AuditContext } from "@/server/audit/record";
import type { Db } from "@/server/db/client";
import {
departmentSettlements,
departments,
settlementAllocations,
users,
} from "@/server/db/schema";
import { departmentSettlements, departments } from "@/server/db/schema";
import { withTransaction } from "@/server/db/transaction";
import { getSettlementView } from "./service";
// 核定名單匯出(company-settlement「匯出核定名單」,remove-payout-management):
// 某刷卡月份已最終核定(含舊的已發放)月結中,最終補助大於 0 的申請人。不追蹤發放狀態。
// 核定名單匯出(company-settlement「匯出核定名單」):與部門主管匯出預覽相同的月結明細表
// (unify-settlement-sheet)。某刷卡月份所有已最終核定(含舊的已發放)部門,各自接部門合計,
// 最後一列全公司合計。不追蹤發放狀態。
/** 某刷卡月份的核定名單,依部門名稱、員工編號排序。 */
export function approvedPayoutRows(db: Db, month: string): PayoutExportSource[] {
return db
.select({
employeeNo: users.employeeNo,
name: users.name,
departmentName: departments.name,
amount: settlementAllocations.finalAmount,
})
.from(settlementAllocations)
.innerJoin(
departmentSettlements,
eq(departmentSettlements.id, settlementAllocations.settlementId),
)
/**
* 某刷卡月份的核定名單:已核定部門依名稱排序,每個部門的成員(含 0 元)+部門合計,
* 最後加全公司合計;沒有已核定部門時為空陣列。已核定的月結取存下的結果,不重算。
*/
export function approvedSheetRows(db: Db, month: string, now: Date): SheetRow[] {
const settled = db
.select({ departmentId: departmentSettlements.departmentId, name: departments.name })
.from(departmentSettlements)
.innerJoin(departments, eq(departments.id, departmentSettlements.departmentId))
.innerJoin(users, eq(users.id, settlementAllocations.userId))
.where(
and(
eq(departmentSettlements.month, month),
inArray(departmentSettlements.status, ["finalized", "paid"]),
gt(settlementAllocations.finalAmount, 0),
),
)
.all()
.sort(
(a, b) =>
a.departmentName.localeCompare(b.departmentName, "zh-Hant") ||
a.employeeNo.localeCompare(b.employeeNo),
)
.map((r) => ({
...r,
name: r.name ?? "",
payoutMonth: payoutMonth(month),
chargeMonth: month,
payItem: PAY_ITEM,
}));
.sort((a, b) => a.name.localeCompare(b.name, "zh-Hant"));
if (settled.length === 0) return [];
const rows = settled.flatMap(({ departmentId }) => {
const view = getSettlementView(db, departmentId, month, now);
if (!view.ok) throw new Error(view.error);
return departmentSheetRows(view.value);
});
return [...rows, companyTotalRow(month, rows)];
}
/** 匯出的資料列(固定欄位與順序)。 */
export function payoutExportRows(rows: readonly PayoutExportSource[]): (string | number)[][] {
return rows.map((r) => PAYOUT_EXPORT_COLUMNS.map((c) => c.value(r)));
}
/** 成員列數(操作紀錄用)。 */
export const memberCount = (rows: readonly SheetRow[]) =>
rows.filter((r) => r.kind === "member").length;
export function payoutCsv(rows: readonly PayoutExportSource[]): string {
/** CSV:金額為整數元(不含 NT$ 與千分位),比例為 `77.39%`。 */
export function payoutCsv(rows: readonly SheetRow[]): string {
const shareColumn = SETTLEMENT_SHEET_COLUMNS.findIndex((c) => c.type === "share");
return toCsv([
PAYOUT_EXPORT_COLUMNS.map((c) => c.header),
...payoutExportRows(rows).map((r) => r.map(String)),
SHEET_HEADERS,
...rows.map((r) =>
sheetCells(r, "numeric").map((cell, i) =>
i === shareColumn && typeof cell === "number"
? `${(cell / 100).toFixed(2)}%`
: String(cell),
),
),
]);
}
export async function payoutWorkbook(
month: string,
rows: readonly PayoutExportSource[],
): Promise<Buffer> {
/** Excel:金額與比例為數值儲存格(顯示 NT$ 千分位與百分比),合計列粗體,凍結標題列。 */
export async function payoutWorkbook(month: string, rows: readonly SheetRow[]): Promise<Buffer> {
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet(`核定名單 ${month}`);
sheet.addRow(PAYOUT_EXPORT_COLUMNS.map((c) => c.header)).font = { bold: true };
for (const row of payoutExportRows(rows)) sheet.addRow(row);
const amountColumn = PAYOUT_EXPORT_COLUMNS.findIndex((c) => c.header === "補助金額") + 1;
sheet.getColumn(amountColumn).numFmt = "0";
sheet.columns.forEach((col) => (col.width = 14));
const sheet = workbook.addWorksheet(`核定名單 ${month}`, {
views: [{ state: "frozen", ySplit: 1 }],
});
sheet.addRow(SHEET_HEADERS).font = { bold: true };
for (const row of rows) {
const cells = sheetCells(row, "numeric").map((cell, i) =>
SETTLEMENT_SHEET_COLUMNS[i].type === "share" && typeof cell === "number"
? cell / 10000
: cell === ""
? null
: cell,
);
const added = sheet.addRow(cells);
if (row.kind !== "member") added.font = { bold: true };
}
SETTLEMENT_SHEET_COLUMNS.forEach((c, i) => {
const column = sheet.getColumn(i + 1);
if (c.type === "money") column.numFmt = '"NT$"#,##0';
if (c.type === "share") column.numFmt = "0.00%";
if (c.type === "adjustment") column.numFmt = "+0";
column.width = c.header.length > 8 ? 26 : 14;
});
return Buffer.from(await workbook.xlsx.writeBuffer());
}
/** 匯出寫入操作紀錄(刷卡月份、格式與筆數)。 */
/** 匯出寫入操作紀錄(刷卡月份、格式與成員列數)。 */
export function recordPayoutExport(
db: Db,
audit: AuditContext,
+14 -7
View File
@@ -176,7 +176,10 @@ test("退回月結:原因必填;部長看到原因並可再提交;保留
await expect(versions.nth(1)).toContainText("退回:人數快照有誤,請重新確認");
});
test("匯出核定名單:只有已最終核定的部門,欄位固定;沒有發放管理", async ({ page, browser }) => {
test("匯出核定名單:與部門預覽相同的明細表,含部門合計與全公司合計;沒有發放管理", async ({
page,
browser,
}) => {
const t = team();
const { context } = await managerSubmits(browser, t.managerNo!);
await context.close();
@@ -195,13 +198,17 @@ test("匯出核定名單:只有已最終核定的部門,欄位固定;沒
const csv = readFileSync((await (await csvDownload).path())!, "utf8");
expect(csv.charCodeAt(0)).toBe(0xfeff);
const lines = csv.slice(1).trim().split("\r\n");
expect(lines[0]).toBe("發放月份,員工編號,姓名,部門,刷卡月份,補助金額,薪資名目");
expect(lines).toContain(
`${display(PAYOUT)},${t.a},${t.nameA},${t.departmentName},${display(MONTH)},500,其他獎金`,
);
expect(lines).toContain(
`${display(PAYOUT)},${t.b},${t.nameB},${t.departmentName},${display(MONTH)},500,其他獎金`,
expect(lines[0]).toBe(
"刷卡月份,發放月份,部門,員工編號,姓名,平台,實際支付金額,個人可補助上限,系統計算可補助/部門分配上限,佔月上限/部門成員補助比例,最終補助,尾差調整",
);
// 與部門預覽相同的明細表:成員、部門合計(共用資料庫有其他部門,只檢查自己部門),最後全公司合計
const months = `${display(MONTH)},${display(PAYOUT)}`;
const dept = t.departmentName;
expect(lines).toContain(`${months},${dept},${t.a},${t.nameA},ChatGPT,1800,900,500,50.00%,500,`);
expect(lines).toContain(`${months},${dept},${t.b},${t.nameB},ChatGPT,3400,1700,500,50.00%,500,`);
expect(lines).toContain(`${months},${dept},,部門合計,,5200,2600,1000,100.00%,1000,`);
// 共用資料庫中可能有舊月結(沒有個人上限):個人上限合計可能留白
expect(lines.at(-1)).toMatch(new RegExp(`^${months},,,全公司合計,,\\d+,\\d*,\\d+,,\\d+,$`));
const xlsxDownload = page.waitForEvent("download");
await page.getByTestId("approved-export").getByRole("link", { name: "匯出 Excel" }).click();
const xlsx = await xlsxDownload;
+1 -1
View File
@@ -131,7 +131,7 @@ test("使用說明:員工看不到主管端與管理端段落,主管、管
await expect(page.getByRole("heading", { name: title })).toHaveCount(0);
}
// 管理端段落的內容不送到員工的瀏覽器(含 RSC 資料)。
expect(await page.content()).not.toContain("發放管理可匯出");
expect(await page.content()).not.toContain("全公司月結頁可匯出");
for (const user of [DEMO.manager, DEMO.admin, DEMO.sysadmin]) {
await loginAs(page, user, "/help");
+14 -6
View File
@@ -18,6 +18,8 @@ import { DEMO, loginAs } from "./helpers";
const MONTH = monthsAgo(2);
const CURRENT = monthsAgo(0);
const display = (month: string) => month.replace("-", "/");
// 匯出預覽最前面的刷卡月份與預計發放月份(刷卡月份 + 2)
const MONTHS = `${display(MONTH)},${display(monthsAgo(0))}`;
/**
* 月上限 NT$1,000,A 支付 900、B 支付 1,700(個人上限 450/850):超額平分 500,
@@ -177,7 +179,7 @@ test("已存試算後再核准:支付金額即時更新並提示重新計算
await page.getByRole("link", { name: "匯出預覽" }).click();
let csv = readFileSync((await (await downloading).path())!, "utf8");
expect(csv.slice(1).trim().split("\r\n")).toContain(
`${dept},${g},庚員工,ChatGPT,NT$600,NT$300,,,,`,
`${MONTHS},${dept},${g},庚員工,ChatGPT,NT$600,NT$300,,,,`,
);
await page.getByRole("button", { name: "重新計算" }).click();
@@ -195,14 +197,20 @@ test("已存試算後再核准:支付金額即時更新並提示重新計算
expect(csv.charCodeAt(0)).toBe(0xfeff);
const lines = csv.slice(1).trim().split("\r\n");
expect(lines[0]).toBe(
"部門,員工編號,姓名,平台,實際支付金額,個人可補助上限,系統計算可補助/部門分配上限,佔月上限/部門成員補助比例,最終補助,尾差調整",
"刷卡月份,發放月份,部門,員工編號,姓名,平台,實際支付金額,個人可補助上限,系統計算可補助/部門分配上限,佔月上限/部門成員補助比例,最終補助,尾差調整",
);
expect(lines).toContain(`${dept},${a},甲員工,ChatGPT,NT$900,NT$450,NT$350,35.00%,NT$350,`);
expect(lines).toContain(
`${dept},${b},乙員工,Claude、ChatGPT,"NT$2,900","NT$1,450",NT$350,35.00%,NT$350,`,
`${MONTHS},${dept},${a},甲員工,ChatGPT,NT$900,NT$450,NT$350,35.00%,NT$350,`,
);
expect(lines).toContain(
`${MONTHS},${dept},${b},乙員工,Claude、ChatGPT,"NT$2,900","NT$1,450",NT$350,35.00%,NT$350,`,
);
expect(lines).toContain(
`${MONTHS},${dept},${g},庚員工,ChatGPT,NT$600,NT$300,NT$300,30.00%,NT$300,`,
);
expect(lines.at(-1)).toBe(
`${MONTHS},${dept},,部門合計,,"NT$4,400","NT$2,200","NT$1,000",100.00%,"NT$1,000",`,
);
expect(lines).toContain(`${dept},${g},庚員工,ChatGPT,NT$600,NT$300,NT$300,30.00%,NT$300,`);
expect(lines.at(-1)).toBe(',,部門合計,,"NT$4,400","NT$2,200","NT$1,000",100.00%,"NT$1,000",');
});
test("提交:阻擋並列出待處理案件、逾期不核准、取消不變、確認後唯讀", async ({ page }) => {