> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quinnsambal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Financial goals

<style>
  {`
    [class*="max-w-none"][class*="table"] {
      display: block !important;
      overflow-x: auto !important;
      max-width: 100% !important;
      width: 100% !important;
      flex-grow: 0 !important;
    }
    [class*="max-w-none"][class*="table"] > table {
      width: 100% !important;
      max-width: 100% !important;
      table-layout: fixed !important;
    }
    .mermaid {
      max-width: 100% !important;
      overflow-x: auto !important;
    }
    article svg[role="img"] {
      max-width: 100% !important;
      height: auto !important;
    }
    article img, .prose img {
      max-width: 100% !important;
      height: auto !important;
    }
    img[src*="LOGO"], img[src*="logo"] {
      max-width: 120px !important;
      max-height: 40px !important;
      width: auto !important;
      height: auto !important;
      object-fit: contain !important;
    }
    `}
</style>

***

title: "Financial Goals"
description: "Target keuangan perusahaan — 4 jenis goal, priority system, progress tracking, milestone monitoring, dan investment tracking di SNISHOP ERP."
-----------------------------------------------------------------------------------------------------------------------------------------------------------

# Financial Goals

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/finance/financial-goals.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=33954d7c9a803fe95ffed30a65b17f4d" alt="Financial Goals" width="1920" height="1080" data-path="docs/mintlify/screenshots/finance/financial-goals.png" />

Halaman Financial Goals digunakan untuk menetapkan dan memantau target keuangan perusahaan. Sistem mendukung **4 jenis goal** (savings, debt\_payoff, investment, expense\_reduction), **3 level priority** (low, medium, high), progress tracking real-time dari `target_amount` vs `current_amount`, dan notifikasi otomatis saat milestone tercapai. Setiap goal memiliki `target_date` untuk deadline dan visualisasi progress bar untuk monitoring cepat.

## Arsitektur Financial Goals

```mermaid theme={null}
graph TB
    subgraph SETUP["Setup Goal"]
        TYPE["Pilih Jenis Goal<br/>4 tipe"]
        TARGET["Set Target Amount"]
        CURRENT["Input Current Amount"]
        PRIORITY["Set Priority<br/>Low/Medium/High"]
        DATE["Set Target Date"]
    end

    subgraph TRACKING["Progress Tracking"]
        UPDATE["Update Current Amount<br/>Manual / Auto"]
        CALC["Calculate Progress %"]
        MILESTONE["Check Milestones"]
        ALERT["Alert & Notification"]
    end

    subgraph VISUAL["Visualization"]
        BAR["Progress Bar"]
        CHART["Trend Chart"]
        DASH["Dashboard"]
    end

    SETUP --> TRACKING
    TRACKING --> VISUAL
```

## Entity FinancialGoal

### Field FinancialGoal

| Field | Tipe | Deskripsi |
| - | - | - |
| name | string | Nama goal |
| goal\_type | enum | savings, debt\_payoff, investment, expense\_reduction |
| target\_amount | number | Nominal target |
| current\_amount | number | Nominal saat ini |
| priority | enum | low, medium, high |
| target\_date | date | Deadline pencapaian |
| description | string | Deskripsi goal |
| company\_id | UUID | Multi-tenant isolation |

### 4 Jenis Goal

| Type | Deskripsi | Contoh |
| - | - | - |
| **savings** | Pengumpulan dana | Dana ekspansi, dana darurat, dana pembelian aset |
| **debt\_payoff** | Pelunasan hutang | Lunas hutang bank, lunas hutang supplier |
| **investment** | Investasi | Portofolio saham, reksadana, properti |
| **expense\_reduction** | Pengurangan biaya | Kurangi biaya operasional 20% |

### 3 Level Priority

| Priority | Warna | Use Case |
| - | - | - |
| **High** | Merah | Goal kritis, deadline dekat |
| **Medium** | Kuning | Goal penting, timeline normal |
| **Low** | Hijau | Goal jangka panjang, fleksibel |

## Create Financial Goal

### Step-by-Step

1. Klik **"Create Goal"**
2. Isi form:

