# Accounts, Financial Ledgers & User Identity Management

This comprehensive handbook governs all aspects of accounts across **Eniceberny Bakery and Culinary Hub** — spanning customer self-service accounts, staff role access accounts, financial accounting ledgers, cash drawer reconciliation, invoicing, and statutory tax compliance.

---

## 🧭 Architecture of the Accounts Subsystem

```mermaid
graph TD
    subgraph Identity & Access
        UA[User Accounts] --> CR[Customer Accounts /account]
        UA --> SA[Staff Accounts /admin/users]
        SA --> RBAC[Role-Based Access Control]
    end

    subgraph Commerce & Receivables
        CR --> CO[Storefront Orders]
        CO --> AR[Accounts Receivable / Invoices]
        Q[Catering Quotes] -->|Convert| CO
    end

    subgraph Financial Ledgers
        CO --> PT[Payment Transactions]
        POS[Counter POS] --> PT
        PT --> GL[(Unified Payment Ledger)]
        GL --> CRD[Cash Drawer Balancing]
        GL --> MMR[MoMo Reconciliation]
        GL --> PSR[Paystack Settlements]
        GL --> DSS[Daily Sales Summary]
    end
```

---

## 1. Customer User Accounts (`/account`)

Customer accounts provide our patrons with a personalized, secure commerce portal.

### 1.1 Account Dashboard (`/account`)
Upon logging in at `/login`, patrons land on the executive customer dashboard displaying live statistics:
- **Total Orders**: Lifetime count of orders placed across web and counter channels.
- **Pending Orders**: Orders currently being confirmed, baked, or en route.
- **Completed Orders**: Orders safely delivered or collected.
- **Lifetime Spend**: Total Ghanaian Cedis (`GH₵`) settled by the customer.
- **Unpaid Balance Alert**: If an active order or invoice balance is pending payment, an amber notification card is displayed with an instant **"Settle Balance"** link.

### 1.2 Address Book & GhanaPostGPS Coordinates (`/account/addresses`)
To eliminate delivery friction, the address book manages multi-location fulfillment profiles:
- **Button: "Add New Address"**: Opens the address modal to capture:
  - **Recipient Name & Primary Phone**: Recipient at delivery location.
  - **Street Address & Locality**: House or office number, street name, suburb (e.g. *Ahodwo, Kumasi*).
  - **Notable Landmark**: Visual cues for dispatch couriers (e.g. *Opposite Shell Station, blue gate*).
  - **GhanaPostGPS Digital Address**: Official National Digital Address (e.g. `AK-039-2311`).
  - **Geographic Coordinates**: Latitude and Longitude for map-pin navigation.
  - **Address Type**: Delivery vs Billing.
  - **Button: "Save Address"**: Persists the record and marks as default if it is the user's first address.
- **Button: "Set as Default"**: Designates the primary address pre-filled during checkout.
- **Button: "Edit" / "Delete"**: Updates or safely purges stale delivery addresses with audit logging.

### 1.3 Culinary & Dietary Preferences (`/account/settings`)
Patrons can configure tailored culinary profiles stored in JSON (`customer_profiles.preferences`):
- **Dietary Tags**: Select checkboxes for Vegetarian, Nut Allergy, Lactose Intolerant, Halal, or Gluten Sensitivity.
- **Allergy Notes**: Freeform textarea for kitchen instructions (e.g. *"Severe peanut allergy — please sterilize bake trays"*).
- **Delivery Instructions**: Default delivery note (e.g. *"Call when at security gate"*).
- **Notification Preferences**: Toggles for WhatsApp updates, SMS dispatch alerts, and Email order summaries.
- **Button: "Update Culinary Preferences"**: Saves preferences atomically with audit logging.

### 1.4 Security & Password Changes
- **Current Password Verification**: Required to authorize any credential modification.
- **Password Strength Rules**: Minimum 8 characters, confirmed with matching repeat field.
- **Automated Security Email**: A notification email (`PasswordChangedMail`) is automatically dispatched to the customer's verified inbox immediately upon password update.
- **Button: "Save New Password"**: Hashes the new credential with Bcrypt and terminates unauthorized sessions.

---

## 2. Staff Accounts & Granular Role Permissions (`/admin/users`)

Access to the administrative back-office and Point of Sale register is strictly governed by authenticated staff accounts.

