# CHM ERP Model Map

Reference documentation for all Eloquent models in `app/Models/`. Generated from model source analysis only (controllers and services not included).

**Total models:** 91

---

## Domain Overview

| Domain | Models |
|--------|--------|
| CFDP / Child Sponsorship | Children, ChildSponsor, ChildStatus, ChildUpdate, CStatus, Cluster, Church, Pastor, Sponsor, Sponsorship, Guardian, Gift, Donation, Letter, LetterProgress, School, Country |
| Hope Coffee | Farmer, Group, Grn, CoffeeStock, CoffeePurchase, CoffeeProcessing, CoffeeProcessingScreen, CoffeeSale, Buyer, PaymentVoucher, Advance, AdvancePayment, StockTransfer, Roasting, Grinding, Packaging, BeverageSale |
| Accounting / Finance | Account, AccountEntity, JournalEntry, JournalEntryLine, Invoice, InvoiceLine, ArPayment, Vendor, VendorBill, VendorBillLine, ApPayment, BankAccount, BankTransaction, BankStatementLine, BankReconciliation, Budget, BudgetLine, FixedAsset, AssetCategory, DepreciationEntry, TaxRate, TaxProvision, WithholdingEntry, Intercompany, Entity, Currency, FxRate, Customer |
| HR / Recruitment | User, Employee, Department, Payroll, PayrollLine, Applicant, ApplicantEducation, ApplicantExperience, ApplicantSkill, ApplicantPosition, ApplicantNotification, Job, JobSection |
| Transformation / Projects | Project, ProjectTransaction, ProjectResourceCost, Resource, District, SubCounty, Village |
| Reporting / Admin | Report, ReportType, ReportWorkflow, ReportAttachment, ReportComment, SiteSetting, SmtpSetting, PermissionGroup, Message |

---

## Models (Alphabetical)

### Account

| | |
|---|---|
| **Table** | `accounts` |
| **Primary Key** | `id` |

**Relationships**
- `parent()` → belongsTo `Account`
- `children()` → hasMany `Account`
- `childrenRecursive()` → hasMany `Account` (eager-loaded recursive tree)
- `lines()` → hasMany `JournalEntryLine`
- `accountEntity()` → hasOne `AccountEntity`

**Important Methods**
- `getFullNameAttribute()` — hierarchical display path (e.g. `1000 › Cash › Petty Cash`)
- `entity()` — resolves linked Farmer/Buyer/Employee via `AccountEntity` pivot
- `currentBalance()` — sums debits minus credits for this account
- `ensurePayrollAccount()` — returns self (payroll account stub)

**Business Purpose**
Chart of accounts node in a hierarchical general ledger. Links to journal lines and optionally to operational entities (farmers, buyers, employees) via a polymorphic pivot. Supports balance calculation and nested account naming.

---

### AccountEntity

| | |
|---|---|
| **Table** | `account_entities` |
| **Primary Key** | `id` |

**Relationships**
- `account()` → belongsTo `Account`
- `entity()` → morphTo (Farmer, Buyer, Employee, etc.)

**Important Methods**
None beyond relationships.

**Business Purpose**
Polymorphic pivot linking GL accounts to operational entities, enabling per-entity sub-accounts under control accounts such as Accounts Receivable (1020).

---

### Advance

| | |
|---|---|
| **Table** | `advances` |
| **Primary Key** | `id` |

**Relationships**
- `farmer()` → belongsTo `Farmer`

**Important Methods**
- `getTransportRemainAttribute()`, `getAdvanceRemainAttribute()`, `getTarpaulinRemainAttribute()` — remaining balances per advance category
- `getTotalAdvanceTakenAttribute()`, `getAdvanceRemainingAttribute()` — aggregate advance totals
- `resolveArAccount()` — static; returns farmer A/R account code for GL posting
- `allocateCreditCashAtBank()` — static; allocates disbursement across cash-at-bank sub-accounts

**Business Purpose**
Tracks farmer advance payments (transport, general advance, tarpaulin) with approval, disbursement workflow, and GL integration for cash allocation and A/R resolution.

---

### AdvancePayment

| | |
|---|---|
| **Table** | `advance_payments` |
| **Primary Key** | `id` |

**Relationships**
- `advance()` → belongsTo `Advance`
- `payer()` → belongsTo `User`

**Important Methods**
None beyond relationships.

**Business Purpose**
Records individual payment transactions against a farmer advance, including amount, date, method, and proof of payment.

---

### Applicant

| | |
|---|---|
| **Table** | `applicants` |
| **Primary Key** | `id` |
| **Extends** | `Authenticatable` |

**Relationships**
- `applications()` → hasMany `ApplicantPosition`
- `positions()` → hasMany `ApplicantPosition` (duplicate alias of applications)
- `experiences()` → hasMany `ApplicantExperience`
- `education()` → hasMany `ApplicantEducation`
- `skills()` → hasMany `ApplicantSkill`
- `notifications()` → hasMany `ApplicantNotification`
- `job()` → belongsTo `Job`