| Field | Required | Deskripsi |
| - | - | - |
| Name | ✓ | Nama goal (contoh: "Dana Ekspansi 2026") |
| Goal Type | ✓ | Savings, Debt Payoff, Investment, Expense Reduction |
| Target Amount | ✓ | Nominal target |
| Current Amount | ✓ | Nominal saat ini (bisa 0) |
| Priority | ✓ | Low, Medium, High |
| Target Date | ✓ | Deadline pencapaian |
| Description | Opsional | Detail goal |

3. Save goal
4. Sistem mulai track progress

## Progress Tracking

### Progress Calculation

```
Progress % = (current_amount / target_amount) × 100%
Remaining = target_amount - current_amount
```

### Progress Bar

```mermaid theme={null}
graph LR
    subgraph PROGRESS["Progress Visualization"]
        P0["0%<br/>⬜⬜⬜⬜⬜"]
        P25["25%<br/>🟩⬜⬜⬜⬜"]
        P50["50%<br/>🟩🟩⬜⬜⬜"]
        P75["75%<br/>🟩🟩🟩⬜⬜"]
        P100["100%<br/>🟩🟩🟩🟩🟩"]
    end
```

### Status Based on Progress

| Progress | Status | Deskripsi |
| - | - | - |
| 0% | Not Started | Belum ada progress |
| 1-24% | Just Started | Progress awal |
| 25-49% | In Progress | On track |
| 50-74% | Halfway | Good progress |
| 75-99% | Almost There | Hampir tercapai |
| 100% | Completed | Goal tercapai |

### Auto-Update

`current_amount` bisa diupdate:

| Method | Deskripsi |
| - | - |
| Manual | User input langsung |
| Auto-linked | Terhubung dengan Account/Investment |
| Periodic | Update berkala (mingguan/bulanan) |

## Dashboard Financial Goals

### Goal Cards

Setiap goal ditampilkan sebagai card:

| Component | Deskripsi |
| - | - |
| Name | Nama goal |
| Type Badge | Savings/Debt/Investment/Expense Reduction |
| Priority Badge | Low/Medium/High |
| Progress Bar | Visual progress |
| Amount | Current / Target |
| Remaining | Sisa yang harus dikumpulkan |
| Target Date | Deadline |
| Days Left | Hari menuju deadline |

### Summary Cards

| Metric | Deskripsi |
| - | - |
| Total Goals | Jumlah goal aktif |
| Completed | Goal yang sudah tercapai |
| On Track | Goal dengan progress sesuai timeline |
| At Risk | Goal yang progress-nya terlambat |

### Filter & Sort

| Filter | Opsi |
| - | - |
| Goal Type | Savings, Debt Payoff, Investment, Expense Reduction |
| Priority | Low, Medium, High |
| Status | Not Started, In Progress, Completed, At Risk |

| Sort | Opsi |
| - | - |
| Priority | High → Low |
| Progress | 100% → 0% |
| Target Date | Earliest → Latest |
| Amount | Largest → Smallest |

## Milestone Monitoring

### Milestone Alerts

Sistem mengirim notifikasi saat milestone penting tercapai:

| Milestone | Notifikasi |
| - | - |
| 25% reached | "Selamat! Goal X sudah 25% tercapai" |
| 50% reached | "Halfway! Goal X sudah 50% tercapai" |
| 75% reached | "Almost there! Goal X sudah 75% tercapai" |
| 100% reached | "Completed! Goal X sudah tercapai 100%" |

### Deadline Alerts

| Timing | Alert |
| - | - |
| 30 days before | "Goal X jatuh tempo 30 hari lagi" |
| 7 days before | "Goal X jatuh tempo 7 hari lagi" |
| On deadline | "Goal X jatuh tempo hari ini" |
| Past deadline | "Goal X sudah melewati deadline" |

## Investment Tracking

### Investment Entity

Untuk goal tipe `investment`, sistem terintegrasi dengan entity `Investment`:

