# Two-step verification (email code) — client contract

For the web and mobile clients. Everything here is additive: a client that
ignores it keeps working exactly as before for every account that has not
turned two-step verification on, and only a user can turn it on, from their
own profile.

## Sign-in

### 1. `POST /api/auth/login`

```json
{ "email": "a@b.com", "password": "…", "supportsTwoFactor": true }
```

Send `supportsTwoFactor: true` once the client has the code screen below.

| Account | Client sends the flag | Response |
|---|---|---|
| 2FA off | either | `200 { user, accessToken }` + refresh cookie — unchanged |
| 2FA on | yes | `200 { twoFactorRequired: true, challengeId, emailHint, expiresInSeconds, resendAfterSeconds }` — no token, no cookie |
| 2FA on | no (older builds) | `403 { error, code: "TWO_FACTOR_APP_UPDATE_REQUIRED" }` — `error` tells the user to update the app |

A wrong password is still `401` and sends no code.

### 2. `POST /api/auth/login/verify`

```json
{ "challengeId": "<uuid from step 1>", "code": "123456" }
```

`200 { user, accessToken }` + refresh cookie — the same shape as a normal login.

### Resend: `POST /api/auth/login/resend`

```json
{ "challengeId": "<uuid>" }
```

Returns a fresh challenge body (same `challengeId`). The previous code stops
working; the wrong-attempt count carries over.

## Turning it on or off (signed in, any role)

| Call | Body | Result |
|---|---|---|
| `POST /api/auth/2fa/enable` | — | challenge body; `409` if already on |
| `POST /api/auth/2fa/enable/verify` | `{ challengeId, code }` | `200 { user }` with `user.twoFactorEnabled: true` |
| `POST /api/auth/2fa/disable` | — | challenge body; `409` if already off |
| `POST /api/auth/2fa/disable/verify` | `{ challengeId, code }` | `200 { user }` with `user.twoFactorEnabled: false` |
| `POST /api/auth/2fa/resend` | `{ challengeId, purpose: "enable" \| "disable" }` | challenge body |

`GET /api/auth/me` (and login/refresh) now include `user.twoFactorEnabled`.

## Rules the server enforces

- Codes are 6 digits, valid for `OTP_TTL_MINUTES` (default 10), single use.
- 5 wrong codes lock the challenge (`429 OTP_LOCKED`) — start the sign-in again.
- Resend: 30 s cooldown (`429 OTP_RESEND_COOLDOWN`), at most 5 per challenge.
- At most 10 codes per user per hour (`429 OTP_RATE_LIMITED`).
- A code is only accepted for the purpose it was sent for (a sign-in code
  cannot turn 2FA off).
- Error codes a client may branch on: `OTP_INVALID` (400, message says tries
  left), `OTP_EXPIRED` (400), `OTP_LOCKED`, `OTP_RESEND_COOLDOWN`,
  `OTP_RESEND_LIMIT`, `OTP_RATE_LIMITED` (429), `EMAIL_NOT_CONFIGURED`,
  `EMAIL_SEND_FAILED` (503), `TWO_FACTOR_APP_UPDATE_REQUIRED` (403).

## Invoices (related, same release)

- `GET /api/invoices/my-dues` payments now carry `reference` (UPI/UTR, card
  slip or cheque number) when the office recorded one.
- `POST /api/invoices/:id/pay` accepts an optional `reference` (max 80 chars).
- Admin invoice payloads include `student.bed { label, room { number, floor } }`.
- `GET /api/invoices/my-dues/:id/pdf` — same URL and file name; the document
  now uses the GymCare house layout with student name, room, fee period,
  payment ID (`PAY-XXXXXXXX`) and transaction reference.

## Fee cycles, Pending / Partial / Completed, payment history (same release)

All additive; older clients keep working.

- `Room.feeCycleMonths` (default 1): accepted on `POST /api/rooms` and
  `PATCH /api/rooms/:id`, 1–12. Returned on every room payload.
- `Invoice.cycleMonths` (default 1) on every invoice payload; `my-dues` rows
  also carry `periodEnd` (YYYY-MM). A quarterly room's invoice is
  `3 × monthlyRent` with `cycleMonths: 3`. "Generate rent" skips any student
  whose months are already covered and reports `coveredByCycle`.