**Important Methods**
- `setPasswordAttribute()` — bcrypt-hashes password on assignment

**Business Purpose**
Authenticatable job portal user with profile, applications, work history, education, skills, and in-app notifications.

---

### ApplicantEducation

| | |
|---|---|
| **Table** | `applicant_educations` |
| **Primary Key** | `id` |

**Relationships**
- `applicant()` → belongsTo `Applicant`

**Important Methods**
None.

**Business Purpose**
Educational background entries (school, degree, dates) attached to a job applicant profile.

---

### ApplicantExperience

| | |
|---|---|
| **Table** | `applicant_experiences` |
| **Primary Key** | `id` |

**Relationships**
- `applicant()` → belongsTo `Applicant`

**Important Methods**
None.

**Business Purpose**
Work experience entries (company, role, dates, description) attached to a job applicant.

---

### ApplicantNotification

| | |
|---|---|
| **Table** | `applicant_notifications` |
| **Primary Key** | `id` |

**Relationships**
- `applicant()` → belongsTo `Applicant`

**Important Methods**
None. Casts `read` to boolean.

**Business Purpose**
In-app notifications for job applicants (title, message, read status).

---

### ApplicantPosition

| | |
|---|---|
| **Table** | `applicant_positions` |
| **Primary Key** | `id` |

**Relationships**
- `applicant()` → belongsTo `Applicant`
- `job()` → belongsTo `Job`

**Important Methods**
None.

**Business Purpose**
Join record linking an applicant to a job posting, including uploaded CV file.

---

### ApplicantSkill

| | |
|---|---|
| **Table** | `applicant_skills` |
| **Primary Key** | `id` |

**Relationships**
- `applicant()` → belongsTo `Applicant`

**Important Methods**
None.

**Business Purpose**
Skills and proficiency levels listed on an applicant profile.

---

### ApPayment

| | |
|---|---|
| **Table** | `ap_payments` |
| **Primary Key** | `id` |

**Relationships**
- `bill()` → belongsTo `VendorBill`

**Important Methods**
None.

**Business Purpose**
Accounts-payable payment applied against a vendor bill (date, amount, method, notes).

---

### ArPayment

| | |
|---|---|
| **Table** | `ar_payments` |
| **Primary Key** | `id` |

**Relationships**
- `invoice()` → belongsTo `Invoice`

**Important Methods**
None.

**Business Purpose**
Accounts-receivable payment received against a customer or buyer invoice.

---

### AssetCategory

| | |
|---|---|
| **Table** | `asset_categories` |
| **Primary Key** | `id` |

**Relationships**
- `fixedAssets()` → hasMany `FixedAsset`

**Important Methods**
None.

**Business Purpose**
Classification group for fixed assets (name, description), used for organizing depreciation schedules.

---

### BankAccount

| | |
|---|---|
| **Table** | `bank_accounts` |
| **Primary Key** | `id` |

**Relationships**
- `transactions()` → hasMany `BankTransaction`

**Important Methods**
None.

**Business Purpose**
Represents a physical bank account (name, IBAN) and its transaction history.

---

### BankReconciliation

| | |
|---|---|
| **Table** | `bank_reconciliations` |
| **Primary Key** | `id` |

**Relationships**
- `account()` → belongsTo `Account`

**Important Methods**
None.

**Business Purpose**
Monthly bank reconciliation comparing bank statement balance vs. system GL balance, tracking charges, adjustments, and reconciliation status.

---

### BankStatementLine

| | |
|---|---|
| **Table** | `bank_statement_lines` |
| **Primary Key** | `id` |

**Relationships**
- `bankAccount()` → belongsTo `Account` (via `bank_account_id`)

**Important Methods**
None.

**Business Purpose**
Individual line imported from a bank statement for reconciliation (date, description, amount, type, reference, reconciled flag).

---

### BankTransaction

| | |
|---|---|
| **Table** | `bank_transactions` |
| **Primary Key** | `id` |

**Relationships**
- `bankAccount()` → belongsTo `BankAccount`
- `journalLine()` → belongsTo `JournalEntryLine`

**Important Methods**
None.

**Business Purpose**
Bank-side transaction linked to a bank account and optionally matched to a journal entry line for reconciliation.

---

### BeverageSale

| | |
|---|---|
| **Table** | `beverage_sales` |
| **Primary Key** | `id` |

**Relationships**
- `source()` → morphTo (Roasting, Grinding, Packaging, etc.)
- `user()` → belongsTo `User`
- `customer()` → belongsTo `User` (via `customer_id`)

**Important Methods**
None.

**Business Purpose**
Records retail or wholesale beverage sales from processed coffee products, with polymorphic link to the production batch source.

---

### Budget

| | |
|---|---|
| **Table** | `budgets` |
| **Primary Key** | `id` |

**Relationships**
- `lines()` → hasMany `BudgetLine`

**Important Methods**
None.

**Business Purpose**
Top-level budget header with name, date range, and notes; contains budget lines per account.

---

### BudgetLine

| | |
|---|---|
| **Table** | `budget_lines` |
| **Primary Key** | `id` |