| Field | Tipe | Deskripsi |
| - | - | - |
| asset\_type | enum | stocks, mutual\_fund, bond, crypto, property, other |
| purchase\_price | number | Harga beli |
| current\_price | number | Harga terkini |
| gain\_loss | calculated | current\_price - purchase\_price |
| gain\_loss\_% | calculated | (gain\_loss / purchase\_price) × 100% |

### Portfolio Summary

| Metric | Deskripsi |
| - | - |
| Total Investment | Total nilai investasi |
| Total Gain/Loss | Total keuntungan/kerugian |
| Gain/Loss % | Persentase return |
| Asset Allocation | Distribusi per asset type |

## Savings Goals

### Contoh Savings Goals

| Goal | Target | Current | Progress | Deadline |
| - | - | - | - | - |
| Dana Ekspansi | Rp 500.000.000 | Rp 150.000.000 | 30% | 31 Des 2026 |
| Dana Darurat | Rp 100.000.000 | Rp 80.000.000 | 80% | 30 Jun 2026 |
| Beli Kendaraan | Rp 200.000.000 | Rp 50.000.000 | 25% | 31 Des 2027 |

### Auto-Contribution

Jika goal terhubung dengan Account:

```mermaid theme={null}
sequenceDiagram
    participant ACC as Account
    participant G as Goal
    participant D as Dashboard

    ACC->>ACC: Receive income (Rp 5.000.000)
    ACC->>G: Auto-contribute 10% (Rp 500.000)
    G->>G: current_amount += 500.000
    G->>G: Calculate progress %
    G->>D: Update dashboard
```

## Debt Payoff Goals

### Contoh Debt Payoff

| Goal | Target | Current | Progress | Deadline |
| - | - | - | - | - |
| Lunas Hutang Bank | Rp 300.000.000 | Rp 200.000.000 | 67% | 31 Des 2026 |
| Lunas Hutang Supplier | Rp 50.000.000 | Rp 45.000.000 | 90% | 30 Jun 2026 |

### Payoff Strategy

| Strategy | Deskripsi |
| - | - |
| Snowball | Bayar hutang terkecil dulu |
| Avalanche | Bayar hutang bunga tertinggi dulu |
| Custom | Strategi custom |

## Expense Reduction Goals

### Contoh Expense Reduction

| Goal | Target | Current | Progress | Deadline |
| - | - | - | - | - |
| Kurangi Biaya Operasional 20% | Rp 10.000.000 | Rp 8.000.000 | 80% | 31 Des 2026 |

### Tracking

* Compare actual expense vs baseline
* Calculate reduction amount
* Track monthly progress

## Reporting

### Goal Summary

| Metric | Deskripsi |
| - | - |
| Total Goals | Jumlah goal |
| Completed | Goal tercapai |
| In Progress | Goal sedang berjalan |
| At Risk | Goal terlambat |
| Success Rate | Completed / Total × 100% |

### Progress by Type

| Type | Count | Avg Progress |
| - | - | - |
| Savings | 5 | 45% |
| Debt Payoff | 2 | 78% |
| Investment | 3 | 32% |
| Expense Reduction | 1 | 80% |

## Best Practices

### Goal Setting

* Tetapkan target yang realistis dan terukur (SMART)
* Set tenggat waktu yang jelas
* Pecah goal besar menjadi milestone kecil
* Prioritaskan goal berdasarkan urgensi

### Monitoring

* Review progress minimal sebulan sekali
* Track trend (apakah progress melambat?)
* Adjust target jika kondisi bisnis berubah
* Celebrate milestones untuk motivasi

### Strategy

* Gunakan data historis untuk proyeksi
* Align goals dengan business strategy
* Balance short-term vs long-term goals
* Regular review dan adjustment

***

## Entity Schema Reference

### ER Diagram — Financial Goal Entities

