# AccOS Pro — AGENTS.md

> Comprehensive agent-facing reference for the AccOS Pro accounting system.
> Generated from 6 source documents: Accounting & Tax Guide, Master Data Analysis, Workflow Guide, Data Flow Diagram, Tax Data Flow Analysis, and Tax Forms Report.

---

## 1. System Overview

**AccOS Pro** is a Thai GAAP–compliant, multi-tenant accounting operating system built as a monorepo:

| Package | Path               | Stack                                          |
| ------- | ------------------ | ---------------------------------------------- |
| API     | `apps/api/`        | Hono + Drizzle ORM + PostgreSQL                |
| Web     | `apps/web/`        | Next.js (App Router)                           |
| Shared  | `packages/shared/` | Pure TypeScript — engines, schemas, formatters |

**Key Architecture Principles:**

- **Double-Entry Bookkeeping** — every Journal Entry must have `debit === credit`.
- **Single Source of Truth** — `journal_entries` + `journal_lines` feed all reports and tax forms.
- **Auto-posting** — Invoices, Bills, and Payroll automatically generate Journal Entries via `auto-poster.ts`.
- **Multi-tenant** — `companyId` on every table; RLS via `company_id`.

---

## 2. Chart of Accounts (COA)

Standard Thai 4-digit COA seeded in `packages/shared/src/fixtures/`:

| Category    | Codes     | Normal Balance |
| ----------- | --------- | -------------- |
| Assets      | 1xxx      | Debit          |
| Liabilities | 2xxx      | Credit         |
| Equity      | 3xxx      | Credit         |
| Revenue     | 4xxx      | Credit         |
| Expense     | 5xxx–6xxx | Debit          |

**Key accounts used in auto-posting:**

| Code      | Name              | Used in                   |
| --------- | ----------------- | ------------------------- |
| 1110      | Cash on Hand      | Cash sales, cash expenses |
| 1121      | KBank Deposit     | Bank transfers            |
| 1140      | Trade Receivables | Credit sales (AR)         |
| 1150      | Input VAT         | Bills with VAT 7%         |
| 2110      | Trade Payables    | Bills (AP)                |
| 2140      | WHT Payable       | Withholding tax           |
| 2150      | Output VAT        | Invoices with VAT 7%      |
| 4010      | Product Sales     | Revenue                   |
| 5110–5250 | Various Expenses  | Operating expenses        |

---

## 3. Journal Entry Lifecycle

```
draft → pending_approval → in_review → approved → posted → void
```

**Fields on `journal_entries`:**

- `sourceType`: `invoice | bill | payroll | manual | payment`
- `sourceId`: FK back to the originating document
- `taxPeriod`: `YYYY-MM` (cross-month VAT support)
- `isCrossMonth`: boolean flag
- `totalDebit` / `totalCredit`: must balance

**Fields on `journal_lines`:**

- `accountId` → Chart of Accounts
- `debit` / `credit` (numeric 18,2)
- `vatRate` / `vatAmount`
- `whtRate` / `whtAmount`
- `costCenterId` → cost_centers

---

## 4. Quick Templates (11 types)

| Template          | Debit                                       | Credit                                 |
| ----------------- | ------------------------------------------- | -------------------------------------- |
| `sale_cash`       | 1110 Cash                                   | 4010 Product Sales                     |
| `sale_credit`     | 1140 AR (vatRate=7)                         | 4020 Service Revenue + 2150 Output VAT |
| `expense_cash`    | 5230 Materials                              | 1110 Cash                              |
| `expense_credit`  | 5230 Materials (vatRate=7) + 1150 Input VAT | 2110 AP                                |
| `rent`            | 5120 Rent                                   | 2110 AP                                |
| `salary`          | 5110 Salary                                 | 2110 AP                                |
| `utility`         | 5240 Utilities                              | 2110 AP                                |
| `receive_payment` | 1121 Bank                                   | 1140 AR                                |
| `pay_bill`        | 2110 AP                                     | 1121 Bank                              |
| `wht`             | 2110 AP (whtRate=3)                         | 2140 WHT Payable                       |
| `depreciation`    | 5212 Depreciation                           | 1730 Accum. Depreciation               |