**Relationships**
- `budget()` → belongsTo `Budget`
- `account()` → belongsTo `Account`

**Important Methods**
None.

**Business Purpose**
Individual budget allocation for a GL account within a budget period.

---

### Buyer

| | |
|---|---|
| **Table** | `buyers` |
| **Primary Key** | `id` |

**Relationships**
- `coffeeSales()` → hasMany `CoffeeSale`
- `accountEntity()` → morphOne `AccountEntity`
- `account()` — convenience accessor via `accountEntity`

**Important Methods**
- `ensureArAccount()` — get or create A/R sub-account under control account `1020`

**Business Purpose**
Coffee buyer/customer entity with contact details, sales history, and dedicated accounts-receivable GL sub-account.

---

### ChildSponsor

| | |
|---|---|
| **Table** | `child_sponsor` |
| **Primary Key** | `id` |

**Relationships**
None defined in model.

**Important Methods**
None. Uses `$guarded = []`.

**Business Purpose**
Pivot table linking sponsored children to their sponsors (many-to-many bridge between `child` and `sponsor`).

---

### ChildStatus

| | |
|---|---|
| **Table** | `child_status` |
| **Primary Key** | `id_status` |

**Relationships**
- `children()` → hasMany `Children`
- `status()` → belongsTo `ChildStatus` (self-referential; likely legacy)

**Important Methods**
None.

**Business Purpose**
Lookup/reference table for child sponsorship status codes (active, graduated, terminated, etc.).

---

### ChildUpdate

| | |
|---|---|
| **Table** | `child_updates` |
| **Primary Key** | `id` |

**Relationships**
- `child()` → belongsTo `Children`
- `school()` → belongsTo `School`
- `guardian()` → belongsTo `Guardian`

**Important Methods**
None.

**Business Purpose**
Periodic social-worker field visit report for a sponsored child — schooling, home conditions, church attendance, family, coffee harvest, photos, and remarks.

---

### Children

| | |
|---|---|
| **Table** | `child` |
| **Primary Key** | `id_child` |

**Relationships**
- `sponsor()` → hasOneThrough `Sponsor` (via `ChildSponsor`)
- `sponsorship()` → hasOne `Sponsorship`
- `child_status()` → belongsTo `ChildStatus`
- `letterProgress()` → hasMany `LetterProgress`
- `gifts()` → hasMany `Gift`
- `cStatusLogs()` → hasMany `CStatus`
- `cluster()` → belongsTo `Cluster`
- `guardianModel()` → belongsTo `Guardian`
- `childUpdates()` → hasMany `ChildUpdate`
- `country()` → belongsTo `Country`
- `latestUpdate()` → hasOne `ChildUpdate` (latestOfMany)
- `latestSchool()` → hasOneThrough `School` (via latest `ChildUpdate`)

**Important Methods**
None beyond relationships.

**Business Purpose**
Core child sponsorship record — demographic info, family/guardian details, cluster assignment, sponsor linkage, status history, letters, gifts, and field updates.

---

### Church

| | |
|---|---|
| **Table** | `church` |
| **Primary Key** | `id_church` |

**Relationships**
- `pastors()` → hasMany `Pastor`

**Important Methods**
None.

**Business Purpose**
Church entity in the organizational hierarchy; pastors are assigned to churches.

---

### Cluster

| | |
|---|---|
| **Table** | `cluster` |
| **Primary Key** | `id_cluster` |

**Relationships**
- `children()` → hasMany `Children`
- `pastors()` → hasMany `Pastor`

**Important Methods**
None.

**Business Purpose**
Geographic/organizational cluster grouping sponsored children and assigned pastors within the child sponsorship program.

---

### CoffeeProcessing

| | |
|---|---|
| **Table** | `coffee_processings` |
| **Primary Key** | `id` |

**Relationships**
- `purchase()` → belongsTo `CoffeePurchase`
- `screens()` → hasMany `CoffeeProcessingScreen`

**Important Methods**
None.

**Business Purpose**
Processing event for purchased coffee (type, quantity, date) that produces screened/graded output.

---

### CoffeeProcessingScreen

| | |
|---|---|
| **Table** | `coffee_processing_screens` |
| **Primary Key** | `id` |

**Relationships**
- `processing()` → belongsTo `CoffeeProcessing`
- `stock()` → belongsTo `CoffeeStock`
- `stocks()` → belongsToMany `CoffeeStock` (pivot: `coffee_processing_screen_stocks`)

**Important Methods**
None.

**Business Purpose**
Screen/grade output from a processing run, linking to one or more stock entries with quantities per screen size.

---

### CoffeePurchase

| | |
|---|---|
| **Table** | `coffee_purchases` |
| **Primary Key** | `id` |

**Relationships**
- `farmer()` → belongsTo `Farmer`

**Important Methods**
None.

**Business Purpose**
Direct coffee purchase from a farmer (date, weight, price, reference) as the upstream source for processing and inventory.

---

### CoffeeSale

| | |
|---|---|
| **Table** | `coffee_sales` |
| **Primary Key** | `id` |