- `InvoiceStatus` gains `PARTIAL` (some money in, not all). Clients that
  test `status === 'PAID'` need no change; clients that test
  `status === 'PENDING'` to mean "unpaid" must use `!== 'PAID'`.
  `GET /api/invoices?status=PARTIAL` filters on it.
- `POST /api/invoices/:id/pay` also accepts `method` `BANK_TRANSFER` and
  `CHEQUE`, and optional `paidAt` (`YYYY-MM-DD`, not in the future) so an
  offline payment can be dated the day it was received.
- `GET /api/invoices/my-dues/stats` adds `currentFee`:
  `{ rent: { monthly, cycleMonths, perCycle, dueDay, pricingMode } | null,
  rentBilledToSomeoneElse, mess: { subscribed, mode, monthlyFee, dailyRate } }`.
- `GET /api/invoices/my-dues/payments` (student): the student's payments,
  newest first, each with `invoice { id, type, periodMonth, cycleMonths,
  periodEnd, amount, status }`. Pass `page`/`limit` for an envelope.

## Email notifications (same release)

Server-side; nothing for a client to do. Each is on by default per hostel and
can be switched off in Settings → Reminders & emails. All run after the API
response, so no endpoint got slower. Nothing is delivered until
`EMAIL_PROVIDER=smtp` with the `SMTP_*` values and `EMAIL_FROM` are set (see
the runbook) — until then every send is logged as a dry run.

| Event | Who is emailed | Trigger |
|---|---|---|
| Payment confirmation (receipt PDF attached) | the student | `POST /api/invoices/:id/pay` |
| Payment failed | the student | `POST /api/invoices/payments/:paymentId/fail` |
| Fee due (new invoice) | each student invoiced | `POST /api/invoices/generate` |
| Fee reminder | the student | the existing reminder schedule (now HTML) |
| Important notice | everyone in the hostel except the poster | `POST /api/notices` with `important: true` |

Additive API changes:

- `Payment.status` (`CLEARED` default, or `FAILED`) with `failedAt`,
  `failureReason`. Failed payments are left out of every `payments` array and
  balance the API returns, except the student's own
  `GET /api/invoices/my-dues/payments`, which lists them with `status: "FAILED"`.
- `GET /api/invoices/:id/payments` (MANAGE_RENT): all payments on an invoice,
  failed included. `POST /api/invoices/payments/:paymentId/fail`
  `{ reason? }` reverses one; the invoice drops back to PARTIAL/PENDING.
- `Notice.important` (boolean, default false) accepted on `POST /api/notices`
  and returned with `emailedAt` / `emailedCount`.
- `GET/PUT /api/billing-settings` carry `notifyPaymentEmail`,
  `notifyInvoiceEmail`, `notifyNoticeEmail`.
- `GET /api/billing-settings/notifications/recent?limit=` (MANAGE_RENT): the
  audit of recent sends — kind, recipient, status (`SENT` / `DRY_RUN` /
  `FAILED`).

## Billing rules — pro-rata, late fee, charges, GST (Sprint 1)

Four per-property rules, all OFF by default. A hostel that never opens
Settings → Billing rules keeps producing exactly the invoices it does today,
so no client needs to change. Everything below is additive.

What a client sees on an invoice (`GET /api/invoices`, `GET /api/invoices/my-dues`,
`POST …/pay` responses, student `my-dues` rows):

- `lines: [{ id, kind, label, amount, meta, createdAt }]` — the explanation
  under `amount`. `kind` is one of `RENT`, `MESS`, `CHARGE`, `LATE_FEE`,
  `PRORATA_CREDIT`, `GST`. A negative `amount` is a credit. Invoices raised
  before this release have `lines: []`; render them as the single row you do
  today. `amount` is still the total and still what the student pays.
- `taxAmount` (int, default 0): the GST included in `amount`.
- `coveredFrom` / `coveredTo` (ISO date or null): the days actually billed
  when pro-rata trimmed the cycle at either end. Null means the whole cycle.
- `type` can now also be `OTHER`: a standalone invoice for one-off charges.
  An old build that switches on `RENT`/`MESS` should fall back to a generic
  label (“Charges”), not crash.