---

## 5. Revenue Journal Entries

### Cash Sale (no VAT)

```
Dr. 1110 Cash           10,000
    Cr. 4010 Product Sales   10,000
```

### Credit Sale + VAT 7%

```
Dr. 1140 AR             37,450    (vatRate: 7)
    Cr. 4020 Service Revenue  35,000
    Cr. 2150 Output VAT        2,450
```

### Zero-Rated Export

```
Dr. 1140 AR             50,000    (vatRate: '0')
    Cr. 4020 Service Revenue  50,000
```

---

## 6. Expense Journal Entries

### Cash Purchase (no VAT)

```
Dr. 5230 Materials       5,000
    Cr. 1110 Cash             5,000
```

### Credit Purchase + VAT 7%

```
Dr. 5230 Materials      20,000    (vatRate: 7)
Dr. 1150 Input VAT       1,400
    Cr. 2110 AP              21,400
```

### Rent + VAT 7%

```
Dr. 5120 Rent           30,000    (vatRate: 7)
Dr. 1150 Input VAT       2,100
    Cr. 2110 AP              32,100
```

> ⚠️ **Forbidden Input VAT**: Entertainment, gifts — VAT must be separated to `vatForbidden` account (Section 82/5 Revenue Code).

---

## 7. Withholding Tax (WHT)

| Rate | Section 40 | Income Type   | Example                 |
| ---- | ---------- | ------------- | ----------------------- |
| 1%   | 40(4)(a)   | Interest      | Bank deposits           |
| 2%   | 40(1)      | Salary        | Freelancer              |
| 3%   | 40(2)      | Fees/Services | Advertising, consulting |
| 5%   | 40(5)      | Rent          | Office rent             |
| 10%  | 40(4)(b)   | Dividends     | Shareholder dividends   |

### WHT 3% on Service Fee

```
Dr. 2110 AP             20,000    (vatRate: '0', whtRate: '3')
    Cr. 2140 WHT Payable       600
```

### Remit WHT

```
Dr. 2140 WHT Payable     8,500
    Cr. 1121 Bank              8,500
```

---

## 8. Period-End Adjustments

### Depreciation

```
Dr. 5212 Depreciation     5,000
    Cr. 1730 Accum. Depr.     5,000
```

### Accrued Expense

```
Dr. 5240 Utilities        4,500
    Cr. 2160 Accrued Payables 4,500
```

### Accrued Revenue

```
Dr. 1140 Other Receivables 12,000
    Cr. 4020 Service Revenue  12,000
```

### Closing Entries

- Close Revenue → Retained Earnings (3110): `Dr. 4xxx → Cr. 3110`
- Close Expenses → Retained Earnings (3110): `Dr. 3110 → Cr. 5xxx-6xxx`
- Engine: `generateClosingEntries()` in `packages/shared/src/accounting/closing-engine.ts`
- API: `POST /api/closing-entries` with `periodStart` + `periodEnd`

---

## 9. Financial Reports

| Report           | Engine Function            | Source                   | Filter                                           |
| ---------------- | -------------------------- | ------------------------ | ------------------------------------------------ |
| Trial Balance    | `buildTrialBalance()`      | journal_lines + accounts | All posted journals                              |
| Balance Sheet    | `buildBalanceSheet()`      | journals                 | `date ≤ asOf`, group by category                 |
| Income Statement | `buildProfitLoss()`        | journals                 | `date ∈ [start, end]`, group by subCategory      |
| Cash Flow        | `buildCashFlow()`          | journals                 | Operating/Investing/Financing by subCategory     |
| Working Paper    | `buildWorkingPaper()`      | journals                 | TB → adjustments → adjusted TB                   |
| Financial Ratios | `computeFinancialRatios()` | journals + accounts      | Current Ratio, D/E, ROA, ROE, DSO, DPO, DIO, CCC |