**Relationships**
- `buyer()` → belongsTo `Buyer`
- `coffeeStocks()` → belongsToMany `CoffeeStock` (pivot: quantity, purchase_price)

**Important Methods**
- `resolveArAccount()` — static; buyer A/R account code for GL
- `mcLossAmount()`, `inventoryReductionAmount()` — static COGS/inventory calculations
- `calculateCogsNet()`, `calculateInventoryReduction()` — static cost helpers

**Business Purpose**
Coffee export or domestic sale to a buyer with weight grading, MC deductions, pricing, and inventory/COGS accounting integration.

---

### CoffeeStock

| | |
|---|---|
| **Table** | `coffee_stocks` |
| **Primary Key** | `id` |

**Relationships**
- `grn()` → belongsTo `Grn`
- `screens()` → belongsToMany `CoffeeProcessingScreen` (pivot: `coffee_processing_screen_stocks`)

**Important Methods**
None.

**Business Purpose**
Inventory lot of coffee received via GRN or processing, tracking quantity, purchase price, type, and screen allocations.

---

### Country

| | |
|---|---|
| **Table** | `country` |
| **Primary Key** | `id_country` |

**Relationships**
None defined.

**Important Methods**
None.

**Business Purpose**
Country lookup/reference for sponsors and children.

---

### CStatus

| | |
|---|---|
| **Table** | `c_status` |
| **Primary Key** | `id` |

**Relationships**
- `child()` → belongsTo `Children`
- `status()` → belongsTo `ChildStatus`

**Important Methods**
None.

**Business Purpose**
Audit log of child status changes (death, termination, registration cancellation) with dates and reasons.

---

### Currency

| | |
|---|---|
| **Table** | `currencies` |
| **Primary Key** | `id` |

**Relationships**
- `rates()` → hasMany `FxRate`

**Important Methods**
None.

**Business Purpose**
Currency master (code, name, symbol) with historical exchange rates for multi-currency journal entries.

---

### Customer

| | |
|---|---|
| **Table** | `customers` |
| **Primary Key** | `id` |

**Relationships**
- `invoices()` → hasMany `Invoice`

**Important Methods**
None.

**Business Purpose**
General AR customer with contact/address details, distinct from coffee `Buyer` entity; used for invoicing.

---

### Department

| | |
|---|---|
| **Table** | `departments` |
| **Primary Key** | `id` |

**Relationships**
- `employees()` → hasMany `Employee`

**Important Methods**
None.

**Business Purpose**
Organizational department for grouping employees.

---

### DepreciationEntry

| | |
|---|---|
| **Table** | `depreciation_entries` |
| **Primary Key** | `id` |

**Relationships**
- `asset()` → belongsTo `FixedAsset`

**Important Methods**
None.

**Business Purpose**
Individual depreciation charge for a fixed asset in a given period (amount, type, description).

---

### District

| | |
|---|---|
| **Table** | `districts` |
| **Primary Key** | `id` |

**Relationships**
- `subCounties()` → hasMany `SubCounty`
- `farmer()` → hasMany `Farmer`

**Important Methods**
None.

**Business Purpose**
Top-level geographic division in the Uganda-style admin hierarchy; contains sub-counties and farmers.

---

### Donation

| | |
|---|---|
| **Table** | `donations` |
| **Primary Key** | `id` |

**Relationships**
- `child()` → belongsTo `Children`

**Important Methods**
None.

**Business Purpose**
Donation record linked to a sponsored child.

---

### Employee

| | |
|---|---|
| **Table** | `employees` |
| **Primary Key** | `id` |

**Relationships**
- `accountEntity()` → morphOne `AccountEntity`
- `account()` — convenience accessor via `accountEntity`

**Important Methods**
- `ensureArAccount()` — get or create A/R sub-account under control `1020`

**Business Purpose**
Staff member with optional GL account linkage for payroll and receivables tracking.

---

### Entity

| | |
|---|---|
| **Table** | `entities` |
| **Primary Key** | `id` |

**Relationships**
- `parent()` → belongsTo `Entity`
- `children()` → hasMany `Entity`
- `currency()` → belongsTo `Currency`

**Important Methods**
None.

**Business Purpose**
Multi-entity/consolidation structure for intercompany accounting; hierarchical org units with base currency.

---

### Farmer

| | |
|---|---|
| **Table** | `farmer` |
| **Primary Key** | `id_farmer` |

**Relationships**
- `group()` → belongsTo `Group`
- `village()` → belongsTo `Village`
- `district()` → belongsTo `District`
- `accounts()` → morphMany `Account`

**Important Methods**
- `ensureArAccount()` — get or create A/R sub-account under control `1020`

**Business Purpose**
Coffee farmer supplier with geographic/group affiliation and dedicated A/R GL sub-account for advances and payment vouchers.

---

### FixedAsset

| | |
|---|---|
| **Table** | `fixed_assets` |
| **Primary Key** | `id` |