### 2.1 Role Hierarchy & Permissions Matrix

| Role Enum (`UserRole`) | Display Label | Scope & Permissions | Target Personnel |
| :--- | :--- | :--- | :--- |
| `super_admin` | **Super Administrator** | Full platform control: settings, financial reports, user provisioning, database audits, secret keys | Managing Director, Lead Software Architect |
| `admin` | **Administrator** | Catalog management, customer accounts, order processing, quote approval, broadcasts | Store General Manager, Operations Head |
| `manager` | **General Manager** | Kitchen queue oversight, inventory adjustments, quote drafting, daily reports | Floor Supervisor, Assistant Manager |
| `order_manager` | **Order Fulfillment Manager**| Kitchen display dispatch, order status progression, rider assignments | Dispatch Lead, Kitchen Expediter |
| `cashier` | **Cashier / POS Operator** | Counter register (`/admin/pos`), cash tender calculation, receipt printing, customer lookup | Front Desk Cashiers |
| `kitchen_staff` | **Chef / Kitchen Staff** | Read-only kitchen display, preparation status flags, recipe notes | Pastry Chefs, Line Cooks |
| `content_manager`| **Content & Media Manager**| CMS homepage sections, banners, gallery uploads, FAQs, blog articles | Marketing Officer, Graphic Designer |
| `customer` | **Valued Customer** | Public storefront browsing, cart, checkout, personal invoice payment, account settings | Patrons, Corporate Clients |

### 2.2 Staff Account Provisioning Workflow
1. Navigate to `/admin/users` and click **"Create Staff Account"**.
2. Complete the staff profile form:
   - **Full Name**: Legal name of employee.
   - **Work Email**: Official email address for authentication and OTP verification.
   - **Phone Number**: Primary mobile contact for urgent operational escalations.
   - **Assigned Role**: Select from the dropdown menu (e.g. `Cashier / POS Operator`).
   - **Initial Temporary Password**: Strong generated password.
   - **Active Status**: Set to `Active` (toggle switch).
3. Click **"Save Staff Member"**.
4. The system logs `user.created` in `audit_logs` including operator ID and IP address.

### 2.3 Staff Offboarding & Deactivation
- To immediately revoke back-office and POS terminal access, open the staff member profile and toggle **Active Status** to `Inactive` or click **"Suspend Account"**.
- All active sessions for the user are invalidated instantly. Soft deletes preserve historical sales attribution.

---

## 3. Financial Accounting, Ledgers & Reconciliation

Eniceberny maintains an immutable, multi-channel financial ledger tracking every pesewa across Cash, Mobile Money, Bank Cards, and Invoices.

### 3.1 Daily Cash Drawer Float & Balancing SOP

```mermaid
sequenceDiagram
    autonumber
    actor Cashier
    participant Terminal as POS Terminal (/admin/pos)
    participant Supervisor as Shift Supervisor
    participant Ledger as Reports & Ledgers (/admin/reports)

    Cashier->>Supervisor: Receive Starting Cash Float (GH₵ 200.00)
    Cashier->>Terminal: Sign in to POS Register
    Note over Cashier,Terminal: Process walk-in sales throughout shift
    Cashier->>Cashier: Count physical cash drawer at shift close
    Cashier->>Supervisor: Present Cash Drawer Handover Slip
    Supervisor->>Ledger: Compare Physical Cash vs System total_cash
    alt Variance == 0.00
        Supervisor->>Ledger: Sign off Balanced Shift
    else Variance != 0.00
        Supervisor->>Ledger: Record Discrepancy Note in Shift Audit
    end
```

#### Step-by-Step Balancing Protocol:
1. **Shift Opening (07:30 GMT)**:
   - The Shift Supervisor dispenses a standard physical cash float of **`GH₵ 200.00`** in small denominations:
     - 10 × GH₵ 5 notes (`GH₵ 50.00`)
     - 10 × GH₵ 10 notes (`GH₵ 100.00`)
     - 2 × GH₵ 20 notes (`GH₵ 40.00`)
     - 1 × GH₵ 10 coin pack (`GH₵ 10.00`)
   - Cashier verifies the count and signs the Register Opening Log.

2. **Mid-Shift Petty Cash Payouts**:
   - If emergency cash is disbursed from the register (e.g. local supply run or ice delivery), a formal **Petty Cash Voucher** must be signed by the Supervisor and placed inside the cash drawer.