```mermaid theme={null}
erDiagram
    User ||--o{ FinancialGoal : "memiliki"
    User ||--o{ Investment : "memiliki"
    User ||--o{ Account : "memiliki"
    User ||--o{ FinancialRecord : "mencatat"
    User ||--o{ Budget : "membuat"

    Company ||--o{ FinancialGoal : "memiliki"
    Company ||--o{ Investment : "memiliki"
    Company ||--o{ Account : "memiliki"
    Company ||--o{ FinancialRecord : "mencatat"
    Company ||--o{ Budget : "membuat"

    FinancialGoal }o--o| Budget : "related_budget_id"
    FinancialGoal }o--o{ Investment : "goal_type=investment"
    FinancialRecord }o--|| Account : "account_id"
    FinancialRecord }o--o| FinancialRecord : "transfer_to_account_id"

    FinancialGoal {
        string id PK
        string user_id FK
        string company_id FK "nullable"
        string title
        string description
        enum goal_type "savings|debt_payoff|investment|expense_reduction"
        number target_amount
        number current_amount "default 0"
        date deadline
        enum status "active|paused|completed|failed"
        enum priority "low|medium|high"
        string related_budget_id FK "nullable"
    }

    Investment {
        string id PK
        string user_id FK
        string company_id FK "nullable"
        string asset_name
        enum asset_type "stocks|mutual_fund|bond|crypto|property|other"
        number quantity
        number purchase_price
        date purchase_date
        number current_price
        number current_value
        string currency "default IDR"
        string platform
        string notes
    }

    Account {
        string id PK
        string user_id FK
        string company_id FK "nullable"
        string name
        enum type "cash|bank|e-wallet|other"
        string account_number
        string bank_name
        number initial_balance
        number current_balance
        string currency "default IDR"
        string icon
        string color
        boolean is_active
        boolean is_default_pos
        string notes
        enum mode "personal|business"
    }

    FinancialRecord {
        string id PK
        string user_id FK
        string company_id FK "nullable"
        string account_id FK
        enum type "income|expense|transfer"
        number amount
        string category
        string description
        datetime date
        string attachment_url
        enum source "manual|ai_text|ai_scan|pos|manufacturing|distribution|recall|stock_opname"
        enum mode "personal|business"
        string transfer_to_account_id FK
        number transfer_fee
        string reference_id
        enum reference_type
        string idempotency_key
        boolean is_inventory_material
        number channel_fee
        number cogs_amount
        number tax_amount
    }

    Budget {
        string id PK
        string user_id FK
        string company_id FK "nullable"
        string name
        string description
        string category
        number planned_amount
        number actual_amount
        enum period "monthly|quarterly|yearly|custom"
        date start_date
        date end_date
        enum status "active|completed|archived"
        number alert_threshold
    }
```

### Tabel Schema — FinancialGoal

| Field | Tipe | Required | Default | Deskripsi |
| - | - | - | - | - |
| `id` | string (UUID) | PK | auto-generated | Primary key |
| `user_id` | string (UUID) | ✓ | — | ID pengguna pemilik tujuan |
| `company_id` | string (UUID) | — | null | ID perusahaan (null untuk personal) |
| `title` | string | ✓ | — | Judul tujuan keuangan |
| `description` | string | — | — | Deskripsi detail tujuan |
| `goal_type` | enum | ✓ | — | Jenis tujuan: `savings`, `debt_payoff`, `investment`, `expense_reduction` |
| `target_amount` | number | ✓ | — | Jumlah target yang ingin dicapai |
| `current_amount` | number | — | 0 | Jumlah yang sudah terkumpul/terbayar |
| `deadline` | date | ✓ | — | Tanggal target pencapaian |
| `status` | enum | — | `active` | Status goal: `active`, `paused`, `completed`, `failed` |
| `priority` | enum | — | `medium` | Prioritas: `low`, `medium`, `high` |
| `related_budget_id` | string (UUID) | — | null | ID Budget terkait (jika ada) |

### Tabel Schema — Investment