- The PDF (`/pdf` routes) prints one row per line, plus “Taxable amount” and
  “GST included” rows when `taxAmount > 0`. Same endpoints, same file names.

Student record: `movedInAt` and `vacatedAt` (ISO date or null). The admin
app may send `movedInAt` (YYYY-MM-DD) on `POST /api/students` and on
`PATCH /api/students/:id/bed`, and `vacatedAt` on the same PATCH with
`bedId: null`. Omitted means today, which is what every current build gets.

Admin endpoints (MANAGE_RENT):

- `GET/PUT /api/properties/:id/billing-rules` → `{ rules: { prorataEnabled,
  lateFeeEnabled, lateFeeGraceDays, lateFeeMode: 'FLAT'|'DAILY', lateFeeAmount,
  lateFeeCap, gstEnabled, gstRate, gstThreshold } }`. PUT takes any subset.
- `POST /api/properties/:id/billing-rules/run-late-fees` → the pass that
  otherwise runs hourly; `{ result: { invoicesCharged, totalAdded } }`.
- `GET/POST /api/properties/:id/charge-types`,
  `PATCH/DELETE …/charge-types/:chargeTypeId`,
  `PUT …/charge-types/:chargeTypeId/students { studentIds }`.
  `frequency` is `MONTHLY` (× months covered), `PER_CYCLE` (once per
  invoice) or `ONE_OFF` (a preset only). DELETE answers
  `{ deactivated: true }` instead of removing a type that has been billed.
- `GET/POST /api/students/:id/charges` — one-off charges.
  `POST { label, amount, chargeTypeId?, note?, date?, billNow }` answers
  `{ charge, invoice }`: with `billNow: true`, `invoice` is a new `OTHER`
  invoice due in 7 days; otherwise `invoice` is null and the charge becomes a
  `CHARGE` line on the student's next rent invoice.

Rules of thumb the server applies: pro-rata counts whole days from the
move-in date to the end of the cycle, rounded to the rupee; a move-out under
pro-rata credits unused days on the open rent invoice but never below what
is already paid; late fees run once per invoice per day, FLAT once or DAILY ×
days since the last pass, capped; GST applies only when the monthly rent is
above the threshold, on the rent line, never on charges.

## Online collection — Razorpay Payment Links + Route (Sprint 2)

A student pays an invoice through a hosted Razorpay page; the webhook is the
only thing that records money. Per hostel and OFF by default: until the owner
connects a bank account and switches it on, nothing sends or shows a link,
and every existing build behaves exactly as today. An online payment appears
to old builds as an ordinary cleared payment with `method: "ONLINE"` and the
Razorpay payment id as `reference`.

What a client sees:

- `GET /api/invoices/my-dues` now also returns a top-level
  `onlineCollection: boolean`, and each row carries `canPayOnline: boolean`
  and `paymentLink` (the live or just-paid request, or null). Office invoice
  rows (`GET /api/invoices`) carry `paymentLink` too.
- A payment request:
  `{ id, invoiceId, status: PENDING|PAID|FAILED|EXPIRED|CANCELLED, baseAmount,
     grossAmount, fees: { gatewayFee, gatewayFeeTax, routeFee, routeFeeTax, total },
     feeBearer: STUDENT|HOSTEL, linkUrl, expiresAt, paidAt, paymentId,
     latestError, sentCount, sentAt, createdAt }`.
  `baseAmount` is what the invoice is owed; `grossAmount` is what the payer is
  charged (the two differ when the student bears the gateway fee). A PENDING
  request past `expiresAt` reads as EXPIRED. `latestError` is the last failed
  attempt's reason while the link stays open.

Student flow (the mobile app should do exactly this):

1. Show **Pay** on an unpaid row when `canPayOnline` is true.
2. `POST /api/invoices/my-dues/:id/pay` → `201 { paymentRequest }`. Idempotent:
   pressing Pay again returns the same live link; a link for a stale balance
   is replaced. Errors: 400 `ONLINE_COLLECTION_OFF`, 400
   `PAYMENT_ACCOUNT_NOT_ACTIVE`, 409 `INVOICE_SETTLED`, 503
   `GATEWAY_NOT_CONFIGURED` / `GATEWAY_ERROR`.
3. Open `linkUrl` (a Razorpay hosted page) in a browser / Custom Tab. Do NOT
   use the Checkout SDK against it; it is a Payment Link.