3. **Shift Closing & Drawer Count (21:30 GMT)**:
   - Total physical banknotes and coins are counted and recorded.
   - The formula for reconciliation is:
     $$\text{Expected Physical Cash} = \text{Opening Float (GH₵ 200.00)} + \text{Total Cash Sales} - \text{Authorized Petty Cash}$$
   - Open `/admin/reports?source=pos&payment_method=cash` for the current date to obtain the exact `total_cash` system figure.
   - **Variance Resolution**:
     - **Balanced**: Expected Cash matches actual count.
     - **Cash Over (Surplus)**: Excess cash is booked as unallocated revenue.
     - **Cash Short (Deficit)**: Shortage requires cashier incident report and managerial sign-off.

---

## 4. Multi-Channel Payment Ledgers & Reconciliation

The platform records all settlements in the `payment_transactions` table:

```sql
SELECT 
    pt.transaction_reference,
    pt.gateway,
    pt.amount,
    pt.currency,
    pt.status,
    pt.paid_at,
    o.order_number,
    o.customer_name
FROM payment_transactions pt
JOIN orders o ON pt.order_id = o.id
ORDER BY pt.paid_at DESC;
```

### 4.1 Payment Gateway Channels & Reconciliation Procedures

| Channel | Gateway Key | Settlement Window | Verification Method | Reconciliation Frequency |
| :--- | :--- | :--- | :--- | :--- |
| **Physical Cash** | `cash` | Instant (In drawer) | Physical count vs POS cash sales | Daily at shift handover |
| **MTN Mobile Money** | `momo` / `paystack` | Instant to 24 hours | Telecom merchant portal SMS + Paystack transaction ID | Daily at 22:00 GMT |
| **Telecel Cash** | `momo` / `paystack` | Instant to 24 hours | Telecel merchant portal + Paystack reference | Daily at 22:00 GMT |
| **Visa / Mastercard** | `card` / `paystack`| T+1 Business Day | Paystack payout settlement batch to Stanbic/GCB bank account | Daily bank statement sync |
| **Corporate Wire / Cheque**| `invoice` | 7 – 14 Days Net | Official bank credit advice / cleared cheque | Weekly on Fridays |

