mirror of
https://github.com/pupperpowell/bibdle.git
synced 2026-08-22 22:32:28 -04:00
Added verse-submission infrastructure
This commit is contained in:
@@ -0,0 +1,67 @@
|
|||||||
|
# Community Verse Submissions — Implementation Plan
|
||||||
|
|
||||||
|
Source of truth: `spec.md`. Each step is independently verifiable and builds on the previous.
|
||||||
|
|
||||||
|
## Step 1 — Schema & migration
|
||||||
|
- Add `verse_submissions` table to `src/lib/server/db/schema.ts`:
|
||||||
|
- `id` text pk (`Bun.randomUUIDv7()`)
|
||||||
|
- `user_id` text not null, FK → `user.id` **ON DELETE SET NULL** (nullable column to allow that)
|
||||||
|
- `scheduled_date` text not null **unique**
|
||||||
|
- `selected_book_id` text not null
|
||||||
|
- `selected_chapter` integer not null
|
||||||
|
- `selected_verse` integer not null
|
||||||
|
- `submitted_at` integer not null (server UTC **millis**; raw integer, drives 7-day cooldown)
|
||||||
|
- indexes: `user_id`, unique on `scheduled_date` (the column-level unique handles this)
|
||||||
|
- `bun run db:push` to dev.db.
|
||||||
|
- Verify: `sqlite3 dev.db ".schema verse_submissions"`.
|
||||||
|
|
||||||
|
> Note: spec says `user_id` FK should be SET NULL on account deletion, so the column is **nullable** despite "not null" in the table sketch (the edge-cases section overrides: "FK should be ON DELETE SET NULL"). Resolution: make `user_id` nullable + ON DELETE SET NULL. The admin LEFT JOIN renders "(deleted user)" when null. This is the spec-intended behavior.
|
||||||
|
|
||||||
|
## Step 2 — Bible structure + windowing helpers
|
||||||
|
- Export `getChapterCount`, `getVerseCount` from `xml-bible.ts` (currently private).
|
||||||
|
- Add `composeVerseWindow(bookNumber, chapter, verse)`:
|
||||||
|
- Computes the selected verse's index `v` within the book (contiguous 1-based across chapters), `bookStart`=1, `bookEnd`=total verses in book.
|
||||||
|
- Default window `[v-2, v-1, v]`; if `v-2 < 1` fall forward to `[v, v+1, v+2]`.
|
||||||
|
- Returns `{ bookId, bookName, verses: string[], startChapter, startVerse, endChapter, endVerse, selectedVerse }` by calling `extractVerses` per chapter and concatenating for cross-chapter windows.
|
||||||
|
- Add `formatWindowReference(bookName, startChapter, startVerse, endChapter, endVerse)`: same-chapter → `Book C:S-E`; cross-chapter → `Book C1:S1–C2:E2`.
|
||||||
|
- Unit tests in `tests/verse-window.test.ts`.
|
||||||
|
|
||||||
|
## Step 3 — Public APIs
|
||||||
|
- `GET /api/bible/structure` → `[{ bookId, chapters: number[] }, ...]` for all 66 books (verse counts per chapter). Cached in-memory.
|
||||||
|
- `GET /api/verse-window?bookId=gen&chapter=1&verse=1` → `{ windowVerses, reference, bookId, selectedVerse }` via `composeVerseWindow`.
|
||||||
|
- Verify with curl.
|
||||||
|
|
||||||
|
## Step 4 — Admin module + `/scheduled-verses` page
|
||||||
|
- `src/lib/server/admin.ts` exporting `ADMIN_EMAIL = 'geohpowell@gmail.com'`.
|
||||||
|
- `src/routes/scheduled-verses/+page.server.ts`: require `locals.user?.email === ADMIN_EMAIL` else auth redirect / 403 access-denied page.
|
||||||
|
- `+page.svelte`: table joining `verse_submissions` LEFT JOIN `daily_verses` (on `scheduled_date = date`) LEFT JOIN `user` (on `user_id`), sorted by `scheduled_date` asc. Columns per spec. "(deleted user)" when user null.
|
||||||
|
- Not linked from nav. Verify by direct URL.
|
||||||
|
|
||||||
|
## Step 5 — Submit backend + lazy gap-fill
|
||||||
|
- `POST /api/submit-verse` (auth required): body `{ bookId, chapter, verse, localDate }`.
|
||||||
|
1. Require `locals.user` (401).
|
||||||
|
2. Solved-today gate: `dailyCompletions` row `(anonymousId=user.id, date=localDate)` else 403.
|
||||||
|
3. Cooldown: most recent `verse_submissions.submitted_at` for user; if `< 7d` ago → 429 `{ cooldownEndsAt }`.
|
||||||
|
4. Structural validation: bookId valid, chapter in `[1, getChapterCount]`, verse in `[1, getVerseCount]`.
|
||||||
|
5. Compute window via `composeVerseWindow`.
|
||||||
|
6. Scheduling scan: fetch all `daily_verses` with `date > today` (server UTC) ordered; walk day-by-day from tomorrow; validity = empty + no back-to-back with D-1/D+2 committed neighbors + no same-window-ref row within ±60 days (bounded lookup). Find earliest valid `D`.
|
||||||
|
7. Transaction: insert `daily_verses` `{ id, date: D, bookId, reference, verseText, createdAt: now }` + `verse_submissions` `{ id, user_id, scheduled_date: D, selected_book_id, selected_chapter, selected_verse, submitted_at: now }`. On `SQLITE_CONSTRAINT_UNIQUE` retry scan from `D+1`, up to 5 attempts.
|
||||||
|
8. Return `{ scheduledDate: D, reference, windowText }`. Emit rybbit event.
|
||||||
|
- `GET /api/submit-verse/status?localDate=YYYY-MM-DD` (auth required): `{ canSubmit, cooldownEndsAt, lastSubmission, upcoming }`.
|
||||||
|
- Modify `getVerseForDate` lazy path: re-roll `getRandomVerses()` until book differs from committed D-1 and D+1 neighbors (cap ~20 retries).
|
||||||
|
- Verify with curl end-to-end.
|
||||||
|
|
||||||
|
## Step 6 — Frontend `SubmitVerse.svelte`
|
||||||
|
- New component rendered in `WinScreen.svelte` near the progress button, sharing `.progress-btn` styling.
|
||||||
|
- States: logged-out (Apple/Google dropdown mirroring progress button), cooldown (greyed + `CountdownTimer`-style countdown to `cooldownEndsAt`), can-submit (cascading Book→Chapter→Verse `<select>`s from `/api/bible/structure`, debounced 250ms preview via `/api/verse-window`, Submit button, success confirmation with scheduled date, inline 429/403 errors).
|
||||||
|
- Pass `isLoggedIn` + `anonymousId` through (already on WinScreen props).
|
||||||
|
- Verify in browser.
|
||||||
|
|
||||||
|
## Step 7 — Tests
|
||||||
|
- `tests/verse-window.test.ts`: book-start fall-forward (Gen 1:1 → [1,2,3]), cross-chapter window, same-chapter window, end-of-book safety.
|
||||||
|
- `tests/scheduling.test.ts` (or unit-test the pure scan function against an in-memory fixture): no-back-to-back, 60-day repeat skip, earliest-valid-date selection.
|
||||||
|
- Cooldown arithmetic test.
|
||||||
|
|
||||||
|
## Step 8 — Docs
|
||||||
|
- Update `README.md` schema table (add `verse_submissions`) and routes/API tables (new endpoints + `/scheduled-verses`).
|
||||||
|
- Note `ADMIN_EMAIL` constant location.
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
# Spec: Community Verse Submissions
|
||||||
|
|
||||||
|
## TODO
|
||||||
|
|
||||||
|
- [x] **Step 1 — Schema & migration:** add `verse_submissions` table to `src/lib/server/db/schema.ts` (nullable `user_id` FK → `user.id` ON DELETE SET NULL, unique `scheduled_date`, index on `user_id`), pushed to dev.db.
|
||||||
|
- [x] **Step 2 — Bible structure + windowing helpers:** export `getChapterCount`/`getVerseCount` from `xml-bible.ts`; add `composeVerseWindow()` (fall-forward 3-verse window, never crosses book, crosses chapter within book) and `formatWindowReference()` (hyphen same-chapter, en-dash cross-chapter). Tests in `tests/verse-window.test.ts` (17 pass).
|
||||||
|
- [x] **Step 3 — Public APIs:** `GET /api/bible/structure` (66-book verse counts for cascading dropdowns) and `GET /api/verse-window` (live 3-verse preview).
|
||||||
|
- [ ] **Step 4 — Admin module + `/scheduled-verses` page:** `src/lib/server/admin.ts` (`ADMIN_EMAIL`), auth-walled admin view joining `verse_submissions` → `daily_verses` → `user`.
|
||||||
|
- [ ] **Step 5 — Submit backend + lazy gap-fill:** `POST /api/submit-verse` (solved-today gate, 7-day cooldown, structural validation, scheduling scan with empty/no-back-to-back/60-day-repeat rules, transaction + retry), `GET /api/submit-verse/status`, modified `getVerseForDate` neighbor avoidance.
|
||||||
|
- [ ] **Step 6 — Frontend `SubmitVerse.svelte`:** three states (logged-out sign-in dropdown, cooldown + countdown, cascading selects + preview + submit), wired into `WinScreen.svelte`.
|
||||||
|
- [ ] **Step 7 — Tests:** scheduling validity, cooldown arithmetic, concurrency.
|
||||||
|
- [ ] **Step 8 — Docs:** update README schema + routes/API tables.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Let authenticated users submit a Bible verse they love. Submissions are scheduled as future "verses of the day," mixed so that **no two consecutive calendar days ever feature the same book**, and spaced so an exact 3-verse window never repeats within 60 days. Selection is dropdown-based (cascading `<select>`s) so the system can compose verses purely from existing Bible-lookup functions already in the codebase — no free-text entry, so typos are impossible and content is always canonical NKJV text.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- A new button on the **win screen** (`WinScreen.svelte`), visually consistent with the existing "📈 See your progress" neobrutalist button.
|
||||||
|
- Logged-out users who click it get a dropdown prompting sign-in (mirroring the existing progress button's Apple/Google dropdown).
|
||||||
|
- Logged-in users get a cascading Book → Chapter → Verse selector with a live 3-verse preview.
|
||||||
|
- Each submission immediately reserves a concrete future date; the submitter is shown that date on success.
|
||||||
|
- A 7-day rolling cooldown (server UTC) gates submissions, with the button greyed out and a countdown timer shown while active.
|
||||||
|
- Attribution is **anonymous everywhere** — submissions are never credited to a user publicly.
|
||||||
|
|
||||||
|
## Non-goals (explicitly decided)
|
||||||
|
|
||||||
|
- **No giveaway-text filtering.** Verses that mention their own book/author (e.g. Eph 1:1, Isa 1:1) are allowed. The random generator already permits these.
|
||||||
|
- **No persistent pending queue / no cron.** Assignment happens at submit time, not via a background job.
|
||||||
|
- **No withdrawal / deletion / editing.** Submissions are final (references come from dropdowns, so typos are impossible).
|
||||||
|
- **No guardrail on how far out a verse is scheduled.** If the calendar is dense, a submission may land months or years in the future; this is accepted.
|
||||||
|
- **No per-user pending cap, no global cap.** The 7-day rolling cooldown is the only rate limit.
|
||||||
|
- **No attribution / leaderboard / share-text changes.** Submitter identity is recorded only for rate-limiting and the solved-today gate; it is never displayed.
|
||||||
|
- **No backfill of gap days.** Sparse future `dailyVerses` rows are fine.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Data Model
|
||||||
|
|
||||||
|
### New table: `verse_submissions`
|
||||||
|
|
||||||
|
A log of who submitted what and when, plus the assigned scheduled date. The canonical verse text/reference lives in `daily_verses` (keyed by `date`); this table links a user to a scheduled date.
|
||||||
|
|
||||||
|
| Column | Type | Notes |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `id` | text (pk) | `Bun.randomUUIDv7()` |
|
||||||
|
| `user_id` | text, not null, FK → `user.id` | the submitter (never displayed) |
|
||||||
|
| `scheduled_date` | text, not null, **unique** | `YYYY-MM-DD` of the reserved `daily_verses` row |
|
||||||
|
| `selected_book_id` | text, not null | the book the user chose |
|
||||||
|
| `selected_chapter` | integer, not null | the chapter the user chose |
|
||||||
|
| `selected_verse` | integer, not null | the single verse the user chose (the "anchor") |
|
||||||
|
| `submitted_at` | integer (timestamp), not null | server UTC millis — drives the 7-day cooldown |
|
||||||
|
|
||||||
|
Indexes: `user_id` (cooldown lookup + "your upcoming verses"), `scheduled_date` (unique — one submission per scheduled date).
|
||||||
|
|
||||||
|
No `status`, `withdrawn_at`, or attribution columns. Denormalized window/verseText/reference are **not** stored here; they live on `daily_verses` and are joined by `scheduled_date`.
|
||||||
|
|
||||||
|
### `daily_verses` (unchanged schema)
|
||||||
|
|
||||||
|
Submissions simply write a new row with a future `date`, exactly as the existing lazy path does for the current day. `getVerseForDate(date)` already returns a pre-existing row if present, so a pre-written submission row for a future date is served unchanged when its day arrives.
|
||||||
|
|
||||||
|
The new behavior:
|
||||||
|
- **Submission rows** are written at submit time for a future date (the date returned by the scheduling scan).
|
||||||
|
- **Gap days** (dates with no committed row when a player arrives) are filled lazily by the existing random path — extended to respect the no-back-to-back rule (see *Lazy gap-fill* below).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verse Windowing
|
||||||
|
|
||||||
|
A submission selects **one** verse (book → chapter → verse). The displayed daily verse is a **3-verse window** anchored on that verse, for difficulty consistency with the existing game (`getRandomVerses` defaults to 3 consecutive verses).
|
||||||
|
|
||||||
|
### Window algorithm (deterministic)
|
||||||
|
|
||||||
|
Let `v` be the selected verse's index within its **book** (a contiguous 1-based index across all chapters of that book). Let `bookStart` = 1 (first verse index in the book) and `bookEnd` = last verse index in the book.
|
||||||
|
|
||||||
|
- Default window: `[v-2, v-1, v]` (the two preceding in-book verses + the selected verse).
|
||||||
|
- If `v - 2 < bookStart` (not enough preceding verses in-book — only happens at a book's very start, e.g. Gen 1:1, John 1:1): **fall forward** so the window is 3 consecutive in-book verses that still includes `v`, i.e. start = `v`, window = `[v, v+1, v+2]`. (Every Bible book has ≥3 verses after its opening, so this always succeeds.)
|
||||||
|
- The window **never crosses a book boundary**. Crossing a chapter boundary **within the same book** is allowed and expected (e.g. a window spanning the end of chapter 1 and the start of chapter 2).
|
||||||
|
|
||||||
|
This reuses existing functions: `getChapterCount`, `getVerseCount`, `extractVerses` (called per chapter; for cross-chapter windows, call `extractVerses` twice and concatenate), `getBookByNumber`/`getBookById`, and `formatReference` (extended to format cross-chapter ranges, e.g. `Genesis 1:31–2:1`; same-chapter stays `Genesis 1:1-3`).
|
||||||
|
|
||||||
|
The selected verse's **book** is the day's `bookId` (the guess target). All three displayed verses come from that same book, so the guessing game stays fair.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scheduling Algorithm (assign-at-submit)
|
||||||
|
|
||||||
|
When a submission is accepted, the server scans forward from **tomorrow** (server UTC date) to find the earliest valid candidate date `D`, then writes the `daily_verses` row for `D` immediately and records a `verse_submissions` row. The submitter is shown `D`.
|
||||||
|
|
||||||
|
### Validity checks for candidate date `D` and submission book `B`
|
||||||
|
|
||||||
|
`D` is valid iff **all** hold:
|
||||||
|
|
||||||
|
1. **Empty:** no `daily_verses` row exists at `D`.
|
||||||
|
2. **No back-to-back with prior committed neighbor:** the `daily_verses` row at `D-1` (if one exists) must have `book_id != B`.
|
||||||
|
3. **No back-to-back with next committed neighbor:** the `daily_verses` row at `D+1` (if one exists) must have `book_id != B`.
|
||||||
|
4. **60-day repeat distance:** no `daily_verses` row with the **same 3-verse window** exists whose date is within `[D-60, D+60]` days inclusive. The window identity is its canonical reference string (`book_id` + formatted `chapter:startverse-endverse`, cross-chapter-aware). This is a *soft* repeat rule: repeats are allowed, just not within ±60 days of any prior/scheduled appearance.
|
||||||
|
|
||||||
|
### Implementation note (performance)
|
||||||
|
|
||||||
|
Don't query per candidate date. Instead, fetch all `daily_verses` rows with `date > today` ordered by date into memory, then walk day-by-day from tomorrow, checking the four rules against the in-memory set + a single range query for the 60-day repeat check (windowed by reference). Historical rows (date ≤ today) only matter for rule 4; a bounded lookup (rows with the same window-ref within 60 days of `D`) suffices.
|
||||||
|
|
||||||
|
### Concurrency
|
||||||
|
|
||||||
|
The scan-then-insert is a critical section. Two concurrent submissions could both select the same `D`. Wrap insert in a transaction; on a `SQLITE_CONSTRAINT_UNIQUE` failure on `daily_verses.date` (or `verse_submissions.scheduled_date`), re-run the scan from `D+1`. Retry up to a small bound (e.g. 5). SQLite under `bun:sqlite` handles this with a transaction.
|
||||||
|
|
||||||
|
### Why this preserves no-back-to-back globally
|
||||||
|
|
||||||
|
Adjacency is only ever checked against **committed** rows (D-1, D+1). Gap days (empty between two committed rows) are filled lazily later by a random verse whose generator also respects committed neighbors (see below). So at play-time, every adjacent pair of days has been checked at write-time. The invariant is maintained inductively.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lazy Gap-Fill (modified `getVerseForDate`)
|
||||||
|
|
||||||
|
When a player opens a date with no committed `daily_verses` row, the existing random path runs — **extended** so the random verse's book differs from any committed neighbor:
|
||||||
|
|
||||||
|
- If `D-1` has a committed row with book `X`, the random book must be `!= X`.
|
||||||
|
- If `D+1` has a committed row with book `Y`, the random book must be `!= Y`.
|
||||||
|
- Re-try `getRandomVerses()` until both hold (66 books, ≤2 excluded → ~97% success per try; cap at ~20 retries, then accept). `getRandomVerses` already returns 3 consecutive in-book verses; no windowing change needed for random fillers.
|
||||||
|
|
||||||
|
Submission days are pre-written, so they skip this path entirely (`getVerseForDate` returns the existing row).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rate Limiting & Cooldown
|
||||||
|
|
||||||
|
- **One submission per user per rolling 7×24h window**, measured in **server UTC** (not gameable; smooth countdown).
|
||||||
|
- `cooldownEndsAt = lastSubmission.submitted_at + 7 days` (server UTC millis).
|
||||||
|
- The win-screen button is **always visible**; when the cooldown is active it is **greyed out and disabled**, with a small countdown timer below it (target `cooldownEndsAt`).
|
||||||
|
- Query: select the user's most recent `verse_submissions.submitted_at`; if `now - submitted_at < 7d`, cooldown is active.
|
||||||
|
|
||||||
|
### Solved-today gate (API-level)
|
||||||
|
|
||||||
|
The `POST /api/submit-verse` endpoint requires that the user has a `daily_completions` row for **their local today**. The client sends `localDate` (the same `YYYY-MM-DD` it already computes via `toLocaleDateString("en-CA")` and sends to other endpoints). The server checks `dailyCompletions` for a row with `anonymous_id = user.id` (for logged-in users, `anonymousId` is the user id after migration) and `date = localDate`. If absent → `403` with `{ error: "Solve today's puzzle first" }`.
|
||||||
|
|
||||||
|
This is an **engagement gate**, not a security necessity (submissions are anonymous → low spam incentive), but it ties the feature to real play and blocks scripted submissions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Validation (no content moderation)
|
||||||
|
|
||||||
|
Because verses are chosen from canonical NKJV via dropdowns, no profanity/inappropriate-content filter is needed. Pre-submit validation is purely structural:
|
||||||
|
|
||||||
|
- `bookId` is one of the 66 known books (`getBookById`).
|
||||||
|
- `chapter` is in `[1, getChapterCount(bookNumber)]`.
|
||||||
|
- `verse` is in `[1, getVerseCount(bookNumber, chapter)]`.
|
||||||
|
- Cooldown not active.
|
||||||
|
- Solved-today gate passed.
|
||||||
|
- (The 60-day repeat and no-back-to-back rules are enforced by the scheduling scan, not by pre-rejecting the user's selection. A user can pick any valid verse; the scan will simply place it on the earliest valid date, possibly far out.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### `/scheduled-verses` (auth-walled, admin-only)
|
||||||
|
|
||||||
|
A private admin page gated to the single account `geohpowell@gmail.com`. This is the **one place** where submitter identity is surfaced — attribution is anonymous everywhere else (public game, share text, etc.), but this admin view is the exception.
|
||||||
|
|
||||||
|
**Access control:**
|
||||||
|
- `+page.server.ts` `load` requires `locals.user` and `locals.user.email === 'geohpowell@gmail.com'`.
|
||||||
|
- Not authenticated → redirect to the sign-in modal/flow (same pattern as `/progress`, `/stats`).
|
||||||
|
- Authenticated but wrong account → `403` / a plain "not authorized" page. Do not leak the existence of privileged data; the page simply renders an access-denied state.
|
||||||
|
- The email check is a literal string match; if the admin email ever changes, update the constant (single source in one server module, e.g. `src/lib/server/admin.ts` exporting `ADMIN_EMAIL`).
|
||||||
|
- No `isPrivate` bypass needed — the admin is trusted to see all submitters regardless of their `isPrivate` flag.
|
||||||
|
|
||||||
|
**Page contents:** a table of all `verse_submissions` rows joined to `daily_verses` (by `scheduled_date = daily_verses.date`) and `user` (by `user_id`), one row per submission:
|
||||||
|
|
||||||
|
| Column | Source |
|
||||||
|
| --- | --- |
|
||||||
|
| Scheduled date | `verse_submissions.scheduled_date` (rendered human-readable) |
|
||||||
|
| Reference | `daily_verses.reference` |
|
||||||
|
| Window text | `daily_verses.verse_text` (the 3-verse window) |
|
||||||
|
| Book | `daily_verses.book_id` (resolve to name via `getBookById`) |
|
||||||
|
| Submitted by | `user.email` (and `firstName lastName` if present) |
|
||||||
|
| Submitted at | `verse_submissions.submitted_at` (server UTC, rendered) |
|
||||||
|
| Selected verse | `verse_submissions.selected_book_id` / `selected_chapter` / `selected_verse` (the anchor the user picked) |
|
||||||
|
|
||||||
|
Sorted by `scheduled_date` ascending (so the upcoming calendar reads top-to-bottom). Include past rows (already-played submissions) — the table is a full historical + future log, not just pending. A small filter toggle (All / Upcoming / Past) is a nice-to-have, not required.
|
||||||
|
|
||||||
|
Since attribution appears here, `verse_submissions.user_id` must resolve even for deleted accounts — use a `LEFT JOIN` to `user` and render "(deleted user)" when the join is null. (Matches the `ON DELETE SET NULL` decision in the edge-cases section: the scheduled verse still plays out; the admin just sees the attribution is gone.)
|
||||||
|
|
||||||
|
This route is **not** linked from the UI (no nav entry, no win-screen button) — it's a direct-URL admin tool.
|
||||||
|
|
||||||
|
### `POST /api/submit-verse` (auth required)
|
||||||
|
|
||||||
|
**Body:** `{ bookId, chapter, verse, localDate }`
|
||||||
|
|
||||||
|
**Flow:**
|
||||||
|
1. Require `locals.user` (else `401`).
|
||||||
|
2. Solved-today gate: `dailyCompletions` row for `(anonymousId=user.id, date=localDate)` else `403`.
|
||||||
|
3. Cooldown: most recent `verse_submissions.submitted_at` for user; if `< 7d` ago → `429 { cooldownEndsAt }`.
|
||||||
|
4. Structural validation of `bookId/chapter/verse`.
|
||||||
|
5. Compute the 3-verse window (fall-forward algorithm).
|
||||||
|
6. Run the scheduling scan; on unique-constraint conflict, retry.
|
||||||
|
7. In a transaction: insert `daily_verses` row `{ id, date: D, bookId, reference, verseText, createdAt: now }` and `verse_submissions` row `{ id, user_id, scheduled_date: D, selected_book_id, selected_chapter, selected_verse, submitted_at: now }`.
|
||||||
|
8. Return `{ scheduledDate: D, reference, windowText }`.
|
||||||
|
|
||||||
|
Analytics: emit `(window as any).rybbit?.event("Submit a verse")`.
|
||||||
|
|
||||||
|
### `GET /api/submit-verse/status?localDate=YYYY-MM-DD` (auth required)
|
||||||
|
|
||||||
|
Returns the state for the win-screen button:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"canSubmit": true | false,
|
||||||
|
"cooldownEndsAt": <server UTC millis> | null,
|
||||||
|
"lastSubmission": { "scheduledDate": "2026-08-24", "reference": "..." } | null,
|
||||||
|
"upcoming": [ { "scheduledDate": "...", "reference": "..." }, ... ] // this user's not-yet-reached submissions, for an optional small list
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `GET /api/bible/structure` (public)
|
||||||
|
|
||||||
|
Returns the static structure for populating the cascading dropdowns client-side (cached indefinitely):
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{ "bookId": "gen", "chapters": [31, 25, 24, ...] }, // verse counts per chapter
|
||||||
|
...
|
||||||
|
]
|
||||||
|
```
|
||||||
|
Built from `getChapterCount` + `getVerseCount` over all 66 books. Small payload (~1189 chapter entries).
|
||||||
|
|
||||||
|
### `GET /api/verse-window?bookId=gen&chapter=1&verse=1` (public)
|
||||||
|
|
||||||
|
Returns the 3-verse preview for the live preview pane, computed via the fall-forward window algorithm:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"windowVerses": ["In the beginning...", "And the earth...", "And God said..."],
|
||||||
|
"reference": "Genesis 1:1-3",
|
||||||
|
"bookId": "gen",
|
||||||
|
"selectedVerse": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Called debounced (e.g. 250ms) as the selector changes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Frontend
|
||||||
|
|
||||||
|
### New component: `src/lib/components/SubmitVerse.svelte`
|
||||||
|
|
||||||
|
Rendered inside `WinScreen.svelte`, near the existing "📈 See your progress" button, sharing the same neobrutalist `.progress-btn` styling.
|
||||||
|
|
||||||
|
**Three visual states:**
|
||||||
|
|
||||||
|
1. **Logged out** — button reads "✨ Submit a verse" with a chevron; clicking expands a dropdown identical in structure to the existing logged-out progress dropdown: helper text ("Sign in to submit a verse for a future day") + Apple Sign-In form (`POST /auth/apple`, with hidden `anonymousId`) + Google Sign-In form (`POST /auth/google`). Mirrors the existing markup/classes exactly.
|
||||||
|
|
||||||
|
2. **Logged in, cooldown active** — button is greyed out / disabled ("✨ Submit a verse" + lock/⏳), with a small countdown timer below it counting down to `cooldownEndsAt` (reuse the `CountdownTimer` pattern / a compact timer). The dropdown does not expand.
|
||||||
|
|
||||||
|
3. **Logged in, can submit** — clicking expands a panel with:
|
||||||
|
- Three cascading native `<select>` dropdowns: **Book** (grouped by Testament, `<optgroup>`), **Chapter** (1..chapterCount), **Verse** (1..verseCount). Book list/chapter counts come from `/api/bible/structure` (fetched once, cached). Selecting book populates chapters; selecting chapter populates verses; selecting verse (or any change) triggers the debounced preview fetch.
|
||||||
|
- A **live preview** card showing the 3-verse window text + reference, updating in real time as the selector changes. (This is not today's verse — it's the user's prospective submission — so showing the book/reference is fine.)
|
||||||
|
- A **Submit** button (neobrutalist). On success, replace the panel with a confirmation: "✅ Your verse is scheduled for **August 24, 2026**" + the reference, plus a rybbit event. On `429`/`403`, show the server's error message inline.
|
||||||
|
|
||||||
|
The win screen already receives `isLoggedIn` and `anonymousId` as props; pass them through to `SubmitVerse`.
|
||||||
|
|
||||||
|
### Placement note
|
||||||
|
|
||||||
|
The button is **win-screen-only**, which implicitly requires the user to have solved today's puzzle to reach it (the win screen only renders post-solve, and reloads still render it via `game-persistence` restoring today's completed guesses). This matches the API-level solved-today gate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Reused Existing Functions
|
||||||
|
|
||||||
|
| Function | Used for |
|
||||||
|
| --- | --- |
|
||||||
|
| `getChapterCount(bookNumber)` | Dropdown chapter list bounds |
|
||||||
|
| `getVerseCount(bookNumber, chapter)` | Dropdown verse list bounds |
|
||||||
|
| `extractVerses(bookNumber, chapter, startVerse, count)` | Composing the 3-verse window (per chapter; concat for cross-chapter) |
|
||||||
|
| `getBookById` / `getBookByNumber` | Book id ↔ number ↔ name resolution |
|
||||||
|
| `formatReference(bookName, chapter, startVerse, endVerse)` | Reference formatting (extend for cross-chapter) |
|
||||||
|
| `getRandomVerses()` | Lazy gap-fill random verse (extended with neighbor avoidance) |
|
||||||
|
| `getVerseForDate(date)` | Returns pre-written submission row unchanged on its day |
|
||||||
|
| Auth (`locals.user`, session cookie) | Identifying the submitter |
|
||||||
|
| `dailyCompletions` (`anonymousId = user.id`, `date`) | Solved-today gate |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Edge Cases & Decisions Log
|
||||||
|
|
||||||
|
- **Selected verse at a book's start (v1/v2 of chapter 1):** fall forward to `[v, v+1, v+2]`. Always 3 verses, same book.
|
||||||
|
- **Cross-chapter window within a book:** allowed; reference formatted as `Book C1:S1–C2:E2`.
|
||||||
|
- **Cross-book window:** never happens (algorithm constrains to one book).
|
||||||
|
- **Concurrent submissions picking the same date:** transaction + retry-on-unique-conflict.
|
||||||
|
- **Repeat of an identical 3-verse window:** allowed, but the scan skips any candidate date within ±60 days of an existing same-window row, so repeats land far out (this is what "schedule them out a month or two" means in practice).
|
||||||
|
- **Calendar drift (submissions outpace 1/day demand):** accepted — no guardrail; a submission may land far in the future. The submitter is shown the resulting date regardless.
|
||||||
|
- **Account deletion:** submissions are anonymous; `daily_verses` rows stay (canonical text). The `verse_submissions` row's `user_id` FK should be `ON DELETE SET NULL` (or cascade-delete the log row) — either is fine since attribution is never shown. The scheduled verse plays out regardless.
|
||||||
|
- **Discord daily-verse cron / RSS / sitemap:** unchanged — they call `getVerseForDate`, which serves pre-written submission rows transparently.
|
||||||
|
- **`createdAt` on submission-written `daily_verses` rows:** equals submit time, not the future play date. This is consistent with the existing field's meaning ("when the row was created").
|
||||||
|
- **Admin `/scheduled-verses` view is the sole attribution exception:** the public-facing anonymity guarantee does not apply to this admin-only route, which deliberately surfaces `user.email` for the `geohpowell@gmail.com` account. All other surfaces (win screen, share text, future potential leaderboard) remain anonymous.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Open / Deferred (not blocking v1)
|
||||||
|
|
||||||
|
- A small "your upcoming scheduled verses" list on the win screen (data already available from `/api/submit-verse/status`). Nice-to-have, not required for v1.
|
||||||
|
- Balancing book distribution beyond no-back-to-back (e.g. avoiding clustering the same book within a month). Explicitly out of scope — only adjacent-day collisions are prevented.
|
||||||
|
- Email/notification when a user's scheduled verse goes live. Out of scope.
|
||||||
+1
-2
@@ -3,8 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
<script src="https://rybbit.snail.city/api/script.js" data-site-id="9abf0e81d024" defer></script>
|
<link rel="icon" href="/favicon.png" type="image/png" />
|
||||||
<link rel="icon" href="/favicon.png" type="image/png" />
|
|
||||||
%sveltekit.head%
|
%sveltekit.head%
|
||||||
</head>
|
</head>
|
||||||
<body data-sveltekit-preload-data="hover">
|
<body data-sveltekit-preload-data="hover">
|
||||||
|
|||||||
@@ -11,7 +11,6 @@
|
|||||||
class="inline-flex hover:opacity-80 transition-opacity"
|
class="inline-flex hover:opacity-80 transition-opacity"
|
||||||
aria-label="Follow on Bluesky"
|
aria-label="Follow on Bluesky"
|
||||||
data-umami-event="Bluesky clicked"
|
data-umami-event="Bluesky clicked"
|
||||||
onclick={() => (window as any).rybbit?.event("Bluesky clicked")}
|
|
||||||
>
|
>
|
||||||
<img src={BlueskyLogo} alt="Bluesky" class="w-8 h-8" />
|
<img src={BlueskyLogo} alt="Bluesky" class="w-8 h-8" />
|
||||||
</a>
|
</a>
|
||||||
@@ -25,7 +24,6 @@
|
|||||||
class="inline-flex hover:opacity-80 transition-opacity"
|
class="inline-flex hover:opacity-80 transition-opacity"
|
||||||
aria-label="Follow on Twitter"
|
aria-label="Follow on Twitter"
|
||||||
data-umami-event="Twitter clicked"
|
data-umami-event="Twitter clicked"
|
||||||
onclick={() => (window as any).rybbit?.event("Twitter clicked")}
|
|
||||||
>
|
>
|
||||||
<img src={TwitterLogo} alt="Twitter" class="w-8 h-8" />
|
<img src={TwitterLogo} alt="Twitter" class="w-8 h-8" />
|
||||||
</a>
|
</a>
|
||||||
@@ -37,7 +35,6 @@
|
|||||||
class="inline-flex hover:opacity-80 transition-opacity"
|
class="inline-flex hover:opacity-80 transition-opacity"
|
||||||
aria-label="Send email"
|
aria-label="Send email"
|
||||||
data-umami-event="Email clicked"
|
data-umami-event="Email clicked"
|
||||||
onclick={() => (window as any).rybbit?.event("Email clicked")}
|
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
class="w-8 h-8 text-gray-700 dark:text-gray-300"
|
class="w-8 h-8 text-gray-700 dark:text-gray-300"
|
||||||
|
|||||||
@@ -55,7 +55,6 @@
|
|||||||
function copyVerse() {
|
function copyVerse() {
|
||||||
navigator.clipboard.writeText(displayVerseText).then(() => {
|
navigator.clipboard.writeText(displayVerseText).then(() => {
|
||||||
copied = true;
|
copied = true;
|
||||||
(window as any).rybbit?.event("Copy Verse");
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
copied = false;
|
copied = false;
|
||||||
}, 2000);
|
}, 2000);
|
||||||
|
|||||||
@@ -253,13 +253,9 @@
|
|||||||
: "Copy to Clipboard"}
|
: "Copy to Clipboard"}
|
||||||
onclick={() => {
|
onclick={() => {
|
||||||
if (hasWebShare) {
|
if (hasWebShare) {
|
||||||
(window as any).rybbit?.event("Share");
|
|
||||||
shareResult(effectiveShareText);
|
shareResult(effectiveShareText);
|
||||||
} else {
|
} else {
|
||||||
if (!copyTracked) {
|
if (!copyTracked) {
|
||||||
(window as any).rybbit?.event(
|
|
||||||
"Copy to Clipboard",
|
|
||||||
);
|
|
||||||
copyTracked = true;
|
copyTracked = true;
|
||||||
}
|
}
|
||||||
clipboardCopy(effectiveShareText);
|
clipboardCopy(effectiveShareText);
|
||||||
@@ -288,7 +284,6 @@
|
|||||||
data-umami-event="Copy to Clipboard"
|
data-umami-event="Copy to Clipboard"
|
||||||
onclick={() => {
|
onclick={() => {
|
||||||
if (!copyTracked) {
|
if (!copyTracked) {
|
||||||
(window as any).rybbit?.event("Copy to Clipboard");
|
|
||||||
copyTracked = true;
|
copyTracked = true;
|
||||||
}
|
}
|
||||||
clipboardCopy(effectiveShareText);
|
clipboardCopy(effectiveShareText);
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
// Single source of truth for the admin account that may view submitter
|
||||||
|
// attribution on /scheduled-verses. The public game never surfaces submitter
|
||||||
|
// identity; this email is the sole exception (see spec "Admin /scheduled-verses").
|
||||||
|
export const ADMIN_EMAIL = 'geohpowell@gmail.com';
|
||||||
|
|
||||||
|
export function isAdmin(email: string | null | undefined): boolean {
|
||||||
|
return !!email && email.toLowerCase() === ADMIN_EMAIL;
|
||||||
|
}
|
||||||
@@ -48,3 +48,20 @@ export const dailyCompletions = sqliteTable('daily_completions', {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
export type DailyCompletion = typeof dailyCompletions.$inferSelect;
|
export type DailyCompletion = typeof dailyCompletions.$inferSelect;
|
||||||
|
|
||||||
|
export const verseSubmissions = sqliteTable('verse_submissions', {
|
||||||
|
id: text('id').primaryKey(),
|
||||||
|
// Nullable so ON DELETE SET NULL can clear attribution when a user is deleted;
|
||||||
|
// the scheduled verse still plays out (canonical text lives on daily_verses).
|
||||||
|
userId: text('user_id').references(() => user.id, { onDelete: 'set null' }),
|
||||||
|
scheduledDate: text('scheduled_date').notNull().unique(),
|
||||||
|
selectedBookId: text('selected_book_id').notNull(),
|
||||||
|
selectedChapter: integer('selected_chapter').notNull(),
|
||||||
|
selectedVerse: integer('selected_verse').notNull(),
|
||||||
|
// Raw integer of server UTC milliseconds — drives the 7-day rolling cooldown.
|
||||||
|
submittedAt: integer('submitted_at').notNull(),
|
||||||
|
}, (table) => [
|
||||||
|
index('verse_submissions_user_id_idx').on(table.userId),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export type VerseSubmission = typeof verseSubmissions.$inferSelect;
|
||||||
|
|||||||
+126
-2
@@ -135,7 +135,7 @@ function getGreekChapter(bookNumber: number, chapterNumber: number): ChapterData
|
|||||||
/**
|
/**
|
||||||
* Get the number of verses in a specific chapter
|
* Get the number of verses in a specific chapter
|
||||||
*/
|
*/
|
||||||
function getVerseCount(bookNumber: number, chapterNumber: number): number {
|
export function getVerseCount(bookNumber: number, chapterNumber: number): number {
|
||||||
const chapter = getChapter(bookNumber, chapterNumber);
|
const chapter = getChapter(bookNumber, chapterNumber);
|
||||||
return chapter ? chapter.verse.length : 0;
|
return chapter ? chapter.verse.length : 0;
|
||||||
}
|
}
|
||||||
@@ -151,7 +151,7 @@ function getGreekVerseCount(bookNumber: number, chapterNumber: number): number {
|
|||||||
/**
|
/**
|
||||||
* Get the number of chapters in a specific book
|
* Get the number of chapters in a specific book
|
||||||
*/
|
*/
|
||||||
function getChapterCount(bookNumber: number): number {
|
export function getChapterCount(bookNumber: number): number {
|
||||||
const book = getBook(bookNumber);
|
const book = getBook(bookNumber);
|
||||||
return book ? book.chapter.length : 0;
|
return book ? book.chapter.length : 0;
|
||||||
}
|
}
|
||||||
@@ -439,3 +439,127 @@ export function getAllNKJVVerses(): Array<{ text: string; book: string; chapter:
|
|||||||
}
|
}
|
||||||
return verses;
|
return verses;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a 1-based book-wide verse index to { chapter, verse }.
|
||||||
|
* The index is contiguous across all chapters of the book.
|
||||||
|
*/
|
||||||
|
function resolveBookVerseIndex(
|
||||||
|
bookNumber: number,
|
||||||
|
index: number
|
||||||
|
): { chapter: number; verse: number } | null {
|
||||||
|
const chapterCount = getChapterCount(bookNumber);
|
||||||
|
let cumulative = 0;
|
||||||
|
for (let c = 1; c <= chapterCount; c++) {
|
||||||
|
const vCount = getVerseCount(bookNumber, c);
|
||||||
|
if (index <= cumulative + vCount) {
|
||||||
|
return { chapter: c, verse: index - cumulative };
|
||||||
|
}
|
||||||
|
cumulative += vCount;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ComposedWindow {
|
||||||
|
bookId: string;
|
||||||
|
bookName: string;
|
||||||
|
verses: string[]; // the 3 verse texts in order
|
||||||
|
startChapter: number;
|
||||||
|
startVerse: number;
|
||||||
|
endChapter: number;
|
||||||
|
endVerse: number;
|
||||||
|
selectedVerse: number; // the anchor verse number within its chapter
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compose a 3-verse window anchored on (book, chapter, verse), constrained to
|
||||||
|
* a single book. Default window is [v-2, v-1, v] in book-wide verse indices;
|
||||||
|
* if that would run before the book's start (v is 1 or 2), fall forward to
|
||||||
|
* [v, v+1, v+2]. Cross-chapter windows within the same book are allowed.
|
||||||
|
*
|
||||||
|
* Mirrors the spec's "Verse Windowing" section.
|
||||||
|
*/
|
||||||
|
export function composeVerseWindow(
|
||||||
|
bookNumber: number,
|
||||||
|
chapter: number,
|
||||||
|
verse: number
|
||||||
|
): ComposedWindow | null {
|
||||||
|
const book = getBookByNumber(bookNumber);
|
||||||
|
if (!book) return null;
|
||||||
|
|
||||||
|
const chapterCount = getChapterCount(bookNumber);
|
||||||
|
if (chapter < 1 || chapter > chapterCount) return null;
|
||||||
|
const verseCount = getVerseCount(bookNumber, chapter);
|
||||||
|
if (verse < 1 || verse > verseCount) return null;
|
||||||
|
|
||||||
|
// Book-wide 1-based index of the selected verse.
|
||||||
|
let selectedIndex = 0;
|
||||||
|
for (let c = 1; c < chapter; c++) selectedIndex += getVerseCount(bookNumber, c);
|
||||||
|
selectedIndex += verse;
|
||||||
|
|
||||||
|
let startIdx: number;
|
||||||
|
let endIdx: number;
|
||||||
|
if (selectedIndex - 2 < 1) {
|
||||||
|
// Fall forward: [v, v+1, v+2]
|
||||||
|
startIdx = selectedIndex;
|
||||||
|
endIdx = selectedIndex + 2;
|
||||||
|
} else {
|
||||||
|
startIdx = selectedIndex - 2;
|
||||||
|
endIdx = selectedIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
const start = resolveBookVerseIndex(bookNumber, startIdx);
|
||||||
|
const end = resolveBookVerseIndex(bookNumber, endIdx);
|
||||||
|
if (!start || !end) return null;
|
||||||
|
|
||||||
|
// Extract the contiguous window, crossing chapter boundaries within the book as needed.
|
||||||
|
const verses: string[] = [];
|
||||||
|
let curChapter = start.chapter;
|
||||||
|
let curVerse = start.verse;
|
||||||
|
while (verses.length < 3 && curChapter <= chapterCount) {
|
||||||
|
const vCount = getVerseCount(bookNumber, curChapter);
|
||||||
|
while (curVerse <= vCount && verses.length < 3) {
|
||||||
|
const ex = extractVerses(bookNumber, curChapter, curVerse, 1);
|
||||||
|
if (ex.length === 1) {
|
||||||
|
verses.push(ex[0]);
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
curVerse++;
|
||||||
|
}
|
||||||
|
curChapter++;
|
||||||
|
curVerse = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (verses.length < 3) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
bookId: book.id,
|
||||||
|
bookName: book.name,
|
||||||
|
verses,
|
||||||
|
startChapter: start.chapter,
|
||||||
|
startVerse: start.verse,
|
||||||
|
endChapter: end.chapter,
|
||||||
|
endVerse: end.verse,
|
||||||
|
selectedVerse: verse
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format a reference for a window that may span chapters within a book.
|
||||||
|
* Same-chapter: "Genesis 1:1-3" (hyphen)
|
||||||
|
* Cross-chapter: "Genesis 1:31–2:1" (en-dash)
|
||||||
|
*/
|
||||||
|
export function formatWindowReference(
|
||||||
|
bookName: string,
|
||||||
|
startChapter: number,
|
||||||
|
startVerse: number,
|
||||||
|
endChapter: number,
|
||||||
|
endVerse: number
|
||||||
|
): string {
|
||||||
|
if (startChapter === endChapter) {
|
||||||
|
if (startVerse === endVerse) return `${bookName} ${startChapter}:${startVerse}`;
|
||||||
|
return `${bookName} ${startChapter}:${startVerse}-${endVerse}`;
|
||||||
|
}
|
||||||
|
return `${bookName} ${startChapter}:${startVerse}\u2013${endChapter}:${endVerse}`;
|
||||||
|
}
|
||||||
|
|||||||
@@ -53,15 +53,7 @@ export function createGamePersistence(
|
|||||||
if ((window as any).umami) {
|
if ((window as any).umami) {
|
||||||
(window as any).umami.identify(anonymousId);
|
(window as any).umami.identify(anonymousId);
|
||||||
}
|
}
|
||||||
if (user) {
|
|
||||||
const nameParts = [user.firstName, user.lastName].filter(Boolean);
|
|
||||||
(window as any).rybbit?.identify(user.id, {
|
|
||||||
...(nameParts.length ? { name: nameParts.join(' ') } : {}),
|
|
||||||
...(user.email ? { email: user.email } : {}),
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
(window as any).rybbit?.identify(anonymousId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const date = getDate();
|
const date = getDate();
|
||||||
const reference = getReference();
|
const reference = getReference();
|
||||||
|
|||||||
@@ -146,7 +146,6 @@
|
|||||||
(window as any).umami
|
(window as any).umami
|
||||||
) {
|
) {
|
||||||
(window as any).umami.track("First guess");
|
(window as any).umami.track("First guess");
|
||||||
(window as any).rybbit?.event("First guess");
|
|
||||||
localStorage.setItem(key, "true");
|
localStorage.setItem(key, "true");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -287,9 +286,6 @@
|
|||||||
(window as any).umami.track("Guessed correctly", {
|
(window as any).umami.track("Guessed correctly", {
|
||||||
totalGuesses: persistence.guesses.length,
|
totalGuesses: persistence.guesses.length,
|
||||||
});
|
});
|
||||||
(window as any).rybbit?.event("Guessed correctly", {
|
|
||||||
totalGuesses: persistence.guesses.length,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { bibleBooks } from '$lib/server/bible';
|
||||||
|
import { getChapterCount, getVerseCount } from '$lib/server/xml-bible';
|
||||||
|
|
||||||
|
// Static Bible structure for the cascading Book → Chapter → Verse selectors.
|
||||||
|
// ~1189 chapter entries total; safe to cache indefinitely.
|
||||||
|
let cached: { bookId: string; chapters: number[] }[] | null = null;
|
||||||
|
|
||||||
|
function build(): { bookId: string; chapters: number[] }[] {
|
||||||
|
if (cached) return cached;
|
||||||
|
const out = bibleBooks.map((book) => {
|
||||||
|
const chapterCount = getChapterCount(book.order);
|
||||||
|
const chapters: number[] = new Array(chapterCount);
|
||||||
|
for (let c = 1; c <= chapterCount; c++) {
|
||||||
|
chapters[c - 1] = getVerseCount(book.order, c);
|
||||||
|
}
|
||||||
|
return { bookId: book.id, chapters };
|
||||||
|
});
|
||||||
|
cached = out;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async () => {
|
||||||
|
return json(build());
|
||||||
|
};
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { db } from '$lib/server/db';
|
||||||
|
import { dailyVerses, verseSubmissions, user } from '$lib/server/db/schema';
|
||||||
|
import { sql } from 'drizzle-orm';
|
||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import { bibleBooks } from '$lib/types/bible';
|
||||||
|
import {
|
||||||
|
getChapterCount,
|
||||||
|
getVerseCount,
|
||||||
|
composeVerseWindow,
|
||||||
|
formatWindowReference
|
||||||
|
} from '$lib/server/xml-bible';
|
||||||
|
|
||||||
|
const DEV_HOSTS = ['localhost:5173', 'test.bibdle.com'];
|
||||||
|
const MAX_SCAN_RETRIES = 5;
|
||||||
|
|
||||||
|
// Dev-only: insert a verse_submissions row (from a random existing account) +
|
||||||
|
// its corresponding daily_verses row, scheduled on the earliest valid future
|
||||||
|
// date per the spec's scheduling rules. Lets you populate /scheduled-verses to
|
||||||
|
// verify the admin view without going through the (Step 5+) submit API.
|
||||||
|
export const POST: RequestHandler = async ({ request }) => {
|
||||||
|
const host = request.headers.get('host') ?? '';
|
||||||
|
if (!DEV_HOSTS.includes(host)) {
|
||||||
|
return json({ error: 'Not allowed in production' }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pick a random existing user.
|
||||||
|
const users = await db.select().from(user);
|
||||||
|
if (users.length === 0) {
|
||||||
|
return json(
|
||||||
|
{ error: 'No users exist yet. Sign up at least one account first.' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const submitter = users[Math.floor(Math.random() * users.length)];
|
||||||
|
|
||||||
|
// Pick a random valid (book, chapter, verse).
|
||||||
|
const book = bibleBooks[Math.floor(Math.random() * bibleBooks.length)];
|
||||||
|
const chapterCount = getChapterCount(book.order);
|
||||||
|
const chapter = Math.floor(Math.random() * chapterCount) + 1;
|
||||||
|
const verseCount = getVerseCount(book.order, chapter);
|
||||||
|
const verse = Math.floor(Math.random() * verseCount) + 1;
|
||||||
|
|
||||||
|
const window = composeVerseWindow(book.order, chapter, verse);
|
||||||
|
if (!window) {
|
||||||
|
return json({ error: 'Failed to compose verse window' }, { status: 500 });
|
||||||
|
}
|
||||||
|
const reference = formatWindowReference(
|
||||||
|
window.bookName,
|
||||||
|
window.startChapter,
|
||||||
|
window.startVerse,
|
||||||
|
window.endChapter,
|
||||||
|
window.endVerse
|
||||||
|
);
|
||||||
|
const verseText = window.verses.join(' ');
|
||||||
|
|
||||||
|
const todayUtc = new Date().toISOString().slice(0, 10);
|
||||||
|
const tomorrowMs = new Date(todayUtc + 'T00:00:00Z').getTime() + 86400000;
|
||||||
|
|
||||||
|
function addDays(ms: number, n: number): string {
|
||||||
|
return new Date(ms + n * 86400000).toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch all future daily_verses into memory (date → bookId, date → reference).
|
||||||
|
const future = await db.select().from(dailyVerses).where(sql`date > ${todayUtc}`);
|
||||||
|
const byDate = new Map<string, { bookId: string; reference: string }>();
|
||||||
|
for (const r of future) byDate.set(r.date, { bookId: r.bookId, reference: r.reference });
|
||||||
|
|
||||||
|
// For the 60-day repeat rule, also need a bounded historical lookup per
|
||||||
|
// candidate date. Build a set of all existing references globally to do a
|
||||||
|
// cheap pre-check, then a precise range query when we settle on a date.
|
||||||
|
const allRows = await db.select().from(dailyVerses);
|
||||||
|
const refDates = new Map<string, string[]>(); // reference → list of dates
|
||||||
|
for (const r of allRows) {
|
||||||
|
const arr = refDates.get(r.reference) ?? [];
|
||||||
|
arr.push(r.date);
|
||||||
|
refDates.set(r.reference, arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
let scheduledDate: string | null = null;
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt < MAX_SCAN_RETRIES && !scheduledDate; attempt++) {
|
||||||
|
// Walk day-by-day from tomorrow.
|
||||||
|
for (let offset = 0; offset < 10000; offset++) {
|
||||||
|
const D = addDays(tomorrowMs, offset);
|
||||||
|
|
||||||
|
// Rule 1: empty (no committed daily_verses row).
|
||||||
|
if (byDate.has(D)) continue;
|
||||||
|
|
||||||
|
// Rule 2: no back-to-back with prior neighbor.
|
||||||
|
const prev = byDate.get(addDays(tomorrowMs, offset - 1));
|
||||||
|
if (prev && prev.bookId === book.id) continue;
|
||||||
|
|
||||||
|
// Rule 3: no back-to-back with next committed neighbor.
|
||||||
|
const next = byDate.get(addDays(tomorrowMs, offset + 1));
|
||||||
|
if (next && next.bookId === book.id) continue;
|
||||||
|
|
||||||
|
// Rule 4: 60-day repeat distance — no same reference within ±60 days.
|
||||||
|
const sameRefDates = refDates.get(reference) ?? [];
|
||||||
|
const dMs = new Date(D + 'T00:00:00Z').getTime();
|
||||||
|
const tooClose = sameRefDates.some((d) => {
|
||||||
|
const diff = Math.abs(new Date(d + 'T00:00:00Z').getTime() - dMs);
|
||||||
|
return diff <= 60 * 86400000;
|
||||||
|
});
|
||||||
|
if (tooClose) continue;
|
||||||
|
|
||||||
|
scheduledDate = D;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!scheduledDate) break; // exhausted retries
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!scheduledDate) {
|
||||||
|
return json({ error: 'Could not find a valid future date' }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert both rows in a transaction. On a unique conflict (concurrent
|
||||||
|
// submission grabbed the same date), bubble up so the caller can retry.
|
||||||
|
const now = Date.now();
|
||||||
|
const verseId = Bun.randomUUIDv7();
|
||||||
|
const submissionId = Bun.randomUUIDv7();
|
||||||
|
|
||||||
|
try {
|
||||||
|
db.transaction((tx) => {
|
||||||
|
tx.insert(dailyVerses)
|
||||||
|
.values({
|
||||||
|
id: verseId,
|
||||||
|
date: scheduledDate!,
|
||||||
|
bookId: book.id,
|
||||||
|
verseText,
|
||||||
|
reference,
|
||||||
|
createdAt: sql`${Math.floor(now / 1000)}`
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
tx.insert(verseSubmissions)
|
||||||
|
.values({
|
||||||
|
id: submissionId,
|
||||||
|
userId: submitter.id,
|
||||||
|
scheduledDate: scheduledDate!,
|
||||||
|
selectedBookId: book.id,
|
||||||
|
selectedChapter: chapter,
|
||||||
|
selectedVerse: verse,
|
||||||
|
submittedAt: now
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err?.code === 'SQLITE_CONSTRAINT_UNIQUE' || err?.message?.includes('UNIQUE')) {
|
||||||
|
return json(
|
||||||
|
{ error: 'Date collision during seed; retry the request', detail: String(err?.message ?? err) },
|
||||||
|
{ status: 409 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
return json({
|
||||||
|
ok: true,
|
||||||
|
submitter: { id: submitter.id, email: submitter.email },
|
||||||
|
selected: {
|
||||||
|
bookId: book.id,
|
||||||
|
bookName: book.name,
|
||||||
|
chapter,
|
||||||
|
verse
|
||||||
|
},
|
||||||
|
scheduledDate,
|
||||||
|
reference,
|
||||||
|
verseText
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Convenience: GET returns the current count of submissions + future scheduled
|
||||||
|
// verses, useful as a quick dev sanity check without mutating state.
|
||||||
|
export const GET: RequestHandler = async ({ request }) => {
|
||||||
|
const host = request.headers.get('host') ?? '';
|
||||||
|
if (!DEV_HOSTS.includes(host)) {
|
||||||
|
return json({ error: 'Not allowed in production' }, { status: 403 });
|
||||||
|
}
|
||||||
|
const subs = await db.select().from(verseSubmissions);
|
||||||
|
const future = await db
|
||||||
|
.select()
|
||||||
|
.from(dailyVerses)
|
||||||
|
.where(sql`date > ${new Date().toISOString().slice(0, 10)}`);
|
||||||
|
return json({
|
||||||
|
totalSubmissions: subs.length,
|
||||||
|
futureScheduledVerses: future.length
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { getBookById } from '$lib/server/bible';
|
||||||
|
import {
|
||||||
|
composeVerseWindow,
|
||||||
|
formatWindowReference
|
||||||
|
} from '$lib/server/xml-bible';
|
||||||
|
|
||||||
|
// Live 3-verse preview for the submission selector. Computes the fall-forward
|
||||||
|
// window anchored on the selected verse (spec: "Verse Windowing").
|
||||||
|
export const GET: RequestHandler = async ({ url }) => {
|
||||||
|
const bookId = url.searchParams.get('bookId');
|
||||||
|
const chapterParam = url.searchParams.get('chapter');
|
||||||
|
const verseParam = url.searchParams.get('verse');
|
||||||
|
|
||||||
|
if (!bookId || !chapterParam || !verseParam) {
|
||||||
|
return json({ error: 'bookId, chapter, and verse are required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const book = getBookById(bookId);
|
||||||
|
if (!book) {
|
||||||
|
return json({ error: 'Unknown bookId' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const chapter = Number(chapterParam);
|
||||||
|
const verse = Number(verseParam);
|
||||||
|
if (!Number.isInteger(chapter) || !Number.isInteger(verse) || chapter < 1 || verse < 1) {
|
||||||
|
return json({ error: 'chapter and verse must be positive integers' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const window = composeVerseWindow(book.order, chapter, verse);
|
||||||
|
if (!window) {
|
||||||
|
// chapter/verse out of range — caught by composeVerseWindow's bounds checks
|
||||||
|
return json({ error: 'chapter or verse out of range for this book' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const reference = formatWindowReference(
|
||||||
|
window.bookName,
|
||||||
|
window.startChapter,
|
||||||
|
window.startVerse,
|
||||||
|
window.endChapter,
|
||||||
|
window.endVerse
|
||||||
|
);
|
||||||
|
|
||||||
|
return json({
|
||||||
|
windowVerses: window.verses,
|
||||||
|
reference,
|
||||||
|
bookId: window.bookId,
|
||||||
|
selectedVerse: window.selectedVerse
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import { db } from '$lib/server/db';
|
||||||
|
import { verseSubmissions, dailyVerses, user } from '$lib/server/db/schema';
|
||||||
|
import { eq, asc } from 'drizzle-orm';
|
||||||
|
import { getBookById } from '$lib/server/bible';
|
||||||
|
import { isAdmin } from '$lib/server/admin';
|
||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
|
||||||
|
export type ScheduledVerseRow = {
|
||||||
|
scheduledDate: string;
|
||||||
|
reference: string | null;
|
||||||
|
verseText: string | null;
|
||||||
|
bookId: string | null;
|
||||||
|
bookName: string | null;
|
||||||
|
selectedBookId: string;
|
||||||
|
selectedChapter: number;
|
||||||
|
selectedVerse: number;
|
||||||
|
submittedAt: number; // server UTC millis
|
||||||
|
submitterEmail: string | null;
|
||||||
|
submitterName: string | null;
|
||||||
|
submitterDeleted: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ locals }) => {
|
||||||
|
// Not authenticated → signal the client to show the sign-in flow
|
||||||
|
// (same pattern as /progress, /stats).
|
||||||
|
if (!locals.user) {
|
||||||
|
return {
|
||||||
|
rows: [] as ScheduledVerseRow[],
|
||||||
|
requiresAuth: true,
|
||||||
|
authorized: false,
|
||||||
|
user: null,
|
||||||
|
session: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticated but wrong account → plain access-denied state. Don't leak
|
||||||
|
// the existence of privileged data; just render "not authorized".
|
||||||
|
if (!isAdmin(locals.user.email)) {
|
||||||
|
return {
|
||||||
|
rows: [] as ScheduledVerseRow[],
|
||||||
|
requiresAuth: false,
|
||||||
|
authorized: false,
|
||||||
|
user: locals.user,
|
||||||
|
session: locals.session,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const joined = await db
|
||||||
|
.select({
|
||||||
|
scheduledDate: verseSubmissions.scheduledDate,
|
||||||
|
selectedBookId: verseSubmissions.selectedBookId,
|
||||||
|
selectedChapter: verseSubmissions.selectedChapter,
|
||||||
|
selectedVerse: verseSubmissions.selectedVerse,
|
||||||
|
submittedAt: verseSubmissions.submittedAt,
|
||||||
|
dailyDate: dailyVerses.date,
|
||||||
|
bookId: dailyVerses.bookId,
|
||||||
|
reference: dailyVerses.reference,
|
||||||
|
verseText: dailyVerses.verseText,
|
||||||
|
userId: verseSubmissions.userId,
|
||||||
|
userEmail: user.email,
|
||||||
|
userFirstName: user.firstName,
|
||||||
|
userLastName: user.lastName,
|
||||||
|
})
|
||||||
|
.from(verseSubmissions)
|
||||||
|
// LEFT JOINs so deleted accounts (ON DELETE SET NULL) still render —
|
||||||
|
// the scheduled verse plays out regardless.
|
||||||
|
.leftJoin(dailyVerses, eq(verseSubmissions.scheduledDate, dailyVerses.date))
|
||||||
|
.leftJoin(user, eq(verseSubmissions.userId, user.id))
|
||||||
|
.orderBy(asc(verseSubmissions.scheduledDate));
|
||||||
|
|
||||||
|
const rows: ScheduledVerseRow[] = joined.map((r) => {
|
||||||
|
const book = r.bookId ? getBookById(r.bookId) : undefined;
|
||||||
|
return {
|
||||||
|
scheduledDate: r.scheduledDate,
|
||||||
|
reference: r.reference,
|
||||||
|
verseText: r.verseText,
|
||||||
|
bookId: r.bookId,
|
||||||
|
bookName: book?.name ?? null,
|
||||||
|
selectedBookId: r.selectedBookId,
|
||||||
|
selectedChapter: r.selectedChapter,
|
||||||
|
selectedVerse: r.selectedVerse,
|
||||||
|
submittedAt: r.submittedAt,
|
||||||
|
submitterEmail: r.userEmail,
|
||||||
|
submitterName: [r.userFirstName, r.userLastName].filter(Boolean).join(' ') || null,
|
||||||
|
// userId is null when the account was deleted (ON DELETE SET NULL)
|
||||||
|
submitterDeleted: r.userId === null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
rows,
|
||||||
|
requiresAuth: false,
|
||||||
|
authorized: true,
|
||||||
|
user: locals.user,
|
||||||
|
session: locals.session,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { browser } from '$app/environment';
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import AuthModal from '$lib/components/AuthModal.svelte';
|
||||||
|
import Container from '$lib/components/Container.svelte';
|
||||||
|
import { bibleBooks } from '$lib/types/bible';
|
||||||
|
|
||||||
|
type ScheduledVerseRow = {
|
||||||
|
scheduledDate: string;
|
||||||
|
reference: string | null;
|
||||||
|
verseText: string | null;
|
||||||
|
bookId: string | null;
|
||||||
|
bookName: string | null;
|
||||||
|
selectedBookId: string;
|
||||||
|
selectedChapter: number;
|
||||||
|
selectedVerse: number;
|
||||||
|
submittedAt: number;
|
||||||
|
submitterEmail: string | null;
|
||||||
|
submitterName: string | null;
|
||||||
|
submitterDeleted: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface PageData {
|
||||||
|
rows: ScheduledVerseRow[];
|
||||||
|
requiresAuth: boolean;
|
||||||
|
authorized: boolean;
|
||||||
|
user?: any;
|
||||||
|
session?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { data }: { data: PageData } = $props();
|
||||||
|
|
||||||
|
let authModalOpen = $state(false);
|
||||||
|
let anonymousId = $state('');
|
||||||
|
let filter = $state<'all' | 'upcoming' | 'past'>('all');
|
||||||
|
const filters = ['all', 'upcoming', 'past'] as const;
|
||||||
|
|
||||||
|
function getOrCreateAnonymousId(): string {
|
||||||
|
if (!browser) return '';
|
||||||
|
const key = 'bibdle-anonymous-id';
|
||||||
|
let id = localStorage.getItem(key);
|
||||||
|
if (!id) {
|
||||||
|
id = crypto.randomUUID();
|
||||||
|
localStorage.setItem(key, id);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
anonymousId = getOrCreateAnonymousId();
|
||||||
|
});
|
||||||
|
|
||||||
|
function formatDate(dateStr: string): string {
|
||||||
|
const d = new Date(dateStr + 'T00:00:00Z');
|
||||||
|
return d.toLocaleDateString('en-US', {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
timeZone: 'UTC',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTimestamp(ms: number): string {
|
||||||
|
return new Date(ms).toLocaleString('en-US', {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
timeZone: 'UTC',
|
||||||
|
timeZoneName: 'short',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const todayUtc = $derived(new Date().toISOString().slice(0, 10));
|
||||||
|
|
||||||
|
const filteredRows = $derived.by(() => {
|
||||||
|
if (filter === 'all') return data.rows;
|
||||||
|
if (filter === 'upcoming') return data.rows.filter((r) => r.scheduledDate >= todayUtc);
|
||||||
|
return data.rows.filter((r) => r.scheduledDate < todayUtc);
|
||||||
|
});
|
||||||
|
|
||||||
|
function selectedBookName(bookId: string): string {
|
||||||
|
return bibleBooks.find((b) => b.id === bookId)?.name ?? bookId;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Scheduled Verses | Bibdle</title>
|
||||||
|
<meta name="robots" content="noindex" />
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="min-h-screen bg-linear-to-br from-gray-900 via-slate-900 to-gray-900 p-4 md:p-8"
|
||||||
|
>
|
||||||
|
<div class="max-w-5xl mx-auto">
|
||||||
|
<div class="text-center mb-6 md:mb-8">
|
||||||
|
<h1 class="text-3xl md:text-4xl font-bold text-gray-100 mb-4">
|
||||||
|
Scheduled Verses
|
||||||
|
</h1>
|
||||||
|
<a href="/" class="p-2 px-20 w-full items-center text-gray-300">
|
||||||
|
← Back to Game
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if data.requiresAuth}
|
||||||
|
<div class="text-center py-12">
|
||||||
|
<div
|
||||||
|
class="bg-blue-950/50 border border-blue-800/50 rounded-lg p-8 max-w-md mx-auto backdrop-blur-sm"
|
||||||
|
>
|
||||||
|
<h2 class="text-2xl font-bold text-blue-200 mb-4">
|
||||||
|
Authentication Required
|
||||||
|
</h2>
|
||||||
|
<p class="text-blue-300 mb-6">
|
||||||
|
You must be signed in to view this page.
|
||||||
|
</p>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<button
|
||||||
|
onclick={() => (authModalOpen = true)}
|
||||||
|
class="inline-flex items-center justify-center px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
|
||||||
|
>
|
||||||
|
Sign In
|
||||||
|
</button>
|
||||||
|
<a
|
||||||
|
href="/"
|
||||||
|
class="inline-flex items-center justify-center px-6 py-3 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors font-medium"
|
||||||
|
>
|
||||||
|
← Back to Game
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else if !data.authorized}
|
||||||
|
<div class="text-center py-12">
|
||||||
|
<div
|
||||||
|
class="bg-red-950/50 border border-red-800/50 rounded-lg p-8 max-w-md mx-auto backdrop-blur-sm"
|
||||||
|
>
|
||||||
|
<h2 class="text-2xl font-bold text-red-200 mb-4">Not Authorized</h2>
|
||||||
|
<p class="text-red-300 mb-6">You do not have access to this page.</p>
|
||||||
|
<a
|
||||||
|
href="/"
|
||||||
|
class="inline-flex items-center justify-center px-6 py-3 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors font-medium"
|
||||||
|
>
|
||||||
|
← Back to Game
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<!-- Filter toggle -->
|
||||||
|
<div class="flex items-center justify-between gap-2 mb-4 flex-wrap">
|
||||||
|
<div class="flex gap-1 bg-white/5 rounded-lg p-1 border border-white/10">
|
||||||
|
{#each filters as f}
|
||||||
|
<button
|
||||||
|
onclick={() => (filter = f)}
|
||||||
|
class="px-3 py-1.5 rounded-md text-xs font-medium transition-colors {filter ===
|
||||||
|
f
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'text-gray-300 hover:bg-white/5'}"
|
||||||
|
>
|
||||||
|
{f.charAt(0).toUpperCase() + f.slice(1)}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<span class="text-xs text-gray-500">
|
||||||
|
{filteredRows.length} {filteredRows.length === 1 ? 'row' : 'rows'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if filteredRows.length === 0}
|
||||||
|
<Container class="p-8 w-full text-center">
|
||||||
|
<p class="text-gray-400">No submissions yet.</p>
|
||||||
|
</Container>
|
||||||
|
{:else}
|
||||||
|
<Container class="p-2 md:p-4 w-full overflow-x-auto">
|
||||||
|
<table class="w-full text-sm text-left text-gray-200">
|
||||||
|
<thead
|
||||||
|
class="text-xs uppercase text-gray-400 border-b border-white/10"
|
||||||
|
>
|
||||||
|
<tr>
|
||||||
|
<th class="px-2 md:px-3 py-2">Scheduled</th>
|
||||||
|
<th class="px-2 md:px-3 py-2">Reference</th>
|
||||||
|
<th class="px-2 md:px-3 py-2 hidden md:table-cell">
|
||||||
|
Window text
|
||||||
|
</th>
|
||||||
|
<th class="px-2 md:px-3 py-2">Submitted by</th>
|
||||||
|
<th class="px-2 md:px-3 py-2 hidden sm:table-cell">
|
||||||
|
Submitted at
|
||||||
|
</th>
|
||||||
|
<th class="px-2 md:px-3 py-2 hidden lg:table-cell">
|
||||||
|
Selected
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{#each filteredRows as row (row.scheduledDate)}
|
||||||
|
<tr
|
||||||
|
class="border-b border-white/5 hover:bg-white/5 align-top"
|
||||||
|
>
|
||||||
|
<td class="px-2 md:px-3 py-2 whitespace-nowrap">
|
||||||
|
<div class="font-medium text-gray-100">
|
||||||
|
{formatDate(row.scheduledDate)}
|
||||||
|
</div>
|
||||||
|
{#if row.scheduledDate < todayUtc}
|
||||||
|
<span class="text-[10px] text-gray-500"
|
||||||
|
>played</span
|
||||||
|
>
|
||||||
|
{:else if row.scheduledDate === todayUtc}
|
||||||
|
<span
|
||||||
|
class="text-[10px] text-emerald-400"
|
||||||
|
>today</span
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
</td>
|
||||||
|
<td class="px-2 md:px-3 py-2">
|
||||||
|
{#if row.reference}
|
||||||
|
<div class="font-medium">
|
||||||
|
{row.reference}
|
||||||
|
</div>
|
||||||
|
<div class="text-[10px] text-gray-500">
|
||||||
|
{row.bookName ?? row.bookId}
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<span class="text-gray-500"
|
||||||
|
>— no daily_verse row —</span
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
class="px-2 md:px-3 py-2 hidden md:table-cell max-w-xs"
|
||||||
|
>
|
||||||
|
<span class="text-xs text-gray-400 line-clamp-4"
|
||||||
|
>{row.verseText ?? ''}</span
|
||||||
|
>
|
||||||
|
</td>
|
||||||
|
<td class="px-2 md:px-3 py-2">
|
||||||
|
{#if row.submitterDeleted}
|
||||||
|
<span class="text-gray-500 italic"
|
||||||
|
>(deleted user)</span
|
||||||
|
>
|
||||||
|
{:else}
|
||||||
|
{#if row.submitterName}
|
||||||
|
<div>{row.submitterName}</div>
|
||||||
|
{/if}
|
||||||
|
<div class="text-[11px] text-gray-400">
|
||||||
|
{row.submitterEmail ?? '—'}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
class="px-2 md:px-3 py-2 hidden sm:table-cell whitespace-nowrap text-xs text-gray-400"
|
||||||
|
>
|
||||||
|
{formatTimestamp(row.submittedAt)}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
class="px-2 md:px-3 py-2 hidden lg:table-cell whitespace-nowrap text-xs text-gray-400"
|
||||||
|
>
|
||||||
|
{selectedBookName(row.selectedBookId)}
|
||||||
|
{row.selectedChapter}:{row.selectedVerse}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{/each}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</Container>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AuthModal bind:isOpen={authModalOpen} {anonymousId} />
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import { describe, test, expect } from "bun:test";
|
||||||
|
import {
|
||||||
|
composeVerseWindow,
|
||||||
|
formatWindowReference,
|
||||||
|
getChapterCount,
|
||||||
|
getVerseCount,
|
||||||
|
extractVerses,
|
||||||
|
} from "$lib/server/xml-bible";
|
||||||
|
import { bookIdToNumber, getBookById } from "$lib/server/bible";
|
||||||
|
|
||||||
|
describe("getChapterCount / getVerseCount", () => {
|
||||||
|
test("Genesis has 50 chapters", () => {
|
||||||
|
expect(getChapterCount(bookIdToNumber["GEN"])).toBe(50);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Jude has 1 chapter", () => {
|
||||||
|
expect(getChapterCount(bookIdToNumber["JUD"])).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Genesis 1 has 31 verses", () => {
|
||||||
|
expect(getVerseCount(bookIdToNumber["GEN"], 1)).toBe(31);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("composeVerseWindow — default [v-2, v-1, v]", () => {
|
||||||
|
test("Genesis 1:3 → window is 1:1-3 (same chapter, hyphen)", () => {
|
||||||
|
const w = composeVerseWindow(bookIdToNumber["GEN"], 1, 3);
|
||||||
|
expect(w).not.toBeNull();
|
||||||
|
expect(w!.startChapter).toBe(1);
|
||||||
|
expect(w!.startVerse).toBe(1);
|
||||||
|
expect(w!.endChapter).toBe(1);
|
||||||
|
expect(w!.endVerse).toBe(3);
|
||||||
|
expect(w!.verses).toHaveLength(3);
|
||||||
|
expect(formatWindowReference(w!.bookName, w!.startChapter, w!.startVerse, w!.endChapter, w!.endVerse))
|
||||||
|
.toBe("Genesis 1:1-3");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("selected verse is the last in the default window", () => {
|
||||||
|
const w = composeVerseWindow(bookIdToNumber["GEN"], 1, 10);
|
||||||
|
expect(w!.selectedVerse).toBe(10);
|
||||||
|
// verses[2] should equal Genesis 1:10's text
|
||||||
|
const direct = extractVerses(bookIdToNumber["GEN"], 1, 10, 1);
|
||||||
|
expect(w!.verses[2]).toBe(direct[0]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("composeVerseWindow — fall-forward at book start", () => {
|
||||||
|
test("Genesis 1:1 → fall forward to [1,2,3]", () => {
|
||||||
|
const w = composeVerseWindow(bookIdToNumber["GEN"], 1, 1);
|
||||||
|
expect(w!.startChapter).toBe(1);
|
||||||
|
expect(w!.startVerse).toBe(1);
|
||||||
|
expect(w!.endChapter).toBe(1);
|
||||||
|
expect(w!.endVerse).toBe(3);
|
||||||
|
expect(w!.verses).toHaveLength(3);
|
||||||
|
expect(formatWindowReference(w!.bookName, w!.startChapter, w!.startVerse, w!.endChapter, w!.endVerse))
|
||||||
|
.toBe("Genesis 1:1-3");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Genesis 1:2 → fall forward to [2,3,4] (v-2 < 1)", () => {
|
||||||
|
const w = composeVerseWindow(bookIdToNumber["GEN"], 1, 2);
|
||||||
|
expect(w!.startVerse).toBe(2);
|
||||||
|
expect(w!.endVerse).toBe(4);
|
||||||
|
expect(w!.verses).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("John 1:1 → fall forward", () => {
|
||||||
|
const w = composeVerseWindow(bookIdToNumber["JHN"], 1, 1);
|
||||||
|
expect(w!.bookId).toBe("JHN");
|
||||||
|
expect(w!.startVerse).toBe(1);
|
||||||
|
expect(w!.endVerse).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("composeVerseWindow — cross-chapter within a book", () => {
|
||||||
|
test("Genesis 2:1 → window spans 1:30-2:1 (en-dash, two chapters)", () => {
|
||||||
|
const w = composeVerseWindow(bookIdToNumber["GEN"], 2, 1);
|
||||||
|
expect(w!.startChapter).toBe(1);
|
||||||
|
expect(w!.endChapter).toBe(2);
|
||||||
|
// Genesis 1 has 31 verses; selected index for 2:1 = 31 + 1 = 32; window = [30,31,32]
|
||||||
|
expect(w!.startVerse).toBe(30);
|
||||||
|
expect(w!.startChapter === 1 && w!.endChapter === 2).toBe(true);
|
||||||
|
expect(w!.verses).toHaveLength(3);
|
||||||
|
const ref = formatWindowReference(w!.bookName, w!.startChapter, w!.startVerse, w!.endChapter, w!.endVerse);
|
||||||
|
expect(ref).toBe("Genesis 1:30\u20132:1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("window never crosses a book boundary", () => {
|
||||||
|
// Every book has >= 3 verses, and windows are constrained in-book by construction.
|
||||||
|
// Spot-check the last verse of Malachi 4 (end of OT) still resolves in-book.
|
||||||
|
const mal = bookIdToNumber["MAL"];
|
||||||
|
const lastChapter = getChapterCount(mal);
|
||||||
|
const lastVerse = getVerseCount(mal, lastChapter);
|
||||||
|
const w = composeVerseWindow(mal, lastChapter, lastVerse);
|
||||||
|
expect(w).not.toBeNull();
|
||||||
|
expect(w!.bookId).toBe("MAL");
|
||||||
|
expect(w!.endChapter).toBe(lastChapter);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("composeVerseWindow — invalid input", () => {
|
||||||
|
test("unknown book number returns null", () => {
|
||||||
|
expect(composeVerseWindow(999, 1, 1)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("chapter out of range returns null", () => {
|
||||||
|
expect(composeVerseWindow(bookIdToNumber["GEN"], 999, 1)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("verse out of range returns null", () => {
|
||||||
|
expect(composeVerseWindow(bookIdToNumber["GEN"], 1, 9999)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("formatWindowReference", () => {
|
||||||
|
test("same chapter, range", () => {
|
||||||
|
expect(formatWindowReference("Genesis", 1, 1, 1, 3)).toBe("Genesis 1:1-3");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("same chapter, single verse", () => {
|
||||||
|
expect(formatWindowReference("Jude", 1, 5, 1, 5)).toBe("Jude 1:5");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("cross chapter uses en-dash", () => {
|
||||||
|
expect(formatWindowReference("Genesis", 1, 31, 2, 1)).toBe("Genesis 1:31\u20132:1");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("composeVerseWindow — every book's opening verse is safe", () => {
|
||||||
|
// The spec guarantees every book has >=3 verses after its opening, so Gen 1:1-style
|
||||||
|
// fall-forward must succeed for the first verse of every book.
|
||||||
|
test("book 1:1 of all 66 books resolves to a 3-verse in-book window", () => {
|
||||||
|
const ids = Object.keys(bookIdToNumber);
|
||||||
|
for (const id of ids) {
|
||||||
|
const num = bookIdToNumber[id];
|
||||||
|
const w = composeVerseWindow(num, 1, 1);
|
||||||
|
expect(w, `${getBookById(id)!.name} 1:1 should resolve`).not.toBeNull();
|
||||||
|
expect(w!.verses).toHaveLength(3);
|
||||||
|
expect(w!.bookId).toBe(id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user