| Field | Tipe | Required | Default | Deskripsi |
| - | - | - | - | - |
| `id` | string (UUID) | PK | auto-generated | Primary key |
| `user_id` | string (UUID) | ✓ | — | ID pengguna pemilik investasi |
| `company_id` | string (UUID) | — | null | ID perusahaan (null untuk personal) |
| `asset_name` | string | ✓ | — | Nama aset investasi |
| `asset_type` | enum | ✓ | — | Jenis aset: `stocks`, `mutual_fund`, `bond`, `crypto`, `property`, `other` |
| `quantity` | number | ✓ | — | Jumlah/unit kepemilikan |
| `purchase_price` | number | ✓ | — | Harga pembelian per unit |
| `purchase_date` | date | ✓ | — | Tanggal pembelian |
| `current_price` | number | — | — | Harga pasar saat ini per unit |
| `current_value` | number | — | — | Total nilai investasi saat ini (`current_price * quantity`) |
| `currency` | string | — | `IDR` | Mata uang |
| `platform` | string | — | — | Platform atau perusahaan penyedia investasi |
| `notes` | string | — | — | Catatan tambahan |

### Tabel Schema — Account

| Field | Tipe | Required | Default | Deskripsi |
| - | - | - | - | - |
| `id` | string (UUID) | PK | auto-generated | Primary key |
| `user_id` | string (UUID) | ✓ | — | ID pengguna pemilik rekening |
| `company_id` | string (UUID) | — | null | ID perusahaan (null untuk personal) |
| `name` | string | ✓ | — | Nama rekening/kantong (contoh: Kas, BCA, Mandiri, Dompet) |
| `type` | enum | ✓ | `cash` | Jenis rekening: `cash`, `bank`, `e-wallet`, `other` |
| `account_number` | string | — | — | Nomor rekening (opsional) |
| `bank_name` | string | — | — | Nama bank (untuk `type=bank`) |
| `initial_balance` | number | — | 0 | Saldo awal |
| `current_balance` | number | — | 0 | Saldo saat ini (server-authoritative) |
| `currency` | string | — | `IDR` | Mata uang |
| `icon` | string | — | 💰 | Icon rekening untuk UI |
| `color` | string | — | `#3B82F6` | Warna untuk UI |
| `is_active` | boolean | — | true | Status aktif rekening |
| `is_default_pos` | boolean | — | false | Rekening default untuk POS Kasir |
| `notes` | string | — | — | Catatan tambahan |
| `mode` | enum | — | `personal` | Mode rekening: `personal`, `business` |

### Tabel Schema — FinancialRecord

| Field | Tipe | Required | Default | Deskripsi |
| - | - | - | - | - |
| `id` | string (UUID) | PK | auto-generated | Primary key |
| `user_id` | string (UUID) | ✓ | — | ID pengguna |
| `company_id` | string (UUID) | — | null | ID perusahaan (null untuk personal) |
| `account_id` | string (UUID) | — | — | ID rekening/kantong sumber dana |
| `type` | enum | ✓ | — | Jenis transaksi: `income`, `expense`, `transfer` |
| `amount` | number | ✓ | — | Jumlah transaksi |
| `category` | string | — | — | Kategori transaksi |
| `description` | string | — | — | Deskripsi singkat |
| `date` | datetime | ✓ | — | Tanggal transaksi |
| `attachment_url` | string | — | — | URL bukti transaksi |
| `source` | enum | — | `manual` | Sumber: `manual`, `ai_text`, `ai_scan`, `pos`, `manufacturing`, `distribution`, `recall`, `stock_opname` |
| `mode` | enum | — | `personal` | Mode: `personal`, `business` |
| `transfer_to_account_id` | string (UUID) | — | — | ID rekening tujuan (untuk `type=transfer`) |
| `transfer_fee` | number | — | 0 | Biaya transfer (jika ada) |
| `reference_id` | string | — | — | ID referensi transaksi sumber (invoice, POS, expense) |
| `reference_type` | enum | — | — | Tipe referensi: `invoice_payment`, `pos_transaction`, `expense`, `manual`, `transfer`, `production_order`, `distribution_shipment`, `distribution_return`, `batch_recall`, `stock_opname` |
| `idempotency_key` | string | — | — | Kunci idempoten transaksi keuangan |
| `is_inventory_material` | boolean | — | false | Apakah pembelian bahan baku persediaan (anti double-counting) |
| `channel_fee` | number | — | 0 | Potongan biaya marketplace / platform fee |
| `cogs_amount` | number | — | 0 | Biaya pokok penjualan (HPP/COGS) |
| `tax_amount` | number | — | 0 | Jumlah pajak yang termasuk dalam amount |