**Relationships**
- `depreciationEntries()` → hasMany `DepreciationEntry`
- `category()` → belongsTo `AssetCategory`
- `account()` → belongsTo `Account`
- `journalEntry()` → belongsTo `JournalEntry` (via `journal_entry_ref` → `reference`)

**Important Methods**
- `bookValue()` — cost minus accumulated depreciation, floored at salvage value

**Business Purpose**
Capital asset register with acquisition cost, useful life, disposal tracking, linked GL account, and depreciation schedule.

---

### FxRate

| | |
|---|---|
| **Table** | `fx_rates` |
| **Primary Key** | `id` |

**Relationships**
- `currency()` → belongsTo `Currency`

**Important Methods**
None.

**Business Purpose**
Historical exchange rate for a currency on a given date, used in multi-currency journal entries.

---

### Gift

| | |
|---|---|
| **Table** | `gifts` |
| **Primary Key** | `id` |

**Relationships**
- `child()` → belongsTo `Children`

**Important Methods**
None. Fillable includes `id_sponsor` but no `sponsor()` relationship is defined.

**Business Purpose**
Sponsor-sent gift to a child (amount, description, cost, dates, photo) as part of the sponsorship program.

---

### Grinding

| | |
|---|---|
| **Table** | `grindings` |
| **Primary Key** | `id` |

**Relationships**
- `roasting()` → belongsTo `Roasting`
- `user()` → belongsTo `User`

**Important Methods**
None.

**Business Purpose**
Coffee grinding production step converting roasted beans to ground product, tracking input/output quantities and saleability.

---

### Grn

| | |
|---|---|
| **Table** | `grn` |
| **Primary Key** | `id` |

**Relationships**
- `farmer()` → belongsTo `Farmer`
- `coffeeStocks()` → hasMany `CoffeeStock`

**Important Methods**
None.

**Business Purpose**
Goods Received Note for farmer coffee delivery — bags, moisture, grades (kiboko, FAQ, ungraded), status, and linked stock lots.

---

### Group

| | |
|---|---|
| **Table** | `group` |
| **Primary Key** | `id_group` |

**Relationships**
None defined.

**Important Methods**
None.

**Business Purpose**
Farmer cooperative/group (name, code) for organizing coffee suppliers.

---

### Guardian

| | |
|---|---|
| **Table** | `guardians` |
| **Primary Key** | `id` |

**Relationships**
- `children()` → hasMany `Children`

**Important Methods**
None.

**Business Purpose**
Legal guardian/caregiver for sponsored children, linked from child records and field updates.

---

### Intercompany

| | |
|---|---|
| **Table** | `intercompany` |
| **Primary Key** | `id` |

**Relationships**
- `fromEntity()` → belongsTo `Entity`
- `toEntity()` → belongsTo `Entity`

**Important Methods**
None.

**Business Purpose**
Inter-entity transfer transaction between organizational units for consolidation accounting.

---

### Invoice

| | |
|---|---|
| **Table** | `invoices` |
| **Primary Key** | `id` |

**Relationships**
- `customer()` → belongsTo `Customer`
- `buyer()` → belongsTo `Buyer`
- `lines()` → hasMany `InvoiceLine`
- `payments()` → hasMany `ArPayment`

**Important Methods**
- `getPaidAttribute()` — sum of AR payments
- `getBalanceAttribute()` — grand_total minus paid

**Business Purpose**
Accounts-receivable invoice to a customer or buyer with line items, tax, payment tracking, and balance calculation.

---

### InvoiceLine

| | |
|---|---|
| **Table** | `invoice_lines` |
| **Primary Key** | `id` |

**Relationships**
- `invoice()` → belongsTo `Invoice`
- `account()` → belongsTo `Account`

**Important Methods**
None.

**Business Purpose**
Individual line item on an invoice with GL account, quantity, unit price, and line total.

---

### Job

| | |
|---|---|
| **Table** | `jobs` |
| **Primary Key** | `id` |

**Relationships**
- `creator()` → belongsTo `User` (via `posted_by`)
- `sections()` → hasMany `JobSection`

**Important Methods**
None.

**Business Purpose**
Job posting for recruitment portal — title, department, description, requirements, deadline, status, and structured sections.

---

### JobSection

| | |
|---|---|
| **Table** | `job_sections` |
| **Primary Key** | `id` |

**Relationships**
- `job()` → belongsTo `Job`

**Important Methods**
None.

**Business Purpose**
Structured content section (title + content) within a job posting.

---

### JournalEntry

| | |
|---|---|
| **Table** | `journal_entries` |
| **Primary Key** | `id` |

**Relationships**
- `lines()` → hasMany `JournalEntryLine`

**Important Methods**
None. Casts `entry_date` to date.

**Business Purpose**
GL journal entry header (date, reference, description, currency, exchange rate) containing debit/credit lines.

---

### JournalEntryLine

| | |
|---|---|
| **Table** | `journal_entry_lines` |
| **Primary Key** | `id` |

**Relationships**
- `entry()` → belongsTo `JournalEntry`
- `account()` → belongsTo `Account`
- `bankTransaction()` → belongsTo `BankTransaction`
- `currency()` → belongsTo `Currency`

