Skip to content

Wire up real Embassy backend: bookings, applications, admin CRUD, PDF#14

Merged
Kitkatnik merged 18 commits intomainfrom
Kitkatnik/embassy-backend
Apr 26, 2026
Merged

Wire up real Embassy backend: bookings, applications, admin CRUD, PDF#14
Kitkatnik merged 18 commits intomainfrom
Kitkatnik/embassy-backend

Conversation

@Kitkatnik
Copy link
Copy Markdown
Collaborator

Summary

  • Replaces the Embassy mockup (FakeEmbassy module + browser-print HTML) with a real backend: 5 new models (Question, NotaryProfile, EmbassyBooking, EmbassyApplication, EmbassyApplicationAnswer), 7 migrations, full admin CRUD on the question bank, and capacity-checked bookings inside row-locked transactions.
  • Section 3 question and notary draws now prefer least-used items so 70 applicants get a near-uniform distribution; applications support edit-while-draft and reuse one finalize_or_redirect path for both submit and save-draft intents.
  • PDF is generated server-side with Prawn — 3 pages (sections 1-4, then Section 5 + signature + 3-column small-print legalese in Tax-Form voice, then notary), real Page X of N footers, aligned signature/date blocks, and a per-question max_length that caps both the HTML form and PDF answer-box height.
  • Question + notary content loads idempotently from db/seeds/embassy_questions.rb (80 questions, 18 notaries) keyed by external_id, plus a defensive view fix and PlanItem has_one :embassy_booking, dependent: :destroy so stale schedule rows don't crash the Plan page and destroys cascade properly.

Test plan

  • bin/rails db:migrate && bin/rails db:seed — confirms 80 Questions, 18 NotaryProfiles
  • Sign in, book an embassy slot end-to-end (new passport + stamping paths), verify capacity enforcement and Section 5 forced page break
  • Submit application, download PDF — verify 3 pages, justified columns, ACKNOWLEDGMENT in column 3, footer "Page N of 3"
  • Edit-while-draft: leave the form, return via /embassy_applications/:serial/edit, verify answers persist and "Save & Return Later" routes to /plan
  • Admin: visit /admin/embassy_questions, confirm live usage counts, edit + archive a question, verify it stops appearing on new applications

- Add Question, NotaryProfile, EmbassyBooking, EmbassyApplication, and
  EmbassyApplicationAnswer models, with embassy_mode/embassy_capacity
  columns on ScheduleItem.
- Seed 80 questions and 18 notaries from db/seeds/embassy_questions.rb
  via idempotent EmbassyQuestionsSeed.import! (keyed by external_id).
- Wire EmbassyBookings, EmbassyApplications, and the Admin::* controllers
  to real ActiveRecord queries in place of FakeEmbassy.
- Generate real PDF downloads with Prawn (PassportApplicationPdf, formal
  tax-form aesthetic), replacing the browser-print HTML partial.
- Draw Section 3 questions and notary by least-used-first
  (EmbassyApplicationDraw) for fair distribution across applicants.
- Enforce booking capacity inside a row-locked transaction; support
  edit-while-draft on EmbassyApplication.
- Add Stimulus controller to toggle the embassy capacity/mode fields on
  the admin schedule-item form when kind = embassy.
- Delete fake_embassy.rb, _pdf.html.erb, _expired.html.erb.
Switch from f.submit (which renders <input type="submit"> where the value
attribute IS the displayed label) to <button type="submit"> elements with
separate inner text and submitted value. The button now shows "Submit
Application" instead of the literal "1" that was being submitted as the
form value. Renames the discriminator parameter from `submit` to `intent`
for clarity.
Previously "Save & Return Later" was a link that navigated away without
saving any answers — confusing alongside a separate "Save draft" button
that did save. Removes the redundant Save draft button and converts
"Save & Return Later" into a submit button (intent=draft) that saves the
in-progress answers and redirects to /plan.

Extracts the shared "submit vs. draft" branch into finalize_or_redirect
so both create and update go through one path.
PDF layout overhaul addressing five visual issues:

- Application now spans 2 pages instead of 8+. Short fields (Given Name +
  GitHub handle, Pronouns + Age in Coding Years, etc.) render side-by-side
  in two columns. Long answers get more vertical room sized from
  question.max_length.
- Add max_length column on Question, surfaced on the admin form and as
  HTML maxlength on the user-facing form. Defaults: 60 chars (short),
  240 chars (long). Caps text so it always fits the printed PDF box.
- Page footer now uses pdf.repeat(:all, dynamic: true) inside pdf.canvas
  so it renders in the bottom margin (not the content area) and shows
  the actual page number on every page (was always "Page 2 of 2").