***

## State Machine — Goal Lifecycle

```mermaid theme={null}
stateDiagram-v2
    [*] --> active : Create Goal

    active --> active : Update current_amount
    active --> active : Progress tracking
    active --> paused : User pause goal
    active --> completed : current_amount >= target_amount
    active --> failed : deadline terlewat & progress < target

    paused --> active : User resume goal
    paused --> completed : Auto-complete jika target tercapai
    paused --> failed : deadline terlewat saat paused

    completed --> [*] : Goal tercapai (archived)
    failed --> active : User reactivate & extend deadline
    failed --> [*] : Goal dihapus

    state active {
        [*] --> tracking
        tracking --> milestone_25 : 25% tercapai
        milestone_25 --> milestone_50 : 50% tercapai
        milestone_50 --> milestone_75 : 75% tercapai
        milestone_75 --> milestone_100 : 100% tercapai
        milestone_100 --> [*]
    }

    note right of active
        Progress = (current_amount / target_amount) × 100%
        Notifikasi otomatis pada setiap milestone
    end note

    note right of completed
        Trigger: current_amount >= target_amount
        Status otomatis berubah menjadi completed
    end note

    note right of failed
        Trigger: deadline < today AND status = active
        Cron job memeriksa setiap hari
    end note
```

### Transisi Status

| Dari | Ke | Trigger | Deskripsi |
| - | - | - | - |
| `[*]` | `active` | Create goal | Goal baru dibuat langsung aktif |
| `active` | `paused` | User pause | User menjeda goal sementara |
| `active` | `completed` | `current_amount >= target_amount` | Target tercapai secara otomatis |
| `active` | `failed` | `deadline < today` | Deadline terlewat tanpa target tercapai |
| `paused` | `active` | User resume | User melanjutkan goal yang dijeda |
| `paused` | `completed` | Target tercapai | Auto-complete meskipun paused |
| `paused` | `failed` | `deadline < today` | Deadline terlewat saat paused |
| `failed` | `active` | User reactivate | User mengaktifkan ulang dengan deadline baru |

***

## Sequence Diagrams

### 1. Goal Creation Flow

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant FE as Frontend
    participant API as Backend API
    participant DB as Database
    participant NOTIF as Notification Service

    U->>FE: Klik "Create Goal"
    FE->>FE: Tampilkan form (title, goal_type, target_amount, priority, deadline)
    U->>FE: Isi form & submit
    
    FE->>API: POST /api/financial-goals
    Note over FE,API: Payload: {title, goal_type, target_amount, current_amount, priority, deadline, description}
    
    API->>API: Validasi required fields
    API->>API: Validasi goal_type ∈ {savings, debt_payoff, investment, expense_reduction}
    API->>API: Validasi priority ∈ {low, medium, high}
    API->>API: Validasi target_amount > 0
    API->>API: Validasi deadline > today
    
    API->>DB: INSERT INTO financial_goals
    DB-->>API: Return created record (status=active)
    
    API->>NOTIF: Trigger: Goal baru dibuat
    NOTIF-->>U: "Goal '{title}' berhasil dibuat"
    
    API-->>FE: 201 Created
    FE->>FE: Redirect ke goal detail
    FE->>FE: Render progress bar (0%)