### 4.2 Paystack Automated Settlement Verification
- When an online or invoice payment completes, Paystack dispatches a cryptographically signed HMAC SHA512 webhook to `/webhooks/paystack`.
- The webhook payload updates `payment_transactions` to `status = 'success'`, updates `orders.payment_status` to `'paid'`, and stamps `paid_at = now()`.
- If an unverified transaction occurs (e.g. customer's network drops before redirect), the admin can click **"Verify Gateway Transaction"** on `/admin/orders/{id}` to query Paystack's REST API `/transaction/verify/:reference` directly.

---

## 5. Accounts Receivable, Public Invoices & Debt Collection (`/invoices`)

For telephone orders, corporate catering, or delayed settlements, Eniceberny provides an online billing and invoice collection portal.

### 5.1 Public Invoice Lookup (`/invoices`)
Patrons or corporate procurement officers can retrieve invoices without requiring a user password:
1. Visit [`https://enicebakerygh.com/invoices`](https://enicebakerygh.com/invoices).
2. Enter the **Order Number** (e.g. `EB-20260927-1402`) or the billing **Phone Number**.
3. Click **"Search Invoice"**.
4. The system renders the invoice summary card detailing:
   - Line items with portion sizes and quantities.
   - Subtotal, delivery charges, discounts, and VAT/levy totals.
   - Total Amount Settled (`GH₵`) and Outstanding Balance Due (`GH₵`).

### 5.2 One-Click Digital Balance Settlement
- If an invoice has an outstanding balance, the customer clicks **"Pay Online Now"**.
- The system routes the user to the secure Paystack checkout modal where they can settle via MTN MoMo, Telecel Cash, or Visa/Mastercard.
- Upon successful payment, the invoice updates instantly to **PAID**, issues an official receipt PDF with embedded QR code, and sends an SMS/Email receipt.

---

## 6. Catering & Banquet Deposit Schedules (`/admin/quotes`)

Corporate and high-volume catering bookings adhere to a structured 2-phase milestone schedule:

```mermaid
stateDiagram-v2
    [*] --> InquiryReceived: Patron submits /catering form
    InquiryReceived --> ProposalDrafted: Admin creates Quote (/admin/quotes/create)
    ProposalDrafted --> QuoteSent: Quote sent via PDF / Email
    QuoteSent --> DepositPaid: Client pays 50% Milestone Deposit
    DepositPaid --> OrderConverted: One-click conversion to Order
    OrderConverted --> KitchenPrep: Staging & Chef Prep
    KitchenPrep --> FinalSettlement: Remaining 50% paid 48h prior to event
    FinalSettlement --> EventDelivered: Banquet execution
    EventDelivered --> [*]
```

1. **Phase 1: Milestone Deposit (50%)**:
   - Required upon client quotation acceptance to lock kitchen capacity and reserve event dates.
   - Recorded as a partial payment on the converted catering order.
2. **Phase 2: Final Balance (50%)**:
   - Due 48 hours prior to event staging.
   - Payable via the public invoice portal (`/invoices/{orderNumber}`) or bank transfer.

---

## 7. Financial Reporting, Analytics & CSV Export (`/admin/reports`)

The reporting suite empowers management with actionable intelligence and automated audit exports.

### 7.1 Key Analytical Metrics
- **Gross Revenue**: Total monetary value of all orders marked `payment_status = paid`.
- **Average Order Value (AOV)**: Calculated as:
  $$\text{AOV} = \frac{\text{Total Paid Revenue}}{\text{Total Paid Orders}}$$
- **Mobile Money Share (%)**: Percentage of gross revenue captured via MTN MoMo and Telecel Cash versus Cash and Card.
- **Channel Breakdown**: Revenue split between Online Storefront (`web`) and In-Store Counter (`pos`).
- **Top 10 Bestselling Delicacies**: Volume and revenue ranking to drive kitchen prep planning.

### 7.2 Automated Daily Sales Summary (`daily_sales_summaries`)
At the conclusion of each trading day, an automated ledger job aggregates daily performance into `daily_sales_summaries`:
- `summary_date`: Date of trading.
- `total_orders`: Number of completed tickets.
- `total_sales`: Gross daily revenue.
- `total_cash`: Total cash tendered.
- `total_momo`: Total mobile money transactions.
- `total_card`: Total card transactions.
- `total_pos`: Total in-store sales volume.
- `total_online`: Total storefront web volume.

### 7.3 Streaming CSV Export for Accounting Software
Financial accountants can export raw transaction records for import into **QuickBooks, Sage, or Microsoft Excel**:
1. Open `/admin/reports`.
2. Select desired date filters: **From Date** and **To Date**.
3. Filter by **Channel** (All, Web, POS), **Payment Method** (Cash, MoMo, Card), or **Payment Status** (Paid, Pending).
4. Click **"Export CSV"** (`/admin/reports?export=csv`).
5. The system streams a high-speed UTF-8 BOM CSV response with the filename format:
   `eniceberny-sales-report-YYYY-MM-DD-HHMMSS.csv`.
6. Includes full column breakdown: Order Number, Date, Customer Name, Phone, Channel, Order Type, Payment Method, Payment Status, Subtotal, Discount, Delivery Fee, and Line-by-Line Total.

---

## 8. Ghana Tax & Regulatory Compliance (GRA & Act 843)

### 8.1 Ghana Revenue Authority (GRA) Tax & Levies
Eniceberny's financial parameters in `/admin/settings` (Card 6) allow dynamic configuration of statutory levies:
- **Value Added Tax (VAT)**: Configurable standard rate applied to catering and retail goods.
- **National Health Insurance Levy (NHIL)**: 2.5% statutory contribution.
- **Ghana Education Trust Fund (GETFund)**: 2.5% statutory contribution.
- **COVID-19 Health Recovery Levy**: 1.0% statutory levy where applicable.
- Itemized tax amounts are stored in `orders.tax_amount` and rendered on all formal PDF invoices and receipts.

### 8.2 Data Privacy & Financial Audit Trail (Act 843)
- Under the **Data Protection Act, 2012 (Act 843)**, all payment details (such as Mobile Money numbers and customer addresses) are stored securely with encrypted communication.
- Audit logs capture every financial status change, refund, and price modification in `audit_logs` with the operator ID, timestamp, and client IP address.

---

*For technical integration details or payment gateway webhooks, consult the [Payment Systems Guide](payments.md) and [REST API Guide](api.md).*