**Important Methods**
None.

**Business Purpose**
Individual debit/credit line in a journal entry, with optional multi-currency amounts and bank transaction matching.

---

### Letter

| | |
|---|---|
| **Table** | `letters` |
| **Primary Key** | `id` |

**Relationships**
- `progress()` → hasOne `LetterProgress`

**Important Methods**
None.

**Business Purpose**
Sponsorship letter template/campaign that children write to sponsors, tracked via progress records.

---

### LetterProgress

| | |
|---|---|
| **Table** | `letter_progresses` |
| **Primary Key** | `id` |

**Relationships**
- `child()` → belongsTo `Children`
- `letter()` → belongsTo `Letter`

**Important Methods**
None.

**Business Purpose**
Tracks a specific child's progress on writing/sending a sponsorship letter.

---

### Message

| | |
|---|---|
| **Table** | `messages` |
| **Primary Key** | `id` |

**Relationships**
- `user()` → belongsTo `User`

**Important Methods**
None.

**Business Purpose**
Simple user message/comment (body text) — likely internal messaging.

---

### Packaging

| | |
|---|---|
| **Table** | `packagings` |
| **Primary Key** | `id` |

**Relationships**
- `roasting()` → belongsTo `Roasting`
- `grinding()` → belongsTo `Grinding`
- `user()` → belongsTo `User`

**Important Methods**
None.

**Business Purpose**
Final packaging production step from roasted or ground coffee, tracking input and packaged output quantities.

---

### Pastor

| | |
|---|---|
| **Table** | `pastor` |
| **Primary Key** | `id_pastor` |

**Relationships**
- `cluster()` → belongsTo `Cluster`
- `church()` → belongsTo `Church`

**Important Methods**
None.

**Business Purpose**
Pastor assigned to a cluster and church within the child sponsorship organizational structure.

---

### PaymentVoucher

| | |
|---|---|
| **Table** | `payment_vouchers` |
| **Primary Key** | `id` |

**Relationships**
- `grn()` → belongsTo `Grn`
- `farmer()` — convenience accessor via `$this->grn->farmer()` (not a standard Eloquent relation)

**Important Methods**
- `mcDeductionAmount()` — static; MC deduction × unit price
- `resolveAdvanceAccount()` — static; farmer A/R account code via GRN
- `allocateCashAtBank()` — static; single allocation from account `1110`

**Business Purpose**
Farmer payment settlement voucher for a GRN — grades, deductions (moisture, advances, hulling, transport), net pay, and GL posting rules.

---

### Payroll

| | |
|---|---|
| **Table** | `payrolls` |
| **Primary Key** | `id` |

**Relationships**
- `lines()` → hasMany `PayrollLine`

**Important Methods**
- `postingRules()` — static; defines GL posting template (PAYE, NSSF, net pay, salary expense)
- `payeAmount()`, `nssfTotalAmount()`, `netPayAmount()` — static aggregators from lines
- `salaryExpenseLines()` — static; per-employee debit lines mapped to accounts

**Business Purpose**
Payroll run header for a pay period with tax/NSSF totals and configurable GL journal posting rules.

---

### PayrollLine

| | |
|---|---|
| **Table** | `payroll_lines` |
| **Primary Key** | `id` |

**Relationships**
- `payroll()` → belongsTo `Payroll`
- `account()` → belongsTo `Account`
- `employee()` → belongsTo `Employee`

**Important Methods**
None.

**Business Purpose**
Per-employee payroll line with taxable income, PAYE, NSSF, deductions, net pay, and linked expense account.

---

### PermissionGroup

| | |
|---|---|
| **Table** | `permission_group` |
| **Primary Key** | `id` |

**Relationships**
None defined.

**Important Methods**
None.

**Business Purpose**
Permission grouping lookup for role-based access control (used alongside Spatie permissions on `User`).

---

### Project

| | |
|---|---|
| **Table** | `projects` |
| **Primary Key** | `id` |

**Relationships**
- `transactions()` → hasMany `ProjectTransaction`
- `resourceCosts()` → hasMany `ProjectResourceCost`

**Important Methods**
- `totalRevenue()` — sum of revenue-type transactions
- `totalCost()` — sum of cost transactions + resource costs

**Business Purpose**
Project tracking with budget, date range, revenue/cost transactions, and resource utilization for P&L reporting.

---

### ProjectResourceCost

| | |
|---|---|
| **Table** | `project_resource_costs` |
| **Primary Key** | `id` |

**Relationships**
- `project()` → belongsTo `Project`
- `resource()` → belongsTo `Resource`

**Important Methods**
None.

**Business Purpose**
Resource time/cost entry for a project (hours × rate = total_cost).

---

### ProjectTransaction

| | |
|---|---|
| **Table** | `project_transactions` |
| **Primary Key** | `id` |

**Relationships**
- `project()` → belongsTo `Project`
- `account()` → belongsTo `Account`

**Important Methods**
None.

**Business Purpose**
Revenue or cost transaction posted to a project, linked to a GL account.