```

### 2. Progress Tracking Flow

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant FE as Frontend
    participant API as Backend API
    participant DB as Database
    participant CALC as Progress Engine
    participant NOTIF as Notification Service

    U->>FE: Update current_amount
    FE->>API: PATCH /api/financial-goals/{id}
    Note over FE,API: Payload: {current_amount: new_value}
    
    API->>DB: SELECT financial_goal WHERE id = {id}
    DB-->>API: Return goal data
    
    API->>CALC: Calculate progress
    CALC->>CALC: progress = (current_amount / target_amount) × 100%
    CALC->>CALC: remaining = target_amount - current_amount
    
    alt progress >= 100%
        CALC->>API: Set status = "completed"
        API->>DB: UPDATE status = "completed"
        API->>NOTIF: Trigger: Goal tercapai!
        NOTIF-->>U: "Selamat! Goal '{title}' telah tercapai 100%"
    else milestone tercapai (25%, 50%, 75%)
        CALC->>NOTIF: Trigger milestone alert
        NOTIF-->>U: "Goal '{title}' sudah {milestone}% tercapai"
    end
    
    API->>DB: UPDATE current_amount, progress
    DB-->>API: Return updated record
    
    API-->>FE: 200 OK
    FE->>FE: Update progress bar
    FE->>FE: Update remaining amount display
```

### 3. Goal Achievement & Investment Linking

```mermaid theme={null}
sequenceDiagram
    participant U as User
    participant FE as Frontend
    participant API as Backend API
    participant DB as Database
    participant INV as Investment Service
    participant ACC as Account Service
    participant NOTIF as Notification Service

    Note over U,NOTIF: Skenario: Goal tipe investment dengan auto-link ke Investment entity

    U->>FE: Buat goal (goal_type = "investment")
    FE->>API: POST /api/financial-goals
    API->>DB: Create goal (status=active)
    
    U->>FE: Tambah investment baru
    FE->>API: POST /api/investments
    API->>INV: Create investment record
    INV->>DB: INSERT INTO investments
    
    INV->>API: Link investment ke goal
    API->>DB: UPDATE financial_goal SET current_amount += investment.current_value
    
    loop Periodic Sync (harian)
        INV->>INV: Fetch current_price dari market
        INV->>DB: UPDATE investments SET current_price, current_value
        INV->>API: Recalculate goal current_amount
        API->>DB: UPDATE financial_goal SET current_amount = SUM(linked investments)
    end
    
    alt current_amount >= target_amount
        API->>DB: UPDATE status = "completed"
        API->>NOTIF: Goal tercapai!
        NOTIF-->>U: "Investment goal '{title}' berhasil dicapai!"
    end

    Note over U,NOTIF: Skenario: Auto-contribution dari Account

    U->>FE: Setup auto-contribution
    FE->>API: POST /api/financial-goals/{id}/auto-contribute
    API->>ACC: Link account ke goal
    
    loop Setiap ada income masuk
        ACC->>ACC: Receive income
        ACC->>API: Trigger auto-contribute (persentase tertentu)
        API->>DB: UPDATE financial_goal SET current_amount += contribution
        API->>CALC: Recalculate progress
    end
```

***

## Enum Tables

### goal\_type

| Value | Label (ID) | Deskripsi | Contoh Use Case |
| - | - | - | - |
| `savings` | Tabungan | Pengumpulan dana untuk tujuan tertentu | Dana ekspansi, dana darurat, dana pembelian aset |
| `debt_payoff` | Pelunasan Hutang | Pelunasan kewajiban/hutang | Lunas hutang bank, lunas hutang supplier |
| `investment` | Investasi | Pertumbuhan nilai melalui instrumen investasi | Portofolio saham, reksadana, obligasi, properti |
| `expense_reduction` | Pengurangan Biaya | Menurunkan pengeluaran hingga target tertentu | Kurangi biaya operasional 20% |

### goal\_status

| Value | Label (ID) | Deskripsi | Kondisi |
| - | - | - | - |
| `active` | Aktif | Goal sedang berjalan dan dipantau | Default saat dibuat, progress \< 100% dan belum melewati deadline |
| `paused` | Dijeda | Goal sementara dihentikan oleh user | User memilih untuk menjeda sementara |
| `completed` | Tercapai | Goal berhasil dicapai | `current_amount >= target_amount` |
| `failed` | Gagal | Goal gagal dicapai dalam deadline | `deadline < today` dan `current_amount < target_amount` |

### priority

| Value | Label (ID) | Warna Badge | Deskripsi | SLA Review |
| - | - | - | - | - |
| `high` | Tinggi | Merah | Goal kritis dengan deadline dekat atau dampak besar | Mingguan |
| `medium` | Sedang | Kuning | Goal penting dengan timeline normal | Bulanan |
| `low` | Rendah | Hijau | Goal jangka panjang, fleksibel timeline-nya | Kuartalan |

