# MongoDB setup

## Requirements

- Node.js 20 or newer
- A MongoDB Atlas cluster or a local MongoDB instance

## JavaScript application

The application runs with Node.js, Express, EJS, and the official MongoDB driver:

```powershell
npm install
Copy-Item .env.example .env
npm start
```

Open `http://localhost:3000` after setting `MONGODB_URI`, `MONGODB_DATABASE`, and `SESSION_SECRET` in `.env`.

## Master stock database

The portal database is the master copy of stock. Every unit has one status: **In stock**, **Issued** (through a requisition), **Assigned / deployed** (to a client or person), or **Retired**. Each change is recorded in `stock_movements`.

- **First load:** run `npm run import:stock` once to load `MasterDatabase/Master Stock Database.xlsx` (or pass another path: `npm run import:stock -- "D:\path\stock.xlsx"`). Units assigned to a person or client, or showing deployment details, are imported as Assigned; the rest as In stock. Re-running the import only adds units that are not in the database yet; it never changes existing units.
- **Upgrading from the workbook-synced version:** the first start migrates existing records in place (adds `stock_status` and `product_id`, creates the product catalogue). The workbook is no longer read at startup.
- **Day to day (Admin & Logistics, Master Database page):** receive new stock by pasting identifiers, add catalogue products, record returns, deployments to clients and write-offs, and export the current view to Excel. The Operations Manager can view and export.
- **Requisitions** pick products from the catalogue, and Admin & Logistics issues specific in-stock units of that product. Issuing reserves the units, approves the requisition and logs the movements in one transaction.

## Configure the connection

Copy `.env.example` to `.env` and set the MongoDB connection string:

```text
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority
MONGODB_DATABASE=staff_system
SESSION_SECRET=replace-with-a-long-random-secret
PORT=3000
```

The application reads these values from environment variables. Do not commit `.env`.

## Production settings

Set these before running with `NODE_ENV=production`:

- `SESSION_SECRET`: at least 32 random characters. The app refuses to start in production without it.
- `APP_BASE_URL`: the public origin used in password-reset links (for example `https://portal.gaptechsolutions.com`). Links are never built from the request's `Host` header in production.
- `TRUST_PROXY=true` when the app runs behind a reverse proxy, so secure cookies and client IPs work.
- `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`, `SMTP_FROM`: outgoing mail for password resets and notifications. Without `SMTP_HOST`, messages are only written to the console.
- `APP_TIMEZONE` (default `Africa/Nairobi`): used for request dates, leave accrual, and monthly reports.

## Security behaviour

- Every form POST carries a per-session CSRF token (added automatically by `public/app.js`). The M-Pesa callback routes are exempt because they are authenticated by their secret path token.
- Sign-in is limited to 8 failed attempts per email and IP in 15 minutes; reset-link requests to 5 per hour.
- Signed-in users are re-checked on every request, so deactivating an account or changing a role takes effect immediately.
- Self-registration only offers Staff, Technician, and Head Technician. Approval, finance, logistics, and director positions are granted by an administrator.
- Password-reset tokens are stored as SHA-256 hashes.

## Leave rules

Annual leave accrues at the user's entitlement ÷ 12 per month of the current year (21 days by default). Unused days from the previous year carry forward until 31 March. Only approved **annual** leave reduces the balance; leave awaiting approval is reserved so it cannot be double-booked. The staff dashboard, the application form, and HR's computation all use the same calculation.

Leave approval depends on the applicant's position:

| Applicant | Approved by |
|---|---|
| Technician | Head Technician → Operations Manager |
| Staff, Head Technician, Finance Officer, Admin & Logistics | Operations Manager |
| Operations Manager | Director Operations → Managing Director |
| Director Operations, Managing Director | Do not apply for leave in the portal |

Each step goes to the person holding that position in the applicant's reporting line (the **Supervisor** set on the Users page). If the line doesn't reach one, any active holder of the position can approve. Only the person at the current step can act; nobody can skip a step. The next approver is emailed after each approval. Every approver sees the applicant's leave balance, calculated automatically. There is no separate HR computation step.

## Petty cash expense reports

After a payout is disbursed, the staff member files an expense report from their dashboard. The amount received is always the confirmed payout; any unspent change is recorded as **change due**. The wallet is credited only when Admin & Logistics reconciles the report, confirming the cash was returned. Petty-cash amounts are whole shillings because M-Pesa B2C pays whole shillings.

## Daraja B2C sandbox