4. While the sheet is open, poll `GET /api/payment-requests/:id` every 5 s.
   When `status` becomes PAID, refresh dues and show the receipt
   (`/api/invoices/my-dues/:id/pdf` unchanged).
5. Razorpay redirects to `<PUBLIC_WEB_URL>/pay/result?razorpay_payment_link_status=paid&…`
   — a display-only page. The app may ignore the redirect and rely on polling.

Office endpoints (MANAGE_RENT): `POST /api/invoices/:id/payment-link { send? }`,
`POST /api/invoices/payment-links/send-unpaid { period }`,
`POST /api/invoices/fee-preview { amount }`, `GET /api/payment-requests/:id`,
`POST /api/payment-requests/:id/send`, `POST /api/payment-requests/:id/cancel`,
`GET/POST /api/billing-settings/payments-account`,
`POST /api/billing-settings/payments-account/refresh`. `PUT /api/billing-settings`
accepts `onlineCollectionEnabled` and `feeBearer`; switching on needs an
active account (400 `PAYMENT_ACCOUNT_NOT_ACTIVE`).

Server-side, for whoever operates it: env `RAZORPAY_KEY_ID`,
`RAZORPAY_KEY_SECRET`, `RAZORPAY_WEBHOOK_SECRET`, `PUBLIC_WEB_URL`; point
Razorpay's webhook at `POST /api/webhooks/razorpay` for `payment_link.paid`,
`payment.captured`, `order.paid`, `payment.failed`, `payment_link.expired`,
`payment_link.cancelled`, `refund.processed`, `account.*` and
`product.route.*`. Replays are no-ops; a capture for the wrong amount is
rejected; a refund reverses the payment in the books; a late capture on an
expired link is still honoured. Reminders carry the pay link when collection
is on.

## Collection hardening (Sprint 3) — additive

- `GET /api/invoices/my-dues` now also returns `virtualAccount`
  (`{ accountNumber, ifsc, bankName, upiId, status }` or null): the student's
  own Razorpay Smart Collect details. Show them as "Pay by bank transfer or
  UPI" when present; a transfer to them is recorded on the oldest open
  invoice by webhook with the UTR as `reference` and `method: "VIRTUAL_ACCOUNT"`.
  Any excess becomes a settled `OTHER` invoice labelled "Advance received…".
- Payments can carry `gatewayPaymentId`, `refundId`,
  `refundStatus` (`REQUESTED` | `PROCESSED` | `FAILED`), `refundAmount`,
  `refundedAt` (office list `GET /api/invoices/:id/payments`). A processed
  refund shows as a FAILED payment with the reason, exactly like a reversal.
- `GET /api/invoices/summary` gains `collectedOnline`.
- `GET /api/students/me` gains `mandateRef`, `mandateStatus`, `mandateSetAt`;
  `PUT /api/students/me/mandate { mandateRef, mandateStatus? }` stores a UPI
  Autopay mandate reference the student set up through Razorpay
  Subscriptions. Storage only — nothing is debited.
- Office (MANAGE_RENT): `GET /api/collections/dashboard?period=`,
  `GET /api/collections/reconciliation?date=`, `POST /api/collections/reconcile`,
  `POST /api/invoices/payments/:paymentId/refund { amount?, reason }`,
  `GET/POST/DELETE /api/students/:id/virtual-account`,
  `PUT /api/students/:id/mandate`. `PUT /api/billing-settings` accepts
  `virtualAccountsEnabled`.
- Webhook handles `refund.created`, `refund.failed`, `virtual_account.credited`
  in addition to Sprint 2's events. A reconciliation job re-checks open
  links every 10 minutes and compares each day with Razorpay nightly, so a
  client never needs to "confirm" a payment itself.

## Move-out and settlement (Sprint 4) — additive

Students keep working exactly as before until they, or the office, start a
move-out. The existing `PATCH /api/students/:id/bed { bedId: null }` still
frees a bed without a settlement.

- `StudentProfile.residencyStatus`: `ACTIVE` | `NOTICE` | `VACATED` (new
  field, default ACTIVE). Vacated students keep signing in and reading
  receipts; their `bed` is null and `vacatedAt` is set.
