Bring website/ into the dev/prod workflow: local bring-up + a real test suite

dev.sh now also brings up website/'s own stack (bi.bettersight.io,
bettersight.io, shared backend) via its own docker compose up -d --build,
and force-recreates marketing locally too — its content-hash label never
changes on a plain local `up -d` the way generate-dokploy-compose.sh
makes it change for Dokploy, so local edits to bettersightbox-index.html
were silently not picked up either without this.

website/backend gets a real test suite (17 tests: contact form
validation/success/failure, both calculator endpoints, and build_pdf()
exercised for real since it's pure/offline) — previously completely
untested. prod.sh now gates the ship on both test suites passing, since
one git push now triggers both Dokploy apps' AutoDeploy.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012pc2x7vyuUofdT3kLuqF3Y
This commit is contained in:
JasonFraser 2026-10-04 17:49:48 -04:00
parent 363f9ec134
commit d22b628945
10 changed files with 371 additions and 19 deletions

View File

@ -1,18 +1,20 @@
#!/usr/bin/env bash
# Local iteration loop: build both custom images for this machine's own
# architecture (fast, no registry push — see erpnext-image/build.sh and
# backend/build.sh's own local-vs-registry branching) and bring the
# affected services up immediately so you can test against them. Run this
# as often as you want while developing; nothing here touches git or the
# registry — see scripts/prod.sh for shipping what you've tested here.
# backend/build.sh's own local-vs-registry branching), bring the ERPNext
# stack's affected services up, and bring up website/'s own stack (a
# completely separate Compose project — bi.bettersight.io,
# bettersight.io, and their shared backend) too. Run this as often as you
# want while developing; nothing here touches git or any registry — see
# scripts/prod.sh for shipping what you've tested here.
#
# What happens when this runs, in order:
# 1. ./generate-dokploy-compose.sh — keeps docker-compose.dokploy.yml's
# marketing content-hash in sync as you edit website/website-bettersightbox/
# bettersightbox-index.html,
# so there's nothing new for prod.sh to auto-commit at ship time. Not
# committed here — dev.sh never touches git; prod.sh is the only one
# that commits, gated behind its own clean-tree/test checks.
# bettersightbox-index.html, so there's nothing new for prod.sh to
# auto-commit at ship time. Not committed here — dev.sh never
# touches git; prod.sh is the only one that commits, gated behind
# its own clean-tree/test checks.
# 2. ./erpnext-image/build.sh — CUSTOM_IMAGE in the root .env is a bare
# local tag (not a registry path), so this takes the local branch:
# builds sightbox-erpnext for this machine's own architecture, no push.
@ -24,7 +26,17 @@
# plus backend-billing — so the freshly-built images actually get
# picked up. (Compose has no "recreate everyone using image X" — it
# only accepts service names, so all eight get listed individually
# even though only one or two images actually changed.)
# even though only one or two images actually changed.) marketing is
# force-recreated here too — its own content-hash label only changes
# via generate-dokploy-compose.sh's literal-value substitution
# (step 1), which this script never runs against the LOCAL
# docker-compose.yml, so a plain `up -d` would never notice a
# bettersightbox-index.html edit locally either, same root cause as
# the production staleness bug that label exists to fix.
# 5. website/'s own `docker compose up -d --build` — separate Compose
# project (see website/docker-compose.yml, website/README.md), no
# content-hash trick needed there since every one of its services
# gets rebuilt from source on every run of this step.
#
# Usage (from the sightbox/ project root or from here — either works):
# ./scripts/dev.sh
@ -44,7 +56,11 @@ echo
echo "Bringing up the affected services locally..."
docker compose up -d --force-recreate \
configurator backend frontend websocket queue-short queue-long scheduler \
backend-billing
backend-billing marketing
echo
echo "Bringing up website/'s own stack (bi.bettersight.io, bettersight.io, shared backend)..."
( cd website && docker compose up -d --build )
echo
echo "Done — test against your local stack now."

View File

@ -1,10 +1,11 @@
#!/usr/bin/env bash
# Ships what scripts/dev.sh already built and you've tested locally:
# rebuilds both images for the real production target (linux/amd64, via
# each build.sh's own registry-path branch) and pushes them, runs the
# backend test suite as the one gate before any of that happens, then
# pushes this branch to main so Dokploy's existing AutoDeploy (triggered
# by the git push itself, not by this script) pulls the new images.
# each build.sh's own registry-path branch) and pushes them, runs both
# backend test suites as the one gate before any of that happens, then
# pushes this branch to main — which now triggers TWO Dokploy AutoDeploy
# webhooks (the ERPNext app and the separate website/ app, see
# website/README.md), not just one.
#
# Requires:
# - Currently checked out on main, with no uncommitted changes — this
@ -12,6 +13,10 @@
# - backend/tests/ passing — the one gate between this and production;
# see playbook/ENTERPRISE_STANDARDS.md's coverage rules for
# stripe_webhook.py/billing.py specifically.
# - website/backend/tests/ passing too — a smaller suite (no 100%-
# coverage standard applies there, ENTERPRISE_STANDARDS.md is scoped
# to the ERPNext app's backend/ only), but still gates the push since
# website/ ships on this same `git push origin main`.
# - scripts/.env.prod (gitignored, copy from scripts/.env.prod.example)
# with the real registry image paths. Deliberately does NOT set
# DOKPLOY_URL/DOKPLOY_API_TOKEN/DOKPLOY_COMPOSE_ID — this script
@ -42,17 +47,22 @@
# BACKEND_BILLING_TAG registry paths into this shell.
# 5. Runs backend/tests/ via pytest — any failure stops here, before
# anything is built or pushed.
# 6. ./erpnext-image/build.sh — sees the registry-path CUSTOM_IMAGE from
# 6. Runs website/backend/tests/ via pytest too — same reasoning, before
# anything is built or pushed. website/'s own images are never built
# or pushed by this script (Dokploy builds them server-side from
# source on deploy, see website/docker-compose.yml) — this step is
# purely the test gate for it.
# 7. ./erpnext-image/build.sh — sees the registry-path CUSTOM_IMAGE from
# step 4, takes its registry branch: builds for linux/amd64 via
# buildx (not this machine's own arch) and pushes straight to the
# registry.
# 7. ./backend/build.sh — same thing for backend-billing: builds for
# 8. ./backend/build.sh — same thing for backend-billing: builds for
# linux/amd64, pushes to the registry. DOKPLOY_URL/DOKPLOY_API_TOKEN/
# DOKPLOY_COMPOSE_ID are deliberately unset (see above), so this step
# stops after pushing — it does not call Dokploy's API itself.
# 8. git push origin main — the actual deploy trigger (carries step 3's
# auto-commit too, if one happened). Dokploy's AutoDeploy watches main
# and redeploys on push, pulling both freshly-pushed images.
# 9. git push origin main — the actual deploy trigger (carries step 3's
# auto-commit too, if one happened). Both Dokploy apps' AutoDeploy
# webhooks fire on this one push and redeploy independently.
#
# Usage: ./scripts/prod.sh
@ -98,6 +108,9 @@ set +a
echo "Running backend test suite..."
( cd backend && .venv/bin/pytest tests/ -q )
echo "Running website/backend test suite..."
( cd website/backend && .venv/bin/pytest tests/ -q )
echo
echo "Building and pushing for linux/amd64..."
./erpnext-image/build.sh

View File

@ -4,3 +4,5 @@ Dockerfile
.dockerignore
__pycache__
*.pyc
.pytest_cache/
.coverage

5
website/backend/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.venv/
__pycache__/
*.pyc
.pytest_cache/
.coverage

View File

@ -3,3 +3,5 @@ gunicorn==22.0.0
httpx==0.27.2
flask-limiter==3.8.0
fpdf2==2.7.9
pytest==8.3.2
pytest-cov==5.0.0

View File

@ -0,0 +1,38 @@
"""
tests/conftest.py — makes backend/'s modules importable from tests/ (no
package/__init__.py, matching the sightbox backend/'s own flat layout) and
builds one Flask test client per test with rate limiting disabled, since
Flask-Limiter's in-memory store is a module-level singleton
(middleware/rate_limit.py) shared across the whole pytest session — left
enabled, the suite's own request volume would eventually trip
RATELIMIT_PER_HOUR against itself.
"""
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app import create_app # noqa: E402
@pytest.fixture
def client():
app = create_app()
app.config["TESTING"] = True
app.config["RATELIMIT_ENABLED"] = False
with app.test_client() as test_client:
yield test_client
@pytest.fixture
def configured_resend(monkeypatch):
"""Sets the env vars send_email() requires, via Config directly (already-imported module attributes, not os.environ, since Config reads env once at import time)."""
import config
monkeypatch.setattr(config.Config, "RESEND_API_KEY", "re_test_key")
monkeypatch.setattr(config.Config, "MAIL_SENDER_NAME", "Bettersight")
monkeypatch.setattr(config.Config, "MAIL_SENDER_ADDRESS", "support@bettersight.io")
monkeypatch.setattr(config.Config, "SALES_EMAIL", "sales@bettersight.io")

View File

@ -0,0 +1,121 @@
"""
tests/test_calculator.py — tests for POST /api/calculator/copy and
POST /api/calculator/contact. build_pdf() runs for real (pure, fast, no
network — see services/pdf_service.py); Resend is mocked at the
httpx.post level, same as test_contact.py.
"""
from unittest.mock import MagicMock
import httpx
import services.email_service as email_service
_PAYLOAD = {
"calculator": "self-assess",
"title": "Your Results",
"summary_text": "You could save <strong>6 hours/week</strong>.",
"results": [
{"label": "Hours saved / week", "value": "6"},
{"label": "Annual cost", "value": "$18,000"},
],
"basis_footnote": "Estimates based on inputs provided.",
}
def _mock_post(monkeypatch, status_code=200):
response = MagicMock()
response.status_code = status_code
if status_code >= 400:
response.raise_for_status.side_effect = httpx.HTTPStatusError(
"error", request=MagicMock(), response=response
)
else:
response.raise_for_status.return_value = None
mock_post = MagicMock(return_value=response)
monkeypatch.setattr(email_service.httpx, "post", mock_post)
return mock_post
# --- /api/calculator/copy ---------------------------------------------------
def test_copy_missing_email_returns_400(client):
response = client.post("/api/calculator/copy", json={**_PAYLOAD, "recipient_email": ""})
assert response.status_code == 400
def test_copy_valid_request_sends_pdf_to_visitor_only(client, configured_resend, monkeypatch):
mock_post = _mock_post(monkeypatch)
response = client.post(
"/api/calculator/copy",
json={**_PAYLOAD, "recipient_email": "visitor@example.com"},
)
assert response.status_code == 200
assert response.get_json()["status"] == "sent"
mock_post.assert_called_once()
sent = mock_post.call_args.kwargs["json"]
assert sent["to"] == ["visitor@example.com"]
assert len(sent["attachments"]) == 1
assert sent["attachments"][0]["filename"] == "bettersight-results.pdf"
def test_copy_resend_failure_returns_502(client, configured_resend, monkeypatch):
_mock_post(monkeypatch, status_code=500)
response = client.post(
"/api/calculator/copy",
json={**_PAYLOAD, "recipient_email": "visitor@example.com"},
)
assert response.status_code == 502
# --- /api/calculator/contact -------------------------------------------------
def test_contact_missing_fields_returns_400(client):
response = client.post(
"/api/calculator/contact", json={**_PAYLOAD, "contact": {"name": "Jason"}}
)
assert response.status_code == 400
def test_contact_valid_request_notifies_sales_with_reply_to(client, configured_resend, monkeypatch):
mock_post = _mock_post(monkeypatch)
response = client.post(
"/api/calculator/contact",
json={
**_PAYLOAD,
"contact": {
"name": "Jason Fraser",
"email": "jason@example.com",
"organization": "Acme Co",
},
},
)
assert response.status_code == 200
assert response.get_json()["status"] == "received"
sent = mock_post.call_args.kwargs["json"]
assert sent["to"] == ["sales@bettersight.io"]
assert sent["reply_to"] == "jason@example.com"
assert "Jason Fraser" in sent["subject"]
def test_contact_resend_failure_returns_502(client, configured_resend, monkeypatch):
_mock_post(monkeypatch, status_code=500)
response = client.post(
"/api/calculator/contact",
json={**_PAYLOAD, "contact": {"name": "Jason", "email": "jason@example.com"}},
)
assert response.status_code == 502

View File

@ -0,0 +1,109 @@
"""
tests/test_contact.py — tests for POST /api/contact. Resend is always
mocked at the httpx.post level (services/email_service.py's one outbound
call) — no test hits it live.
"""
from unittest.mock import MagicMock
import httpx
import services.email_service as email_service
def _mock_post(monkeypatch, status_code=200):
response = MagicMock()
response.status_code = status_code
if status_code >= 400:
response.raise_for_status.side_effect = httpx.HTTPStatusError(
"error", request=MagicMock(), response=response
)
else:
response.raise_for_status.return_value = None
mock_post = MagicMock(return_value=response)
monkeypatch.setattr(email_service.httpx, "post", mock_post)
return mock_post
# --- validation ------------------------------------------------------------
def test_missing_name_returns_400(client):
response = client.post("/api/contact", json={"email": "lead@example.com"})
assert response.status_code == 400
assert response.get_json()["error"] == "name is required"
def test_missing_email_returns_400(client):
response = client.post("/api/contact", json={"name": "Jason"})
assert response.status_code == 400
assert response.get_json()["error"] == "a valid email is required"
def test_malformed_email_returns_400(client):
response = client.post("/api/contact", json={"name": "Jason", "email": "not-an-email"})
assert response.status_code == 400
# --- happy path --------------------------------------------------------------
def test_valid_submission_sends_via_resend(client, configured_resend, monkeypatch):
mock_post = _mock_post(monkeypatch)
response = client.post(
"/api/contact",
json={
"name": "Jason Fraser",
"email": "jason@example.com",
"organization": "Acme Co",
"message": "Tell me more.",
},
)
assert response.status_code == 202
assert response.get_json()["status"] == "sent"
mock_post.assert_called_once()
args, kwargs = mock_post.call_args
assert args[0] == "https://api.resend.com/emails"
assert kwargs["json"]["to"] == ["sales@bettersight.io"]
assert "Jason Fraser" in kwargs["json"]["html"]
def test_html_in_submission_is_escaped(client, configured_resend, monkeypatch):
mock_post = _mock_post(monkeypatch)
client.post(
"/api/contact",
json={"name": "<script>alert(1)</script>", "email": "lead@example.com"},
)
sent_html = mock_post.call_args.kwargs["json"]["html"]
assert "<script>" not in sent_html
assert "&lt;script&gt;" in sent_html
# --- failure paths -----------------------------------------------------------
def test_missing_resend_config_returns_502(client):
response = client.post(
"/api/contact", json={"name": "Jason", "email": "lead@example.com"}
)
assert response.status_code == 502
assert "error" in response.get_json()
def test_resend_failure_returns_502(client, configured_resend, monkeypatch):
_mock_post(monkeypatch, status_code=422)
response = client.post(
"/api/contact", json={"name": "Jason", "email": "lead@example.com"}
)
assert response.status_code == 502

View File

@ -0,0 +1,5 @@
def test_health_returns_ok(client):
response = client.get("/health")
assert response.status_code == 200
assert response.get_json() == {"status": "ok"}

View File

@ -0,0 +1,41 @@
"""
tests/test_pdf_service.py — build_pdf() is pure and offline (no network,
no mocking needed), so this exercises the real thing.
"""
from services.pdf_service import build_pdf
def test_build_pdf_returns_valid_pdf_bytes():
result = build_pdf(
{
"title": "Your Results",
"summary_text": "You could save <strong>6 hours/week</strong>.",
"results": [{"label": "Hours saved / week", "value": "6"}],
"basis_footnote": "Estimates based on inputs provided.",
}
)
assert result[:5] == b"%PDF-"
def test_build_pdf_handles_missing_optional_fields():
result = build_pdf({"title": "Your Results"})
assert result[:5] == b"%PDF-"
def test_build_pdf_sanitizes_unicode_punctuation():
# A real "email me a copy" request crashed generation outright on an
# em dash before _sanitize_text existed (see pdf_service.py's own
# comment) — this is the regression test for that.
result = build_pdf(
{
"title": "Your Results",
"summary_text": "Savings — up to 20% — guaranteed.",
"proactive_question": "What about edge cases?",
"proactive_answer": "We've got you covered — see below.",
}
)
assert result[:5] == b"%PDF-"