The Admin & Logistics **Send via M-Pesa** action uses Safaricom Daraja B2C in sandbox mode only. It will not send real money, and the app intentionally refuses any `MPESA_ENV` value other than `sandbox`.

1. Create a Daraja sandbox app and obtain its consumer key and secret.
2. Obtain a sandbox B2C shortcode and API initiator from Safaricom's M-Pesa organization onboarding. Generate the sandbox security credential using Safaricom's sandbox certificate; never put the initiator password in this application.
3. Copy `.env.example` to `.env` and set the sandbox values. Leave no `replace-with-*` placeholders.
4. Expose the app's callback endpoints through a public HTTPS URL during local testing, then set `MPESA_CALLBACK_BASE_URL` to that origin. Set `MPESA_CALLBACK_TOKEN` to a cryptographically random URL-safe value of at least 32 characters. The token is part of the callback path; do not log or share it.
5. Ensure MongoDB supports sessions/transactions (for example, MongoDB Atlas or a replica set). Payout reservation and treasury balance updates use a transaction to prevent duplicate sends and overspending.

The app reserves funds and records a pending transaction before requesting B2C. A successful Safaricom result callback changes the transaction to **Disbursed**. A definitive failure marks it failed and restores the reserved amount. Timeouts and ambiguous network outcomes remain reserved and cannot be retried until reconciled; do not treat the initial API acceptance as proof of payment.

Admin & Logistics enters the recipient's Kenyan M-Pesa number when initiating a payout. The API request is made server-side; no M-Pesa PIN is requested or stored by this app. Production credentials/endpoints are intentionally not enabled in this initial integration.

Official references: [Daraja B2C API](https://developer.safaricom.co.ke/apis/BusinessToCustomer), [Getting Started](https://developer.safaricom.co.ke/apis/GettingStarted), and [Transaction Status](https://developer.safaricom.co.ke/apis/TransactionStatus).

## Treasury balance from Safaricom

The treasury is funded outside the portal: finance loads the B2C utility account in the M-Pesa organisation portal (from the paybill or the bank). The portal reads that balance with the Daraja **Account Balance** API, using the same B2C credentials.

- **Available to disburse** on the Wallet page is the utility account's available balance, less payouts the portal has sent that Safaricom has not confirmed yet.
- The balance is read when the portal starts, every three hours, after each confirmed payout, and when Admin & Logistics (or the Managing Director) presses **Refresh balance**. Requests are at least a minute apart.
- The result arrives on `/mpesa/b2c/callback/<token>/balance/result`; the last 30 readings are kept on the wallet document for audit.
- The API initiator needs the balance-query role in the M-Pesa organisation portal.

## Create collections and indexes

Run the setup script from the project directory:

```powershell
npm run setup:mongodb
```

This creates indexes for users, requests, leave balances, wallet transactions, and expenditure reports. It also creates the request counters and company wallet document.

## Seed an administrator

Self-registration cannot create privileged accounts, so create the first Managing Director with the setup script:

```powershell
$env:ADMIN_NAME = "Jane Doe"; $env:ADMIN_EMAIL = "jane.doe@gaptechsolutions.com"; $env:ADMIN_PASSWORD = "Choose-A-Strong-Passw0rd"
npm run create:admin
```

That account can then activate registrations and assign positions from the **Users** page.

The **Managing Director** and **Director Operations** accounts are protected: they cannot be created, promoted into, demoted, re-roled, deactivated or deleted from the Users page, by anyone. Create or reset them with the same script; add `$env:ADMIN_POSITION = "manager"` to create the Director Operations (the default, `director`, is the Managing Director). You can also insert a user document manually with a password hash generated by `bcryptjs`.

Example document shape:

```json
{
  "id": 1,
  "full_name": "Admin User",
  "email": "admin@example.com",
  "password": "<bcrypt_hash>",
  "role": "super_admin",
  "position_level": "director",
  "supervisor_id": null,
  "department": "IT",
  "is_active": true,
  "reset_token": null,
  "reset_expires": null
}
```

## Data model

Requests are stored in the `requests` collection. Type-specific fields are embedded under `details`, which removes the SQL joins between request types.

The wallet uses these collections:

- `wallet`
- `wallet_transactions`
- `wallet_expenditures`
- `wallet_topups`

The wallet balance is changed with atomic MongoDB updates so concurrent disbursements cannot reduce it below zero.

The application is JavaScript-only and uses MongoDB collection operations. Keep secrets in `.env`, never commit them, and use a strong `SESSION_SECRET` in production.