### asset\_type (Investment)

| Value | Label (ID) | Deskripsi | Contoh |
| - | - | - | - |
| `stocks` | Saham | Instrumen ekuitas publik | Saham BBCA, TLKM, BBRI |
| `mutual_fund` | Reksadana | Dana investasi dikelola manajer | Reksadana pendapatan tetap |
| `bond` | Obligasi | Surat hutang (pemerintah/korporasi | SBN, ORA, obligasi korporasi |
| `crypto` | Kripto | Aset digital terdesentralisasi | Bitcoin, Ethereum |
| `property` | Properti | Aset tidak bergerak | Tanah, gedung, ruko |
| `other` | Lainnya | Jenis aset di luar kategori above | Emas, barang koleksi, P2P lending |

### account\_type

| Value | Label (ID) | Deskripsi | Contoh |
| - | - | - | - |
| `cash` | Tunai | Uang tunai fisik | Kas kecil, dompet |
| `bank` | Bank | Rekening bank | BCA, Mandiri, BNI, BRI |
| `e-wallet` | E-Wallet | Dompet digital | GoPay, OVO, DANA, ShopeePay |
| `other` | Lainnya | Akun keuangan lainnya | PayPal, Payoneer |

### financial\_record\_type

| Value | Label (ID) | Deskripsi | Efek pada Saldo |
| - | - | - | - |
| `income` | Pemasukan | Uang masuk | `current_balance` bertambah |
| `expense` | Pengeluaran | Uang keluar | `current_balance` berkurang |
| `transfer` | Transfer | Perpindahan antar rekening | Sumber berkurang, tujuan bertambah |

***

## RBAC — Hak Akses Financial Goals

| Role | Create | Read | Update | Delete | Deskripsi |
| - | - | - | - | - | - |
| **Admin** | ✓ | ✓ | ✓ | ✓ | Akses penuh ke semua goal dalam perusahaan |
| **Manager** | ✓ | ✓ | ✓ | ✗ | Dapat membuat dan mengelola goal, tidak bisa hapus |
| **Staff** | ✓ | ✓ | ✓ (own) | ✗ | Dapat membuat goal sendiri, update goal sendiri |
| **Viewer** | ✗ | ✓ | ✗ | ✗ | Hanya bisa melihat goal (read-only) |

### Row-Level Security (RLS)

| Operasi | Kondisi Akses | Deskripsi |
| - | - | - |
| **Create** | `company_id = user.active_company_id` AND `company_id IS NOT NULL` | User harus berada dalam perusahaan yang aktif |
| **Read** | `company_id = user.active_company_id` OR `user_id = current_user` OR `role = admin` | User bisa baca goal perusahaan atau goal pribadi |
| **Update** | `company_id = user.active_company_id` OR `user_id = current_user` OR `role = admin` | Same as read — owner atau admin |
| **Delete** | `company_id = user.active_company_id` OR `user_id = current_user` OR `role = admin` | Same as read — owner atau admin |

### Data Isolation

```mermaid theme={null}
graph LR
    subgraph TENANT["Multi-Tenant Isolation"]
        C1["Company A"] --> FG1["Financial Goals A"]
        C1 --> INV1["Investments A"]
        C1 --> ACC1["Accounts A"]
        C1 --> FR1["Financial Records A"]
        
        C2["Company B"] --> FG2["Financial Goals B"]
        C2 --> INV2["Investments B"]
        C2 --> ACC2["Accounts B"]
        C2 --> FR2["Financial Records B"]
    end
    
    U1["User 1 (Company A)"] --> C1
    U2["User 2 (Company B)"] --> C2
    U3["Admin"] --> C1
    U3 --> C2
    
    style TENANT fill:#f0f9ff,stroke:#3b82f6
    style C1 fill:#dcfce7,stroke:#22c55e
    style C2 fill:#fef3c7,stroke:#f59e0b
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.