**API Endpoints:**

- `GET /api/reports/trial-balance?startDate=&endDate=`
- `GET /api/reports/balance-sheet?endDate=`
- `GET /api/reports/income-statement?startDate=&endDate=`
- `GET /api/reports/cash-flow?startDate=&endDate=`
- `GET /api/reports/working-paper?startDate=&endDate=`
- `GET /api/reports/vat?startDate=&endDate=`
- `GET /api/reports/general-ledger?startDate=&endDate=`
- `GET /api/reports/aging`
- `GET /api/reports/ratios`
- `GET /api/reports/by-cost-center`

---

## 10. Tax Forms — 63 Forms

### 10.1 VAT (ภ.พ.30, ภ.พ.20, ภ.พ.60)

**Data source:** Invoices (output VAT) + Bills (input VAT) — auto-compute.

```
POST /api/tax-forms  { "formType": "pp30", "period": "2026-06" }
POST /api/tax-forms/:id/compute
```

- Output VAT = Σ invoice.vatAmount (non-void, non-export)
- Input VAT = Σ bill.vatAmount − forbidden (entertainment/gifts)
- **VAT Payable = Output − Input Allowed**

### 10.2 WHT Main (ภ.ง.ด.1, ภ.ง.ด.3, ภ.ง.ด.53)

| Form  | Source           | Filter                                    |
| ----- | ---------------- | ----------------------------------------- |
| PND3  | Bills            | vendor.type = `individual`, whtAmount > 0 |
| PND53 | Bills            | vendor.type = `corporate`, whtAmount > 0  |
| PND1  | Bills + Journals | PND3 + PND53 + `computeWHTFromJournals()` |

**PND1 is Hybrid:** combines sub-ledger (Bills) + GL (journal WHT lines from payroll/manual).

```
POST /api/tax-forms  { "formType": "pnd1", "period": "2026-06" }
```

### 10.3 WHT Special (9 forms)

| Form  | Description                  |
| ----- | ---------------------------- |
| PND2  | Corporate WHT (primary)      |
| PND2a | Corporate WHT — real estate  |
| PND3a | Individual WHT — real estate |
| PND5  | Other income WHT             |
| PND6  | Auction WHT                  |
| PND9  | Dividend/interest WHT        |
| PND20 | Foreign corporate WHT        |
| PND22 | Product sale WHT             |
| PND54 | Mutual fund WHT              |

All computed via `computeWHTByType(period, formType, bills, vendors)`.

### 10.4 CIT (ภ.พ.36, ภ.ธ.40)

**Data source:** Journal Entries 100% (Pure GL pattern).

```
POST /api/tax-forms  { "formType": "pp36", "period": "2026-H1" }
POST /api/tax-forms  { "formType": "por40", "period": "2026" }
```

**CIT Progressive Tax Rates:**
| Net Profit (THB) | Rate |
|-----------------|------|
| ≤ 300,000 | 0% (exempt) |
| ≤ 3,000,000 | 15% |
| > 3,000,000 | 20% |

**12 CIT Add-back Rules** (`cit-rules.ts`):

- AB-ENTERTAINMENT (auto-detect accounts 5220-5240)
- AB-PROVISIONS (auto-detect accounts 5440-5450)
- AB-PENALTY (auto-detect accounts 5500-5510)
- AB-LOSS-SALE (auto-detect account 5910)
- 8 manual rules (depreciation excess, donations, bad debt, etc.)

### 10.5 Other Tax Forms (50+)