---

### Report

| | |
|---|---|
| **Table** | `reports` |
| **Primary Key** | `id` |

**Relationships**
- `type()` → belongsTo `ReportType`
- `user()` → belongsTo `User`
- `attachments()` → hasMany `ReportAttachment`
- `comments()` → hasMany `ReportComment`

**Important Methods**
- `getActivitylogOptions()` — Spatie activity log configuration
- Uses `LogsActivity` trait

**Business Purpose**
Submitted operational report with typed template data, workflow status/stage, location, attachments, comments, and audit trail.

---

### ReportAttachment

| | |
|---|---|
| **Table** | `report_attachments` |
| **Primary Key** | `id` |

**Relationships**
- `report()` → belongsTo `Report`

**Important Methods**
None.

**Business Purpose**
File attachment linked to a submitted report.

---

### ReportComment

| | |
|---|---|
| **Table** | `report_comments` |
| **Primary Key** | `id` |

**Relationships**
- `report()` → belongsTo `Report`
- `user()` → belongsTo `User`

**Important Methods**
None.

**Business Purpose**
User comment/review note on a submitted report.

---

### ReportType

| | |
|---|---|
| **Table** | `report_types` |
| **Primary Key** | `id` |

**Relationships**
- `workflows()` → hasMany `ReportWorkflow` (ordered)

**Important Methods**
None. Casts `template` to array.

**Business Purpose**
Report template definition with structured form fields and associated approval workflow stages.

---

### ReportWorkflow

| | |
|---|---|
| **Table** | `report_workflows` |
| **Primary Key** | `id` |

**Relationships**
- `reportType()` → belongsTo `ReportType`

**Important Methods**
None.

**Business Purpose**
Ordered workflow stage/step within a report type's approval pipeline.

---

### Resource

| | |
|---|---|
| **Table** | `resources` |
| **Primary Key** | `id` |

**Relationships**
- `projectCosts()` → hasMany `ProjectResourceCost`

**Important Methods**
None.

**Business Purpose**
Billable resource (person/equipment) with hourly rate for project cost tracking.

---

### Roasting

| | |
|---|---|
| **Table** | `roastings` |
| **Primary Key** | `id` |

**Relationships**
- `stockTransfer()` → belongsTo `StockTransfer`
- `user()` → belongsTo `User`

**Important Methods**
None.

**Business Purpose**
Coffee roasting production step from transferred stock, tracking raw input, roasted output, and saleability.

---

### School

| | |
|---|---|
| **Table** | `school` |
| **Primary Key** | `id_school` |

**Relationships**
- `children()` → hasMany `Children` (via `id_school`)

**Important Methods**
None.

**Business Purpose**
School lookup for tracking where sponsored children attend (name, address, contact).

---

### SiteSetting

| | |
|---|---|
| **Table** | `site_settings` |
| **Primary Key** | `id` |

**Relationships**
None.

**Important Methods**
None.

**Business Purpose**
Application-wide configuration key-value settings.

---

### SmtpSetting

| | |
|---|---|
| **Table** | `smtp_settings` |
| **Primary Key** | `id` |

**Relationships**
None.

**Important Methods**
None.

**Business Purpose**
SMTP email server configuration for outbound mail.

---

### Sponsor

| | |
|---|---|
| **Table** | `sponsor` |
| **Primary Key** | `id_sponsor` |

**Relationships**
- `children()` → belongsToMany `Children` (pivot: `child_sponsor`)
- `country()` → belongsTo `Country`
- `gifts()` → hasMany `Gift`

**Important Methods**
None.

**Business Purpose**
Child sponsorship donor with country, linked children (many-to-many), and gift history.

---

### Sponsorship

| | |
|---|---|
| **Table** | `sponsorship` |
| **Primary Key** | `id_sponsorship` |

**Relationships**
- `child()` → belongsTo `Children`

**Important Methods**
None.

**Business Purpose**
Active sponsorship assignment linking a child to sponsorship terms/details (complements `ChildSponsor` pivot).

---

### StockTransfer

| | |
|---|---|
| **Table** | `stock_transfers` |
| **Primary Key** | `id` |

**Relationships**
- `user()` → belongsTo `User`

**Important Methods**
None.

**Business Purpose**
Internal transfer of ungraded coffee stock into the roasting pipeline (date, weight, reason).

---

### SubCounty

| | |
|---|---|
| **Table** | `sub_counties` |
| **Primary Key** | `id` |

**Relationships**
- `district()` → belongsTo `District`
- `villages()` → hasMany `Village`

**Important Methods**
None.

**Business Purpose**
Sub-county within a district; contains villages in the geographic hierarchy.

---

### TaxProvision

| | |
|---|---|
| **Table** | `tax_provisions` |
| **Primary Key** | `id` |

**Relationships**
None.

**Important Methods**
None.

**Business Purpose**
Corporate tax provision for an accounting period (profit before tax, provision amount).

---

### TaxRate

| | |
|---|---|
| **Table** | `tax_rates` |
| **Primary Key** | `id` |