- Student: `GET /api/students/me/move-out` →
  `{ residencyStatus, policy: { noticeDays, refundDays, earliestLastDay }, moveOut }`.
  `POST /api/students/me/move-out { lastDay: YYYY-MM-DD, reason? }` (400
  `NOTICE_TOO_SHORT` when earlier than policy; 409 `MOVE_OUT_EXISTS`).
  `DELETE /api/students/me/move-out` withdraws a notice nobody has acted on.
  `GET /api/students/me/settlement` → `{ settlement, moveOut }` — `settlement`
  is null until the office shares it. `GET /api/students/me/settlement/pdf`.
  `POST /api/students/me/settlement/dispute { body }` opens a
  `DISPUTE_SETTLEMENT` request (new `StudentRequestType` value; a client
  that switches on the type should fall back to a generic label).
- A move-out: `{ id, status: NOTICE|CHECKLIST|DRAFT|SHARED|DISPUTED|REFUNDED|CANCELLED,
  lastDay, noticeDate, startedBy, reason, daysToGo, settlement }`. A settlement:
  `{ depositHeld, duesBalance, prorataCredit, deductions: [{ label, amount, note, photoKey, fromCheck }],
  deductionsTotal, refundDue, shortfall, shortfallInvoiceId, promisedDate, sharedAt,
  refundedAt, refundAmount, refundMethod, refundReference, disputeRequestId, overdue }`.
  `refundDue = max(0, depositHeld − deductions − (dues − credit))`; a shortfall is
  raised as an `OTHER` invoice on share and appears in `my-dues`.
- Office: `GET /api/move-outs` (MANAGE_STUDENTS) → `{ items, refundsOverdue }`;
  `GET/PATCH /api/move-outs/:id`, `POST …/cancel`; `PUT …/settlement`,
  `POST …/share`, `POST …/reopen`, `POST …/refund { amount?, method, reference?, paidAt? }`
  (MANAGE_RENT); `GET …/pdf`. `POST /api/students/:id/move-out`,
  `GET/POST /api/students/:id/asset-check { phase: IN|OUT, items: [{ key, ok, note?, photoKey? }] }`,
  `GET/PUT /api/properties/:id/asset-template` (MANAGE_ROOMS). Property gains
  `noticeDays` (30) and `refundDays` (15), editable through `PATCH /api/properties/:id`.
  Upload kind `ASSET_PHOTO` for checklist photos.

## Gate passes, guard, visitors, attendance, guardians (Sprint 5) — additive

New roles `GUARD` and `GUARDIAN` on the `Role` enum. Old builds never meet
them: those users are new, and a build that switches on role should treat
unknown roles as "unsupported account, use the web app". Leave requests
keep their shape; the pass is a separate object.

- `PATCH /api/requests/:id/status { status: "APPROVED", issuePass?: true, destination? }`
  answers `{ request, pass }` (`pass` null unless issued). Also
  `POST /api/requests/:id/pass { destination? }` → `{ pass, qr }`.
- A pass: `{ id, requestId, validFrom, validTo, destination, status:
  PENDING_GUARDIAN|ACTIVE|OUT|RETURNED|OVERDUE|DECLINED|CANCELLED|EXPIRED,
  guardianRequired, guardianApprovedAt, guardianDeclinedAt, guardianNote,
  outAt, inAt, nextAction: OUT|IN|NONE, band: green|amber|red|grey }`.
- Student: `GET /api/passes/me`; `GET /api/passes/:id/qr` → `{ pass, qr }`.
  The QR string is `HCPASS1.<passId>.<token>` — opaque, names nobody, and
  **rotates on every call** (render it fresh when the card opens; a
  screenshot is not accepted at the gate). `GET /api/students/me/attendance`
  → `{ days: [{ date, firstOut, lastIn, moves, nightIn, today }], summary }`
  (30 days). Visitors: `GET/POST /api/visitors/me`, `DELETE /api/visitors/me/:id`.
- Guard (role GUARD, or any staff with MANAGE_GATE): `POST /api/gate/scan { qr }`
  → `{ pass, student: { name, room, photoUrl }, allowed, reason }`;
  `POST /api/gate/punch { passId?, studentProfileId?, direction: IN|OUT }`;
  `GET /api/gate/summary`; `GET /api/gate/students?q=`; visitors
  `GET/POST /api/visitors`, `POST /api/visitors/:id/arrived|left`,
  `GET /api/visitors/export?date=` (CSV). The web guard screen is `/guard`.