| Category          | Forms             | Data Source                          |
| ----------------- | ----------------- | ------------------------------------ |
| Signboard Tax     | ภ.ป.4             | Manual input (signboard dimensions)  |
| Entertainment Tax | ภ.ป.13            | Manual input (venue revenue)         |
| SBT               | ภ.พ.40, ภ.บ.จ.1-2 | Manual input (gross receipt × 3%)    |
| Land/Building Tax | land_building     | Manual input (appraised value)       |
| Vehicle Tax       | vehicle           | Manual input (cc/weight)             |
| Stamp Duty        | ภ.ด.ส.1-5         | Manual input (contract type)         |
| RE Transfer       | ภ.ร.ด.1-3, 90, 91 | Manual input (property transfer)     |
| Securities        | ภ.ส.ร.1-4         | Manual input                         |
| Remittance Tax    | ภ.บ.ท.1-4         | Manual input (5% of exported income) |
| Insurance         | ภ.ย.1-3           | Manual input (2.5% premium)          |
| Hotel Tax         | ภ.ร.1-2           | Manual input (1.5% room revenue)     |
| Petroleum         | ภ.อ.1-3           | Manual input                         |
| BOI               | boi               | Manual input                         |
| Transfer Pricing  | transfer_pricing  | Manual input                         |

### 10.6 Tax Form State Machine

```
draft → computing → computed → reviewing → approved → filed → acknowledged
                                                              ↗
                                            rejected ← reviewing
```

API: `POST /api/tax-forms/:id/submit` → `POST /api/filings/:id/approve` → `POST /api/filings/:id/file`

### 10.7 Cross-Form Validation

Before submitting PND1, system validates: **PND1 = PND3 + PND53**. Mismatch blocks submission.

---

## 11. 3 Computation Patterns

| Pattern               | Tax Forms                | Source                  | Speed         |
| --------------------- | ------------------------ | ----------------------- | ------------- |
| **Sub-ledger Direct** | PP30, PND3, PND53, PND50 | Bills/Invoices directly | Fast          |
| **Pure GL**           | PP36, Por40              | Journal Entries 100%    | Authoritative |
| **Hybrid**            | PND1                     | Bills + Journals        | Combined      |

---

## 12. Data Flow Pipeline

```
Source Documents (Invoices, Bills, Payroll, Manual, Bank)
        ↓ auto-post
Journal Entries (GL) — Single Source of Truth
        ↓
   ┌────┴────┐
   ↓         ↓
Tax Forms   Financial Reports
(PP30,      (Balance Sheet,
 PND1/3/53,  Income Statement,
 PP36,       Cash Flow,
 Por40)      Ratios)
```

**Engine Files:**

- `packages/shared/src/accounting/tax-engine.ts` — PP30, PND1/3/53, PP36, Por40
- `packages/shared/src/accounting/tax-engine-extended.ts` — PorPor12/4/13, Land/Vehicle
- `packages/shared/src/accounting/tax-engine-extended-v2.ts` — WHT variants, SBT, Insurance, Hotel, Petroleum, Remittance
- `packages/shared/src/accounting/cit-rules.ts` — CIT add-back rules
- `packages/shared/src/accounting/book-tax-recon.ts` — Book-tax reconciliation
- `packages/shared/src/accounting/ratio-engine.ts` — Financial ratios
- `packages/shared/src/accounting/etax-engine.ts` — e-Tax invoice validation
- `packages/shared/src/accounting/auto-poster.ts` — Auto-post from Bills/Invoices
- `packages/shared/src/accounting/closing-engine.ts` — Period-end closing

---

## 13. Master Data (27 Master Data Tables, 91 Total)

| Group                | Tables                                                                    |
| -------------------- | ------------------------------------------------------------------------- |
| Organization         | `companies`, `users`, `memberships`, `company_branches`                   |
| Accounting           | `accounts` (COA), `fiscal_periods`, `cost_centers`, `projects`, `budgets` |
| Business Partners    | `customers`, `vendors`                                                    |
| Products & Inventory | `products`, `warehouses`                                                  |
| Banking & Assets     | `bank_accounts`, `assets`                                                 |
| HR & Payroll         | `employees`                                                               |

### 13.1 New Tables (Added since initial analysis) ✅

All 12 previously recommended master data tables have been implemented:

