# FoxFitt LabourPay v5 — Features Guide

A complete guide to every feature in the payroll management system for FoxFitt Construction.

---

## 1. Dashboard (Home Page)

**URL:** `/` (after login)

### Admin View
- **Outstanding Payments** stat card — total unpaid wages with breakdown (wages + additions - deductions)
- **Paid This Month** stat card — total payments made in current month
- **Active Loans & Advances** stat card — count and total balance
- **Outstanding by Project** — breakdown of unpaid amounts per project
- **Quick Action buttons** — Log Work, Run Payroll, View History
- **This Week Summary** — count of work logs created this week
- **Recent Activity** — last 10 work logs with project, date, worker count, supervisor badge
- **Manage Resources** — tabbed panel (Workers / Projects / Teams) with:
  - Active / Inactive / All filter buttons
  - Toggle switches to activate/deactivate items (AJAX, no page reload)
  - Export Workers CSV button

### Supervisor View (simplified)
- My Projects, My Teams, My Workers counts
- This Week Summary and Recent Activity (limited to their own projects/teams)
- No payroll access, no resource management toggles

---

## 2. Attendance Logging

**URL:** `/attendance/log/`
**Access:** Supervisors and Admins

### Features
- **Date Range Support** — set a start date and optional end date to log multiple days at once
- **Weekend Controls** — checkboxes to include Saturdays and/or Sundays in date range
- **Project Selection** — dropdown of active projects (supervisors see only their assigned projects)
- **Team Auto-Select** — choosing a team auto-checks all its members in the worker list
- **Worker Multi-Select** — scrollable checkbox list of active workers
- **Overtime** — dropdown: None, 1/4 Day, 1/2 Day, 3/4 Day, Full Day
- **Notes** — free text field for any additional info
- **Conflict Detection** — if any selected worker already has a log on the selected date+project:
  - Warning shown with list of conflicts
  - Two options: "Skip Conflicts" (create only non-conflicting) or "Overwrite Existing"
- **Estimated Cost** (Admin only) — live-updating card showing: R amount, N workers x M days. Recalculates as selections change. Does not include overtime.

---

## 3. Work History

**URL:** `/history/`
**Access:** All logged-in users (supervisors see only their projects)

### List View
- Table: Date, Project, Team, Workers (count), Supervisor, Amount, Payment Status (Paid/Unpaid badge)
- Filters: Worker dropdown, Project dropdown, Payment Status (All / Paid / Unpaid)
- Filter feedback bar: "Showing X of Y work logs" with active filter badges and clear button
- CSV export button (preserves active filters)

### Calendar View
- Monthly grid with previous/next navigation
- Each day shows: work log count badge, first 3 project indicators, "+X more" for overflow
- Colour coding: green checkmark (paid), orange clock (unpaid)
- Today's cell highlighted
- Click a day to see full details in a panel below
- Multi-day selection: click multiple days to see combined totals
- Footer: total days, total logs, unique workers, total amount (admin only)

### CSV Export
- **Work Logs CSV** (`/history/export/`) — Date, Project, Team, Workers, Supervisor, Worker Count, Daily Cost, Payment Status
- **Workers CSV** (`/workers/export/`, admin only) — Name, ID Number, Phone, Monthly Salary, Daily Rate, Employment Date, Active, Notes, Shoe Size, Overall Top Size, Pants Size, T-Shirt Size, Has Drivers License

---

## 4. Payroll Dashboard

**URL:** `/payroll/`
**Access:** Admin only

### Header Buttons
- **Worker Lookup** — opens modal to view any worker's financial report card
- **Batch Pay** — pay multiple workers at once based on pay schedules
- **Add Adjustment** — create bonuses, deductions, loans, advances
- **Price Overtime** — convert unpriced overtime entries into Overtime adjustments

### Analytics Cards
- **Outstanding Payments** — total unpaid with breakdown (wages + additions - deductions)
- **Paid (Last 60 Days)** — recent payment total
- **Active Loans & Advances** — count + total remaining balance
- **Outstanding by Project** — per-project unpaid amounts