- Office: `GET /api/gate/tonight` (VIEW_ATTENDANCE), `GET /api/passes`,
  `PATCH /api/passes/:id`, `POST /api/passes/:id/cancel`,
  `POST /api/gate/late-returns/run`; guardians `GET/POST/DELETE
  /api/students/:id/guardians[/:linkId]` (POST returns a one-time password
  once, and emails it). Property gains `guardianApprovesPasses` and
  `curfewTime` via `PATCH /api/properties/:id`.
- Guardian (role GUARDIAN): `GET /api/guardian/students`, and per student
  `/dues`, `/invoices/:id/pdf`, `/attendance`, `/passes`, `/notices`,
  `/settlement[/pdf]`; `POST /api/guardian/passes/:id/approve|decline { note }`.
- Hourly: a pass still OUT past `validTo` becomes OVERDUE, the warden(s) and
  the guardian are emailed, and it shows on the gate summary and overview.

## Sprint 6 — meal opt-out, request SLAs, Tally, vacancy page, salary (additive)

Everything here is new; an older build keeps working unchanged. The mess
calendar stays read-only for a build that does not know about opt-out.

- **Meal opt-out** (off per hostel until the mess admin enables it):
  `GET /api/mess/opt-out/me?period=YYYY-MM` →
  `{ optOut: { enabled, cutoff: "20:00", minRebateDays, weights: { BREAKFAST, LUNCH, DINNER },
  onMess, days: [{ date, meals: ["DINNER"] }], billing: { mode, openDays, billedDays, dailyRate, estimate } } }`.
  `PUT /api/mess/opt-out/me { date, meals: { BREAKFAST?: bool, LUNCH?: bool, DINNER?: bool } }`
  (`true` = skipping). Refused with 409 `OPT_OUT_DISABLED` when the hostel has
  not enabled it, 400 `OPT_OUT_CUTOFF` after the cutoff (IST, the day
  before), 400 on a mess holiday or a day the student is not on the mess.
  Show the cutoff on the sheet; the toggles disable after it. `billing.estimate`
  is what the month would cost at the current rate (null under actual-cost).
- Mess invoices: `billableDays` is now fractional when opt-out is on (a dinner
  is 0.4 of a day by default). Under `minRebateDays > 1` only runs of whole
  days at least that long reduce the bill; single meals still change the
  kitchen's headcount. Admin-marked day-offs are unchanged.
- Office/mess admin: `GET /api/mess/headcount?date=` → `{ headcount: { onMess,
  dayOff, breakfast, lunch, dinner, optedOut } }`; `PUT /api/mess/settings`
  gains `messOptOutEnabled, messOptOutCutoff, messMinRebateDays,
  messBreakfastWeight, messLunchWeight, messDinnerWeight` (weights together, sum 100).
- **Request SLAs and vendors** (MANAGE_STUDENTS): `GET/PUT /api/requests/slas
  { slas: [{ type, hours }] }`; `GET/POST /api/requests/vendors`,
  `PATCH /api/requests/vendors/:id`. A new request carries `dueBy` when its
  type has a target (null otherwise); `PATCH /api/requests/:id { vendorId?,
  dueBy?, cost? }`. Requests gain `dueBy`, `vendor { id, name, trade, phone }`,
  `cost`, `costExpenseId`. Closing a request with a cost books a
  MAINTENANCE/OTHER expense once. `/api/requests/summary` gains `breached`;
  `GET /api/requests?status=BREACHED` lists open requests past `dueBy`.
  Student app: show an "expected by" line from `dueBy` when present.
- **Tally** (HOSTEL_ADMIN): `GET /api/account/export/tally?period=YYYY-MM[&format=csv][&preview=true]`
  → Tally Prime import XML (Sales per invoice, Receipt per cleared payment,
  Payment per expense, ledger masters included) or a ledger CSV.
- **Public vacancy page** (no session, rate limited, keyed by slug only):
  `GET /api/public/properties/:slug` → `{ property: { name, hostel, city,
  address, description, phone, amenities, accentColor, logoUrl, photos,
  roomTypes: [{ type, beds, vacant, rentFrom }], vacantBeds } }` (404 until the
  owner enables it); `POST /api/public/properties/:slug/enquiries { name,
  phone, email?, roomType?, moveIn?, message? }`. Property settings via
  `PATCH /api/properties/:id { publicEnabled, publicSlug, publicDescription,
  publicPhone, amenities[], photos[] }` (slug unique across HostelCare; 409
  when taken). The web page is `/stay/:slug`.
- **Enquiries** (MANAGE_STUDENTS): `GET /api/enquiries[?status=]`,
  `GET /api/enquiries/summary`, `PATCH /api/enquiries/:id { status, note }`,
  `GET /api/enquiries/:id/free-beds`, `POST /api/enquiries/:id/reserve
  { bedId, days }` (bed → RESERVED), `POST /api/enquiries/:id/release`. Holds
  past `reservedUntil` are released hourly. Leaving RESERVED by any status
  change frees the bed.
- **Staff salary** (HOSTEL_ADMIN for the money fields): `POST/PATCH
  /api/sub-admins[/:id]` accept `monthlySalary`, `salaryDay` (1–28); staff
  rows carry both. `GET /api/sub-admins/salary-run?period=` previews;
  `POST /api/sub-admins/salary-run { period }` books one SALARY expense per
  paid staff member (idempotent per month). The hourly tick books it on the
  pay day by itself. GUARD staff are now listed and editable like wardens.
- Deferred from the plan: a token payment link on a reserved bed (needs a
  student record), staff on the biometric roll and guard scan.

## Tenant kind (additive)

Every tenant is a `HOSTEL`, `PG` or `DORMITORY`; existing rows are hostels.
Set at `POST /api/tenants { kind }` (super admin; omitted = HOSTEL) and
changed with `PATCH /api/tenants/:id { kind }`. Tenant list and detail carry
`kind`. The signed-in user (login, refresh, `GET /api/auth/me`) gains
`tenantKind` (null for platform admins) and `features: string[]`, and
`GET /api/features` answers `{ kind, kindLabel, features, catalogue }`.
Today every kind gets every module, so a build may ignore all of this; a
build that reads `features` should hide the navigation for a key that is
absent, which is how a kind will start to differ without an app release.
Keys: rooms, students, billing, onlinePayments, moveOuts, mess, requests,
gate, guardians, notices, expenses, staff, biometric, analytics, publicPage.

## Dormitory stays (additive; only used when the tenant kind is DORMITORY)

- Property gains `checkInTime` / `checkOutTime` (HH:MM, defaults 12:00 /
  11:00) and `earlyCheckInCharge` / `lateCheckOutCharge` (rupees, default 0)
  via `PATCH /api/properties/:id`.
- Rooms gain `rateBasis: MONTHLY|DAILY` (default MONTHLY) and `nightlyRent`;
  beds gain `nightlyRent`. `POST /api/rooms` accepts `rateBasis`,
  `nightlyRent`, `bedNightlyRent`; `PATCH /api/beds/:id/rent` accepts
  `nightlyRent`. The monthly rent run skips DAILY rooms.
- `PATCH /api/students/:id/bed { bedId, checkIn, checkOut, amount? }` (ISO
  datetimes) books a stay instead of a plain move-in and answers
  `{ profile, stay }`. A booking reserves the window only: the bed is taken
  (bed OCCUPIED, profile.bedId) at check-in and freed at check-out, so one
  bed can carry several bookings in a day as long as their windows do not
  overlap (409 names the clash). `amount` charges a figure of the office's
  own instead of nights × rate and sets `stay.amountOverridden`.
  Under a DAILY room the stay is invoiced at once: nights × nightly rate, as
  a RENT invoice for the check-in month (OTHER when that month already has
  one). Without the two times the old move-in behaviour is unchanged.
- `/api/stays` (MANAGE_STUDENTS): `GET ?open=true|status=|studentProfileId=`
  plus `q=` (customer name, email or phone), `from=`/`to=` (planned
  check-in day, YYYY-MM-DD) and `page=`/`limit=` for a paged history; each
  stay in a list carries `billing: { invoiceId, amount, paid, due, status }`
  for its own rent invoice (null when nothing was invoiced),
  `GET /board?date=` → `{ arrivals, departures, inHouse }`,
  `GET /availability?from=&to=` (ISO datetimes) → `{ availability: { from,
  to, free, beds: [{ bedId, roomId, free, reason: 'clash'|'hold'|'occupied'|null,
  clash, occupant? }] } }` — which beds are free for a whole window, for
  planning a booking,
  `GET /occupancy?date=` → `{ occupancy: { date, stays } }` (the booked or
  checked-in stays holding a bed on that day; an overstay past its planned
  check-out still holds the bed for today and earlier), `POST` (same body
  as above plus `studentProfileId`), `POST /:id/check-in { at?, early? }`,
  `POST /:id/check-out { at?, late? }`, `POST /:id/cancel` (takes the charge off
  the stay's rent invoice when nothing was paid on it — the invoice goes, or
  a shared charges invoice gets a negative adjustment line; a paid one is
  left for a refund),
  `PATCH /:id { bedId?, checkIn?, checkOut?, amount?, note? }` to reschedule
  or edit — a booked stay can change everything, a checked-in one only the
  check-out, note and charge; `amount: null` returns to nights × rate; the
  rent invoice is rewritten to the new charge (or, on a shared charges
  invoice, gets an adjustment line), and the charge cannot drop below what
  has been collected (409). Early and late
  default from the property's standard times on the planned day and can be
  overridden; each raises an OTHER invoice for the charge when one is set,
  and a check-out on a later day adds the extra nights at the stay's rate.
  Check-out frees the bed; the customer record stays.
- A stay: `{ id, status: BOOKED|CHECKED_IN|CHECKED_OUT|CANCELLED,
  plannedCheckIn, plannedCheckOut, actualCheckIn, actualCheckOut,
  earlyCheckIn, lateCheckOut, nights, ratePerNight, amount, invoiceId,
  earlyInvoiceId, lateInvoiceId, student { id, user }, bed { id, label, room } }`.
- Wording: the web app says "Customers" instead of "Students" for a
  DORMITORY tenant; the API paths are unchanged.

## Feature list by tenant kind

`FEATURES_BY_KIND` in `src/lib/tenant-features.ts`: hostels and PGs get
every module; a DORMITORY leaves out `moveOuts`, `gate`, `mess` and
`notices` (5 Oct 2026). The list rides on the signed-in user's `features`
and on `GET /api/features`; the clients hide the matching navigation. The
routes themselves are not gated yet.

## Customers without a login (additive)

- `POST /api/students` now accepts `name` without `email` and `password`
  (both or neither; one without the other is 400). The account is created
  with `hasLogin: false`, a placeholder address under
  `no-login.hostelcare.invalid`, and a password nobody holds. Sign-in with
  that address answers 401 like a wrong password, and every email send to
  it is skipped (`sendEmail` reports `mode: 'no-login'`).
- Every user payload (`/api/auth/*`, student lists and details) carries
  `hasLogin` (true for every account that existed before the flag). Clients
  should print "No login yet" in place of the email when it is false.
- `POST /api/students/:id/login { email, password }` (MANAGE_STUDENTS) gives
  such an account a real login; 409 when it already has one or the email is
  taken. Older clients that always send email and password are unaffected.

## Plans by properties and beds (additive)

- `Plan.maxBeds` (nullable = unlimited) joins `maxProperties`; the
  migration sets `maxBeds = maxStudents` on existing plans. `maxRooms` and
  `maxStudents` stay in the table but are no longer accepted by
  `POST/PATCH /api/plans` (dropped silently) nor enforced.
- Enforced: properties at property creation, beds at room creation (the
  room's `bedCount`) and at `POST /api/beds`. Students and rooms are not
  capped. Error code `PLAN_LIMIT_REACHED` as before.
- Validation: limits are whole numbers 1–100,000 or null; `maxBeds` must be
  ≥ `maxProperties` (400). Lowering a plan below what a tenant on it already
  has, or moving a tenant onto a plan it has outgrown, is refused with
  `PLAN_BELOW_USAGE` (409) naming the tenant and the figure.
- `GET /api/plan-usage` adds `beds { used, max }`; `rooms` and `students`
  are still reported with `max: null` for older app builds. Tenant rows
  carry `bedCount`, and `plan.maxBeds`.