| Table                | Category     | Fields                                                               |
| -------------------- | ------------ | -------------------------------------------------------------------- |
| `banks`              | Organization | code, nameTh, nameEn, swiftCode, logoUrl, supportsPromptPay          |
| `departments`        | Organization | code, name, headEmployeeId, isActive                                 |
| `positions`          | Organization | name, isActive                                                       |
| `currencies`         | Organization | code, nameTh, nameEn, symbol, decimalPlaces                          |
| `exchange_rates`     | Organization | fromCurrency, toCurrency, rate, effectiveDate                        |
| `payment_methods`    | Partners     | name, type (cash/bank/credit/electronic), defaultAccountId, isActive |
| `tax_rates`          | Accounting   | type, code, name, rate, effectiveFrom, effectiveTo, isActive         |
| `units_of_measure`   | Products     | name, baseUnit, conversionFactor                                     |
| `product_categories` | Products     | name, isActive                                                       |
| `holidays`           | HR           | date, name, type                                                     |

### 13.2 Remaining Nice-to-Have (3 items)

1. **Financial Policies** — Depreciation defaults, rounding rules, consolidation rules
2. **Licenses/Contracts** — Business licenses, leases with expiry tracking
3. **Customer/Vendor Groups** — Segmented partner classification

### 13.3 Transaction & Feature Tables (64 tables)

Including: journal_entries, journal_lines, invoices, invoice_lines, bills, bill_lines, quotations, purchase_orders, credit_notes, payment_receipts, bank_transactions, tax_forms, tax_filings, payroll_runs, stock_movements, stock_levels, construction_contracts, subcontractors, and many more.

### 13.4 Additional Infrastructure Tables

- Branch management: `branch_tax_registrations`, `branch_users`, `inter_branch_transfers`
- Period control: `period_locks`, `closing_entries`, `closing_checklist_items`
- Auth/Settings: `approvals`, `approval_chains`, `audit_log`, `notifications`, `copilot_*`, `refresh_token_families`
- Data I/O: `import_jobs`, `import_job_errors`, `export_jobs`, `share_links`

---

## 14. Accountant Workflow (7 Phases)

### Phase 1: System Setup (one-time)

1. Create Company (`/companies`)
2. Chart of Accounts (`/chart-of-accounts`) — pre-seeded Thai GAAP
3. Fiscal Periods (`/closing`) — 12 monthly periods
4. Users & Roles (`/settings`) — Super Admin, Senior/Junior Accountant, Auditor
5. Master Data — Customers, Vendors, Bank Accounts

### Phase 2: Daily Operations

- **Sales Cycle**: Quotation → Invoice → Receive Payment (auto-post to Journal)
- **Purchase Cycle**: PO → Bill → Pay (auto-post with WHT)
- **Payroll** (monthly): auto-post to Journal
- **Bank Reconciliation** (daily/weekly)
- **Manual Journals** (as needed)

### Phase 3: Tax Operations

- PP30 (VAT) — due 15th of next month
- PND1/PND3/PND53 (WHT) — due 7th of next month
- e-Tax Invoice/Receipt
- WHT Certificate (50 ทวิ) — after PND1 filing
- PP36 (CIT half-year) / Por40 (CIT annual)

### Phase 4: Reconciliation

- Bank reconciliation (upload statement → AI matching)
- AR/AP aging reconciliation

### Phase 5: Period Close

Checklist: all entries posted, bank reconciled, AR/AP reconciled, depreciation run, tax filed, Trial Balance balanced → Lock period

### Phase 6: Adjusting Entries

- Depreciation, accrued expenses/revenue, prepaid items
- Entry via `/journal/new`, Fixed Asset module, or Recurring Templates

### Phase 7: Financial Statements

- Balance Sheet, Income Statement, Cash Flow, Ratios
- Trial Balance, General Ledger, Working Paper, VAT Report
- Budget Variance, Book-Tax Reconciliation

---

## 15. Key API Endpoints

### Journal Entries

- `POST /api/journals` — Create
- `POST /api/journals/:id/approve` — Approve
- `POST /api/journals/:id/post` — Post (status → posted)
- `POST /api/journals/:id/void` — Void