- Applicant signature + date side-by-side in fixed-position bounding
  boxes — they now align horizontally (was vertically stacked due to
  fragile move_up arithmetic).
- Notary printed name + date aligned the same way; signature + notary
  ID below them no longer overlap.

Root-cause fix for the runaway pagination: boxed_text's inner
bounding_box had height < line height for short fields, which silently
triggered Prawn auto-pagination. Switched to draw_text/text_box for
single-line fields and made the inner-box height calculations safe.
PDF refinements:
- Render checkbox_group options inline with formatted_text fragments so
  short option lists ("Learning / Networking / Vibes / Free coffee") fit
  on one line; longer lists wrap naturally to 2 lines.
- Add INSTRUCTIONS TO THE APPLICANT (4 paragraphs) and EMBASSY
  ORDINANCES (7 §-numbered clauses) after the signature block to fill
  the otherwise mostly-blank page 2 with parodic legalese.
- Rename header subtitle from "United Embassy of Ruby" to
  "Blue Ridge Ruby Embassy" on both application + notary pages.

Confirmation page:
- Reword photography etiquette to ask about consent for photographing
  other attendees instead of the (fictional) Stamping Apparatus.
The inline checkbox rendering works well for short option lists like
Section 1.7 (Learning / Networking / Vibes / Free coffee) but turns
Section 4's longer affirmations into a hard-to-scan run-on. Branch
on a heuristic: 6+ options OR any option > 30 characters falls back
to the 2-column grid. Section 4 (7 options, ~50 chars each) now uses
the grid; Sections 1.7-1.9 keep the inline layout.
- APPLICANT SIGNATURE box left blank for physical ink signing; caption
  reads "Signature of Applicant" (drops "(typed)" — the typed name is
  already captured above as 5.4).
- §2 Discretion: replaces "tabs over spaces" jab with "documented hatred
  of the Ruby programming language" — fits the Embassy theme.
- §5 Right of Appeal: replaces /dev/null gag with noreply@blueridgeruby.com
  so the appeal channel is at least nominally plausible.
- Instruction #2: rewritten generically ("Answer all questions as
  printed...") to keep Section 3's randomization a surprise — attendees
  comparing applications will see different questions and not realize
  why.

Removes the now-unused PassportApplicationPdf#answer_text helper.
The inline formatted_text path packed options as natural-width
fragments, so spacing varied between every option. Replaces it with a
universal grid layout that adapts column count from option width:

  - Short options (max ~12 chars): 4 columns
  - Medium phrases (max ~25 chars): 3 columns
  - Long affirmations (Section 4): 2 columns

Each option gets a fixed-width slot, so they line up vertically within
a question — even across multiple rows. Drops the two_column_options?
branch since one grid path now handles all sizes.
Section spacing:
- Bump pre-section padding from 5pt to 8pt and pre-questions padding
  from 2pt to 3pt for more breathing room without forcing extra pages.

Legal text expansion (page 2 onward, ~2 pages of dense parody legalese):
- Add INSTRUCTION #5 about pens.
- Expand EMBASSY ORDINANCES from 7 § to 20 §, adding clauses on Decorum,
  Documentation, Reciprocal Recognition, Jurisdiction, Force Majeure,
  Amendments, Counterparts, No Third-Party Beneficiaries,
  Indemnification, Survival, Entire Agreement, Conflict of Laws, Notices.
- Add SCHEDULE A — DEFINITIONS (Applicant, Attaché, Business Gem,
  Embassy, Notary, Passport, Stamping, Vibe).
- Add SCHEDULE B — PROHIBITED ACTIVITIES (forgery, photography of the
  Stamping Apparatus mid-impact, narrating proceedings, etc.).
- Add SCHEDULE C — RULES OF CONSTRUCTION (singular/plural, business gem
  carve-outs, Schrödinger-cat gender clause).
- Add SCHEDULE D — REPRESENTATIONS AND WARRANTIES.
- Expand ACKNOWLEDGMENT to four paragraphs ending in "IN WITNESS
  WHEREOF, the Applicant has caused this Application to be executed by
  clicking a button on a website..."

Drop the cursor-based break guards in render_instructions so the legal
text now flows across page boundaries instead of being silently
truncated when a paragraph would orphan.
A handful of dev DB records had ScheduleItem#kind values (4, 5, 6) that
no longer exist in the model's enum, leftover from an earlier schema
that included additional kinds like meal/break/mystery. Reading the
enum returned nil, which then crashed item.kind.humanize on the Plan
and Admin Schedule Items pages.