### Charts
1. **Monthly Payroll** — line chart of monthly totals, with toggle to view by individual worker (dropdown selector)
2. **Cost by Project** — monthly project cost breakdown

### Three Tabs

#### Tab 1: Pending Payments
- **Filter Bar:**
  - Team dropdown (All Teams or specific team)
  - "Overdue only" checkbox (shows workers with unpaid work from completed pay periods)
  - Loan filter dropdown (All Workers / With loans only / Without loans)
- **Table Columns:** Worker, Days, Day Rate, Log Amount, Adjustments (colour-coded badges), Net Adj, Total, Actions
- **Row Badges:**
  - Red "Overdue" — worker has unpaid work from a completed pay period
  - Yellow "Loan" — worker has an active loan or advance
- **Action Buttons per Worker:**
  - Preview (eye icon) — opens Payslip Preview modal
  - Adjust (slider icon) — opens Add Adjustment modal pre-filled with this worker and their last project
  - Pay (green button) — processes payment for all pending items immediately

#### Tab 2: Payment History
- Table: Date, Worker, Amount Paid, Work Logs (count), Adjustments (badges), View Payslip link
- Worker names are clickable (opens Worker Lookup modal)

#### Tab 3: Loans & Advances
- Sub-filter: Active / History toggle buttons
- Table: Worker, Type (Loan/Advance badge), Principal, Balance, Date, Reason, Status (Active/Paid Off)
- Worker names are clickable (opens Worker Lookup modal)

---

## 5. Payment Processing

### Individual Payment
- Click "Pay" on a worker's pending row — processes all unpaid work logs and adjustments
- Creates a PayrollRecord linking the worker, their work logs, and adjustments
- Generates HTML + PDF payslip and emails to Spark Receipt
- Atomic transaction with `select_for_update()` to prevent duplicate payments

### Payslip Preview Modal ("Worker Payment Hub")
- Opened via the Preview (eye) button on pending payments
- Shows: worker name, ID, days worked, day rate, log amount
- **Work Logs list** with checkboxes (all checked by default) — uncheck to exclude from payment
- **Adjustments list** with checkboxes — uncheck to exclude
- **Split at Pay Date button** — auto-unchecks items after the last completed pay period cutoff (useful for paying only what's due)
- **Active Loans section** — shows outstanding balances with inline repayment forms
- **Net Pay total** — updates live as items are checked/unchecked
- **Pay Selected button** — processes only checked items (split payslip)

### Batch Pay
- Opened via "Batch Pay" button in header
- **Two modes** (radio buttons):
  - **Until Last Paydate** (default) — splits at each worker's last completed pay period; workers without team schedules are skipped
  - **Pay All** — includes all unpaid items regardless of date
- **Team filter** — pay only workers in a specific team
- **Loan filter** (3 options) — All Workers / With loans only / Without loans
- Preview shows list of workers and amounts before confirming
- Processes each worker in independent atomic transactions
- Emails sent after all payments complete

---

## 6. Payroll Adjustments

### Types
| Type | Effect | Auto-created? | Details |
|------|--------|---------------|---------|
| **Bonus** | Additive (+) | No | Requires a linked project |
| **Deduction** | Deductive (-) | No | Requires a linked project |
| **Overtime** | Additive (+) | Yes | Created by "Price Overtime" from unpriced OT entries |
| **New Loan** | Additive (+) | No | Creates a Loan record. "Pay Immediately" checkbox (default: checked) auto-processes and emails payslip |
| **Advance Payment** | Additive (+) | No | Auto-processed immediately (never sits in pending). Creates Loan + PayrollRecord + emails payslip. Auto-creates an Advance Repayment for next salary |
| **Loan Repayment** | Deductive (-) | Yes | Created from payslip preview inline form. Linked to a Loan |
| **Advance Repayment** | Deductive (-) | Yes | Auto-created when an advance is paid |

### Add Adjustment Modal
- Type dropdown, Project (required for some types), Amount, Date, Description
- Worker multi-select with checkboxes (team helper to select all team members)
- "Pay Immediately" checkbox appears for New Loan type (checked by default)

### Quick Adjust Button
- Each pending payments row has an "Adjust" button (slider icon)
- Opens Add Adjustment modal with the worker pre-checked and their most recent project pre-selected
- Header "Add Adjustment" button resets modal to clean state

### Edit/Delete Adjustments
- Click any adjustment badge in the pending payments table to edit
- Can change type, project, amount, date, description
- Delete button with confirmation modal
- Only unpaid adjustments can be edited/deleted

### Price Overtime
- Opens modal showing all unpriced overtime work log entries
- Filter by worker name
- Table: Worker, Date, Project, OT Amount, Day Rate, Total
- Checkboxes to select which entries to price
- Price multiplier input (default 1.5x)
- Creates Overtime-type PayrollAdjustments for selected entries

---

## 7. Loans & Advances

### New Loan Flow
1. Create via Add Adjustment → type "New Loan"
2. "Pay Immediately" checkbox (checked by default):
   - **Checked:** Creates Loan + PayrollRecord + emails payslip to Spark immediately
   - **Unchecked:** Creates Loan, sits in Pending Payments for next pay cycle
3. Editing a loan adjustment syncs amount/balance/reason on the Loan record
4. Deleting cascades to Loan + any unpaid repayments

### Advance Payment Flow
1. Create via Add Adjustment → type "Advance Payment"
2. Always auto-processed immediately (no pending state)
3. Creates Loan (type='advance') + PayrollRecord + emails payslip
4. Auto-creates an "Advance Repayment" adjustment for next salary cycle
5. Requires at least one unpaid work log (otherwise use New Loan)

### Repayments
- **From Payslip Preview:** Inline form to add repayment against any active loan
- **Loan Repayment:** Manual deduction linked to a specific loan
- **Advance Repayment:** Auto-created, deducts from advance balance during payment processing
- **Partial Repayment:** If an advance is only partially repaid, the Loan's type changes from 'advance' to 'loan' so the remainder is tracked as a regular loan

### Loans Tab
- Active loans: shows all current outstanding loans/advances
- History: shows all loans including paid-off ones
- Columns: Worker, Type, Principal, Balance, Date, Reason, Status

---

## 8. Worker Lookup Modal

**Trigger:** Click any worker name on the payroll dashboard, or click the "Worker Lookup" button

### Report Card Contents
- **Identity:** Name, ID number, phone, employment date, team, current project + days on project
- **Quick Stats (4 cards):**
  - Amount Payable (unpaid earnings + net adjustments)
  - Outstanding Loans (total remaining balance)
  - Paid This Month
  - Loans This Year (total principal issued)
- **Recent Activity:**
  - Last payslip paid (date + amount)
  - Last loan given (date + amount + reason)
  - Last loan repayment (date + amount)
  - Last advance paid (date + amount)
- **Active Loans Table** (if any): Type, Amount, Balance, Date, Reason
- **Paid This Year** total
- **Sizing & Info:** Shoe size, Overall Top, Pants, T-Shirt, Drivers License status, Notes

### Features
- Searchable worker dropdown to switch between workers without closing the modal
- Worker names are clickable links throughout the dashboard (Pending Payments, Payment History, Loans tabs)

---

## 9. Worker Management

**Location:** Django Admin (`/admin/core/worker/`) and Dashboard Manage Resources panel

### Worker Fields
| Section | Fields |
|---------|--------|
| **Personal Info** | Name, ID Number, Phone, Monthly Salary, Employment Date, Active, Notes |
| **Sizing** | Shoe Size, Overall Top Size, Pants Size, T-Shirt Size |
| **Documents & License** | Photo (image), ID Document (file), Has Drivers License (checkbox), Drivers License (file) |

### Admin Features
- Fieldsets organise fields into 3 sections
- List view: Name, ID Number, Monthly Salary, Active
- Filters: Active status, Has Drivers License
- Search: Name, ID Number, Phone Number

### Dashboard Toggle
- Manage Resources panel on main dashboard
- Toggle switches to activate/deactivate workers (AJAX)
- Active / Inactive / All filter buttons

### Computed Properties
- `daily_rate` = monthly_salary / 20 working days

---

## 10. Team Pay Schedules

### Configuration
- Each team has optional `pay_frequency` (Weekly / Fortnightly / Monthly) and `pay_start_date` (anchor date)
- Set via Django Admin (editable directly in the team list view)

### How It Works
- `pay_start_date` is an anchor — the first day of the very first pay period (never needs updating)
- The system steps forward from the anchor to find the current period
- Weekly = 7 days, Fortnightly = 14 days, Monthly = calendar month stepping
- Handles month-length edge cases using `calendar.monthrange()`

### Impact on Features
- **Overdue Detection:** Workers with unpaid work from completed pay periods get a red "Overdue" badge
- **Split at Pay Date:** Preview modal button auto-unchecks items after the cutoff date
- **Batch Pay (Until Last Paydate):** Only pays items within completed pay periods
- **Cutoff date** = last day of the most recently completed period (includes ALL overdue work)

---

## 11. Expense Receipts

**URL:** `/receipts/create/`
**Access:** All staff (admin + supervisors)

### Form Fields
- Date, Vendor Name, Payment Method (Cash/Card/EFT/Other), Description
- **Dynamic Line Items** — add/remove rows with Product Name + Amount
- **VAT Options** — radio buttons: Included (15% extracted) / Excluded (15% added) / None

### Live Calculations
- Subtotal, VAT amount, and Total update in real-time as you type
- VAT calculation adjusts based on Included/Excluded selection

### On Submit
- Saves ExpenseReceipt + ExpenseLineItems to database
- Generates HTML email + PDF attachment
- Emails to Spark Receipt (spark@sparkreceipthq.com)

---

## 12. Email & PDF Generation

### Payslip Email
- **Sent to:** Spark Receipt (for record-keeping)
- **Content:** Worker name, ID, payment date, base pay, all adjustments, net pay
- **Attachment:** PDF payslip
- **Three variants:** Regular (work + adjustments), Advance-only, Loan-only

### Receipt Email
- **Sent to:** Spark Receipt
- **Content:** Vendor, date, payment method, line items, VAT breakdown, total
- **Attachment:** PDF receipt

### Payslip Detail Page
- **URL:** `/payroll/payslip/<id>/`
- Print-friendly view of a completed payslip
- Accessible from Payment History tab "View" button

---

## 13. Authentication & Permissions

### Roles
| Role | Access |
|------|--------|
| **Admin** (is_staff or is_superuser) | Full access: payroll, adjustments, resource management, exports |
| **Supervisor** (assigned to projects) | Attendance logging, work history (own projects only), expense receipts |

### Permission Groups (created by `setup_groups` command)
- **Admin** — full CRUD on all core models
- **Work Logger** — add/change/view WorkLog; view-only on Project/Worker/Team

### Authentication
- Django built-in auth at `/accounts/login/`
- All views require login except `/import-data/`
- Login redirects to dashboard (`/`)

---

## 14. Data Exports

| Export | URL | Format | Access | Contents |
|--------|-----|--------|--------|----------|
| Work Logs | `/history/export/` | CSV | Supervisor+ | Date, Project, Team, Workers, Supervisor, Cost, Status |
| Workers | `/workers/export/` | CSV | Admin | Name, ID, Phone, Salary, Rate, Dates, Sizes, License |

Both exports respect active filters (work log export preserves filter parameters in URL).

---

## 15. Setup & Deployment Tools

| Feature | URL | Purpose |
|---------|-----|---------|
| Import Data | `/import-data/` | One-time: loads production worker data from JSON fixtures |
| Run Migrate | `/run-migrate/` | Applies pending database migrations on production (for when Flatlogic doesn't auto-apply) |
| Setup Groups | `manage.py setup_groups` | Creates Admin + Work Logger permission groups |
| Setup Test Data | `manage.py setup_test_data` | Populates sample workers, projects, teams, work logs |
| Import Production Data | `manage.py import_production_data` | Imports real production data (14 workers) |