### Bills & Invoices

- `POST /api/bills` — Create bill (triggers auto-post)
- `POST /api/invoices` — Create invoice (triggers auto-post)

### Tax Forms

- `POST /api/tax-forms` — Create form
- `POST /api/tax-forms/:id/compute` — Compute
- `POST /api/tax-forms/:id/submit` — Submit for review
- `POST /api/filings/:id/approve` — Approve
- `POST /api/filings/:id/file` — File
- `POST /api/filings/:id/acknowledge` — Acknowledge

### Reports

- `GET /api/reports/trial-balance`
- `GET /api/reports/balance-sheet`
- `GET /api/reports/income-statement`
- `GET /api/reports/cash-flow`
- `GET /api/reports/working-paper`
- `GET /api/reports/vat`
- `GET /api/reports/general-ledger`
- `GET /api/reports/aging`
- `GET /api/reports/ratios`
- `GET /api/reports/financial-ratios`

### Closing

- `POST /api/closing-entries` — Generate closing entries

### Payroll

- `POST /api/payrolls` — Create payroll (auto-post to journal)

---

## 16. Key Source Files

| File                                                       | Purpose                                                                    |
| ---------------------------------------------------------- | -------------------------------------------------------------------------- |
| `packages/shared/src/accounting/tax-engine.ts`             | Core tax computation (PP30, PND1/3/53, PP36, Por40)                        |
| `packages/shared/src/accounting/tax-engine-extended.ts`    | Extended tax (PorPor12/4/13, Land, Vehicle, Stamp, BOI, TP)                |
| `packages/shared/src/accounting/tax-engine-extended-v2.ts` | V2 extensions (WHT variants, SBT, Insurance, Hotel, Petroleum, Remittance) |
| `packages/shared/src/accounting/cit-rules.ts`              | 12 CIT add-back rules + progressive tax calculator                         |
| `packages/shared/src/accounting/book-tax-recon.ts`         | Book-tax reconciliation                                                    |
| `packages/shared/src/accounting/ratio-engine.ts`           | Financial ratio analysis                                                   |
| `packages/shared/src/accounting/etax-engine.ts`            | e-Tax Invoice/Receipt generation & validation                              |
| `packages/shared/src/accounting/auto-poster.ts`            | Auto-post Journal Entries from Bills/Invoices                              |
| `packages/shared/src/accounting/closing-engine.ts`         | Period-end closing entries                                                 |
| `packages/shared/src/accounting/payment-engine.ts`         | Payment processing                                                         |
| `packages/shared/src/schemas/schema-pg.ts`                 | Drizzle PostgreSQL schema (57 tables)                                      |
| `packages/shared/src/tax/labels.ts`                        | Tax form labels and metadata                                               |
| `apps/api/src/services/tax.ts`                             | Tax service layer (loadSourceData, computeTaxForm)                         |

---

## 17. Documentation Index

| Document               | URL                            | Content                                                |
| ---------------------- | ------------------------------ | ------------------------------------------------------ |
| Landing Page           | `/`                            | Links to all docs                                      |
| Accounting & Tax Guide | `/ACCOUNTING_TAX_GUIDE.html`   | JE templates, journal entries, reports, tax forms, COA |
| Master Data Analysis   | `/MASTER_DATA_ANALYSIS.html`   | Existing vs missing master data, priority matrix       |
| Workflow Guide         | `/WORKFLOW_GUIDE.html`         | 7-phase accountant workflow                            |
| Data Flow Diagram      | `/data-flow-accos.html`        | Mermaid diagrams, computation patterns, CIT rules      |
| Tax Data Flow Analysis | `/tax-data-flow-analysis.html` | Per-form data source mapping, feature matrix           |
| Tax Forms Report       | `/tax-forms-report.html`       | All 63 tax forms catalog                               |

**Live at:** https://acc-os-pro-docs.pages.dev

---

_Generated 2026-06-30 from AccOS Pro codebase (57 tables, 65 routes, 63 tax forms)._