**Relationships**
None.

**Important Methods**
None.

**Business Purpose**
Tax rate definition (name, rate, type) used for withholding and tax calculations.

---

### User

| | |
|---|---|
| **Table** | `users` |
| **Primary Key** | `id` |
| **Extends** | `Authenticatable` |
| **Traits** | `HasApiTokens`, `HasRoles` (Spatie), `Notifiable` |

**Relationships**
- `reports()` → hasMany `Report`

**Important Methods**
- `UserOnline()` — checks Cache for online presence
- `getpermissionGroups()` — static; groups permissions by group_name
- `getpermissionByGroupName()` — static; permissions in a group
- `roleHasPermissions()` — static; checks if role has all given permissions

**Business Purpose**
System user with role-based permissions (Spatie), API tokens, online status tracking, and submitted reports.

---

### Vendor

| | |
|---|---|
| **Table** | `vendors` |
| **Primary Key** | `id` |

**Relationships**
- `bills()` → hasMany `VendorBill`
- `billLines()` → hasManyThrough `VendorBillLine` via `VendorBill`

**Important Methods**
None.

**Business Purpose**
Accounts-payable vendor/supplier with contact details and associated bills.

---

### VendorBill

| | |
|---|---|
| **Table** | `vendor_bills` |
| **Primary Key** | `id` |

**Relationships**
- `vendor()` → belongsTo `Vendor`
- `lines()` → hasMany `VendorBillLine`
- `payments()` → hasMany `ApPayment`

**Important Methods**
- `getPaidAttribute()` — sum of AP payments
- `getBalanceAttribute()` — grand_total minus paid

**Business Purpose**
Vendor invoice/bill with line items, tax, AP payment tracking, and balance calculation.

---

### VendorBillLine

| | |
|---|---|
| **Table** | `vendor_bill_lines` |
| **Primary Key** | `id` |

**Relationships**
- `bill()` → belongsTo `VendorBill`
- `account()` → belongsTo `Account`

**Important Methods**
None.

**Business Purpose**
Individual expense line on a vendor bill with GL account, quantity, and pricing.

---

### Village

| | |
|---|---|
| **Table** | `villages` |
| **Primary Key** | `id` |

**Relationships**
- `subCounty()` → belongsTo `SubCounty`

**Important Methods**
None.

**Business Purpose**
Village within a sub-county; farmers are linked to villages in the geographic hierarchy.

---

### WithholdingEntry

| | |
|---|---|
| **Table** | `withholding_entries` |
| **Primary Key** | `id` |

**Relationships**
- `payment()` → belongsTo `ApPayment` (via `vendor_payment_id`)
- `rate()` → belongsTo `TaxRate`

**Important Methods**
None.

**Business Purpose**
Withholding tax deducted on a vendor payment, linked to the applicable tax rate.

---

## Cross-Domain Patterns

### Polymorphic GL linking

`AccountEntity` connects `Account` to `Farmer`, `Buyer`, and `Employee` via `morphTo` / `morphOne`. `Farmer` also declares `morphMany(Account::class, 'entity')`.

### A/R account auto-provisioning

`Farmer`, `Buyer`, and `Employee` each implement `ensureArAccount()`, creating sub-accounts under control account `1020` (Accounts Receivable).

### GL posting helpers on models

Static methods on `Payroll`, `PaymentVoucher`, `Advance`, and `CoffeeSale` define journal entry generation rules (posting templates, account resolution, allocation logic). Actual posting should go through `PostingService` and existing workflows per accounting rules.

### Coffee production pipeline

```
Grn → CoffeeStock → CoffeeProcessing → CoffeeProcessingScreen
  → StockTransfer → Roasting → Grinding → Packaging → BeverageSale
                                                      ↘ CoffeeSale (export)
```

### Child sponsorship graph

`Children` is the central hub connecting sponsors, clusters, guardians, schools, letters, gifts, status logs, and field updates.

### Geographic hierarchy

```
District → SubCounty → Village → Farmer
```

### AR/AP symmetry

| Receivables | Payables |
|-------------|----------|
| `Customer` / `Buyer` | `Vendor` |
| `Invoice` / `InvoiceLine` | `VendorBill` / `VendorBillLine` |
| `ArPayment` | `ApPayment` |

Both invoice and bill models expose computed `paid` and `balance` attributes.

---

## Notes for Architects

1. **Legacy table naming** — Several CFDP and coffee models use singular or non-standard table names (`child`, `farmer`, `grn`, `sponsor`, etc.) with custom primary keys (`id_child`, `id_farmer`, `id_sponsor`, etc.).
2. **Dual customer entities** — `Buyer` (coffee sales) and `Customer` (general invoicing) serve overlapping AR purposes; `Invoice` can link to either.
3. **Missing relationships** — `ChildSponsor` has no Eloquent relations defined; `Gift` stores `id_sponsor` without a `sponsor()` relation; `ChildStatus.status()` appears self-referential and may be legacy.
4. **No model-level soft deletes observed** — Deletion behavior is enforced at the application/service layer, especially for accounting records.