- View guard: render the kind badge only when item.kind is present;
  Admin shows "unknown (N)" so stale rows are visible.
- Add has_one :embassy_booking, dependent: :destroy on PlanItem so
  destroying a plan item properly cascades to its booking + application
  + answers. Without this inverse the cascade chain went via
  ScheduleItem and tried to delete plan_items before their referencing
  bookings, raising PG::ForeignKeyViolation.
Layout:
- Use Prawn column_box(columns: 3) for INSTRUCTIONS / EMBASSY ORDINANCES /
  SCHEDULES A-D in 5.5pt small print, leaving the page-bottom for
  ACKNOWLEDGMENT full-width at 6pt. PDF is back to 3 pages: application
  (p1), Section 5 + signature + all legal text (p2), notary (p3).

Copy edits:
- Reciprocal Recognition (§9): swap CoffeeScript/Crystal/Elixir name-drops
  for generic "sister Ruby Embassies hosted at other regional and
  international Ruby gatherings."
- Business Gem definition: now refers to three (3) ceremonial gemstones
  used for symbolic Embassy purposes; "business gem" usage elsewhere
  rephrased as "(3) event days."
- Drop Schedule B (b) (Stamping Apparatus photography prohibition) and
  (d) (no narration / livestreaming) — attendees are free to photograph
  and livestream.
- Drop Schedule C #8 (Schrödinger-cat gender clause) — keep wording
  inclusive and avoid commentary on protected categories.
- Drop "and the open bar" from Schedule D (e).
The ACKNOWLEDGMENT was rendering full-width below the column box and
overlapping the page footer divider. Putting it inside the column box
as just another section lets Prawn handle layout uniformly — no cursor
math, no overlap.

Also rewrites the "Business Gems" definition to actually be about
RubyGems (the package manager) instead of literal gemstones, since the
joke is meant to be coding-flavored not jewelry-flavored.
- Set align: :justify on all column-flow paragraphs so text reads
  flush to both column edges (matches the formal-document register).
- Bump section-break gap from 4pt to 5pt for clearer separation
  between sections.
- Bump post-divider gap from 1pt to 3pt so the first paragraph of
  each section has visible breathing room below its header.
- Bump inter-paragraph gap from 1pt to 2pt for uniform rhythm
  throughout each section.
Prawn's column_box has no built-in column_break primitive, so simulate
one by overflowing the cursor past the bottom of the current column —
Prawn snaps to the top of the next one.

Tagging which sections want this in a small constant so it's data-
driven and easy to add other forced breaks if the layout shifts.
@railway-app
Copy link
Copy Markdown

railway-app Bot commented Apr 26, 2026

🚅 Deployed to the ruby-embassy-pr-14 environment in ruby-embassy

Service Status Web Updated (UTC)
ruby-embassy ✅ Success (View Logs) Web Apr 26, 2026 at 5:27 am

@railway-app railway-app Bot temporarily deployed to ruby-embassy / ruby-embassy-pr-14 April 26, 2026 05:09 Destroyed
- Auto-corrected Layout/SpaceInsideArrayLiteralBrackets across migrations,
  seed file, controllers, and PDF service to match the project's
  rubocop-rails-omakase preference for [ ... ] over [...].
- Empty out the auto-generated test/fixtures/*.yml stubs for the new
  Question, NotaryProfile, EmbassyBooking, EmbassyApplication, and
  EmbassyApplicationAnswer models. The placeholder rows produced by
  rails g model violated NOT NULL constraints (jsonb columns expect
  [], not nil) and broke fixture loading in every test. No tests use
  these fixtures yet; they can be filled in when real model tests are
  written.
@railway-app railway-app Bot temporarily deployed to ruby-embassy / ruby-embassy-pr-14 April 26, 2026 05:19 Destroyed
…kend

# Conflicts:
#	app/controllers/admin/embassy_applications_controller.rb
#	app/services/passport_application_pdf.rb
#	app/views/admin/embassy_applications/index.html.erb
#	db/schema.rb
#	test/fixtures/embassy_application_answers.yml
#	test/fixtures/embassy_applications.yml
#	test/fixtures/embassy_bookings.yml
#	test/fixtures/notary_profiles.yml
#	test/fixtures/questions.yml
@railway-app railway-app Bot temporarily deployed to ruby-embassy / ruby-embassy-pr-14 April 26, 2026 05:26 Destroyed
@Kitkatnik Kitkatnik merged commit 943a9bd into main Apr 26, 2026
6 checks passed
@Kitkatnik Kitkatnik deleted the Kitkatnik/embassy-backend branch April 26, 2026 07:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant