# Library v2 Setup (Enroll + Dash)

Library V2 pairs [enroll.html](../enroll.html) (Google-Form-style enrollment) with [dash.html](../dash.html) (4-tab seat / member dashboard). The earlier setup used `library.html` and [dashboard-v2.html](../dashboard-v2.html). V2 uses a fresh `Members` sheet so existing `Orders` data is untouched.

## What's different from v1

| | v1 (library.html + dashboard-v2.html) | v2 (enroll.html + dash.html) |
|---|---|---|
| Form fields | Marketing-driven (plan picker, hero, reviews, scarcity) | Plain Google-Form-style: Name, Photo, Father, Phone, DOB, Email, Aadhar, Preparation, Exam details |
| Seat tracking | Capacity counter only | Per-seat (S1..SN) + shift assignment |
| Shifts | None | N shifts + optional Full Day, all configurable |
| Storage | `Orders` sheet | `Members` sheet (+ `Members_Archive`) |
| Backend | `scripts/store-apps-script.js` | `scripts/library-apps-script.js` |
| Expiry reminders | None | WhatsApp deep-link + Fast2SMS, daily cron |
| Photo size limit | 10 MB | 4 MB default (configurable via `MaxPhotoMB`) |

## One-time setup per tenant

Start with the [library setup wizard](../library-setup.html) to customize the spreadsheet starter. Downloading a workbook prepares the files; connecting the live app still requires the steps below. See the [onboarding and rollout guide](../docs/library/LIBRARY_ONBOARDING.md) for the spreadsheet edition and future cloud edition.

### 1. Tenant Sheet

Copy the master template OR create a new Google Sheet with these tabs:

- **`Config`** — paste [library-v2-config.csv](library-v2-config.csv). Edit `ShopName`, `Phone`, `WhatsApp`, `BrandColor`, `ShopkeeperPhone`, `SMSApiKey`, `RenewLink`. Set the dashboard PIN through Apps Script as described below; do not leave an example PIN in Config.
- **`Products`** — paste [library-v2-plans.csv](library-v2-plans.csv). Adjust prices.
- **`Members`** — use the wizard's header-only tab (24 columns), or omit this tab so the backend creates it on first use. Do not create a completely empty tab without headers.
- **`Members_Archive`** — use the wizard's header-only tab (26 columns), or omit it so the backend creates it on first archive.

### 2. Apps Script

In the tenant Sheet → **Extensions → Apps Script**:

1. Paste the contents of [scripts/library-apps-script.js](../scripts/library-apps-script.js) into `Code.gs`.
2. **Deploy → New deployment → Web app**:
   - Execute as: **Me**
   - Who has access: **Anyone**
   - Copy the resulting `/exec` URL.
3. For a new library, replace the example PIN inside `setupPin()` with a unique 4–8 digit PIN, run it once from the editor, then clear the literal from the source. This stores its hash in Script Properties. For an existing Config PIN, run `migrateDashboardPin()` once and verify that the plaintext Config value was removed.
4. (Optional) **Triggers → Add Trigger** → `dailyExpiryReminders` → Time-driven → Day timer → 8am-9am. This sends the 24h reminders. Without it, reminders still work but only when the shopkeeper taps **Send reminders now** in the dashboard.

### Floor 1 cutover for an existing library

1. Update the existing Apps Script web app to library script v11 or later so the registered `/exec` URL stays in place. In the Apps Script editor, add **Google Sheets API** under **Services** before deploying. Standard Google Cloud projects also need the Sheets API enabled in the linked project. Sign in to the updated dashboard again with its PIN. [Apps Script advanced services](https://developers.google.com/apps-script/guides/services/advanced)
2. Save a private copy of the tenant spreadsheet. In dashboard **Settings → Shifts & seating → Floors**, check the destination floor's capacity and reservations. Pause direct edits to the Config and Members tabs while reviewing and confirming the move.
3. In **Floors**, select **Floor 1 → Floor 2** or **Floor 2 → Floor 1** using the configured floor names. Review the seat mapping and verify that the destination will have at least one unassigned physical seat. Select **Confirm move and lock** to open the destination and close the source. If the response is unconfirmed, retry the same preview to verify whether Google Sheets completed the batch.
4. Check the seat map and operations workbook for the destination assignments and zero open capacity on the source floor. The `Floor_Migrations` tab records each old and new seat against its member ID. Use the dashboard reassignment flow for individual corrections.

To accept bookings on both floors after the move, clear the source floor's lock in **Floors**. Keep at least one floor open. To close the only open floor, open another floor first.

### 3. Registry row

Add the tenant to the Master Registry (Sheet ID `1U1T-OS6xx3xRRn2O7KoTw8NE6C-IwrQs6r88sACpejo`, tab `Stores`):

| Column | Value |
|---|---|
| `slug` | `study-point-library` |
| `SheetID` | the tenant Sheet ID |
| `ScriptURL` | the `/exec` URL from step 2 |
| `Type` | `LibraryV2` (used by the router to send `?store=…` to `enroll.html` instead of `library.html`) |

### 4. URLs

- Enrollment (customer): `https://storepro.in/enroll.html?store=<slug>`
- Dashboard (shopkeeper): `https://storepro.in/dash.html?store=<slug>` — PIN-gated.

## Configurable behaviour (everything is opt-in)

All toggles live in the `Config` sheet and can also be changed from **Dash → More → Settings**.

| Key | Default | What it does |
|---|---|---|
| `EnableShifts` | `yes` | Show the shift picker on enrollment. `no` = single-shift library, plan duration is the only thing tracked. |
| `ShiftCount` | `2` | How many time-of-day shifts. Supports 1–4. Labels/times pulled from `Shift1Label`/`Shift1Time` … `Shift4Label`/`Shift4Time`. |
| `EnableFullDay` | `yes` | Whether the "Full Day" option appears alongside the shifts. Full Day locks every shift for that seat. |
| `SeatCapacity` | `40` | Seats on Floor 1. Additional floor capacities are stored in `Floors`; the app totals unlocked floors. |
| `SeatPrefix` | `S` | Seat IDs become `S1`, `S2`, … `S<N>`. |
| `SeatGridCols` | `8` | Columns in the seat-map grid (8 cols × 5 rows = 40). |
| `RequireStudentPhoto` | `yes` | Block submit if no photo. |
| `RequireFatherName`, `RequireDOB`, `RequireEmail`, `RequireAadhar`, `RequirePreparation`, `RequireExamDetails` | varies | Hide / make-optional / require each field. |
| `MaxPhotoMB` | `4` | Reject photos larger than this. Bump higher if you want — Cloudinary free tier handles up to ~10 MB without issue. |
| `PhotoMinWidth` / `PhotoMinHeight` | `400` | Cheap client-side image-quality check (rejects screenshots-of-screenshots). |
| `ShowHistory` | `no` | If `yes`, **More → History** is visible with deleted + expired members. Off by default for cleanliness. |
| `ArchiveAfterDays` | `365` | Members deleted/expired more than this many days ago are moved from `Members` to `Members_Archive` when the shopkeeper taps **Archive old records**. Reduces gviz response size. |
| `ReminderEnabled` | `yes` | Master switch for expiry reminders. |
| `ReminderChannel` | `both` | `whatsapp`, `sms`, or `both`. |
| `ReminderHoursBefore` | `24` | How far ahead the cron looks. |
| `SMSProvider` | `fast2sms` | Currently only Fast2SMS is wired. Drop the API key in `SMSApiKey`. |
| `SMSTemplate` / `WhatsAppTemplate` | preset | `{name}`, `{plan}`, `{expiry}`, `{seat}`, `{shop}`, `{renewLink}` are substituted. |

## Test buttons

**Dash → More**:

- 🧪 **Send test SMS** — sends `SMSTemplate` to `ShopkeeperPhone`. Costs one Fast2SMS credit. Surfaces the provider's full response so you can debug a bad API key / DLT mismatch quickly.
- 🧪 **Send test WhatsApp** — opens a `wa.me` link to `ShopkeeperPhone` with the rendered template. Free.
- 🔔 **Send reminders now** — runs the daily cron manually for whoever's expiring in the next `ReminderHoursBefore` hours. Lets you sanity-check the cron without waiting for 8 AM.

## Fast2SMS notes (the "free SMS" part)

Fast2SMS is the only India-friendly provider with a real free tier you can hit from Apps Script. Two routes:

- **Route `q` (Quick SMS)** — free / cheap, **promotional** category, lower delivery rate (~60-70% in our testing). No DLT registration needed. Use this for v1.
- **Route `dlt` / `dlt_manual`** — high delivery, but requires DLT registration via the operator (BSNL / Jio / Airtel) — 2-3 weeks + a small fee. Only worth it once the library has > 50 members.

If `SMSApiKey` is empty, the reminder still gets sent on WhatsApp (assuming `ReminderChannel` is `both` or `whatsapp`) and the SMS step is logged-and-skipped.

## Data shape

### `Members` sheet columns

`MemberID | EnrolledAt | Name | FatherName | Phone | DOB | Email | Aadhar | Preparation | ExamDetails | PhotoURL | Plan | StartDate | ExpiryDate | Seat | Shift | TotalPaid | Discount | PaymentDate | Status | LastReminderSent | Notes | AadharPhotoURL | EnrollmentMode`

These are the 24 columns in the backend's `MEMBERS_HEADERS`. Keep their names intact and format IDs, phone numbers and identity fields as text.

- `Status` = `Active` | `Deleted` | `Expired` | `Paused`
- `Shift` = `S1` / `S2` / … / `Full`
- `Seat` = `S1` / `S2` / … / `S<N>`, or empty when shopkeeper didn't pick (allowed)
- Members deleted from Dash are **soft-deleted** (Status = `Deleted`), not removed. They become visible only when `ShowHistory=yes`.

### `Members_Archive`

The same 24 member columns followed by `ArchivedReason` and `ArchivedAt` (26 columns total). The backend stores member snapshots here and moves older records through `archiveOldMembers()` when the shopkeeper selects **Archive old records**. Keep this tab empty apart from its headers in a new workbook.

## Migration from v1 (existing library.html tenants)

Not required — v1 keeps working. If a tenant wants to switch:

1. Export their `Orders` rows that have `Items` containing `Plan:` (these are enrollments) to a CSV.
2. Transform the CSV to the Members schema. The notes column has `plan=…`, `idPhoto=…`, etc. in `key=value · key=value` form — straight string splits.
3. Paste into the new `Members` sheet.
4. Flip the registry row's `Type` to `LibraryV2`.

A scripted migration is not provided in v1; eyeball-and-paste is fine for a 40-seat library.
