diff --git a/.env.example b/.env.example index 2d850b3..5847446 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,3 @@ -# owner account password (username: owner); changing it here resets the owner login -APP_PASSWORD=pick-a-long-password SECRET_KEY=generate-with-openssl-rand-hex-32 +# Default business time zone until you pick one in first-time setup APP_TZ=America/New_York diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca8d548..d578aca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -175,7 +175,8 @@ jobs: env: DATA_DIR: ${{ github.workspace }}/.ci-visual APP_URL: http://127.0.0.1:8000 - APP_PASSWORD: ci-smoke-only-not-a-real-password + DEMO_OWNER_PASSWORD: ci-smoke-only-not-a-real-password + OWNER_PASSWORD: ci-smoke-only-not-a-real-password SECRET_KEY: cismoke0000000000000000000000000000000000000000000000000000000000 PYTHONPATH: "." steps: @@ -226,7 +227,6 @@ jobs: - name: Boot to healthy run: | docker run -d --name "$SMOKE" \ - -e APP_PASSWORD=ci-smoke-only-not-a-real-password \ -e SECRET_KEY=cismoke0000000000000000000000000000000000000000000000000000000000 \ "$SMOKE" # HEALTHCHECK: 20s start-period, 30s interval — allow ~2 min total. diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..aec2fd4 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,33 @@ +# Publishes the project website (site/) to GitHub Pages. One-time setup in the +# repository: Settings → Pages → Build and deployment → Source: GitHub Actions. +name: Website + +on: + push: + branches: [main] + paths: ["site/**", ".github/workflows/pages.yml"] + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + deploy: + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/checkout@v4 + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v3 + with: + path: site + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/README.md b/README.md index 98852a3..458096d 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@

Self-hosted pool-service management — routes, water chemistry, invoicing, and crew.

+

Website · Docker Hub · Releases

+ --- Self-hosted pool-route app for small pool-service companies, built to run on @@ -24,27 +26,36 @@ one box (Docker + SQLite) and to be used from an iPhone in the field. ## Run - cp .env.example .env # set APP_PASSWORD and SECRET_KEY + cp .env.example .env # set SECRET_KEY (openssl rand -hex 32) docker compose up -d + # (builds from source; to run the published image instead use + # deploy/docker-compose.yml, which pulls dendlomm/openpoolpro:latest) # Put a TLS reverse proxy in front — the compose file binds the app to # 127.0.0.1:8000 ON PURPOSE (the app trusts X-Forwarded-* from the proxy), # so it is NOT reachable from other machines directly. Point the proxy at # 127.0.0.1:8000 and set FORWARDED_ALLOW_IPS to the proxy's address. - # First login is owner / your APP_PASSWORD - # manage crew under Settings → Manage crew - # change APP_PASSWORD in .env + restart to reset the owner login (recovery) + # Open the app: first-time setup asks for the setup code from + # docker compose logs app | grep "Setup code" + # then creates your owner account (your name, username and password). + # Forgot the owner password? Print a one-time reset link: + # docker compose exec app python -m app.manage reset-owner [--clear-2fa] # on iPhone: Share → Add to Home Screen All data lives in ./data (SQLite DB, photos, nightly backups). Back up that folder. +**Upgrading from a version that used `APP_PASSWORD`:** your `owner` account keeps +working with its current password. The first time you sign in after the upgrade, +you're asked to add your name, choose your own username and set a new password. +After that `APP_PASSWORD` is never read, so remove it from `.env`. + ### Deploy the published image (Unraid) CI publishes `:latest` on every merge to `main`, plus an immutable `:vX.Y.Z` per release, to both `ghcr.io/dlommm/openpoolpro` and Docker Hub (`dendlomm/openpoolpro`). `docker-compose.unraid.yml` is a ready-made stack for Unraid's Docker Compose Manager — read the SETUP notes at the top of the file -(cache-only appdata share, required `APP_PASSWORD`/`SECRET_KEY`), then: +(cache-only appdata share, required `SECRET_KEY`), then: docker compose -f docker-compose.unraid.yml pull docker compose -f docker-compose.unraid.yml up -d @@ -54,7 +65,8 @@ for Unraid's Docker Compose Manager — read the SETUP notes at the top of the f python3.12 -m venv .venv && source .venv/bin/activate pip install -r requirements-dev.txt python scripts/build_css.py - APP_PASSWORD=dev COOKIE_SECURE=0 uvicorn app.main:create_app --factory --reload + COOKIE_SECURE=0 uvicorn app.main:create_app --factory --reload + # the setup code is printed in the log on first start ruff check app/ tests/ scripts/ # same gate CI runs pytest -n auto @@ -505,7 +517,7 @@ is how a customer arrives. Every staff screen and the portal are rendered twice, once on a light device and once on a dark one, and each render is held to a 7:1 body-text contrast ratio: - APP_URL=http://localhost:8000 APP_PASSWORD=... python scripts/visual_check.py + APP_URL=http://localhost:8000 OWNER_USER=... OWNER_PASSWORD=... python scripts/visual_check.py Point it at a disposable instance: to reach those screens it creates a "Visual Tech" staff member and issues then revokes a portal link for customer 1, diff --git a/app/analytics_overview.py b/app/analytics_overview.py new file mode 100644 index 0000000..d284aa4 --- /dev/null +++ b/app/analytics_overview.py @@ -0,0 +1,516 @@ +"""The Analytics overview: one range (3, 6 or 12 months) scoping every panel. + +Pure query/aggregation layer, like app.analytics, whose money rules it reuses +to the cent: service is the frozen visit labor (`tax.effective_labor_cents`), +chemicals are billed through `qbo.billable_for_vc` at the current markup, and +"repairs and jobs" is the labor of finished jobs dated by their business-local +completion day. + +The current month is always partial. It is drawn and totalled, but the +like-for-like comparison uses full months only: the full months of the window +against the same number of months just before it. +""" +from collections import defaultdict +from dataclasses import dataclass, field +from datetime import date + +from sqlalchemy import func, select +from sqlalchemy.orm import Session, selectinload + +from app import analytics, models, qbo, receivables, tax +from app.qbo import _local_date +from app.rates import effective_rate_cents, largest_pool_gallons +from app.timefmt import business_today, local_date + +RANGES = (3, 6, 12) +DEFAULT_RANGE = 6 +REVIEW_SHARE = 0.15 # chemical cost at or above this share of the rate -> review + +# Visits a week each schedule frequency produces, for "recurring weekly service". +WEEKLY_FACTOR = {"weekly": 1.0, "biweekly": 0.5, "every4weeks": 0.25} + +SOURCES = ( + ("service", "Weekly service", "var(--c1)"), + ("chemicals", "Chemicals", "var(--c2)"), + ("jobs", "Repairs and jobs", "var(--c3)"), +) + +AGING_LABELS = { + "Current": "Not due yet", + "1-30": "1–30 days late", + "31-60": "31–60 days late", + "61-90": "61–90 days late", + "90+": "Over 90 days", +} + +MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", + "August", "September", "October", "November", "December") + + +def ordinal(n: int) -> str: + suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th") + return f"{n}{suffix}" + + +def parse_range(raw) -> int: + try: + n = int(raw) + except (TypeError, ValueError): + return DEFAULT_RANGE + return n if n in RANGES else DEFAULT_RANGE + + +def month_keys(today: date, months: int) -> list[tuple[int, int]]: + """The `months` calendar months ending with today's, oldest first.""" + out = [] + y, m = today.year, today.month + for _ in range(max(1, months)): + out.append((y, m)) + y, m = (y - 1, 12) if m == 1 else (y, m - 1) + return out[::-1] + + +def _shift(key: tuple[int, int], back: int) -> tuple[int, int]: + idx = key[0] * 12 + (key[1] - 1) - back + return (idx // 12, idx % 12 + 1) + + +@dataclass +class MonthRow: + year: int + month: int + service_cents: int = 0 + chem_cents: int = 0 + jobs_cents: int = 0 + visits: int = 0 + partial_through: int | None = None # day of month the data runs to, when partial + + @property + def key(self) -> tuple[int, int]: + return (self.year, self.month) + + @property + def total_cents(self) -> int: + return self.service_cents + self.chem_cents + self.jobs_cents + + @property + def partial(self) -> bool: + return self.partial_through is not None + + @property + def short(self) -> str: + return MONTH_NAMES[self.month - 1][:3] + + @property + def axis_label(self) -> str: + if self.partial: + return f"{self.short} (to {ordinal(self.partial_through)})" + return self.short + + @property + def long(self) -> str: + name = MONTH_NAMES[self.month - 1] + if self.partial: + return f"{name} 1–{self.partial_through}, {self.year} (so far)" + return f"{name} {self.year}" + + def part(self, source: str) -> int: + return {"service": self.service_cents, "chemicals": self.chem_cents, + "jobs": self.jobs_cents}[source] + + +def monthly_revenue(session: Session, keys: list[tuple[int, int]], today: date, + data: "analytics.PeriodData | None" = None) -> list[MonthRow]: + """One row per month key (zeros included), split service/chemicals/jobs.""" + if not keys: + return [] + start = date(keys[0][0], keys[0][1], 1) + if data is None: + data = analytics.load_period(session, start, today) + markup = analytics._markup(session) + rows = {k: MonthRow(year=k[0], month=k[1]) for k in keys} + cur = (today.year, today.month) + if cur in rows: + rows[cur].partial_through = today.day + for v in data.done_visits: + r = rows.get((v.date.year, v.date.month)) + if r is None: + continue + r.visits += 1 + r.service_cents += tax.effective_labor_cents(v) + r.chem_cents += sum(qbo.billable_for_vc(vc, markup) for vc in v.chemicals) + for j in data.done_jobs: + d = _local_date(j.completed_at) + r = rows.get((d.year, d.month)) + if r is not None: + r.jobs_cents += tax.effective_labor_cents(j) + return [rows[k] for k in keys] + + +@dataclass +class Delta: + pct: float + current_cents: int + previous_cents: int + current_span: str + previous_span: str + + @property + def up(self) -> bool: + return self.pct >= 0 + + +def _span(rows: list[MonthRow]) -> str: + if not rows: + return "" + a, b = rows[0], rows[-1] + if a.key == b.key: + return f"{a.short} {a.year}" + if a.year == b.year: + return f"{a.short}–{b.short} {b.year}" + return f"{a.short} {a.year}–{b.short} {b.year}" + + +def like_for_like(window: list[MonthRow], before: list[MonthRow]) -> Delta | None: + """Full months of the window against the same count of months before it. + + None when there is nothing fair to compare: no full month in the window + (a one-month range is just the partial current month), or no revenue at + all in the earlier months (a new business, or history not entered). + """ + full = [m for m in window if not m.partial] + if not full: + return None + prev = before[-len(full):] if len(before) >= len(full) else [] + prev_total = sum(m.total_cents for m in prev) + if not prev or prev_total <= 0: + return None + cur_total = sum(m.total_cents for m in full) + return Delta(pct=(cur_total / prev_total - 1) * 100, current_cents=cur_total, + previous_cents=prev_total, current_span=_span(full), + previous_span=_span(prev)) + + +@dataclass +class MixRow: + key: str + label: str + colour: str + cents: int + share: float # 0..1 + + +def income_mix(months: list[MonthRow]) -> list[MixRow]: + total = sum(m.total_cents for m in months) + out = [] + for key, label, colour in SOURCES: + cents = sum(m.part(key) for m in months) + out.append(MixRow(key, label, colour, cents, cents / total if total else 0.0)) + return out + + +@dataclass +class RouteRow: + name: str + tech: "models.User | None" + customers: int = 0 + weekly_cents: int = 0 + + @property + def unassigned(self) -> bool: + return self.tech is None + + +def _service_props(session: Session) -> list["models.Property"]: + return session.scalars( + select(models.Property).join(models.Customer).where( + models.Property.active.is_(True), models.Customer.active.is_(True)) + .options(selectinload(models.Property.customer), + selectinload(models.Property.pools), + selectinload(models.Property.assigned_tech))).all() + + +def recurring_by_route(session: Session) -> list[RouteRow]: + """Recurring service a week on each technician's route, from today's customer list. + + Biweekly and four-weekly properties count at a half and a quarter of their + rate, so every route is in the same per-week unit. Unassigned recurring + properties are their own row, last, so nothing billable goes unseen. + """ + rows: dict[int | None, RouteRow] = {} + seen: dict[int | None, set[int]] = defaultdict(set) + for p in _service_props(session): + factor = WEEKLY_FACTOR.get(p.frequency) + if not factor: + continue + key = p.assigned_tech_id + row = rows.get(key) + if row is None: + row = rows[key] = RouteRow( + name=p.assigned_tech.name if p.assigned_tech else "Unassigned", tech=p.assigned_tech) + row.weekly_cents += round(effective_rate_cents(session, p) * factor) + seen[key].add(p.customer_id) + for key, row in rows.items(): + row.customers = len(seen[key]) + return sorted(rows.values(), key=lambda r: (r.unassigned, -r.weekly_cents, r.name)) + + +@dataclass +class AgingRow: + label: str + cents: int = 0 + count: int = 0 + level: str = "" # "" | "warn" | "neg" + + +def receivables_by_age(session: Session, today: date) -> list[AgingRow]: + """Open balances in the accountant's buckets, from the invoices themselves.""" + order = [label for label, _ in receivables.AGING_BUCKETS] + rows = {label: AgingRow(label=AGING_LABELS.get(label, label)) for label in order} + for inv in receivables.open_invoices(session): + r = rows[receivables.bucket_for(inv.days_overdue(today))] + r.cents += inv.balance_cents + r.count += 1 + out = [rows[label] for label in order] + for i, r in enumerate(out): + r.level = "" if i == 0 else ("warn" if i == 1 else "neg") + return out + + +@dataclass +class RatePoint: + name: str + property_id: int + customer_id: int + rate_cents: int + chem_per_visit_cents: int + visits: int + gallons: int + avg_minutes: int | None + + @property + def share(self) -> float: + return self.chem_per_visit_cents / self.rate_cents if self.rate_cents else 0.0 + + @property + def flag(self) -> bool: + return self.share >= REVIEW_SHARE + + +def rate_points(session: Session, data: "analytics.PeriodData", + start: date, end: date) -> list[RatePoint]: + """Chemical cost per visit as a share of the rate, per active property. + + Chemical COST (what the business spends), not the billed amount: the + question is whether the rate still covers the chemicals. The rate is the + property's current rate (the one a review would change), falling back to + what its visits in the range were billed when no rate resolves. + """ + per: dict[int, list] = defaultdict(list) + for v in data.done_visits: + if start <= v.date <= end: + per[v.property_id].append(v) + if not per: + return [] + props = session.scalars( + select(models.Property).where(models.Property.id.in_(per)) + .options(selectinload(models.Property.customer), + selectinload(models.Property.pools))).all() + multi = defaultdict(int) + for p in props: + multi[p.customer_id] += 1 + out = [] + for p in props: + if not p.active or not p.customer.active: + continue + visits = per[p.id] + n = len(visits) + chem = sum(vc.total_cost_cents for v in visits for vc in v.chemicals) + rate = effective_rate_cents(session, p) or round( + sum(tax.effective_labor_cents(v) for v in visits) / n) + if rate <= 0: + continue + mins = [v.duration_minutes for v in visits if v.duration_minutes is not None] + name = p.customer.name if multi[p.customer_id] == 1 else f"{p.customer.name} · {p.label}" + out.append(RatePoint( + name=name, property_id=p.id, customer_id=p.customer_id, rate_cents=rate, + chem_per_visit_cents=round(chem / n), visits=n, + gallons=largest_pool_gallons(p) or largest_pool_gallons(p, "spa"), + avg_minutes=round(sum(mins) / len(mins)) if mins else None)) + return sorted(out, key=lambda r: (-r.share, r.name)) + + +@dataclass +class Move: + name: str + customer_id: int + kind: str # "gained" | "lost" + on: date + + +@dataclass +class Movement: + gained: list[Move] = field(default_factory=list) + lost: list[Move] = field(default_factory=list) + by_month: dict[tuple[int, int], tuple[int, int]] = field(default_factory=dict) + + +def customer_movement(session: Session, keys: list[tuple[int, int]], today: date) -> Movement: + """Customers gained (by when they were added) and lost, per month of the window. + + A lost customer is one marked inactive, dated by when that happened. + Customers deactivated before that was recorded fall back to their last + completed visit, then to when they were added. + """ + mv = Movement(by_month={k: (0, 0) for k in keys}) + if not keys: + return mv + start = date(keys[0][0], keys[0][1], 1) + customers = session.scalars(select(models.Customer)).all() + last_visit = dict(session.execute( + select(models.Property.customer_id, func.max(models.Visit.date)) + .join(models.Visit, models.Visit.property_id == models.Property.id) + .join(models.Customer, models.Customer.id == models.Property.customer_id) + .where(models.Visit.status == "done", models.Customer.active.is_(False)) + .group_by(models.Property.customer_id)).all()) + + def add(move: Move, slot: int): + k = (move.on.year, move.on.month) + if k in mv.by_month and start <= move.on <= today: + g, lost = mv.by_month[k] + mv.by_month[k] = (g + (slot == 0), lost + (slot == 1)) + (mv.gained if slot == 0 else mv.lost).append(move) + + for c in customers: + added = local_date(c.created_at) if c.created_at else None + if added: + add(Move(c.name, c.id, "gained", added), 0) + if not c.active: + ended = (local_date(c.deactivated_at) if c.deactivated_at else None) \ + or last_visit.get(c.id) or added + if ended: + add(Move(c.name, c.id, "lost", ended), 1) + mv.gained.sort(key=lambda m: (m.on, m.name), reverse=True) + mv.lost.sort(key=lambda m: (m.on, m.name), reverse=True) + return mv + + +def nice_top(value: float, steps: int = 3) -> int: + """A round axis maximum at or above `value`, divisible into `steps` ticks.""" + if value <= 0: + return steps + raw = value / steps + mag = 10 ** (len(str(int(raw))) - 1) if raw >= 1 else 1 + for m in (1, 2, 2.5, 5, 10): + step = m * mag + if step >= raw: + return int(round(step * steps)) + return int(round(10 * mag * steps)) + + +def nice_range(lo: float, hi: float, steps: int = 4) -> tuple[int, int]: + """(start, step) of a round axis covering lo..hi in `steps` equal steps. + + The rate axis starts near the cheapest rate rather than at zero, so a + business whose rates all sit between $60 and $90 gets a readable spread. + """ + lo, hi = max(0, lo), max(0, hi) + if hi <= lo: + lo, hi = max(0, lo - steps), hi + steps + raw = (hi - lo) / steps + mag = 10 ** (len(str(int(raw))) - 1) if raw >= 1 else 1 + for m in (1, 2, 2.5, 5, 10, 20, 25, 50, 100): + step = int(m * mag) + start = int(lo // step * step) + if start + step * steps >= hi: + return start, step + return 0, int(hi // steps + 1) + + +@dataclass +class Overview: + months_n: int + today: date + months: list[MonthRow] + delta: Delta | None + mix: list[MixRow] + routes: list[RouteRow] + aging: list[AgingRow] + rates: list[RatePoint] + movement: Movement + active_customers: int + + @property + def start(self) -> date: + return date(self.months[0].year, self.months[0].month, 1) + + @property + def revenue_cents(self) -> int: + return sum(m.total_cents for m in self.months) + + @property + def visits(self) -> int: + return sum(m.visits for m in self.months) + + @property + def per_visit_cents(self) -> int: + return round(self.revenue_cents / self.visits) if self.visits else 0 + + @property + def full_months(self) -> list[MonthRow]: + return [m for m in self.months if not m.partial] + + @property + def visits_per_full_month(self) -> int | None: + full = self.full_months + return round(sum(m.visits for m in full) / len(full)) if full else None + + @property + def best_full_month(self) -> MonthRow | None: + full = [m for m in self.full_months if m.total_cents > 0] + return max(full, key=lambda m: m.total_cents) if full else None + + @property + def span(self) -> str: + return _span(self.months) + + @property + def flagged(self) -> list[RatePoint]: + return [p for p in self.rates if p.flag] + + @property + def weekly_recurring_cents(self) -> int: + return sum(r.weekly_cents for r in self.routes) + + @property + def ar_total_cents(self) -> int: + return sum(a.cents for a in self.aging) + + @property + def ar_over_30_cents(self) -> int: + return sum(a.cents for a in self.aging[2:]) + + @property + def has_revenue(self) -> bool: + return self.revenue_cents > 0 + + +def build(session: Session, months: int = DEFAULT_RANGE, today: date | None = None) -> Overview: + """Everything the overview shows, for the `months` months ending today.""" + today = today or business_today() + keys = month_keys(today, months) + full_count = len(keys) - 1 + before_keys = [_shift(keys[0], full_count - i) for i in range(full_count)] + load_from = before_keys[0] if before_keys else keys[0] + data = analytics.load_period(session, date(load_from[0], load_from[1], 1), today) + window = monthly_revenue(session, keys, today, data) + before = monthly_revenue(session, before_keys, today, data) if before_keys else [] + start = date(keys[0][0], keys[0][1], 1) + active = len(session.scalars(select(models.Customer.id).where( + models.Customer.active.is_(True))).all()) + return Overview( + months_n=len(keys), today=today, months=window, + delta=like_for_like(window, before), mix=income_mix(window), + routes=recurring_by_route(session), aging=receivables_by_age(session, today), + rates=rate_points(session, data, start, today), + movement=customer_movement(session, keys, today), active_customers=active) diff --git a/app/charts.py b/app/charts.py index 6ff971b..d089a2e 100644 --- a/app/charts.py +++ b/app/charts.py @@ -2,8 +2,8 @@ Self-contained SVG (no client JS, no external libs) so it satisfies the app CSP and renders inside the offline PWA. Marks are colored with the active theme's CSS -custom properties (var(--color-pool) etc.), so one chart reads correctly in every -theme and in light/dark without per-theme code. All axis/value text uses ink/mist +custom properties (var(--color-pool), the validated --c1..--c3 categorical slots, +--band for target bands), so one chart reads correctly in light and dark. All axis/value text uses ink/mist tokens — never the series color (dataviz rule). Any caller-supplied label is passed through html.escape before it reaches the SVG (customer/tech names are user data). @@ -17,8 +17,7 @@ # Distinct hue families (teal / gold / green / rose) so they separate for most # CVD types; every slice is also directly labelled, which is the secondary # encoding the dataviz guidance requires when relying on ≤4 hues. -_CAT = ["var(--color-pool)", "var(--color-brass)", "var(--cr-green, #10b981)", - "var(--color-safety)"] +_CAT = ["var(--c1)", "var(--c2)", "var(--c3)", "var(--m)"] def _esc(s) -> str: @@ -268,10 +267,10 @@ def y_of(v): parts.append( f'') + f'fill="var(--band)" opacity="0.75"/>') ty = y_of(series.target) parts.append(f'') for value in (hi, lo): @@ -305,3 +304,113 @@ def y_of(v): def _fmt_reading(v) -> str: v = float(v) return f"{v:.0f}" if abs(v) >= 100 or v == int(v) else f"{v:.1f}" + + +# --- Analytics overview (v0.7) --------------------------------------------- +# These draw MARKS only. Each SVG stretches to its box (preserveAspectRatio +# "none") with non-scaling strokes, while every word (axis ticks, month names, +# readouts) is HTML laid over it by the template, so text stays crisp and +# legible at phone width instead of shrinking with a viewBox. Dots are +# zero-length round-capped lines, which stay circles under any stretch. Colours +# are the fixed colour-blind-safe --c1..--c3 slots, never the company palette. + +def _grid_lines(width, fractions=(0, 1 / 3, 2 / 3)): + out = [] + for f in fractions: + y = f * 100 + out.append(f'') + out.append(f'') + return out + + +def stacked_columns(columns, top, *, colours=("var(--c1)", "var(--c2)", "var(--c3)")): + """Stacked monthly columns. columns: list of (parts, partial) where parts + are bottom-up values in the same order as `colours`. `top` is the axis max.""" + n = max(1, len(columns)) + width = n * 100 + parts = [f''] + parts += _grid_lines(width) + gap = 0.9 # ~2px surface gap between segments at the default chart height + # Units per bar scale with the column count so a bar reads ~28px wide on a + # typical card whether the range is 3 months or 12 (a stretched SVG cannot + # cap a width in pixels). + bw = min(50.0, 4.4 * n) + for i, (values, partial) in enumerate(columns): + x = i * 100 + (100 - bw) / 2 + y = 100.0 + cls = "an-col cur" if partial else "an-col" + parts.append(f'') + for value, colour in zip(values, colours): + h = (max(0, value or 0) / top * 100) if top else 0 + if h <= 0: + continue + seg = max(0.6, h - gap) + y -= h + parts.append(f'') + parts.append('') + parts.append('') + return "".join(parts) + + +def diverging_columns(pairs, top): + """Gained (up, --c1) and lost (down, --c2) per month around a middle line.""" + n = max(1, len(pairs)) + width = n * 100 + parts = [f'', + f''] + bw = min(44.0, 3.5 * n) + for i, (up, down) in enumerate(pairs): + x = i * 100 + (100 - bw) / 2 + if up and top: + h = up / top * 48 + parts.append(f'') + if down and top: + h = down / top * 48 + parts.append(f'') + parts.append('') + return "".join(parts) + + +def scatter_marks(points, threshold=None): + """Dots at (x%, y%) from the bottom-left; flagged dots use --c2 and are + larger, so the flag never relies on colour alone. threshold: y% of the + review line.""" + parts = [''] + parts += _grid_lines(100) + parts.append('') + if threshold is not None: + y = 100 - threshold + parts.append(f'') + for x, y, flag in points: + cls = "an-dot flag" if flag else "an-dot" + at = f'x1="{x:.2f}" y1="{100 - y:.2f}" x2="{x:.2f}" y2="{100 - y:.2f}"' + # A surface-coloured halo first, so overlapping dots stay countable. + parts.append(f'') + parts.append(f'') + parts.append('') + return "".join(parts) + + +def sparkline(values): + """(line points, area points) in a 100x32 box for the revenue hero.""" + vals = [max(0, v or 0) for v in values] + if not vals: + return "", "" + top = max(vals) or 1 + n = len(vals) + pts = [((50.0 if n == 1 else i / (n - 1) * 100), 30 - v / top * 26) for i, v in enumerate(vals)] + if n == 1: # a lone month still draws as a short level line + pts = [(0.0, pts[0][1]), (100.0, pts[0][1])] + line = " ".join(f"{x:.1f},{y:.1f}" for x, y in pts) + return line, f"0,32 {line} 100,32" diff --git a/app/chem_targets.py b/app/chem_targets.py new file mode 100644 index 0000000..f6f3761 --- /dev/null +++ b/app/chem_targets.py @@ -0,0 +1,83 @@ +"""Water targets and the band around each one: the single source of truth. + +The target is where a reading should be; the band (a half-width, in the +reading's own units) is how far it may drift before anything happens. The dose +engine suggests nothing inside the band, water alerts flag readings outside +it, and the history chart and visit screen draw it. All of them read these +two settings, so changing either moves every one of them together. + +Limits keep a typo from switching dosing off (a band of 50 on pH) or making +it fire on every visit (a band of 0). + +Pure apart from the settings read: no FastAPI. +""" +import math +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Spec: + key: str + label: str + unit: str + target: float # default + band: float # default half-width + decimals: int + lo: float # allowed target range; the band may not reach below lo + hi: float + band_min: float + band_max: float + + +SPECS = ( + Spec("fc", "Free chlorine", "ppm", 4.0, 0.5, 1, 0.0, 10.0, 0.2, 2.0), + Spec("ph", "pH", "", 7.5, 0.3, 1, 6.8, 8.2, 0.1, 0.6), + Spec("ta", "Total alkalinity", "ppm", 90.0, 10.0, 0, 40.0, 160.0, 5.0, 40.0), + Spec("cya", "Cyanuric acid", "ppm", 50.0, 10.0, 0, 0.0, 100.0, 5.0, 30.0), + Spec("salt", "Salt", "ppm", 3200.0, 200.0, 0, 2000.0, 4500.0, 100.0, 600.0), +) +BY_KEY = {s.key: s for s in SPECS} + +DEFAULT_TARGETS = {s.key: s.target for s in SPECS} +DEFAULT_BANDS = {s.key: s.band for s in SPECS} + + +def problem(key: str, target: float, band: float) -> str: + """Why this target/band pair can't be saved, or "" when it can.""" + s = BY_KEY[key] + if not math.isfinite(target): + return "Enter a number for the target." + if not s.lo <= target <= s.hi: + return f"Keep the target between {s.lo:g} and {s.hi:g}." + if not math.isfinite(band): + return "Enter a number for the band." + if not s.band_min <= band <= s.band_max: + return (f"Keep the band between ±{s.band_min:g} and ±{s.band_max:g}; outside that, " + "doses would be suggested too often or not at all.") + if target - band < s.lo: + return f"The band reaches below {s.lo:g}." + return "" + + +def _read(session, prefix: str, defaults: dict) -> dict[str, float]: + from app import models + out = {} + for key, default in defaults.items(): + try: + v = float(models.get_setting(session, f"{prefix}_{key}", str(default))) + except (TypeError, ValueError): + v = default + out[key] = v if math.isfinite(v) else default + return out + + +def current(session) -> tuple[dict[str, float], dict[str, float]]: + """(targets, bands) as saved, each pair falling back to its defaults when + the stored values no longer validate -- a stale or hand-edited setting must + never switch dosing off.""" + targets = _read(session, "target", DEFAULT_TARGETS) + bands = _read(session, "band", DEFAULT_BANDS) + for key in DEFAULT_TARGETS: + if problem(key, targets[key], bands[key]): + targets[key], bands[key] = DEFAULT_TARGETS[key], DEFAULT_BANDS[key] + return targets, bands diff --git a/app/company.py b/app/company.py index 97125cd..fc22205 100644 --- a/app/company.py +++ b/app/company.py @@ -6,10 +6,13 @@ _logo_path) inverted the layering — the invoice engine couldn't be used or tested without dragging in FastAPI router machinery. """ +import io import os from app import config, models +MAX_LOGO_BYTES = 2 * 1024 * 1024 + COMPANY_KEYS = ("business_name", "company_address", "company_phone", "company_email", "company_license") @@ -20,6 +23,25 @@ def logo_path() -> str: return os.path.join(d, "logo.png") +def store_logo(data: bytes, content_type: str | None) -> str | None: + """Validate and save an uploaded logo; the reason it was refused, or None.""" + from PIL import Image + if content_type not in ("image/png", "image/jpeg"): + return "Logo must be a PNG or JPEG" + if len(data) > MAX_LOGO_BYTES: + return "Logo must be under 2 MB" + try: + img = Image.open(io.BytesIO(data)) + if img.format not in ("PNG", "JPEG"): + return "Logo must be a PNG or JPEG" + img = img.convert("RGBA") if img.mode in ("RGBA", "LA", "P") else img.convert("RGB") + except Exception: + return "That file isn't a readable logo image (PNG/JPEG)" + img.thumbnail((600, 600)) + img.save(logo_path(), "PNG") + return None + + def company_info(session) -> dict: info = {k: models.get_setting(session, k, "") for k in COMPANY_KEYS} info["has_logo"] = os.path.isfile(logo_path()) diff --git a/app/config.py b/app/config.py index 136a82e..d60e242 100644 --- a/app/config.py +++ b/app/config.py @@ -3,7 +3,6 @@ APP_VERSION = os.environ.get("APP_VERSION", "dev") # baked at build time via --build-arg APP_VERSION DATA_DIR = os.environ.get("DATA_DIR", "./data") -APP_PASSWORD = os.environ.get("APP_PASSWORD", "changeme") SECRET_KEY = os.environ.get("SECRET_KEY", "dev-secret-change-me") # Known placeholder values that MUST NOT reach a real deployment. SECRET_KEY @@ -13,8 +12,6 @@ # ship, so validate_secrets() catches an operator who never set the env vars. _INSECURE_SECRET_KEYS = {"", "dev-secret-change-me", "generate-with-openssl-rand-hex-32", "CHANGE_ME_run_openssl_rand_hex_32"} -_INSECURE_APP_PASSWORDS = {"", "changeme", "pick-a-long-password", - "CHANGE_ME_owner_login_password"} def validate_secrets() -> None: @@ -24,12 +21,10 @@ def validate_secrets() -> None: problems = [] if SECRET_KEY in _INSECURE_SECRET_KEYS: problems.append("SECRET_KEY is unset or a known placeholder") - if APP_PASSWORD in _INSECURE_APP_PASSWORDS: - problems.append("APP_PASSWORD is unset or a known placeholder") if problems: raise RuntimeError( "Refusing to start with insecure configuration: " + "; ".join(problems) - + ". Set SECRET_KEY (openssl rand -hex 32) and APP_PASSWORD in the environment.") + + ". Set SECRET_KEY (openssl rand -hex 32) in the environment.") if not COOKIE_SECURE: # Warn, don't refuse: a plain-HTTP LAN box is a legitimate (if # discouraged) self-hosted setup. But the operator must have CHOSEN it @@ -92,3 +87,15 @@ def validate_secrets() -> None: def tz(): return ZoneInfo(TIMEZONE) + + +def set_timezone(name: str) -> bool: + """Switch the business time zone (the `timezone` setting, chosen in setup + or Admin). APP_TZ is only the default before one is saved. Unknown names + are ignored so a bad setting can't break every date in the app.""" + global TIMEZONE + from zoneinfo import available_timezones + if name and name in available_timezones(): + TIMEZONE = name + return True + return False diff --git a/app/contract_defaults.py b/app/contract_defaults.py index ea24dd8..ce305e3 100644 --- a/app/contract_defaults.py +++ b/app/contract_defaults.py @@ -85,3 +85,26 @@ def get_template(session) -> dict: except (ValueError, TypeError): pass return DEFAULT_TEMPLATE + + +# A sent contract with no signature after this many days lands in the +# Contracts hub's needs-attention digest. Admin-editable on the Contract tab. +STALE_DAYS_KEY = "contract_stale_days" +STALE_SENT_DAYS = 14 +STALE_DAYS_MIN, STALE_DAYS_MAX = 1, 90 + + +def parse_stale_days(raw) -> int | None: + """A whole number of days in range, or None when it isn't one.""" + try: + days = int(str(raw).strip()) + except (TypeError, ValueError): + return None + return days if STALE_DAYS_MIN <= days <= STALE_DAYS_MAX else None + + +def get_stale_days(session) -> int: + """The stored threshold; a missing or out-of-range value falls back to the + default rather than silently flagging every contract (0) or none.""" + days = parse_stale_days(models.get_setting(session, STALE_DAYS_KEY, "")) + return STALE_SENT_DAYS if days is None else days diff --git a/app/dosing.py b/app/dosing.py index 17275ec..cf6eda3 100644 --- a/app/dosing.py +++ b/app/dosing.py @@ -1,18 +1,17 @@ """Target-based dose recommendations. Pure and deterministic. -Deadbands (fixed): FC doses only below target-0.5 ppm; pH only outside -7.2-7.8; TA below target-10; CYA below target-10 (raise only, >100 warns); -salt below target-200 on salt pools. Doses rounding to zero are dropped. +Nothing is dosed inside the band around each target (app/chem_targets.py, +the same band the alerts and charts use): FC only below target-band; pH only +outside target±band; TA and CYA below target-band (CYA raise only, >100 +warns); salt below target-band on salt pools. Doses rounding to zero are +dropped. """ import math from dataclasses import dataclass -DEADBAND_FC = 0.5 -PH_LOW, PH_HIGH = 7.2, 7.8 -DEADBAND_TA = 10.0 -DEADBAND_CYA = 10.0 +from app.chem_targets import DEFAULT_BANDS + CYA_HIGH = 100.0 -DEADBAND_SALT = 200.0 LIQUID_LB_PER_GAL = 10.0 ACID_CAP_FLOZ_PER_10K = 32.0 @@ -60,7 +59,8 @@ def _emit(out, chem, computed_amount, computed_unit, note=""): out.append(Dose(chem.id, chem.name, amount, chem.unit, note=note)) -def recommend(readings, gallons, water_type, chemicals, targets): +def recommend(readings, gallons, water_type, chemicals, targets, bands=None): + band = {**DEFAULT_BANDS, **(bands or {})} out: list[Dose] = [] if not gallons or gallons <= 0: return out @@ -75,7 +75,7 @@ def r(key): fc, ph, ta, cya, salt = r("fc"), r("ph"), r("ta"), r("cya"), r("salt") - if fc is not None and fc < targets["fc"] - DEADBAND_FC: + if fc is not None and fc < targets["fc"] - band["fc"]: deficit = targets["fc"] - fc pure_lbs = deficit * gallons * 8.34 / 1_000_000 chem = _first(chemicals, "chlorine_liquid") @@ -90,7 +90,7 @@ def r(key): out.append(Dose(None, "Chlorine", 0, "", applyable=False, note="no chlorine chemical in catalog")) - if ph is not None and ph > PH_HIGH: + if ph is not None and ph > targets["ph"] + band["ph"]: chem = _first(chemicals, "ph_down") if chem is not None: ta_factor = (ta / 100.0) if ta is not None else 1.0 @@ -105,7 +105,7 @@ def r(key): else: out.append(Dose(None, "pH down", 0, "", applyable=False, note="no ph_down chemical in catalog")) - elif ph is not None and ph < PH_LOW: + elif ph is not None and ph < targets["ph"] - band["ph"]: chem = _first(chemicals, "ph_up") if chem is not None: oz = ((targets["ph"] - ph) / 0.2) * 6.0 * g10k * (100.0 / chem.strength_pct) @@ -114,7 +114,7 @@ def r(key): out.append(Dose(None, "pH up", 0, "", applyable=False, note="no ph_up chemical in catalog")) - if ta is not None and ta < targets["ta"] - DEADBAND_TA: + if ta is not None and ta < targets["ta"] - band["ta"]: chem = _first(chemicals, "alkalinity_up") if chem is not None: lbs = ((targets["ta"] - ta) / 10.0) * 1.5 * g10k @@ -127,7 +127,7 @@ def r(key): if cya > CYA_HIGH: out.append(Dose(None, "Stabilizer", 0, "", applyable=False, note="CYA high — partial drain/dilution recommended")) - elif cya < targets["cya"] - DEADBAND_CYA: + elif cya < targets["cya"] - band["cya"]: chem = _first(chemicals, "stabilizer") if chem is not None: lbs = (targets["cya"] - cya) * g10k / 12.0 @@ -136,7 +136,7 @@ def r(key): out.append(Dose(None, "Stabilizer", 0, "", applyable=False, note="no stabilizer chemical in catalog")) - if water_type == "salt" and salt is not None and salt < targets["salt"] - DEADBAND_SALT: + if water_type == "salt" and salt is not None and salt < targets["salt"] - band["salt"]: chem = _first(chemicals, "salt") if chem is not None: lbs = (targets["salt"] - salt) * gallons * 8.34 / 1_000_000 diff --git a/app/email_brand.py b/app/email_brand.py new file mode 100644 index 0000000..73dbeff --- /dev/null +++ b/app/email_brand.py @@ -0,0 +1,438 @@ +"""Branded emails: one shared HTML template for every message the app sends. + +Each message is built once as a `Mail` -- the exact plain-text body plus the +structured pieces (heading, paragraphs, detail rows, button, attachment name) +the HTML part is drawn from. The plain-text part is always sent; the HTML +part is an `add_alternative` built from templates/emails/branded.html: +table-based, inline CSS only, no remote images. The logo, when shown, travels +as a CID-related part (`cid:opp-logo`) attached at send time. + +What customers see is set under Settings > System > "What customers see": + email_brand "1" use the company palette, "0" standard Lagoon teal + email_logo "1" show the company logo, "0" leave it out + email_format "html" branded HTML + plain-text copy, "plain" text only + email_signoff closing text; "" means the company name + +Escaping: every user or customer string reaches the template as plain text +and Jinja autoescapes it. The only CSS values that come from settings are +hex colours derived from a base that passed palettes.clean_hex, and they are +re-checked here before use. Links are http(s) only. + +No FastAPI imports: mailer, followups and the routers all use this module. +""" +import base64 +import io +import os +import re +from dataclasses import dataclass, field +from datetime import date +from functools import lru_cache + +import jinja2 + +from app import models, palettes + +FORMATS = ("html", "plain") +SIGNOFF_MAX = 300 +SIGNOFF_MAX_LINES = 6 +LOGO_CID = "opp-logo" +DEFAULTS = {"email_brand": "1", "email_logo": "1", "email_format": "html", "email_signoff": ""} + +_URL = re.compile(r"https?://[^\s<>\"'`]+") +_LOGO_BLOCK = re.compile(r".*?", re.S) +_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") + +# Standard OpenPoolPro teal (the Lagoon light tokens in css/v2.css), used when +# the company palette is off or is Lagoon itself. +LAGOON = {"accent": "#1B6C80", "tint": "#E3F1F3", "tint_ink": "#0F4C5C", + "mast_a": "#0E2A3B", "mast_c": "#17677D", "ink": "#0E2A3B"} +NEUTRAL = {"page": "#F1EEE7", "sheet": "#FFFFFF", "muted": "#52626B", "rule": "#EEEAE2"} + +_env = jinja2.Environment( + loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), "templates")), + autoescape=True, trim_blocks=True, lstrip_blocks=True) + + +@dataclass +class Mail: + """One outgoing message. `text` is the plain-text part, sent verbatim.""" + subject: str + text: str + heading: str + paragraphs: list[str] = field(default_factory=list) + # (title, [(label, value)]); a row with an empty value is a list item. + sections: list[tuple[str, list[tuple[str, str]]]] = field(default_factory=list) + cta: tuple[str, str] | None = None # (label, http(s) url) + attachment: str = "" + closing: str = "" + # Resolved blocks from app.email_templates; None = draw the HTML from the + # fields above (the e-sign and test emails). + blocks: list | None = None + + +# --- Settings ------------------------------------------------------------- + +def clean_signoff(raw) -> str | None: + """Normalised sign-off text, or None when it is too long to accept.""" + text = _CONTROL.sub("", str(raw or "").replace("\r\n", "\n").replace("\r", "\n")) + lines = [ln.rstrip() for ln in text.strip().split("\n")] + text = "\n".join(lines).strip() + if len(text) > SIGNOFF_MAX or len(lines) > SIGNOFF_MAX_LINES: + return None + return text + + +def look(session) -> dict: + """The validated "What customers see" settings.""" + g = models.get_setting + fmt = g(session, "email_format", DEFAULTS["email_format"]) + return { + "brand": g(session, "email_brand", DEFAULTS["email_brand"]) != "0", + "logo": g(session, "email_logo", DEFAULTS["email_logo"]) != "0", + "format": fmt if fmt in FORMATS else DEFAULTS["email_format"], + "signoff": clean_signoff(g(session, "email_signoff", "")) or "", + } + + +def colours(session, brand: bool, style: dict | None = None) -> dict: + """Inline-CSS colours for the template. A custom accent from the email + style wins; else the company palette; off, or Lagoon: standard teal.""" + from app import email_templates + + st = style or email_templates.style(session) + base = st["accent"] or None + if base is None and brand: + pal = models.get_setting(session, "palette", palettes.DEFAULT) + base = palettes.base_for(pal, models.get_setting(session, "palette_custom", "")) + if not base: + picked = dict(LAGOON) + else: + t = palettes.derive(base, "light") + picked = {"accent": t["--a"], "tint": t["--as"], "tint_ink": t["--ai"], + "mast_a": t["--mast-a"], "mast_c": t["--mast-c"], "ink": t["--t"]} + # Belt and braces: nothing but a clean hex ever reaches a style attribute. + out = {**NEUTRAL, **{k: palettes.clean_hex(v) or LAGOON[k] for k, v in picked.items()}} + out["button"] = email_templates.button_colour(out["accent"]) + return out + + +def button_radius(session, style: dict | None = None) -> str: + """The email style's button corner (a fixed CSS length, never user text).""" + from app import email_templates + + st = style or email_templates.style(session) + return email_templates.BUTTON_SHAPES.get(st.get("button"), "8px") + + +def company(session) -> dict: + return {"name": models.get_setting(session, "business_name", "") or "OpenPoolPro", + "phone": models.get_setting(session, "company_phone", "") or ""} + + +def closing(session, company_name: str, signoff: str | None = None) -> str: + """The closing line app-written emails end with: the sign-off, else the + company name (what every message ended with before sign-offs existed).""" + if signoff is None: + signoff = look(session)["signoff"] + return signoff or company_name + + +# --- Logo ----------------------------------------------------------------- + +@lru_cache(maxsize=4) +def _logo_cached(path: str, mtime: float): + from PIL import Image + + img = Image.open(path) + img = img.convert("RGBA") if img.mode in ("RGBA", "LA", "P", "PA") else img.convert("RGB") + img.thumbnail((320, 64)) # 2x the displayed size, so it stays crisp + buf = io.BytesIO() + img.save(buf, "PNG", optimize=True) + w, h = img.size + disp_h = min(32, max(1, h // 2)) + disp_w = max(1, round(w * disp_h / h)) + return buf.getvalue(), disp_w, disp_h + + +def logo(): + """(png_bytes, display_width, display_height) for the email logo, or None. + Best-effort: a missing or unreadable logo simply leaves it out.""" + from app import company as company_mod + + try: + path = company_mod.logo_path() + if not os.path.isfile(path): + return None + return _logo_cached(path, os.path.getmtime(path)) + except Exception: + return None + + +def embed_logo(html: str) -> tuple[str, bytes | None]: + """At send time: the logo bytes for `cid:opp-logo`, or the HTML with the + logo block removed when the logo has gone since the message was queued.""" + if f"cid:{LOGO_CID}" not in html: + return html, None + found = logo() + if found is None: + return _LOGO_BLOCK.sub("", html), None + return html, found[0] + + +_IMG_REF = re.compile(r"cid:opp-img-([0-9a-f]{16})") + + +def embed_images(html: str) -> tuple[str, list[tuple[str, bytes, str]]]: + """At send time: [(cid, bytes, subtype)] for each uploaded image the HTML + references, with the block of any image deleted since queueing removed.""" + from app import email_templates + + found = [] + for image_id in dict.fromkeys(_IMG_REF.findall(html)): + info = email_templates.image_info(image_id) + if info is None: + html = re.sub(rf".*?", "", html, flags=re.S) + else: + found.append((f"{email_templates.IMAGE_CID}{image_id}", info["data"], info["subtype"])) + return html, found + + +# --- Rendering ------------------------------------------------------------ + +def _segments(line: str) -> list[tuple[str, str | None]]: + """Split a line into (text, href) runs; only http(s) URLs become links.""" + out, pos = [], 0 + for m in _URL.finditer(line): + url = m.group(0).rstrip(".,;:!?)") + end = m.start() + len(url) + if m.start() > pos: + out.append((line[pos:m.start()], None)) + out.append((url, url)) + pos = end + if pos < len(line): + out.append((line[pos:], None)) + return out + + +def _block(text: str) -> list[list[tuple[str, str | None]]]: + return [_segments(ln.strip()) for ln in text.strip().split("\n") if ln.strip()] + + +def split_paragraphs(text: str) -> list[str]: + return [p.strip() for p in re.split(r"\n\s*\n", text or "") if p.strip()] + + +def _legacy_blocks(mail: Mail) -> list: + """The blocks a field-built Mail draws: heading, paragraphs, detail + tables, attachment, button, closing (the order they always had).""" + out = [{"type": "heading", "text": mail.heading, "align": "left"}] + out += [{"type": "text", "text": p, "align": "left"} for p in mail.paragraphs] + if mail.sections: + out.append({"type": "details", "sections": mail.sections}) + if mail.attachment: + out.append({"type": "attachment", "name": mail.attachment}) + if mail.cta and _URL.fullmatch(mail.cta[1] or ""): + out.append({"type": "button", "label": mail.cta[0], "url": mail.cta[1], "align": "left"}) + lines = [ln for ln in mail.closing.split("\n") if ln.strip()] + if lines: + out.append({"type": "signoff", "lines": lines}) + return out + + +def _image_src(image_id: str, inline: bool) -> str | None: + from app import email_templates + + if not inline: + return f"cid:{email_templates.IMAGE_CID}{image_id}" + info = email_templates.image_info(image_id) + if info is None: + return None + return f"data:image/{info['subtype']};base64,{base64.b64encode(info['data']).decode()}" + + +def render(mail: Mail, *, colours: dict, company: dict, logo_src: str | None = None, + logo_size: tuple[int, int] = (32, 32), meta: dict | None = None, + inline_images: bool = False, button_radius: str = "8px") -> str: + """The HTML part. Images are `cid:` references (attached by the mailer) + or, for the settings preview, data URIs. Never a remote URL.""" + blocks = [] + for b in (mail.blocks if mail.blocks is not None else _legacy_blocks(mail)): + b = dict(b) + if b["type"] == "text": + b["paras"] = [_block(p) for p in split_paragraphs(b["text"])] + elif b["type"] == "button" and not _URL.fullmatch(b.get("url") or ""): + continue + elif b["type"] == "image": + b["src"] = _image_src(b["image"], inline_images) + if not b["src"]: + continue + blocks.append(b) + colours = {"button": colours.get("accent"), **colours} + return _env.get_template("emails/branded.html").render( + mail=mail, c=colours, company=company, meta=meta, blocks=blocks, btn_r=button_radius, + logo_src=logo_src, logo_w=logo_size[0], logo_h=logo_size[1]) + + +def html_for(session, mail: Mail) -> str: + """The HTML part to send with `mail`, or "" when the company sends plain + text only. The logo is referenced by CID and attached by the mailer.""" + lk = look(session) + if lk["format"] != "html": + return "" + found = logo() if lk["logo"] else None + return render(mail, colours=colours(session, lk["brand"]), company=company(session), + logo_src=f"cid:{LOGO_CID}" if found else None, + logo_size=found[1:] if found else (32, 32), + button_radius=button_radius(session)) + + +def preview(session, kind: str, lk: dict, doc: dict | None = None, part: str = "", + style: dict | None = None) -> str: + """A full HTML page showing one sample email as a customer would see it, + for the settings card's and the email builder's sandboxed iframes. + Synthetic data only. `doc` and `style` preview unsaved edits; `part` + "text" or "html" shows that part whatever the format setting.""" + mail = sample(session, kind, lk["signoff"], doc) + co = company(session) + meta = {"from": co["name"], "to": SAMPLE_TO[kind], "subject": mail.subject} + if part == "text" or (lk["format"] != "html" and part != "html"): + return _env.get_template("emails/plain_preview.html").render(mail=mail, meta=meta) + found = logo() if lk["logo"] else None + src = f"data:image/png;base64,{base64.b64encode(found[0]).decode()}" if found else None + return render(mail, colours=colours(session, lk["brand"], style), company=co, logo_src=src, + logo_size=found[1:] if found else (32, 32), meta=meta, inline_images=True, + button_radius=button_radius(session, style)) + + +# --- The messages --------------------------------------------------------- + +def _money(cents: int) -> str: + return f"${cents / 100:,.2f}" + + +def _from_template(key: str, doc: dict | None, values: dict, *, closing: str, + attachment: str = "", readings: dict | None = None) -> Mail: + """One editable email (app.email_templates): both parts from one block + list. `doc` None is the built-in default, which reproduces the original + hard-coded wording exactly.""" + from app import email_templates + + document = doc if doc is not None else email_templates.default_doc(key) + out = email_templates.render(key, document, values, closing=closing, + attachment=attachment, readings=readings) + heading = next((b["text"] for b in out.blocks if b["type"] == "heading"), "") + return Mail(subject=out.subject, text=out.text, heading=heading, blocks=out.blocks, + attachment=attachment, closing=closing) + + +def visit_mail(*, business: str, property_label: str, day: date, tech_name: str, + readings: list[tuple[str, str, str]], chemicals: list[tuple[str, str]], + tasks: list[str], notes: str, signoff: str = "", customer_name: str = "", + doc: dict | None = None) -> Mail: + """Visit completed. readings are (label, "7.5 ppm", "target 7.5" or "").""" + values = {"company_name": business, "customer_name": customer_name, + "property_label": property_label, "visit_date": day.strftime("%B %-d, %Y"), + "technician": tech_name, "notes": notes or "", "signoff": signoff} + return _from_template("visit", doc, values, closing=signoff or business, + readings={"readings": readings, "chemicals": chemicals, "tasks": tasks}) + + +def invoice_mail(*, company_name: str, customer_name: str, number: str, period: str, + total_cents: int, due: date | None, signoff: str = "", + doc: dict | None = None) -> Mail: + values = {"company_name": company_name, "customer_name": customer_name, + "invoice_number": number, "period": period, "total": _money(total_cents), + "due_date": due.strftime("%B %-d, %Y") if due else "", + "due_date_iso": due.isoformat() if due else "", "signoff": signoff} + return _from_template("invoice", doc, values, closing=signoff or company_name, + attachment=f"{number}.pdf") + + +def reminder_mail(*, company_name: str, customer_name: str, number: str, + balance_cents: int, days_overdue: int, signoff: str = "", + doc: dict | None = None) -> Mail: + values = {"company_name": company_name, "customer_name": customer_name, + "invoice_number": number, "balance": _money(balance_cents), + "days_overdue": str(days_overdue) if days_overdue else "", + "days_overdue_text": (f"{days_overdue} day{'s' if days_overdue != 1 else ''}" + if days_overdue else ""), + "signoff": signoff} + return _from_template("reminder", doc, values, closing=signoff or company_name) + + +def followup_mail(*, company_name: str, customer_name: str, number: str, + balance_cents: int, due: date | None, signoff: str = "", + doc: dict | None = None) -> Mail: + values = {"company_name": company_name, "customer_name": customer_name, + "invoice_number": number, "balance": _money(balance_cents), + "due_date": due.strftime("%B %-d, %Y") if due else "on receipt", + "signoff": signoff} + return _from_template("followup", doc, values, closing=signoff or company_name) + + +def sign_request_mail(*, subject: str, body: str, sign_url: str) -> Mail: + """The admin-edited signing request (sign_messages); its text carries its + own closing, so no sign-off is added to either part.""" + return Mail(subject=subject, text=body, heading="Your agreement is ready to sign", + paragraphs=split_paragraphs(body), cta=("Review and sign", sign_url), + attachment="contract.pdf") + + +def signed_copy_mail(*, subject: str, body: str) -> Mail: + return Mail(subject=subject, text=body, heading="Your signed agreement", + paragraphs=split_paragraphs(body), attachment="signed-contract.pdf") + + +def smtp_test_mail(*, company_name: str, signoff: str = "") -> Mail: + close = signoff or company_name + line = "This is a test email from OpenPoolPro." + return Mail(subject="OpenPoolPro test email", + text=line + (f"\n\n{signoff}" if signoff else ""), heading="Test email", + paragraphs=[line, "If this arrived, your outgoing mail settings work."], + closing=close) + + +# --- Previews (synthetic data only) ---------------------------------------- + +PREVIEW_KINDS = (("visit", "Visit done"), ("invoice", "Invoice"), + ("reminder", "Reminder"), ("sign", "Signing")) +SAMPLE_TO = {"visit": "helen.whitfield@example.com", "invoice": "helen.whitfield@example.com", + "reminder": "manager@coralshores.example.com", + "followup": "manager@coralshores.example.com", "sign": "board@laurelpines.example.com"} + + +def sample(session, kind: str, signoff: str, doc: dict | None = None) -> Mail: + """Synthetic sample of one message. Without `doc` the saved template is + used, so the previews show what customers would actually get.""" + from app import email_templates + + name = company(session)["name"] + if doc is None and kind in email_templates.TEMPLATES: + doc = email_templates.doc(session, kind) + if kind == "invoice": + return invoice_mail(company_name=name, customer_name="Helen Whitfield", number="1080", + period="September 2026", total_cents=56000, + due=date(2026, 10, 31), signoff=signoff, doc=doc) + if kind == "reminder": + return reminder_mail(company_name=name, customer_name="Coral Shores HOA", number="1049", + balance_cents=61200, days_overdue=12, signoff=signoff, doc=doc) + if kind == "followup": + return followup_mail(company_name=name, customer_name="Coral Shores HOA", number="1049", + balance_cents=61200, due=date(2026, 9, 12), signoff=signoff, doc=doc) + if kind == "sign": + from app import sign_messages + + ctx = {"customer_name": "Laurel Pines Board", "company_name": name, "season_year": 2027, + "property_address": "12 Laurel Pines Way", "expiry_label": "7 days", + "sign_url": "https://pools.example.com/sign/sample-link", + "signer_name": "", "signed_date": ""} + return sign_request_mail( + subject=sign_messages.resolved(session, "sign_email_subject", ctx), + body=sign_messages.resolved(session, "sign_email_body", ctx), sign_url=ctx["sign_url"]) + return visit_mail(business=name, property_label="5 Port Royal Ln", day=date(2026, 10, 23), + tech_name="Jordan Reyes", + readings=[("Free chlorine", "3.8 ppm", "target 3"), ("pH", "7.5", "target 7.5"), + ("Alkalinity", "90 ppm", "target 100")], + chemicals=[("Liquid chlorine", "1.5 gal")], + tasks=["Skimmed surface", "Brushed walls", "Emptied baskets"], + notes="", signoff=signoff, customer_name="Helen Whitfield", doc=doc) diff --git a/app/email_templates.py b/app/email_templates.py new file mode 100644 index 0000000..d0e6feb --- /dev/null +++ b/app/email_templates.py @@ -0,0 +1,565 @@ +"""Editable customer emails: an ordered block list per template, one shared +email style, and the uploaded images those blocks show. + +A template document is `{"subject": str, "blocks": [block, ...]}`, stored as +JSON in the setting `email_tpl_` (absent = the built-in default). The +same blocks produce both parts of the message: `render()` returns the exact +plain-text body and the resolved blocks the HTML template (emails/branded.html) +draws. Each block says which part it appears in (`show`: both, html, text), so +the defaults reproduce the hard-coded emails byte for byte. + +Text rules, shared by every text field of every block: + {field} replaced by the value of a field on this template's + allow-list. Anything else in braces is left exactly as typed + (and flagged by the editor). + [ ... {field} ] text in square brackets that mentions a field is left out + when that field is empty, otherwise the brackets go and the + text stays. Brackets without a field stay as typed. +Values are inserted once and never re-scanned, so a customer's name holding +"{x}" or "[y]" prints as is. Everything is plain text: the HTML template +autoescapes it, and links are made only from http(s) URLs. + +The email style (`email_style`) holds an accent ("" follows the company +palette, else a validated hex) and a button shape. Images are PNG or JPEG +uploads, re-encoded and stored under DATA_DIR/branding/email (so backups +carry them), referenced by id and embedded as CID parts at send time; never a +remote URL. + +No FastAPI imports: the email builders, mailer and routers all use this. +""" +import hashlib +import io +import json +import os +import re +from dataclasses import dataclass, field + +from app import config, models, palettes + +SUBJECT_MAX = 200 +TEXT_MAX = 2000 +LABEL_MAX = 120 +ALT_MAX = 200 +MAX_BLOCKS = 40 +MAX_ROWS = 12 +DOC_MAX_BYTES = 64 * 1024 +IMAGE_MAX_BYTES = 2 * 1024 * 1024 +IMAGE_MAX_W = 1200 +IMAGE_DISPLAY_W = 544 # the 600px sheet less its padding +IMAGE_CID = "opp-img-" + +SHOWS = (("both", "Both parts"), ("html", "Branded only"), ("text", "Plain-text copy only")) +ALIGNS = (("left", "Left"), ("center", "Centre"), ("right", "Right")) +BUTTON_SHAPES = {"rounded": "8px", "pill": "999px", "square": "2px"} +STYLE_DEFAULT = {"accent": "", "button": "rounded"} +BUTTON_TEXT = "#FFFFFF" +MIN_BUTTON_CONTRAST = 4.5 + +# type -> (label, what it is). Order is the add-a-block palette's order. +TYPES = { + "heading": ("Heading", "A title line"), + "text": ("Text", "A paragraph with fields"), + "details": ("Details", "Label and value rows"), + "readings": ("Visit readings", "Water test, chemicals and tasks, filled in from the visit"), + "button": ("Button", "Opens a page the app links to"), + "attachment": ("Attachment note", "Names the attached PDF"), + "image": ("Image", "A picture you upload, such as a banner"), + "divider": ("Divider", "A thin line"), + "signoff": ("Sign-off", "Your shared sign-off, else the company name"), +} +COMMON_TYPES = ("heading", "text", "details", "image", "divider", "signoff") +TEXT_TYPES = ("heading", "text", "button") + +_TOKEN = re.compile(r"\{([a-z_]+)\}") +_GROUP_OR_TOKEN = re.compile(r"\[([^\[\]]*)\]|\{([a-z_]+)\}") +_ANY_BRACED = re.compile(r"\{([^{}\s]{1,40})\}") +_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") +_IMAGE_ID = re.compile(r"[0-9a-f]{16}") +_URL = re.compile(r"https?://[^\s<>\"'`]+") + + +@dataclass(frozen=True) +class Template: + key: str + name: str + when: str + fields: dict # field -> label; the allow-list for {tokens} and detail rows + default: dict + links: dict = field(default_factory=dict) # url field -> label (button targets) + extra_types: tuple = () + attachment: bool = False + + @property + def types(self) -> tuple: + extra = set(self.extra_types) + if self.links: + extra.add("button") + if self.attachment: + extra.add("attachment") + return tuple(t for t in TYPES if t in COMMON_TYPES or t in extra) + + +def _b(type_, show="both", **kw): + return {"type": type_, "show": show, **kw} + + +def _txt(text, show="both"): + return _b("text", show, text=text, align="left") + + +def _hd(text): + return _b("heading", "html", text=text, align="left") + + +_SIGNOFF = {"signoff": "Your sign-off (blank when none is set)"} + +TEMPLATES = {t.key: t for t in ( + Template( + "visit", "Visit completed", "Sent by itself the first time a visit is marked done.", + {"company_name": "Company name", "customer_name": "Customer name", + "property_label": "Property", "visit_date": "Visit date", "technician": "Technician", + "notes": "Technician's notes", **_SIGNOFF}, + {"subject": "{company_name} — service visit completed", "blocks": [ + _txt("{company_name}\n{property_label} — {visit_date}", "text"), + _hd("Your service visit is complete"), + _txt("{technician} finished your service visit at {property_label} on {visit_date}.", + "html"), + _txt("[Notes from your technician: {notes}]", "html"), + _b("readings"), + _txt("[Notes:\n {notes}]", "text"), + _txt("Serviced by: {technician}", "text"), + _txt("[{signoff}]", "text"), + _b("signoff", "html"), + ]}, + extra_types=("readings",)), + Template( + "invoice", "Invoice", "When you email an invoice. The PDF is attached.", + {"company_name": "Company name", "customer_name": "Customer name", + "invoice_number": "Invoice number", "period": "Billing period", "total": "Invoice total", + "due_date": "Due date (blank when none)", "due_date_iso": "Due date as 2026-10-31", + **_SIGNOFF}, + {"subject": "Invoice {invoice_number} — {period}", "blocks": [ + _hd("Your {period} invoice"), + _txt("Hello {customer_name},"), + _txt("Attached is invoice {invoice_number} for {period}, totalling {total}" + "[, due {due_date_iso}]."), + _txt("Thank you for your business."), + _b("details", "html", title="", rows=[["Invoice", "invoice_number"], + ["Period", "period"], ["Amount", "total"], + ["Due", "due_date"]]), + _b("attachment", "html"), + _b("signoff"), + ]}, + attachment=True), + Template( + "reminder", "Payment reminder", "When someone presses Send reminder on an unpaid invoice.", + {"company_name": "Company name", "customer_name": "Customer name", + "invoice_number": "Invoice number", "balance": "Balance owed", + "days_overdue": "Days past due (blank when not yet due)", + "days_overdue_text": "Days past due in words, e.g. 12 days", **_SIGNOFF}, + {"subject": "Reminder: invoice {invoice_number}", "blocks": [ + _hd("A reminder about invoice {invoice_number}"), + _txt("Hello {customer_name},"), + _txt("Invoice {invoice_number} has an outstanding balance of {balance}. " + "[It is now {days_overdue_text} past due.]"), + _txt("If you have already sent payment, thank you — please disregard this note."), + _b("details", "html", title="", rows=[["Invoice", "invoice_number"], + ["Balance", "balance"], + ["Days past due", "days_overdue"]]), + _b("signoff"), + ]}), + Template( + "followup", "Follow-up reminder", + "Prepared at each follow-up stage and held in Payment follow-ups until approved.", + {"company_name": "Company name", "customer_name": "Customer name", + "invoice_number": "Invoice number", "balance": "Balance owed", + "due_date": "Due date (or “on receipt”)", **_SIGNOFF}, + {"subject": "{company_name} — reminder for invoice {invoice_number}", "blocks": [ + _hd("A reminder about invoice {invoice_number}"), + _txt("Hello {customer_name},"), + _txt("Our records show {balance} outstanding on invoice {invoice_number}, " + "due {due_date}."), + _txt("If you have already paid, thank you — please reply with the payment details " + "so we can update our records. For payment arrangements or questions, please " + "reply to this email."), + _b("details", "html", title="", rows=[["Invoice", "invoice_number"], + ["Balance", "balance"], + ["Was due", "due_date"]]), + _b("signoff"), + ]}), +)} + + +def setting_key(key: str) -> str: + return f"email_tpl_{key}" + + +def default_doc(key: str) -> dict: + return json.loads(json.dumps(TEMPLATES[key].default)) + + +# --- Text ----------------------------------------------------------------- + +def fill(text: str, values: dict) -> str: + """Apply the {field} and [optional {field}] rules (see module docstring).""" + def one(m): + k = m.group(1) + return values[k] if k in values else m.group(0) + + def sub(m): + if m.group(2) is not None: + k = m.group(2) + return values[k] if k in values else m.group(0) + inner = m.group(1) + known = [k for k in _TOKEN.findall(inner) if k in values] + if not known: + return m.group(0) + if any(values[k] == "" for k in known): + return "" + return _TOKEN.sub(one, inner) + + return _GROUP_OR_TOKEN.sub(sub, text or "") + + +def unknown_tokens(text: str, fields) -> list[str]: + """Braced words that are not fields of this template, as typed.""" + return sorted({m.group(1) for m in _ANY_BRACED.finditer(text or "") + if m.group(1) not in fields}) + + +def _clean_text(raw, limit: int, multiline: bool = True) -> tuple[str, bool]: + text = str(raw if raw is not None else "").replace("\r\n", "\n").replace("\r", "\n") + if not multiline: + text = text.replace("\n", " ") + text = _CONTROL.sub("", text) + return text, len(text) <= limit + + +# --- Validation ----------------------------------------------------------- + +def clean(key: str, raw) -> tuple[dict, list[str]]: + """A normalised template document and the reasons it can't be saved + ([] = valid). Only the allowed block types, fields and choices survive.""" + tpl = TEMPLATES[key] + errors: list[str] = [] + if not isinstance(raw, dict): + return default_doc(key), ["The template could not be read."] + subject, ok = _clean_text(raw.get("subject"), SUBJECT_MAX, multiline=False) + subject = subject.strip() + if not ok: + errors.append(f"The subject is longer than {SUBJECT_MAX} characters.") + if not subject: + errors.append("The subject can't be empty.") + blocks_in = raw.get("blocks") + if not isinstance(blocks_in, list): + blocks_in = [] + errors.append("The template has no block list.") + if len(blocks_in) > MAX_BLOCKS: + errors.append(f"Up to {MAX_BLOCKS} blocks fit in one email.") + blocks_in = blocks_in[:MAX_BLOCKS] + shows, aligns = dict(SHOWS), dict(ALIGNS) + plain_fields = [f for f in tpl.fields] + blocks = [] + for n, b in enumerate(blocks_in, 1): + if not isinstance(b, dict): + errors.append(f"Block {n} could not be read.") + continue + t = b.get("type") + if t not in tpl.types: + errors.append(f"Block {n}: that kind of block isn't available in this email.") + continue + out = {"type": t, "show": b.get("show") if b.get("show") in shows else "both"} + if t in TEXT_TYPES: + text, ok = _clean_text(b.get("text"), TEXT_MAX if t == "text" else LABEL_MAX, + multiline=t == "text") + if not ok: + errors.append(f"Block {n}: the text is too long.") + out["text"] = text + out["align"] = b.get("align") if b.get("align") in aligns else "left" + if t == "button": + if b.get("link") not in tpl.links: + errors.append(f"Block {n}: choose what the button opens.") + out["link"] = b.get("link") if b.get("link") in tpl.links else next(iter(tpl.links), "") + if t == "details": + title, ok = _clean_text(b.get("title"), LABEL_MAX, multiline=False) + if not ok: + errors.append(f"Block {n}: the title is too long.") + rows = b.get("rows") if isinstance(b.get("rows"), list) else [] + if len(rows) > MAX_ROWS: + errors.append(f"Block {n}: up to {MAX_ROWS} rows.") + rows = rows[:MAX_ROWS] + clean_rows = [] + for row in rows: + if not isinstance(row, (list, tuple)) or len(row) != 2: + errors.append(f"Block {n}: a row could not be read.") + continue + label, ok = _clean_text(row[0], LABEL_MAX, multiline=False) + if not ok: + errors.append(f"Block {n}: a row label is too long.") + if row[1] not in plain_fields: + errors.append(f"Block {n}: a row shows a field this email doesn't have.") + continue + clean_rows.append([label, row[1]]) + out["title"], out["rows"] = title, clean_rows + if t == "image": + img = str(b.get("image") or "") + if img and not (_IMAGE_ID.fullmatch(img) and image_file(img)): + errors.append(f"Block {n}: that image is no longer available; upload it again.") + img = "" + alt, ok = _clean_text(b.get("alt"), ALT_MAX, multiline=False) + if not ok: + errors.append(f"Block {n}: the image description is too long.") + out["image"], out["alt"] = img, alt + blocks.append(out) + doc = {"subject": subject, "blocks": blocks} + if len(json.dumps(doc)) > DOC_MAX_BYTES: + errors.append("The template is too large.") + return doc, errors + + +def doc(session, key: str) -> dict: + """The saved template, or the default when unset or unreadable.""" + raw = models.get_setting(session, setting_key(key), "") + if raw: + try: + parsed, errors = clean(key, json.loads(raw)) + except ValueError: + errors = ["unreadable"] + if not errors: + return parsed + return default_doc(key) + + +def is_edited(session, key: str) -> bool: + return bool(models.get_setting(session, setting_key(key), "")) + + +def save(session, key: str, document: dict) -> None: + """Store a cleaned document; the default itself is stored as "unset".""" + if document == TEMPLATES[key].default: + models.set_setting(session, setting_key(key), "") + else: + models.set_setting(session, setting_key(key), json.dumps(document, ensure_ascii=False)) + + +def warnings(key: str, document: dict) -> dict: + """{block index: [unknown tokens]} plus "subject", for the editor.""" + fields = TEMPLATES[key].fields + out = {} + if (u := unknown_tokens(document.get("subject", ""), fields)): + out["subject"] = u + for i, b in enumerate(document.get("blocks", [])): + found = set() + for k in ("text", "title", "alt"): + found.update(unknown_tokens(b.get(k, ""), fields)) + for label, _f in b.get("rows", []): + found.update(unknown_tokens(label, fields)) + if found: + out[i] = sorted(found) + return out + + +# --- Rendering ------------------------------------------------------------ + +def _readings_text(r: dict) -> str: + parts = [] + if r.get("readings"): + parts.append("\n".join(["Water test:"] + [ + f" {label}: {value}" + (f" ({target})" if target else "") + for label, value, target in r["readings"]])) + if r.get("chemicals"): + parts.append("\n".join(["Chemicals added:"] + [f" {n}: {a}" for n, a in r["chemicals"]])) + if r.get("tasks"): + parts.append("\n".join(["Completed:"] + [f" {t}" for t in r["tasks"]])) + return "\n\n".join(parts) + + +def _readings_sections(r: dict) -> list: + sections = [] + if r.get("readings"): + sections.append(("Water test", [(label, value + (f" · {target}" if target else "")) + for label, value, target in r["readings"]])) + if r.get("chemicals"): + sections.append(("Chemicals added", [tuple(c) for c in r["chemicals"]])) + if r.get("tasks"): + sections.append(("Completed", [(t, "") for t in r["tasks"]])) + return sections + + +@dataclass +class Rendered: + subject: str + text: str + blocks: list # resolved blocks for the HTML template + + +def render(key: str, document: dict, values: dict, *, closing: str, attachment: str = "", + readings: dict | None = None, links: dict | None = None) -> Rendered: + """Both parts of one message from one document. `values` must hold every + field of the template (strings, "" when empty); unknown keys are ignored.""" + tpl = TEMPLATES[key] + vals = {k: str(values.get(k, "") or "") for k in tpl.fields} + links = links or {} + texts, html = [], [] + for b in document["blocks"]: + t, show = b["type"], b.get("show", "both") + plain, out = "", None + if t == "heading": + plain = fill(b["text"], vals) + if plain.strip(): + out = {"type": "heading", "text": plain.strip(), "align": b.get("align", "left")} + elif t == "text": + plain = fill(b["text"], vals) + if plain.strip(): + out = {"type": "text", "text": plain, "align": b.get("align", "left")} + elif t == "details": + title = fill(b.get("title", ""), vals).strip() + rows = [(fill(label, vals).strip(), vals.get(f, "")) for label, f in b.get("rows", [])] + rows = [(label, v) for label, v in rows if v] + if rows: + body = [f" {label}: {v}" if title else f"{label}: {v}" for label, v in rows] + plain = "\n".join(([f"{title}:"] if title else []) + body) + out = {"type": "details", "sections": [(title, rows)]} + elif t == "readings": + r = readings or {} + plain = _readings_text(r) + if plain: + out = {"type": "details", "sections": _readings_sections(r)} + elif t == "button": + url = links.get(b.get("link", ""), "") + label = fill(b["text"], vals).strip() + if label and _URL.fullmatch(url or ""): + plain = f"{label}: {url}" + out = {"type": "button", "label": label, "url": url, + "align": b.get("align", "left")} + elif t == "attachment": + if attachment: + plain = f"Attached: {attachment}" + out = {"type": "attachment", "name": attachment} + elif t == "image": + info = image_info(b.get("image", "")) + if info: + plain = f"[{b['alt']}]" if b.get("alt") else "" + out = {"type": "image", "image": b["image"], "alt": b.get("alt", ""), + "w": info["w"], "h": info["h"]} + elif t == "divider": + plain, out = "----", {"type": "divider"} + elif t == "signoff": + plain = closing + lines = [ln for ln in closing.split("\n") if ln.strip()] + if lines: + out = {"type": "signoff", "lines": lines} + if show in ("both", "text") and plain.strip(): + texts.append(plain) + if show in ("both", "html") and out is not None: + html.append(out) + return Rendered(subject=fill(document["subject"], vals), text="\n\n".join(texts), blocks=html) + + +# --- Email style ---------------------------------------------------------- + +def style(session) -> dict: + try: + raw = json.loads(models.get_setting(session, "email_style", "") or "{}") + except ValueError: + raw = {} + out, _ = clean_style(raw if isinstance(raw, dict) else {}) + return out + + +def clean_style(raw: dict) -> tuple[dict, list[str]]: + errors = [] + accent = str(raw.get("accent") or "").strip() + if accent: + hexed = palettes.clean_hex(accent) + if hexed is None: + errors.append("The accent must be a colour like #1B6C80.") + accent = "" + else: + accent = hexed + button = raw.get("button") if raw.get("button") in BUTTON_SHAPES else "rounded" + return {"accent": accent, "button": button}, errors + + +def button_colour(accent: str) -> str: + """The accent, darkened just enough that white button text reads on it.""" + if palettes.ratio(accent, BUTTON_TEXT) >= MIN_BUTTON_CONTRAST: + return accent + return palettes.toward(accent, "#000000", BUTTON_TEXT, MIN_BUTTON_CONTRAST) + + +# --- Images --------------------------------------------------------------- + +def image_dir() -> str: + d = os.path.join(config.DATA_DIR, "branding", "email") + os.makedirs(d, exist_ok=True) + return d + + +def image_file(image_id: str) -> str | None: + if not _IMAGE_ID.fullmatch(image_id or ""): + return None + for ext in ("png", "jpg"): + p = os.path.join(image_dir(), f"{image_id}.{ext}") + if os.path.isfile(p): + return p + return None + + +def store_image(data: bytes, content_type: str | None) -> tuple[str | None, str | None]: + """Validate, re-encode and keep an upload: (image id, None) or (None, reason). + Re-encoding drops anything but the pixels (metadata, trailing payloads).""" + from PIL import Image, ImageOps + + if content_type not in ("image/png", "image/jpeg"): + return None, "Images must be PNG or JPEG." + if not data: + return None, "That file is empty." + if len(data) > IMAGE_MAX_BYTES: + return None, "Images must be under 2 MB." + try: + img = Image.open(io.BytesIO(data)) + fmt = img.format + if fmt not in ("PNG", "JPEG"): + return None, "Images must be PNG or JPEG." + if img.width * img.height > 40_000_000: + return None, "That image is too large." + img = ImageOps.exif_transpose(img) + img.thumbnail((IMAGE_MAX_W, IMAGE_MAX_W * 2)) + buf = io.BytesIO() + if fmt == "PNG": + img = img.convert("RGBA") if img.mode in ("RGBA", "LA", "P", "PA") else img.convert("RGB") + img.save(buf, "PNG", optimize=True) + ext = "png" + else: + img.convert("RGB").save(buf, "JPEG", quality=85, optimize=True) + ext = "jpg" + except Exception: + return None, "That file isn't a readable PNG or JPEG image." + out = buf.getvalue() + image_id = hashlib.sha256(out).hexdigest()[:16] + path = os.path.join(image_dir(), f"{image_id}.{ext}") + if not os.path.isfile(path): + tmp = path + ".tmp" + with open(tmp, "wb") as f: + f.write(out) + os.replace(tmp, path) + return image_id, None + + +def image_info(image_id: str) -> dict | None: + """{"data", "subtype", "w", "h"} with the display size, or None.""" + path = image_file(image_id) + if path is None: + return None + try: + from PIL import Image + + with open(path, "rb") as f: + data = f.read() + w, h = Image.open(io.BytesIO(data)).size + except Exception: + return None + disp_w = min(IMAGE_DISPLAY_W, w) + return {"data": data, "subtype": "png" if path.endswith(".png") else "jpeg", + "w": disp_w, "h": max(1, round(h * disp_w / w))} diff --git a/app/followups.py b/app/followups.py index f313e2f..f3ab14c 100644 --- a/app/followups.py +++ b/app/followups.py @@ -4,7 +4,7 @@ from sqlalchemy import select -from app import mailer, models, receivables +from app import email_brand, email_templates, mailer, models, receivables from app.timefmt import business_today, local_date DEFAULT_STAGES = (7, 14, 30) @@ -19,15 +19,18 @@ def stages(session): return list(DEFAULT_STAGES) -def message(session, invoice): +def mail(session, invoice): + """The follow-up as an email_brand.Mail (plain text plus HTML pieces).""" company = models.get_setting(session, "business_name", "OpenPoolPro") or "OpenPoolPro" - subject = f"{company} — reminder for invoice {invoice.number}" - body = (f"Hello {invoice.customer.name},\n\n" - f"Our records show ${invoice.balance_cents / 100:,.2f} outstanding on invoice {invoice.number}, " - f"due {invoice.due_date}.\n\n" - "If you have already paid, thank you — please reply with the payment details so we can update " - f"our records. For payment arrangements or questions, please reply to this email.\n\n{company}") - return subject, body + return email_brand.followup_mail( + company_name=company, customer_name=invoice.customer.name, number=invoice.number, + balance_cents=invoice.balance_cents, due=invoice.due_date, + signoff=email_brand.look(session)["signoff"], doc=email_templates.doc(session, "followup")) + + +def message(session, invoice): + m = mail(session, invoice) + return m.subject, m.text def snapshot(invoice, stage, subject, body): @@ -67,7 +70,9 @@ def approve(session, row, user_id): return False session.delete(old) session.flush() - outbox = mailer.queue(session, inv.customer.email, row["subject"], row["body"], inv.customer_id) + html = email_brand.html_for(session, mail(session, inv)) + outbox = mailer.queue(session, inv.customer.email, row["subject"], row["body"], inv.customer_id, + html=html) session.add(models.InvoiceFollowup(invoice_id=inv.id, stage=row["stage"], balance_cents=inv.balance_cents, due_date=inv.due_date, outbox_id=outbox.id, approved_by_id=user_id)) return True diff --git a/app/mailer.py b/app/mailer.py index 3b17daf..ff3fffe 100644 --- a/app/mailer.py +++ b/app/mailer.py @@ -85,21 +85,30 @@ def smtp_configured(session=None) -> bool: def queue(session: Session, to_addr: str, subject: str, body: str, - customer_id: int | None = None) -> models.EmailOutbox: - """Add a pending outbox row (flushed so callers see row.id). Caller commits.""" + customer_id: int | None = None, html: str = "") -> models.EmailOutbox: + """Add a pending outbox row (flushed so callers see row.id). Caller commits. + + `html` is the optional branded alternative (app.email_brand); "" sends + plain text only. It is stored with the row, so what was approved or + queued is exactly what is delivered, however late the flush.""" row = models.EmailOutbox(customer_id=customer_id, to_addr=to_addr, - subject=subject, body=body) + subject=subject, body=body, html=html or "") session.add(row) session.flush() return row def send_message(to_addr: str, subject: str, body: str, conf: dict | None = None, - attachments: list[tuple[bytes, str]] | None = None) -> None: + attachments: list[tuple[bytes, str]] | None = None, + html: str | None = None) -> None: """The only function that touches smtplib -- tests monkeypatch this. `conf` is a resolved SMTP config (from smtp_settings); None -> env/config. `attachments` is an optional list of (data, filename) pairs attached as application/pdf parts; None -> no behavior change for existing callers. + `html` adds a text/html alternative; the plain-text `body` is always the + first part. A `cid:opp-logo` image, and any `cid:opp-img-*` uploaded + email image, in it is attached as a related part (or dropped if it has + since been removed). Raises on failure; never logs or surfaces credentials.""" conf = conf or _config_conf() msg = EmailMessage() @@ -107,6 +116,18 @@ def send_message(to_addr: str, subject: str, body: str, conf: dict | None = None msg["To"] = to_addr msg["Subject"] = subject msg.set_content(body) + if html: + from app import email_brand + + html, logo = email_brand.embed_logo(html) + html, images = email_brand.embed_images(html) + msg.add_alternative(html, subtype="html") + if logo: + msg.get_payload()[1].add_related(logo, maintype="image", subtype="png", + cid=f"<{email_brand.LOGO_CID}>") + for cid, data, subtype in images: + msg.get_payload()[1].add_related(data, maintype="image", subtype=subtype, + cid=f"<{cid}>") if attachments: for data, name in attachments: msg.add_attachment(data, maintype="application", subtype="pdf", filename=name) @@ -167,7 +188,10 @@ def _flush_outbox(session: Session, limit: int = 20) -> tuple[int, int]: session.commit() continue try: - send_message(row.to_addr, row.subject, row.body, conf) + if row.html: + send_message(row.to_addr, row.subject, row.body, conf, html=row.html) + else: + send_message(row.to_addr, row.subject, row.body, conf) except Exception as exc: row.attempts += 1 row.last_error = str(exc)[:200] diff --git a/app/main.py b/app/main.py index e68eb5e..4914f3d 100644 --- a/app/main.py +++ b/app/main.py @@ -15,7 +15,7 @@ # app.main, and the require_auth middleware below resolves ALLOWED_THEMES via # this module's namespace (which keeps monkeypatch.setattr(app.main, ...) # working). New code should import from app.templating directly. -from app.templating import ALLOWED_THEMES, DEFAULT_THEME, ThemeAwareLoader, active_theme_var, templates # noqa: F401 +from app.templating import UI_DEFAULTS, templates, ui_settings # noqa: F401 log = logging.getLogger("openpoolpro.app") @@ -34,6 +34,7 @@ contracts, csv_io, customers, + email_builder, improvements, inventory, invoices, @@ -46,6 +47,7 @@ quotes, routes, settings, + setup, sign, testers, today, @@ -62,6 +64,7 @@ analytics.router, inventory.router, invoices.router, routes.router, contracts.router, contract_template.router, sign.router, improvements.router, portal.router, qbo_billing.router, testers.router, + setup.router, email_builder.router, ) @@ -148,6 +151,16 @@ def create_app(engine=None) -> FastAPI: from sqlalchemy.orm import Session as _BootS with _BootS(app.state.engine) as _bs: app.state.require_2fa = models.get_setting(_bs, "require_2fa", "0") == "1" + config.set_timezone(models.get_setting(_bs, "timezone", "") or "") + from app import setup_flow + # No owner yet: everything goes to /setup, which needs this one-time + # code from the log. setup_status "legacy": the upgraded owner finishes + # their profile once. Both are refreshed in place by app/routers/setup.py. + app.state.needs_owner = not setup_flow.owner_exists(_bs) + app.state.setup_legacy = setup_flow.status(_bs) == "legacy" + app.state.setup_code = setup_flow.new_setup_code() if app.state.needs_owner else None + if app.state.setup_code: + setup_flow.announce_setup_code(app.state.setup_code) EXEMPT_EXACT = {"/login", "/login/2fa", "/manifest.json", "/sw.js", "/health", "/branding/logo"} # /sign/ is the customer-facing contract e-sign flow: its routes are gated @@ -201,25 +214,44 @@ async def public_body_cap(request, call_next): @app.middleware("http") async def require_auth(request, call_next): path = request.url.path - exempt = path in EXEMPT_EXACT or any(path.startswith(p) for p in EXEMPT_PREFIX) + in_setup = path == "/setup" or path.startswith("/setup/") + # These flags are cached per process, but the owner can appear (or the + # upgraded owner finish their profile) outside this process: another + # worker, a seed script, a restore. While either is set, trust the DB. + if app.state.needs_owner or app.state.setup_legacy: + from sqlalchemy.orm import Session as _S + + from app import setup_flow as _sf + with _S(app.state.engine) as s: + if app.state.needs_owner and _sf.owner_exists(s): + app.state.needs_owner, app.state.setup_code = False, None + if app.state.setup_legacy and _sf.status(s) != "legacy": + app.state.setup_legacy = False + if app.state.needs_owner and not (in_setup or path.startswith("/static/") + or path in ("/manifest.json", "/sw.js", "/health")): + return RedirectResponse("/setup", status_code=303) + # /setup/reset/ is gated by its own single-use token (issued by + # `python -m app.manage reset-owner`); the rest of /setup is public + # only until the owner exists. + exempt = (path in EXEMPT_EXACT or any(path.startswith(p) for p in EXEMPT_PREFIX) + or path.startswith("/setup/reset/") or (in_setup and app.state.needs_owner)) request.state.user = None # Every path (incl. exempt/login/static, which also render base.html) - # gets a theme so `data-theme` and the theme-aware loader always - # resolve. Authenticated requests below override with the saved theme. - request.state.active_theme = DEFAULT_THEME - active_theme_var.set(DEFAULT_THEME) + # gets appearance defaults; signed-in requests below read the saved + # company choices. + request.state.ui = dict(UI_DEFAULTS) # The customer-facing pages are exempt from auth but they are still - # this company's storefront: a company on control-room was emailing - # portal and e-sign links that opened in warm-coastal, a skin the - # customer had never seen. Resolve the saved theme for those two - # prefixes only -- /static/ must not pay a DB read per asset. - if path.startswith(("/sign/", "/portal/")): + # this company's storefront, so they read the saved appearance too -- + # for those two prefixes only: /static/ must not pay a DB read per asset. + if path.startswith(("/sign/", "/portal/")) or path in ("/login", "/login/2fa") or in_setup: from sqlalchemy.orm import Session as _S with _S(app.state.engine) as s: - theme = models.get_setting(s, "active_theme", DEFAULT_THEME) - if theme in ALLOWED_THEMES: - request.state.active_theme = theme - active_theme_var.set(theme) + request.state.ui = ui_settings(s) + # Admin › What customers see: "Use the company palette" off + # puts the customer's own pages back on standard Lagoon. + if (path.startswith(("/sign/", "/portal/")) + and models.get_setting(s, "email_brand", "1") == "0"): + request.state.ui["palette_css"] = "" if not exempt: uid = request.session.get("user_id") # Missing "epoch" (cookie issued before this field existed) is @@ -233,14 +265,8 @@ async def require_auth(request, call_next): if user is not None and user.active and epoch == user.session_epoch: s.expunge(user) request.state.user = user - # Reuse this session to read the active theme once the - # user is confirmed; validate against the allowed set, - # falling back to the default on anything unexpected. - theme = models.get_setting(s, "active_theme", DEFAULT_THEME) - if theme not in ALLOWED_THEMES: - theme = DEFAULT_THEME - request.state.active_theme = theme - active_theme_var.set(theme) + # Reuse this session for the company's appearance. + request.state.ui = ui_settings(s) # No valid session cookie? Try trusted-header SSO before bouncing # to /login: a proxy that already authenticated the user (Pangolin # et al.) injects PROXY_AUTH_HEADER, and we mint a normal session @@ -254,6 +280,7 @@ async def require_auth(request, call_next): if puser is not None: s.expunge(puser) request.state.user = puser + request.state.ui = ui_settings(s) if request.state.user is None: request.session.clear() return RedirectResponse("/login", status_code=303) @@ -267,6 +294,15 @@ async def require_auth(request, call_next): if (app.state.require_2fa and not request.state.user.totp_enabled and not path.startswith("/account") and path != "/logout"): return RedirectResponse("/account?force2fa=1", status_code=303) + # A temporary password from the owner: choose your own first. + if (request.state.user.must_change_password + and not path.startswith("/account") and path != "/logout"): + return RedirectResponse("/account?change=1", status_code=303) + # Upgraded from the APP_PASSWORD era: the owner finishes their + # profile (real name, username, own password) once. + if (app.state.setup_legacy and request.state.user.role == "admin" + and not in_setup and path != "/logout"): + return RedirectResponse("/setup/profile", status_code=303) return await call_next(request) # CSRF defense-in-depth: reject state-changing requests whose Origin (or, diff --git a/app/manage.py b/app/manage.py new file mode 100644 index 0000000..fc912f7 --- /dev/null +++ b/app/manage.py @@ -0,0 +1,66 @@ +"""Command-line maintenance: `python -m app.manage `. + + reset-owner [--username NAME] [--clear-2fa] + Print a one-time link (valid 30 minutes) that sets a new password for an + owner account -- the recovery path now that no password lives in the + environment. Run it on the server, e.g. + `docker compose exec app python -m app.manage reset-owner`. +""" +import argparse +import sys + +from sqlalchemy import select +from sqlalchemy.orm import Session + + +def reset_owner(username: str | None, clear_2fa: bool, base_url: str | None = None) -> int: + from app import models, setup_flow + from app.db import make_engine + engine = make_engine() + with Session(engine) as s: + q = select(models.User).where(models.User.role == "admin", models.User.active) + if username: + q = q.where(models.User.username == username.strip().lower()) + owners = s.scalars(q.order_by(models.User.id)).all() + if not owners: + print("No active owner account" + (f" named {username!r}" if username else "") + ".", + file=sys.stderr) + print("If no owner exists yet, open the app in a browser to run first-time setup.", + file=sys.stderr) + return 1 + if len(owners) > 1 and not username: + print("More than one owner account. Pick one with --username:", file=sys.stderr) + for u in owners: + print(f" {u.username} ({u.name})", file=sys.stderr) + return 2 + user = owners[0] + base_url = (base_url or models.get_setting(s, "public_base_url", "").strip() + or "http://localhost:8000") + token = setup_flow.issue_reset(s, user.id, clear_2fa=clear_2fa) + models.audit(s, None, "setup.owner_reset_issued", detail=user.username or "") + who = f"{user.name} ({user.username})" + s.commit() + print(f"Reset link for {who}, valid for 30 minutes and usable once:") + print(f" {base_url.rstrip('/')}/setup/reset/{token}") + if clear_2fa: + print("Two-step sign-in will be turned off when the new password is saved.") + return 0 + + +def main(argv=None) -> int: + p = argparse.ArgumentParser(prog="python -m app.manage") + sub = p.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("reset-owner", help="print a one-time owner password reset link") + r.add_argument("--username") + r.add_argument("--clear-2fa", action="store_true", + help="also turn off two-step sign-in (lost phone and backup codes)") + r.add_argument("--base-url", help="the address you open the app at (default: the public " + "address saved in Admin, else http://localhost:8000)") + args = p.parse_args(argv) + if args.cmd == "reset-owner": + return reset_owner(args.username, args.clear_2fa, args.base_url) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/app/migrate.py b/app/migrate.py index 5206e9f..a919834 100644 --- a/app/migrate.py +++ b/app/migrate.py @@ -145,6 +145,7 @@ def rank(r): # higher = keep COLUMNS = { "users": [ + ("must_change_password", "BOOLEAN DEFAULT 0"), ("username", "VARCHAR(40)"), ("active", "BOOLEAN DEFAULT 1"), ("view_money", "BOOLEAN DEFAULT 0"), @@ -197,7 +198,7 @@ def rank(r): # higher = keep ("reorder_point", "REAL"), ("reorder_qty", "REAL"), ], - "customers": [("tags", "TEXT DEFAULT '[]'"), ("notify_email", "BOOLEAN DEFAULT 0"), + "customers": [("deactivated_at", "DATETIME"), ("tags", "TEXT DEFAULT '[]'"), ("notify_email", "BOOLEAN DEFAULT 0"), ("qbo_customer_id", "VARCHAR(40) DEFAULT ''"), ("qbo_customer_scope", "VARCHAR(100) DEFAULT ''")], "equipment": [("warranty_end", "DATE")], @@ -219,6 +220,7 @@ def rank(r): # higher = keep ("sign_viewed_at", "DATETIME"), ("signed_pdf_hash", "VARCHAR(64) DEFAULT ''"), ], + "email_outbox": [("html", "TEXT DEFAULT ''")], } diff --git a/app/models.py b/app/models.py index fcfc6ce..98577df 100644 --- a/app/models.py +++ b/app/models.py @@ -57,6 +57,8 @@ class Customer(Base): email: Mapped[str] = mapped_column(String(120), default="") notes: Mapped[str] = mapped_column(Text, default="") active: Mapped[bool] = mapped_column(Boolean, default=True) + # When the customer was last marked inactive (None while active). + deactivated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=utcnow) tags: Mapped[list[str]] = mapped_column(JSON, default=list) notify_email: Mapped[bool] = mapped_column(Boolean, default=False) @@ -487,6 +489,9 @@ class User(Base): totp_secret: Mapped[str | None] = mapped_column(String(200), nullable=True) totp_enabled: Mapped[bool] = mapped_column(Boolean, default=False) session_epoch: Mapped[int] = mapped_column(Integer, default=0) + # Set for a temporary password handed out by the owner; the person must + # choose their own at first sign-in. + must_change_password: Mapped[bool] = mapped_column(Boolean, default=False) PERMISSION_FLAGS = ("view_money", "manage_customers", "can_repairs", "view_all_routes", "mark_cash", "approve_billing") @@ -712,6 +717,8 @@ class EmailOutbox(Base): to_addr: Mapped[str] = mapped_column(String(120)) subject: Mapped[str] = mapped_column(String(200)) body: Mapped[str] = mapped_column(Text) + # Branded HTML alternative ("" = plain text only); see app.email_brand. + html: Mapped[str] = mapped_column(Text, default="") status: Mapped[str] = mapped_column(String(8), default="pending") # pending|sent|failed attempts: Mapped[int] = mapped_column(Integer, default=0) last_error: Mapped[str] = mapped_column(Text, default="") diff --git a/app/nav.py b/app/nav.py new file mode 100644 index 0000000..095fd32 --- /dev/null +++ b/app/nav.py @@ -0,0 +1,168 @@ +"""The staff navigation: one model, drawn three ways by base.html. + +Desktop draws it as the masthead's group tabs with the active group's pages +in a second row (or as a grouped sidebar, when the company picked that +layout); tablet and phone draw it as the menu sheet plus a five-slot bottom +bar on phones. Visibility mirrors each route's own permission dependency -- +hiding an item is a convenience, the server still checks every request. +""" +from dataclasses import dataclass, field + + +def _admin(u): + return u is None or u.role == "admin" + + +def _perm(flag): + return lambda u: u is None or u.can(flag) + + +def _billing(u): + return u is None or u.can("view_money") or u.can("approve_billing") + + +def _all(u): + return True + + +@dataclass(frozen=True) +class Item: + key: str + href: str + label: str + icon: str + show: object = _all + # Other paths that belong to this page (detail views, sub-pages). + also: tuple = () + + +@dataclass(frozen=True) +class Group: + label: str # "" = Home + items: tuple + + +OWNER = ( + Group("Home", (Item("dash", "/dashboard", "Dashboard", "dash", _admin),)), + Group("Field", ( + Item("today", "/", "Today", "today", also=("/visit/", "/today/")), + Item("week", "/week", "Week", "week"), + )), + Group("Customers", ( + Item("customers", "/customers", "Customers", "users", + also=("/properties/", "/pools/", "/search")), + Item("jobs", "/jobs", "Service jobs", "wrench"), + Item("quotes", "/quotes", "Quotes", "quote", _perm("manage_customers")), + Item("contracts", "/contracts", "Contracts", "pen", _perm("manage_customers")), + )), + Group("Money", ( + Item("invoices", "/invoices", "Invoices", "file", _admin), + Item("billing", "/billing", "QuickBooks billing", "money", _billing), + Item("ar", "/ar", "Receivables", "chart", _admin), + Item("followups", "/followups", "Payment follow-ups", "mail", _admin), + Item("money", "/money", "Money summary", "tag", _perm("view_money")), + )), + Group("Operations", ( + Item("plan", "/routes/plan", "Route planner", "map", _perm("view_all_routes"), + also=("/routes/",)), + Item("alerts", "/water-alerts", "Water alerts", "drop", _admin, + also=("/water-tests",)), + Item("inventory", "/inventory", "Inventory", "box", _admin), + Item("equipment", "/equipment", "Equipment", "cog", _admin), + Item("ops", "/operations", "Operations health", "pulse", _admin), + Item("analytics", "/analytics", "Analytics", "chart", _admin), + )), + Group("Admin", ( + Item("settings", "/settings", "Admin", "gear", _admin, + also=("/users", "/audit", "/testers")), + )), +) + +TECH = ( + Group("", ( + Item("today", "/", "Today", "today", also=("/visit/", "/today/")), + Item("week", "/week", "Week", "week"), + Item("customers", "/customers", "My customers", "users", + also=("/properties/", "/pools/", "/search")), + Item("account", "/account", "Account", "user"), + )), +) + + +@dataclass +class NavItem: + key: str + href: str + label: str + icon: str + on: bool = False + badge: str = "" + badge_cls: str = "" + + +@dataclass +class NavGroup: + label: str + items: list = field(default_factory=list) + + @property + def on(self): + return any(i.on for i in self.items) + + @property + def href(self): + return self.items[0].href + + @property + def alert(self): + return any(i.badge_cls == "neg" for i in self.items) + + +def _matches(item: Item, path: str) -> bool: + if item.href == "/": + return path == "/" or any(path.startswith(p) for p in item.also) + return (path == item.href or path.startswith(item.href + "/") + or any(path.startswith(p) for p in item.also)) + + +def build(user, path: str, badges: dict | None = None) -> dict: + """Everything base.html needs to draw the navigation for this request. + + `badges` maps an item key to (text, cls) -- cls "neg" marks something + that needs a decision and also puts a dot on its group's tab.""" + badges = badges or {} + is_tech = user is not None and user.role != "admin" + source = TECH if is_tech else OWNER + groups = [] + for g in source: + items = [NavItem(i.key, i.href, i.label, i.icon, _matches(i, path), + *badges.get(i.key, ("", ""))) + for i in g.items if i.show(user)] + if items: + groups.append(NavGroup(g.label, items)) + # Exactly one active item: the longest match wins (/routes/plan over /). + flat = [i for g in groups for i in g.items] + on = [i for i in flat if i.on] + if len(on) > 1: + best = max(on, key=lambda i: len(i.href)) + for i in on: + i.on = i is best + current = next((i for i in flat if i.on), None) + cur_group = next((g for g in groups if g.on), None) + single = len(groups) == 1 + top = flat if single else groups + sub = cur_group.items if (cur_group and not single and len(cur_group.items) > 1) else [] + if is_tech: + bnav = [("today", "/", "Today", "today"), ("week", "/week", "Week", "week"), + ("customers", "/customers", "Customers", "users"), + ("account", "/account", "Account", "user")] + else: + bnav = [("dash", "/dashboard", "Home", "dash"), ("today", "/", "Today", "today"), + ("customers", "/customers", "Customers", "users"), + ("invoices", "/invoices", "Money", "money")] + visible = {i.key for i in flat} + bnav = [b for b in bnav if b[0] in visible] + return {"groups": groups, "top": top, "single": single, "sub": sub, + "sub_label": f"{cur_group.label} pages" if sub else "", + "current": current, "title": current.label if current else "", + "bnav": bnav} diff --git a/app/observability.py b/app/observability.py index 22a7b0f..7833bc6 100644 --- a/app/observability.py +++ b/app/observability.py @@ -35,6 +35,32 @@ _DATEFMT = "%Y-%m-%d %H:%M:%S" +class RecentLogs(logging.Handler): + """The last `capacity` log lines, in memory, for Admin › Logs. + + It sees exactly what stdout sees (same records, same formatter), so the + method-and-path-only discipline and redact_path still decide what can + appear; nothing new is written anywhere. Bounded, so a noisy day cannot + grow memory, and lost on restart by design: the container's own log is + the durable record.""" + + def __init__(self, capacity: int = 2000): + super().__init__() + from collections import deque + self.lines = deque(maxlen=capacity) + + def emit(self, record): + try: + self.lines.append({"at": record.created, "level": record.levelname.lower(), + "source": record.name, "message": record.getMessage(), + "line": self.format(record)}) + except Exception: # a log line must never take a request down + pass + + +RECENT = RecentLogs() + + def configure_logging() -> None: """Point the root logger at stdout at LOG_LEVEL (default INFO). @@ -53,6 +79,8 @@ def configure_logging() -> None: handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter(_FORMAT, datefmt=_DATEFMT)) root.addHandler(handler) + RECENT.setFormatter(logging.Formatter(_FORMAT, datefmt=_DATEFMT)) + root.addHandler(RECENT) root.setLevel(level) diff --git a/app/palettes.py b/app/palettes.py new file mode 100644 index 0000000..1cc24de --- /dev/null +++ b/app/palettes.py @@ -0,0 +1,159 @@ +"""Company colour palettes: light and dark tokens derived from one base colour. + +Every derived colour is solved for contrast -- accent text 4.6:1 on its +surface, accent on its tint 7:1, white on the masthead and hero 6:1 -- so any +base, a custom pick included, stays WCAG AA. Lagoon keeps the hand-tuned Aqua +Atelier tokens in css/v2.css and emits nothing. Chart colours never change, +so they stay safe for colour-blind readers. + +The page receives the result as a {% endif %} diff --git a/app/templates/_route.html b/app/templates/_route.html new file mode 100644 index 0000000..c823c36 --- /dev/null +++ b/app/templates/_route.html @@ -0,0 +1,16 @@ +{# Route macros shared by Today and Week. #} + +{# Who is on this stop, for someone who can see every route: the assigned + person's initials, a covering person (amber), or a problem worth fixing. #} +{% macro tech_tag(s, tech_by_id) -%} +{% set assigned_id = s.property.assigned_tech_id %} +{% if s.effective_tech_id == assigned_id %} + {% if assigned_id and s.property.assigned_tech %}{{ s.property.assigned_tech.name | initials }}{% endif %} + {% if not assigned_id %}unassigned{% endif %} + {% if s.property.assigned_tech and not s.property.assigned_tech.active %}disabled {{ "owner" if s.property.assigned_tech.role == "admin" else "tech" }}{% endif %} +{% elif s.effective_tech_id %} + {{ (tech_by_id[s.effective_tech_id].name if s.effective_tech_id in tech_by_id else "") | initials }} +{% else %} + unassigned +{% endif %} +{%- endmacro %} diff --git a/app/templates/_ui.html b/app/templates/_ui.html index 223a248..4869e60 100644 --- a/app/templates/_ui.html +++ b/app/templates/_ui.html @@ -1,54 +1,74 @@ -{# Shared UI macros: icons, page header with waterline signature #} +{# Shared UI macros: icons, page header, pills, empty states, pager. #} -{% macro icon(name, cls="") %} - -{% endmacro %} +{# Icon set from the V2 design (24px grid, 1.7 stroke). Old names are kept as + aliases so existing call sites keep working. Unknown names draw nothing. #} +{% set ICONS = { + "dash": "M3 13h8V3H3zM13 21h8V11h-8zM13 3v6h8V3zM3 21h8v-6H3z", + "today": "M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM9 18h5.5a3.5 3.5 0 0 0 0-7h-5a3.5 3.5 0 0 1 0-7H15", + "week": "M4 6h16v14H4zM4 10h16M8 3v4M16 3v4", + "users": "M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM2 21a7 7 0 0 1 14 0M16 3.5a4 4 0 0 1 0 7.5M22 21a7 7 0 0 0-4-6.3", + "user": "M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z", + "wrench": "M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.6 2.6-2.4-.6-.6-2.4z", + "money": "M12 2v20M17 6H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6", + "file": "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M8 13h8M8 17h5", + "pen": "M12 20h9M16.5 3.5a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4z", + "quote": "M4 4h16v12H8l-4 4zM8 9h8M8 12h5", + "box": "M21 8l-9-5-9 5v8l9 5 9-5zM3 8l9 5 9-5M12 13v8", + "map": "M9 4L3 6v14l6-2 6 2 6-2V4l-6 2zM9 4v14M15 6v14", + "gear": "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4 1a7 7 0 0 0-2-1.2L14 3h-4l-.5 2.6a7 7 0 0 0-2 1.2l-2.4-1-2 3.4 2 1.6A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 2 1.2L10 21h4l.5-2.6a7 7 0 0 0 2-1.2l2.4 1 2-3.4-2-1.6c.1-.4.1-.8.1-1.2z", + "drop": "M12 2.7l5.7 5.6a8 8 0 1 1-11.4 0z", + "chart": "M3 3v18h18M7 15l4-4 3 3 5-6", + "pulse": "M3 12h4l3-8 4 16 3-8h4", + "cog": "M12 8v4l3 2M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z", + "log": "M4 4h16v16H4zM8 8h8M8 12h8M8 16h5", + "shield": "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z", + "lock": "M5 11h14v10H5zM8 11V7a4 4 0 0 1 8 0v4", + "check": "M5 12l5 5L20 7", + "next": "M9 18l6-6-6-6", + "back": "M15 18l-6-6 6-6", + "minus": "M5 12h14", + "plus": "M12 5v14M5 12h14", + "chevD": "M6 9l6 6 6-6", + "chevU": "M18 15l-6-6-6 6", + "down": "M12 5v14M19 12l-7 7-7-7", + "up": "M12 19V5M5 12l7-7 7 7", + "nav": "M3 11l19-9-9 19-2-8z", + "wifioff": "M2 2l20 20M8.5 16.5a5 5 0 0 1 7 0M5 12.9a10 10 0 0 1 5.2-2.7M19 12.9a10 10 0 0 0-2.3-1.6M2 8.8a15 15 0 0 1 4.2-2.7M22 8.8A15 15 0 0 0 10.7 5M12 20h.01", + "sync": "M21 12a9 9 0 0 1-15.5 6.2L3 16M3 12a9 9 0 0 1 15.5-6.2L21 8M21 3v5h-5M3 21v-5h5", + "alert": "M12 9v4M12 17h.01M10.3 3.9L1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z", + "phone": "M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2z", + "mail": "M3 5h18v14H3zM3 6l9 7 9-7", + "camera": "M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2zM12 17a4 4 0 1 0 0-8 4 4 0 0 0 0 8z", + "print": "M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2M6 14h12v8H6z", + "search": "M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16zM21 21l-4.3-4.3", + "menu": "M3 6h18M3 12h18M3 18h18", + "close": "M18 6L6 18M6 6l12 12", + "home": "M3 11l9-8 9 8v10h-6v-6H9v6H3z", + "clock": "M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM12 6v6l4 2", + "tag": "M20.6 13.4l-7.2 7.2a2 2 0 0 1-2.8 0L2 12V2h10l8.6 8.6a2 2 0 0 1 0 2.8zM7 7h.01", + "dl": "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3", + "upload": "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12", + "pin": "M12 21s-7-6.2-7-11a7 7 0 0 1 14 0c0 4.8-7 11-7 11zM12 12.6a2.6 2.6 0 1 0 0-5.2 2.6 2.6 0 0 0 0 5.2z", + "dog": "M10 5.5 8.5 3H5l-1 3 1.5 2H8M10 5.5h5.5L19 8l2 .8-1 2.2h-3l-1 2v6h-2.5v-3h-5v3H6v-7", + "sun": "M12 16.2a4.2 4.2 0 1 0 0-8.4 4.2 4.2 0 0 0 0 8.4zM12 2.5v2.4M12 19.1v2.4M4.4 4.4l1.7 1.7M17.9 17.9l1.7 1.7M2.5 12h2.4M19.1 12h2.4M4.4 19.6l1.7-1.7M17.9 6.1l1.7-1.7", + "moon": "M20 14.5A8.5 8.5 0 1 1 9.5 4a7 7 0 0 0 10.5 10.5z", + "logout": "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9", + "edit": "M12 20h9M16.5 3.5a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4z", + "trash": "M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14", + "ext": "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3", + "link": "M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7", + "star": "M12 2l3 6.5 7 .8-5.2 4.8 1.4 7L12 17.6 5.8 21l1.4-7L2 9.3l7-.8z", + "route": "M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM9 18h5.5a3.5 3.5 0 0 0 0-7h-5a3.5 3.5 0 0 1 0-7H15", + "customers": "M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM2 21a7 7 0 0 1 14 0M16 3.5a4 4 0 0 1 0 7.5M22 21a7 7 0 0 0-4-6.3", + "jobs": "M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.6 2.6-2.4-.6-.6-2.4z", + "settings": "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4 1a7 7 0 0 0-2-1.2L14 3h-4l-.5 2.6a7 7 0 0 0-2 1.2l-2.4-1-2 3.4 2 1.6A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 2 1.2L10 21h4l.5-2.6a7 7 0 0 0 2-1.2l2.4 1 2-3.4-2-1.6c.1-.4.1-.8.1-1.2z", + "inventory": "M21 8l-9-5-9 5v8l9 5 9-5zM3 8l9 5 9-5M12 13v8", + "document": "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M8 13h8M8 17h5", + "chevron": "M9 18l6-6-6-6" +} %} +{% macro icon(name, cls="") -%} + +{%- endmacro %} {# Styled file-upload control. Wraps a caller-provided (which keeps its own name/accept/hx-* attributes) in a labelled, tappable button so @@ -71,26 +91,52 @@ appends page=N itself. Mirrors the original customers pager markup. #} {% macro pager(page, total_pages, total, base_url, base_qs="") %} {% set sep = "&" if base_qs else "" %} -
- Page {{ page }} of {{ total_pages }} · {{ total }} total -
+
-
+ + {% endmacro %} -{% macro page_header(eyebrow, title) %} -
-

{{ eyebrow }}

-

{{ title }}

- +{# Page header: optional breadcrumb/eyebrow line, title, lede, and an + actions slot (call block). Usage: + {% call ui.page_header("Customers", "Priya Nair", lede="Salt pool") %}Edit{% endcall %} #} +{% macro page_header(eyebrow, title, lede="") -%} +
+
+ {% if eyebrow %}

{{ eyebrow }}

{% endif %} +

{{ title }}

+ {% if lede %}

{{ lede }}

{% endif %} +
+ {% if caller is defined %}
{{ caller() }}
{% endif %}
-{% endmacro %} +{%- endmacro %} + +{# Status pill: kind is pos | neg | warn | neu | acc | next. #} +{% macro pill(text, kind="neu") -%}{{ text }}{%- endmacro %} + +{# Empty state with the drop mark. #} +{% macro empty(text) -%}

{{ text }}

{%- endmacro %} + +{# Avatar initials disc. #} +{% macro av(name, cls="") -%}{%- endmacro %} + +{# One photo thumbnail with its tag; matches the upload response markup in + app/routers/photos.py. #} +{% macro photo(ph) -%} +
{{ (ph.tag or 'Photo') | capitalize }}{% if ph.tag %}
{{ ph.tag }}
{% endif %}
+{%- endmacro %} + +{# A short numbered flow (CSV import, tester import): each step done, current + or still to come. `steps` is a list of labels; `current` is 1-based. #} +{% macro flow_steps(steps, current) -%} +
    + {% for s in steps %}
  1. {% if loop.index < current %}✓{% else %}{{ loop.index }}{% endif %}{{ s }}
  2. {% endfor %} +
+{%- endmacro %} diff --git a/app/templates/account.html b/app/templates/account.html index 408624f..a6a4f26 100644 --- a/app/templates/account.html +++ b/app/templates/account.html @@ -2,16 +2,59 @@ {% block title %}Account{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{{ ui.page_header("Your account", user.name) }} +

Account

{{ user.name }} · {{ "Owner · administrator" if user.role == "admin" else "Technician" }}

+
+ +
+

Display on this device

Saved on this phone or computer only.

+
+ {% for key, label, help, opts in [ + ("mode", "Light or dark", "Follow device switches with the phone's setting.", [("", "Follow device"), ("light", "Light"), ("dark", "Dark")]), + ("dens", "Density", "Compact fits more rows on a desktop screen.", [("", "Comfortable"), ("compact", "Compact")]), + ("txt", "Text size", "Bigger text for sun and gloves.", [("", "Standard"), ("lg", "Large"), ("xl", "Largest")]), + ("mot", "Motion", "Reduced keeps fades and drops movement.", [("", "Full"), ("reduced", "Reduced")])] %} +
{{ label }}{{ help }}
+
{% for v, l in opts %}{% endfor %}
+ {% endfor %} +
+
+ {% if request.query_params.get("force2fa") and not user.totp_enabled %} -
+ {% endif %} +{% if user.must_change_password %} + +{% endif %} {% if banner %} -
{{ banner }}
+
{{ banner }}
{% endif %} {% if error %}

{{ error }}

{% endif %} @@ -21,7 +64,7 @@ #sidebar, #topbar, .no-print { display: none !important; } } -
+

Your backup codes

Save these somewhere safe — each one works once, and this is the only time they'll be shown. Print this page or write them down now.

@@ -34,7 +77,7 @@

Your bac

{% endif %} -
+

Password

-
+

Two-factor authentication

{% if user.totp_enabled %} @@ -82,7 +125,7 @@

Two-fact {% endif %}

-
+

Sessions

Ends every other session signed in as you. This device stays signed in.

diff --git a/app/templates/analytics.html b/app/templates/analytics.html index 880c607..03a7237 100644 --- a/app/templates/analytics.html +++ b/app/templates/analytics.html @@ -2,68 +2,46 @@ {% block title %}Analytics{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{{ ui.page_header("Business analytics", "Analytics") }} +
+

Money

Analytics

+ {% if tab == "overview" %} +

{% if ov.has_revenue %}{{ v.whole(ov.revenue_cents) }} from {{ '{:,}'.format(ov.visits) }} visit{{ 's' if ov.visits != 1 }}, {{ ov.span }}.{% else %}Nothing billed in {{ ov.span }} yet.{% endif %}{% if ov.flagged %} {{ ov.flagged | length }} {{ 'property costs' if ov.flagged | length == 1 else 'properties cost' }} 15% or more of the rate in chemicals.{% endif %}

+ {% else %} +

{{ start | short_date }} – {{ end | short_date }}. Revenue is billed service, chemicals at your markup and finished jobs.

+ {% endif %}
+ {% if tab == "overview" %} + + {% endif %} +
-{% if summary and not too_large %} -
-
-

Revenue

-

{{ summary.revenue_cents | dollars }}

-
-
-

Profit

-

{{ summary.profit_cents | dollars }}

-
-
-

Visits done

-

{{ summary.visits_done }}

-
-
-

Avg / visit

-

{{ summary.avg_per_visit_cents | dollars }}

-
-
-

Customers

-

{{ summary.customer_count }}

-
-
-

Top customer

- {% if summary.top_customer %} -

{{ summary.top_customer }}

-

{{ summary.top_customer_cents | dollars }}

- {% else %} -

—

- {% endif %} -
-
-{% endif %} + -
- -
- - -
-
- - -
- -
+{% if tab == "overview" %} +{% include "_analytics_overview.html" %} +{% else %} -
- {% for label, qstart, qend in quick %} - {{ label }} - {% endfor %} +
+ Showing +
{% for label, qstart, qend in quick %}{{ label }}{% endfor %}
+
+ + + – + + +
-
- {% for key, label in tab_labels.items() %} - {{ label }} - {% endfor %} +{% if summary and not too_large %} +
+
Revenue
{{ summary.revenue_cents | dollars }}
Profit {{ summary.profit_cents | dollars }} after chemical cost
+
Visits completed
{{ summary.visits_done }}
{{ summary.customer_count }} customers
+
Revenue per visit
{{ summary.avg_per_visit_cents | dollars }}
All income divided by visits
+
Top customer
{{ summary.top_customer or "—" }}
{{ summary.top_customer_cents | dollars if summary.top_customer else "" }}
+{% endif %} {% if too_large %}
@@ -73,8 +51,8 @@ {% else %} {% if chart %} -
-

+

+

{{ tab_labels[tab] }}{% if tab in ("income", "volume") %} by week{% elif tab in ("customers", "crew", "chemicals") %} ranked{% elif tab == "types" %} mix{% endif %}

{{ chart | safe }} @@ -343,4 +321,5 @@ {% endif %}
{% endif %} +{% endif %}{# overview / detailed tabs #} {% endblock %} diff --git a/app/templates/ar.html b/app/templates/ar.html index 8199e56..2db9b4f 100644 --- a/app/templates/ar.html +++ b/app/templates/ar.html @@ -1,42 +1,35 @@ {% extends "base.html" %} {% block title %}Accounts receivable{% endblock %} {% block content %} -Review payment follow-ups {% import "_ui.html" as ui %} -{{ ui.page_header("Money", "Accounts receivable") }} -{% if qbo_invoices %}

QuickBooks · {{ qbo_balance_cents | dollars }} outstanding

{% include "billing/_invoices.html" %}

Local invoices

{% endif %} - -

- {{ totals.total_cents | dollars }} - - outstanding across {{ totals.customer_count }} customer{{ "s" if totals.customer_count != 1 }} -

- -
- {% for b in buckets %} -
-
{{ b }}{{ "" if b == "Current" else " days" }}
-
- {{ totals.buckets[b] | dollars }}
+
+

Receivables

{{ totals.total_cents | dollars }} outstanding across {{ totals.customer_count }} customer{{ "s" if totals.customer_count != 1 }}. Invoices are due {{ net_days }} days after their billing period.

+ +
+{% set peak = [totals.buckets.values() | max, 1] | max %} +
+

By age

{{ totals.total_cents | dollars }}
+
+ {% for b in buckets %} +
{{ b }}{{ "" if b == "Current" else " days" }}{{ totals.buckets[b] | dollars }}
+ {% endfor %}
- {% endfor %} -
- + +{% if qbo_invoices %}

QuickBooks

{{ qbo_balance_cents | dollars }} outstanding
{% include "billing/_invoices.html" %}
{% endif %} {% if request.query_params.get("error") == "email" %} -

No customer email address, or SMTP is not configured in Settings.

+ {% elif request.query_params.get("error") == "payment" %} -

Enter a payment amount greater than zero.

+ {% endif %}
{% for row in rows %} -
60 }}> +
60 }}> {{ row.customer.name }} {% if row.oldest_days %} - {{ row.oldest_days }}d late + {{ row.oldest_days }}d late {% endif %} {{ row.balance_cents | dollars }} @@ -92,8 +85,4 @@ {% endfor %}
-

- Invoices are due {{ net_days }} days after the end of their billing period. - Change that in Settings → Business. -

{% endblock %} diff --git a/app/templates/base.html b/app/templates/base.html index 0be5290..d0de8dc 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -1,131 +1,152 @@ -{% set active_theme = (request.state.active_theme if request else none) or 'warm-coastal' %} - +{#- The staff shell (Aqua Atelier). One layout for every screen: + desktop -- deep-water masthead with group tabs and the active group's + pages in a second row, the working sheet floating over it; or, + when the company chose it in Admin › Appearance, a sidebar. + tablet -- masthead with the page title, search and a menu sheet. + phone -- the same, plus a five-slot bottom bar. + A page that sets `bare = true` (sign-in, customer e-sign) gets the plain + centred shell with no staff chrome. -#} +{% set _ui_cfg = (request.state.ui if request is not none and request.state is defined and request.state.ui is defined else {}) %} +{% set _nav_layout = _ui_cfg.get("nav_layout", "top") %} +{% set _hdr = _ui_cfg.get("header_style", "lit") %} +{% set _org = _ui_cfg.get("company", "") %} + - {% set theme_colors = {'warm-coastal': '#16303B', 'control-room': '#0E141B', 'fresh-field': '#0F172A'} %} - + - - + {% include "_mode_head.html" %} + {% include "_palette.html" %} {% block title %}OpenPoolPro{% endblock %} - - {% import "_ui.html" as ui %} - {% block nav %} - {% set path = request.url.path if request else "/" %} - {% set u = request.state.user if request is not none and request.state is defined else None %} - {% set items = [] %} - {% if u is none or u.role == "admin" %}{% set items = items + [("/dashboard", "Dashboard", "money")] %}{% endif %} - {% if u is none or u.role == "admin" %}{% set items = items + [("/analytics", "Analytics", "week")] %}{% endif %} - {% if u is none or u.role == "admin" %}{% set items = items + [("/invoices", "Invoices", "money")] %}{% endif %} - {% if u is none or u.can("view_money") or u.can("approve_billing") %}{% set items = items + [("/billing", "QuickBooks billing", "money")] %}{% endif %} - {% set items = items + [("/", "Today", "route"), ("/week", "Week", "week"), - ("/customers", "Customers", "customers"), ("/jobs", "Service / Jobs", "jobs")] %} - {% if u is none or u.can("manage_customers") %}{% set items = items + [("/quotes", "Quotes", "money")] %}{% endif %} - {% if u is none or u.can("manage_customers") %}{% set items = items + [("/contracts", "Contracts", "document")] %}{% endif %} - {% if u is none or u.can("view_money") %}{% set items = items + [("/money", "Money", "money")] %}{% endif %} - {% if u is none or u.role == "admin" %}{% set items = items + [("/inventory", "Inventory", "inventory")] %}{% endif %} - {% if u is none or u.role == "admin" %}{% set items = items + [("/settings", "Settings", "settings")] %}{% endif %} - {% if u is not none and u.role == "admin" %}{% set items = items + [("/operations", "Operations", "settings")] %}{% endif %} - {% set low_count = low_stock_count(request) if request is not none and (u is none or u.role == "admin") else 0 %} - + {% endif %} + +
+
+
+{% endif %} + {% block content %}{% endblock %} +{% if bare %} +
+{% else %} +
+ + {% if not hide_bnav %} + {% endif %} -
- -
-
- - - {% if has_logo_check() %}Logo - {% else %}OpenPoolPro{% endif %} - - - - - - {{ ui.icon("menu", "h-6 w-6") }} - - {% if low_count > 0 %}{% endif %} - - - -
-
- -
- +
+ + {# Menu sheet (tablet and phone; also reachable on desktop from nothing). #} +
-
- {% endblock %} -
{% block content %}{% endblock %}
+ {% for g in _navm.groups %} + {% if g.label and not _navm.single and g.label != "Home" %}
{{ g.label }}
{% endif %} + {% for i in g.items %} + {{ ui.icon(i.icon, "ic18") }}{{ i.label }}{% if i.badge %}{{ i.badge }}{% endif %} + {% endfor %} + {% endfor %} + {% if _me %} +
You
+ {% if not _navm.single %}{{ ui.icon("user", "ic18") }}Account{% endif %} + +
+ {% endif %} +
+
+{% endif %} {% include "_uploads.html" %} {% include "_offline.html" %} {% include "_behaviors.html" %} diff --git a/app/templates/billing/_draft_review.html b/app/templates/billing/_draft_review.html new file mode 100644 index 0000000..81f7fe3 --- /dev/null +++ b/app/templates/billing/_draft_review.html @@ -0,0 +1,123 @@ +{#- One draft's review: charges, exceptions and every action the draft + supports. Rendered three ways from the same markup: + * the full page (/billing/drafts/{id}), pane=false + * the right-hand pane of the billing list on desktop, pane=true, either + server-rendered (/billing?ym=..&draft=ID) or swapped in by HTMX + (/billing/drafts/{id}/pane). + In the pane every form carries back=list so the redirect after an action + lands on the list with this draft still selected. -#} +{% import '_ui.html' as ui %} +{% set ymd = '%04d-%02d'|format(draft.period_year, draft.period_month) %} +{# Prepared → Approved → Invoice created → Totals checked → Emailed. #} +{% set order = {"draft": 1, "held": 1, "ready": 2, "approved": 2, "creating": 2, "create_unknown": 3, "mismatch": 4, "sending": 4, "delivery_unknown": 5, "sent": 5, "done": 6} %} +{% set reached = order.get(draft.status, 1) %} +{% set bad = draft.status in ("mismatch", "delivery_unknown", "create_unknown") %} +{% set status_pill = ui.pill(draft.status | replace('_', ' ') | capitalize, "neg" if bad else ("warn" if draft.status == "held" else ("pos" if draft.status in ("sent", "done") else "acc"))) %} +{% macro back_field() %}{% if pane %}{% endif %}{% endmacro %} +
+{% if pane %} +
+ {{ ui.av(draft.customer.name, "qb-av") }} +

{{ draft.customer.name }}

+

{{ ymd | month_name }} · revision {{ draft.revision }} · {{ draft.email or 'Missing billing email' }}

+
{{ status_pill }}{{ draft.total_cents | dollars }}
+
+

{{ ui.icon("ext") }}Open as a page

+{% else %} +
+
+

QuickBooks billing{{ ymd | month_name }}

+

{{ draft.customer.name }}

+

{{ ymd | month_name }} · revision {{ draft.revision }}

+
+
{{ status_pill }}{{ draft.total_cents | dollars }}
+
+{% endif %} +
    + {% for label in ["Prepared", "Approved", "Invoice created", "Totals checked", "Emailed"] %} + {% set n = loop.index %} +
  1. {{ "✓" if reached > n else n }}{{ label }}
  2. + {% endfor %} +
+{% if not pane and request.query_params.get('message') %}

{{ request.query_params.get('message') }}

{% endif %} +{% if draft.last_error %}{% endif %} +{% if not enabled or not connected %}

Drafts can be prepared and reviewed. Connect and enable QuickBooks billing before approval.

{% endif %} +{% if not service_item or not chemical_item %}

Check service and chemical item mappings in Settings before approving billable lines.

{% endif %} + +
+ {{ back_field() }} +
+
+
+
+ {% for line in draft.lines %}{% if line.amount_cents == 0 %} +
{{ ui.icon("alert", "ic18") }}Charge {{ loop.index }} has a zero price. Confirm this work should not be billed before approval.
+ {% endif %}{% endfor %} +
+ + + + {% for line in draft.lines %} + + + + + + + {% endfor %} + +
DateChargeQtyAmount ($)
{{ line.service_date | short_date if line.service_date else '—' }} + + {{ ui.pill(line.item_kind | title, "neu") }}{{ 'Taxable' if line.taxable else 'Non-taxable' }}{% if line.quantity %}{{ line.quantity }} {{ line.unit or '' }}{% else %}—{% endif %} +
+
+ {% if will_create_items %} +
{{ ui.icon("plus", "ic18") }}
Approving will add these to QuickBooks ({{ will_create_items|length }}) +

New items only — nothing existing is changed. An item already in QuickBooks under the same name is used instead of a second one being made.

+
    {% for key, name in will_create_items %}
  • {{ name }}
  • {% endfor %}
+ {% endif %} +
+
Subtotal{{ (draft.total_cents - draft.tax_cents) | dollars }}
+
Estimated tax{{ draft.tax_cents | dollars }}
+
Total to approve{{ draft.total_cents | dollars }}
+

Save edits to recalculate this total. QuickBooks tax and totals are checked before email delivery; differences require another approval.

+
+ {% if editable %} +
+ + + +
+ {% endif %} +
+ +
+{% if editable %}
{{ back_field() }}
{% endif %} +{% if request.state.user.can('approve_billing') and draft.status == 'draft' %} +
{{ back_field() }}
+{% elif request.state.user.can('approve_billing') and draft.status in ('approved','create_retry','create_error','ready') %} +
{{ back_field() }}
+{% endif %} +
+{% if draft.approved_at %}

Approved {{ draft.approved_at | local_date }} by user {{ draft.approved_by_id }}. The approved snapshot is retained.

{% endif %} + +{% if request.state.user.can('approve_billing') %} +{% if draft.status == 'mismatch' and mirror %} +
+ QuickBooks total requires approval +

Previously approved: {{ draft.total_cents | dollars }} · QuickBooks: {{ mirror.total_cents | dollars }}

+
    {% for line in mirror.raw.get('Line', []) %}
  • {{ line.get('Description', line.get('DetailType', 'Line')) }} · ${{ line.get('Amount', 0) }}
  • {% endfor %}
+

QuickBooks tax: ${{ mirror.raw.get("TxnTaxDetail", {}).get("TotalTax", 0) }} · Due {{ mirror.due_date }} · Currency {{ mirror.raw.get("CurrencyRef", {}).get("value", "USD") }} · Recipient {{ mirror.raw.get("BillEmail", {}).get("Address", draft.email) }}

+

Review the official PDF and revised tax before authorizing delivery.

+
+ Review official PDF +
{{ back_field() }}
+
+
+{% elif draft.status in ('create_unknown','recovering') %} +
Invoice creation is being reconciled

Invoice creation is being reconciled with QuickBooks. Another invoice will not be created while the outcome is uncertain.

+{% elif draft.status == 'delivery_unknown' %} +
Delivery not confirmed

Delivery is uncertain. Sync to check QuickBooks before taking further action; automatic email retry is blocked to avoid duplicate delivery.

+{% endif %} +{% else %}

An owner or billing approver must approve delivery.

{% endif %} +
diff --git a/app/templates/billing/_invoices.html b/app/templates/billing/_invoices.html index bb21438..85b7035 100644 --- a/app/templates/billing/_invoices.html +++ b/app/templates/billing/_invoices.html @@ -1,11 +1,11 @@ -
+
{% for inv in qbo_invoices %} -
+
{{ inv.number or 'QuickBooks invoice ' ~ inv.qbo_id }} {% if not qbo_portal %}{{ inv.customer.name }}{% endif %} - {{ 'overdue' if inv.balance_cents > 0 and inv.due_date and inv.due_date < qbo_today and inv.status not in ('void', 'deleted', 'unavailable') else inv.status }} - {% if inv.status not in ('void', 'deleted', 'unavailable') and inv.email_status != 'EmailSent' %}Delivery not confirmed{% endif %} + {{ 'overdue' if inv.balance_cents > 0 and inv.due_date and inv.due_date < qbo_today and inv.status not in ('void', 'deleted', 'unavailable') else inv.status }} + {% if inv.status not in ('void', 'deleted', 'unavailable') and inv.email_status != 'EmailSent' %}Delivery not confirmed{% endif %}
Outstanding {{ inv.balance_cents | dollars }}
@@ -13,11 +13,11 @@

Updated {{ inv.last_synced_at | local_date | short_date }}{% if inv.last_synced_at < qbo_stale_before %} · Balance may be stale; last update was over 30 minutes ago.{% endif %}

{% set payment_url = safe_payment_link(inv.payment_link) %} - {% if payment_url and inv.balance_cents > 0 and inv.status not in ('void', 'deleted', 'unavailable') %}View and pay invoice{% endif %} - {% if inv.status != 'unavailable' %}Download PDF{% endif %} + {% if payment_url and inv.balance_cents > 0 and inv.status not in ('void', 'deleted', 'unavailable') %}View and pay invoice{% endif %} + {% if inv.status != 'unavailable' %}Download PDF{% endif %}
{% else %}

No QuickBooks invoices synced yet.

{% endfor %}
-{% if qbo_transactions %}
Payment and credit history
{% for txn in qbo_transactions %}
{{ txn.kind }} · {{ txn.total_cents | dollars }}

{% if txn.txn_date %}{{ txn.txn_date | short_date }}{% else %}Date unavailable{% endif %}{% if txn.raw.get('PaymentRefNum') %} · Reference {{ txn.raw.get('PaymentRefNum') }}{% endif %}{% if txn.raw.get('PaymentMethodRef', {}).get('name') %} · {{ txn.raw.get('PaymentMethodRef', {}).get('name') }}{% endif %}

{% for line in txn.raw.get('Line', []) %}{% for link in line.get('LinkedTxn', []) %}

{{ link.get('TxnType') }} {{ link.get('TxnId') }}{% if line.get('LinkedTxn', []) | length == 1 %} · ${{ line.get('Amount', 0) }}{% else %} · Shared allocation{% endif %}

{% endfor %}{% endfor %}
{% endfor %}
{% endif %} +{% if qbo_transactions %}
Payment and credit history
{% for txn in qbo_transactions %}
{{ txn.kind }} · {{ txn.total_cents | dollars }}

{% if txn.txn_date %}{{ txn.txn_date | short_date }}{% else %}Date unavailable{% endif %}{% if txn.raw.get('PaymentRefNum') %} · Reference {{ txn.raw.get('PaymentRefNum') }}{% endif %}{% if txn.raw.get('PaymentMethodRef', {}).get('name') %} · {{ txn.raw.get('PaymentMethodRef', {}).get('name') }}{% endif %}

{% for line in txn.raw.get('Line', []) %}{% for link in line.get('LinkedTxn', []) %}

{{ link.get('TxnType') }} {{ link.get('TxnId') }}{% if line.get('LinkedTxn', []) | length == 1 %} · ${{ line.get('Amount', 0) }}{% else %} · Shared allocation{% endif %}

{% endfor %}{% endfor %}
{% endfor %}
{% endif %} diff --git a/app/templates/billing/draft.html b/app/templates/billing/draft.html index 1151b8c..bf73fd2 100644 --- a/app/templates/billing/draft.html +++ b/app/templates/billing/draft.html @@ -1,32 +1,7 @@ {% extends 'base.html' %} {% block title %}Review billing · {{ draft.customer.name }}{% endblock %} {% block content %} -Back to billing -

Review billing: {{ draft.customer.name }}

-

{{ '%04d-%02d'|format(draft.period_year,draft.period_month) }} · {{ draft.status | replace('_',' ') }} · Revision {{ draft.revision }}

-{% if request.query_params.get('message') %}

{{ request.query_params.get('message') }}

{% endif %} -{% if draft.last_error %}{% endif %} -{% if not enabled or not connected %}

Drafts can be prepared and reviewed. Connect and enable QuickBooks billing before approval.

{% endif %} -{% if not service_item or not chemical_item %}

Check service and chemical item mappings in Settings before approving billable lines.

{% endif %} -
- -
-{% for line in draft.lines %}{% if line.amount_cents == 0 %}

Charge {{ loop.index }} has a zero price. Confirm this work should not be billed before approval.

{% endif %}

{{ line.item_kind | title }} · {{ 'Taxable' if line.taxable else 'Non-taxable' }}{% if line.quantity %} · Qty {{ line.quantity }} {{ line.unit or '' }}{% endif %}{% if line.service_date %} · {{ line.service_date }}{% endif %}

{% endfor %} -{% if will_create_items %}
-

Approving will add these to QuickBooks ({{ will_create_items|length }})

-

New items only — nothing existing is changed. An item already in - QuickBooks under the same name is used instead of a second one being made.

-
    {% for key, name in will_create_items %}
  • {{ name }}
  • {% endfor %}
-
{% endif %} -

Subtotal: {{ (draft.total_cents - draft.tax_cents) | dollars }} · Estimated tax: {{ draft.tax_cents | dollars }}

Total to approve: {{ draft.total_cents | dollars }}

Save edits to recalculate this total. QuickBooks tax and totals are checked before email delivery; differences require another approval.

-{% if editable %}{% endif %} -
-{% if editable %}
{% endif %} -{% if draft.approved_at %}

Approved {{ draft.approved_at | local_date }} by user {{ draft.approved_by_id }}. The approved snapshot is retained.

{% endif %} -{% if request.state.user.can('approve_billing') %} -{% if draft.status == 'draft' %}
-{% elif draft.status in ('approved','create_retry','create_error','ready') %}
-{% elif draft.status == 'mismatch' and mirror %}

QuickBooks total requires approval

Previously approved: {{ draft.total_cents | dollars }} · QuickBooks: {{ mirror.total_cents | dollars }}

    {% for line in mirror.raw.get('Line', []) %}
  • {{ line.get('Description', line.get('DetailType', 'Line')) }} · ${{ line.get('Amount', 0) }}
  • {% endfor %}

QuickBooks tax: ${{ mirror.raw.get("TxnTaxDetail", {}).get("TotalTax", 0) }} · Due {{ mirror.due_date }} · Currency {{ mirror.raw.get("CurrencyRef", {}).get("value", "USD") }} · Recipient {{ mirror.raw.get("BillEmail", {}).get("Address", draft.email) }}

Review the official PDF and revised tax before authorizing delivery.

Review official PDF
-{% elif draft.status in ('create_unknown','recovering') %}

Invoice creation is being reconciled with QuickBooks. Another invoice will not be created while the outcome is uncertain.

{% elif draft.status == 'delivery_unknown' %}

Delivery is uncertain. Sync to check QuickBooks before taking further action; automatic email retry is blocked to avoid duplicate delivery.

{% endif %} -{% else %}

An owner or billing approver must approve delivery.

{% endif %} +{#- The full-page review: phones, tablets, no-JS and direct links. Desktop + shows the same partial beside the drafts list on /billing. -#} +{% with pane = false %}{% include 'billing/_draft_review.html' %}{% endwith %} {% endblock %} diff --git a/app/templates/billing/index.html b/app/templates/billing/index.html index 3b822d4..567c1e7 100644 --- a/app/templates/billing/index.html +++ b/app/templates/billing/index.html @@ -2,32 +2,159 @@ {% block title %}QuickBooks billing{% endblock %} {% block content %} {% import '_ui.html' as ui %} -{{ ui.page_header('Business billing', 'QuickBooks billing') }} -

Prepare charges from completed work, review and approve them here, then let QuickBooks invoice the customer and collect payment. Synced records remain available here.

-{% if request.query_params.get('message') %}

{{ request.query_params.get('message') }}

{% endif %} -
-

Connection: {{ 'Connected' if connected else 'Not connected' }} · Delivery: {{ 'Enabled after approval' if enabled else 'Disabled' }}

-

Last reconciliation: {{ last_sync or 'Not yet completed' }}. Automatic reconciliation runs every 5 minutes while QuickBooks is connected. Disconnected balances may be stale.

-{% if sync_error %}{% endif %} -
{% if request.state.user.role == 'admin' %}Connection and item mappings{% endif %}
-{% if request.state.user.role == 'admin' %} -
Billing setup -
-

Before enabling delivery, verify the company, USD currency, United States tax configuration, customer mappings, service and chemical items, and QuickBooks Payments. Turn off automatic invoice delivery in QuickBooks so only approved invoices are emailed. Initial setup and exceptional accounting corrections may require QuickBooks.

- - - -
{% endif %} +{#- The QuickBooks billing workspace (design v0.13): month stepper and Prepare + drafts, the connection bar, a five-stage pipeline that doubles as the + filter, then the drafts. -#} +{% set y, m = ym.split('-') | map('int') | list %} +{% set prev_ym = "%d-%02d"|format(y if m > 1 else y - 1, m - 1 if m > 1 else 12) %} +{% set next_ym = "%d-%02d"|format(y if m < 12 else y + 1, m + 1 if m < 12 else 1) %} +{% set stage_of = {"draft": "review", "ready": "review", "mismatch": "exceptions", "delivery_unknown": "exceptions", "create_unknown": "exceptions", + "held": "held", "approved": "qbo", "creating": "qbo", "sending": "qbo", "done": "sent", "sent": "sent", "discarding": "held"} %} +{% set stages = [("review", "Needs review", "k-acc"), ("exceptions", "Exceptions", "k-neg"), ("held", "Held", "k-warn"), ("qbo", "In QuickBooks", "k-neu"), ("sent", "Sent", "k-pos")] %} +{% set pick = request.query_params.get('stage', '') %} +
+

QuickBooks billing

Prepare charges from finished work, review and approve them, then QuickBooks invoices the customer and collects payment.

+
+ +
+
+
+{% if request.query_params.get('message') %}
{{ request.query_params.get('message') }}
{% endif %} + +
+ +
{{ 'Connected to QuickBooks' if connected else 'QuickBooks is not connected' }} + {{ 'Reconciled ' ~ last_sync if last_sync else 'Not reconciled yet' }} · checks every 5 minutes · delivery {{ 'on after approval' if enabled else 'off' }}
+
QuickBooks outstanding{{ qbo_balance_cents | dollars }}
+ +
+ {% if request.state.user.role == 'admin' %}Connection and item mappings{% endif %} +
+{% if sync_error %}{% endif %} +{% if not connected %}

Preparing drafts needs a connected QuickBooks company but does not contact customers. Disconnected balances may be stale.

{% endif %} + +{% set counts = {} %}{% set sums = {} %} +{% for d in drafts %}{% set st = stage_of.get(d.status, "review") %}{% set _ = counts.update({st: counts.get(st, 0) + 1}) %}{% set _ = sums.update({st: sums.get(st, 0) + d.total_cents}) %}{% endfor %} +{% set all_n = drafts | length %} +
+ {% for key, label, k in stages %} + + {{ label }}{{ counts.get(key, 0) }}{{ sums.get(key, 0) | dollars }} + {% endfor %} +
+ + +{#- Master/detail: on desktop the open draft's review sits beside the list + (/billing?ym=..&draft=ID). Rows are real links to the full review page, + which is what phones, tablets and no-JS get; on desktop a small script + loads the pane with HTMX instead and keeps the address bar in step. -#} +{% set sel = draft if pane is defined and pane else none %} +{% set stage_q = '&stage=' ~ pick if pick else '' %} +
+
+
{{ (stages | selectattr(0, "equalto", pick) | first)[1] if pick else "All drafts" }} · {{ ym | month_name }}{% if pick %}Show all{% endif %}
+ {% set shown = namespace(n=0) %} + {% for row in drafts if not pick or stage_of.get(row.status, "review") == pick %} + {% set shown.n = shown.n + 1 %} + {% set st = stage_of.get(row.status, "review") %} + {% set on = sel and sel.id == row.id %} + + {{ ui.av(row.customer.name) }} + {{ row.customer.name }}{{ row.email or 'Missing billing email' }} + {{ row.total_cents | dollars }}{{ ui.pill(row.status | replace('_', ' ') | capitalize, {"review": "acc", "exceptions": "neg", "held": "warn", "qbo": "neu", "sent": "pos"}[st]) }} + + {% endfor %} + {% if not shown.n %}

{{ "No drafts in this stage." if pick else "No drafts for this month. Prepare drafts to collect billable work." }}

{% endif %} +
+
+ {% if sel %}{% include 'billing/_draft_review.html' %}{% else %} +
{{ ui.icon("file", "ic24") }}

{{ "Choose a draft to review its charges, hold it or approve it." if shown.n else "Prepared drafts open here for review." }}

+ {% endif %} +
-
-
-
-

Preparing drafts requires a connected QuickBooks company but does not contact customers. Periods already reserved for billing are skipped. Drafts are snapshots; review charges before approval.

+ +{% if mapping_customers %} +
Verify existing QuickBooks customer matches +

Existing customer IDs must be verified against the connected company before billing. New customers can be synced from Admin.

+
{% for c in mapping_customers %}{{ c.name }}{% endfor %}
+
+{% endif %} + +
+

QuickBooks invoices and payments

{{ qbo_balance_cents | dollars }} outstanding
+ {% include 'billing/_invoices.html' %} +
+ +{% if request.state.user.role == 'admin' %} + -{% if mapping_customers %}
Verify existing QuickBooks customer matches

Existing customer IDs must be verified against the connected company before billing. New customers can be synced from Settings.

{% for c in mapping_customers %}{{ c.name }}{% endfor %}
{% endif %} -

Drafts and delivery

-
{% for draft in drafts %}{{ draft.customer.name }} · {{ draft.email or 'Missing billing email' }}{{ draft.total_cents | dollars }} · {{ draft.status | replace('_', ' ') }} · Review →{% else %}

No drafts for this month. Prepare drafts to collect billable work.

{% endfor %}
-

Invoices and payments

-

QuickBooks outstanding: {{ qbo_balance_cents | dollars }}

-{% include 'billing/_invoices.html' %} +{% endif %} + {% endblock %} diff --git a/app/templates/contracts/detail.html b/app/templates/contracts/detail.html index a8a5140..4810466 100644 --- a/app/templates/contracts/detail.html +++ b/app/templates/contracts/detail.html @@ -2,32 +2,33 @@ {% block title %}Contract{% endblock %} {% block content %} {% import "_ui.html" as ui %} -← All contracts -{{ ui.page_header(customer.name, pool.label ~ " — " ~ contract.season_year ~ " Service Agreement") }} - -

- {{ contract.status }} - {{ prop.address }} - {% if show_money %}· {{ value | dollars }} season value{% endif %} -

+{% set kinds = {"draft": "neu", "approved": "acc", "sent": "warn", "signed": "pos", "void": "neg"} %} +
+
+

Contracts{{ customer.name }}{{ contract.season_year }}

+

{{ contract.season_year }} service agreement

+

{{ customer.name }} · {{ pool.label }} · {{ prop.address }}{% if show_money %} · {{ value | dollars }} season value{% endif %}

+
+
{{ ui.pill(contract.status | capitalize, kinds.get(contract.status, "neu")) }}
+
{% if send_error %} -
+ {% endif %} {% if sign_error %} -
+ {% endif %} {% if conflict %} -
+ {% endif %} -
+

Season & rates

{% if contract.status == "draft" %}
@@ -81,7 +82,7 @@

Season & rates

{% endif %}
-
+

Documents & workflow

{% if contract.status == "sent" %}

Documents & workflow

-
+

History

    {% for label, at, who in timeline %} diff --git a/app/templates/contracts/index.html b/app/templates/contracts/index.html index 037ae21..7d1bd8c 100644 --- a/app/templates/contracts/index.html +++ b/app/templates/contracts/index.html @@ -2,110 +2,88 @@ {% block title %}Contracts{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{{ ui.page_header("Season register", "Contracts") }} - -
    - - - - {% if status %}{% endif %} - - -
    - Renew season - - {{ ui.icon("plus", "h-4 w-4") }}New contract +{% set kinds = {"draft": "neu", "approved": "acc", "sent": "warn", "signed": "pos", "void": "neg"} %} +{% set qs_base = "season=" ~ season ~ ("&q=" ~ (q | urlencode) if q else "") %} +
    +

    Contracts

    Season service agreements, sent for e-signing. {{ counts.values() | sum }} for {{ season }}.

    + -
    +
-{% set qs_base = "season=" ~ season ~ ("&q=" ~ (q | urlencode) if q else "") %} - +
+
+
+
+ {% if status %}{% endif %} + +
+ -{% if show_money %} -
-
-

Signed value

-

{{ totals.signed | dollars }}

-
-
-

In pipeline

-

{{ totals.pipeline | dollars }}

+
+
+ {% if rows %} +
+
+ {% if show_money %}{% endif %} + + {% for r in rows %} + {% set c = r.c %} + + + + + {% if show_money %}{% endif %} + + + {% endfor %} + +
CustomerProperty and poolStateSeason valueActivity
{{ c.pool.property.customer.name }}{{ c.pool.property.address or c.pool.property.label }} · {{ c.pool.label }}{{ ui.pill(c.status | capitalize, kinds.get(c.status, "neu")) }}{{ r.value | dollars }} + {% if c.status == "sent" and r.days_out is not none %}sent {{ r.days_out }}d ago + {% elif c.status == "signed" %}signed {{ c.signed_at | local_date | short_date }} + {% elif c.status == "approved" %}approved {{ c.approved_at | local_date | short_date }} + {% else %}created {{ c.created_at | local_date | short_date }}{% endif %} +
+
+ {{ ui.pager(page, total_pages, total, "/contracts", qs_base ~ ("&status=" ~ status if status else "")) }} + {% else %} +

No {{ status ~ " " if status }}contracts for {{ season }}{{ " matching “" ~ q ~ "”" if q }}

+

Start a new contract

+ {% endif %}
-
-{% endif %} - -{% if stale_sent or uncovered %} -
-

Needs attention

- -
-{% endif %} - -{% if rows %} -
- - - - - - - {% if show_money %}{% endif %} - - - - - {% for r in rows %} - {% set c = r.c %} - - - - - {% if show_money %}{% endif %} - - - {% endfor %} - -
CustomerProperty / poolStatusSeason valueActivity
{{ c.pool.property.customer.name }}{{ c.pool.property.address or c.pool.property.label }} · {{ c.pool.label }}{{ c.status }}{{ r.value | dollars }} - {% if c.status == "sent" and r.days_out is not none %}sent {{ r.days_out }}d ago - {% elif c.status == "signed" %}signed {{ c.signed_at | local_date | short_date }} - {% elif c.status == "approved" %}approved {{ c.approved_at | local_date | short_date }} - {% else %}created {{ c.created_at | local_date | short_date }}{% endif %} -
-
-{{ ui.pager(page, total_pages, total, "/contracts", qs_base ~ ("&status=" ~ status if status else "")) }} -{% else %} -
-

No {{ status ~ " " if status }}contracts for {{ season }}{{ " matching “" ~ q ~ "”" if q }}.

- - {{ ui.icon("plus", "h-4 w-4") }}New contract +

How a contract moves

+
    +
  1. 1
    Draft

    Prices from the rate tiers; edit before approving.

  2. +
  3. 2
    Approve and send

    The customer gets a signing link that expires.

  4. +
  5. 3
    Signed

    The signed copy and certificate are emailed automatically.

  6. +
+
+
-{% endif %} {% endblock %} diff --git a/app/templates/csv/import.html b/app/templates/csv/import.html index ef66942..f1c578c 100644 --- a/app/templates/csv/import.html +++ b/app/templates/csv/import.html @@ -2,13 +2,20 @@ {% block title %}Import customers{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{{ ui.page_header("Customer files", "Import CSV") }} -{% if error %}

{{ error }}

{% endif %} -
-

One row per property. Columns are mapped on the next step — any spreadsheet export works. 5 MB max.

- {% call ui.upload("Choose CSV file", "document") %} +{% set import_steps = ["Upload", "Map columns", "Dry run", "Done"] %} +
+

CustomersImport

+

Import customers

+

One row per property. Columns are matched on the next step, so any spreadsheet export works.

+
+{{ ui.flow_steps(import_steps, 1) }} +{% if error %}{% endif %} + +

Choose a CSV file

+

Up to 5 MB. Nothing is saved until you confirm the dry run.

+ {% call ui.upload("Choose CSV file", "file") %} {% endcall %} - +
Cancel
{% endblock %} diff --git a/app/templates/csv/mapping.html b/app/templates/csv/mapping.html index c689834..d758640 100644 --- a/app/templates/csv/mapping.html +++ b/app/templates/csv/mapping.html @@ -2,19 +2,25 @@ {% block title %}Map columns{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{{ ui.page_header("Import CSV", "Map columns") }} -

{{ count }} rows found. Match your spreadsheet's columns to the app's fields — guessed matches are pre-selected.

-
- {% for t in targets %} - - {% endfor %} - +{% import "_form.html" as f %} +{% set import_steps = ["Upload", "Map columns", "Dry run", "Done"] %} +
+

CustomersImportMap columns

+

Map columns

+

{{ count }} rows found. Match your spreadsheet's columns to the app's fields — guessed matches are pre-selected.

+
+{{ ui.flow_steps(import_steps, 2) }} + + {% call f.group("Columns", "Leave a field on “skip” when your file has no column for it.") %} + {% for t in targets %} + {% call f.row(t.replace("_", " ") | capitalize, "", "map-" ~ t) %} + + {% endcall %} + {% endfor %} + {% endcall %} + {{ f.savebar("Preview import", cancel="/customers") }}
{% endblock %} diff --git a/app/templates/csv/preview.html b/app/templates/csv/preview.html index 8d359ee..bfa2825 100644 --- a/app/templates/csv/preview.html +++ b/app/templates/csv/preview.html @@ -2,22 +2,31 @@ {% block title %}Preview import{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{{ ui.page_header("Import CSV", "Dry run") }} -

{{ ok }} ok · {{ skips }} skipped · {{ errors }} errors

-
- {% for n, row, status, why in results %} -
- {{ n }} - {{ row[0] if row else "" }} - {{ status }}{{ " — " + why if why }} -
- {% endfor %} +{% set import_steps = ["Upload", "Map columns", "Dry run", "Done"] %} +
+

CustomersImportDry run

+

Dry run

+

Nothing has been saved yet. The import runs all-or-nothing.

+
+{{ ui.flow_steps(import_steps, 3) }} +
+
Ready
{{ ok }}
ok
+
Skipped
{{ skips }}
duplicates or blank
+
Errors
{{ errors }}
{{ "fix and re-upload" if errors else "none" }}
+
+
    + {% for n, row, status, why in results %} +
  • {{ n }}{{ row[0] if row else "" }}{{ status }}{{ " — " + why if why }}
  • + {% endfor %} +
+
{% if errors %} -

Fix the error rows in your spreadsheet and re-upload — the import runs all-or-nothing.

+ {% endif %} -
+ {% for t, h in mapping.items() %}{% endfor %} - + + Start over
{% endblock %} diff --git a/app/templates/csv/result.html b/app/templates/csv/result.html index f5749c6..37b3dff 100644 --- a/app/templates/csv/result.html +++ b/app/templates/csv/result.html @@ -2,16 +2,21 @@ {% block title %}Import result{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{{ ui.page_header("Import CSV", "Done" if not errors else "Nothing imported") }} +{% set import_steps = ["Upload", "Map columns", "Dry run", "Done"] %} +
+

CustomersImport

+

{{ "Imported" if not errors else "Nothing imported" }}

+
+{{ ui.flow_steps(import_steps, 4) }} {% if errors %} -
-

Errors — batch aborted, no rows written:

- {% for n, why in errors %}

row {{ n }}: {{ why }}

{% endfor %} -
+

Errors — batch aborted, no rows written

+
    {% for n, why in errors %}
  • row {{ n }}{{ why }}
  • {% endfor %}
+
{% else %} -
-

{{ created }} created · {{ skipped }} skipped (duplicates)

+
+
Created
{{ created }}
+
Skipped
{{ skipped }}
duplicates
{% endif %} -Back to customers +
Back to customers{% if errors %}Try again{% endif %}
{% endblock %} diff --git a/app/templates/customers/detail.html b/app/templates/customers/detail.html index 244f572..fb35828 100644 --- a/app/templates/customers/detail.html +++ b/app/templates/customers/detail.html @@ -2,244 +2,331 @@ {% block title %}{{ c.name }}{% endblock %} {% block content %} {% import "_ui.html" as ui %} -{% if request.state.user.role == "admin" %}Customer portal{% endif %} +{% set is_admin = request.state.user.role == "admin" %} +{% set days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] %} +{% set freq = {"weekly": "Weekly", "biweekly": "Every 2 weeks", "every4weeks": "Every 4 weeks", "none": "No regular service"} %} -
- {{ ui.page_header("Customer file", c.name) }} - Edit -
- -
- - - -
+
+
+ +
+

Customers{{ c.name }}

+

{{ c.name }}

+

{{ main.address if main and main.address else (c.email or c.phone or "No address yet") }}

+
+
+
+ {% if c.active %}Active{% else %}Inactive{% endif %} + {% if c.phone %}{{ ui.icon("phone") }}Call{% endif %} + {% if c.email %}{{ ui.icon("mail") }}Email{% endif %} + {% if can_manage %}{{ ui.icon("edit") }}Edit{% endif %} +
+
-
-{% if qbo_invoices %}

QuickBooks billing · {{ qbo_balance_cents | dollars }} outstanding

{% include "billing/_invoices.html" %}
{% endif %} -

- {% if c.phone %}{{ ui.icon("phone", "h-4 w-4") }}{{ c.phone }}{% endif %} - {% if c.email %}{{ c.email }}{% endif %} - {% if show_money and lifetime_cents is not none %}Lifetime {{ lifetime_cents | dollars }}{% endif %} -

{% if not c.active %} -
- This customer is inactive. - {% if can_manage %} -
- -
- {% endif %} + {% endif %} -{% if c.notes %}

{{ c.notes }}

{% endif %} -

Tags

-
-
- {% for t in c.tags %} - - {{ t }} - {% if can_manage %} -
- - -
- {% endif %} -
- {% else %}No tags yet.{% endfor %} -
- {% if can_manage %} -
- - -
+
+
Service
{% if main %}{{ freq.get(main.frequency, main.frequency) }}{% if main.frequency != "none" %} · {{ days[main.weekday % 7] }}{% endif %}{% else %}—{% endif %}
+
Pool
{{ (main | pool_summary) if main else "—" }}
+ {% if show_money %} +
Rate
{{ (rates[main.id] | dollars) ~ " a visit" if main else "—" }}
+
Balance
{{ balance_cents | dollars }}
+ {% if lifetime_cents is not none %}
Lifetime
{{ lifetime_cents | dollars }}
{% endif %} {% endif %} +
Customer since
{{ c.created_at.strftime("%b %Y") if c.created_at else "—" }}
+
+ +
+ + + + + {% if show_money or qbo_invoices %}{% endif %} + + + + {% if is_admin %}Portal{% endif %}
-

Properties

-
- {% for p in props %} -
-
-
{{ p.label }}{% if not p.active %} Inactive{% endif %}
-
{% if p.address %}{{ p.address }}{% else %}{{ p.city }}{% if p.state %}, {{ p.state }}{% endif %}{% endif %}
-
- {{ p.frequency }} - {% if show_money %}{{ rates[p.id] | dollars }}/visit{% endif %} -
+{# ======================= OVERVIEW ======================= #} +
+
+
+

Contact and property

+
+
Phone
{% if c.phone %}{{ c.phone }}{% else %}—{% endif %}
+
Email
{% if c.email %}{{ c.email }}{% if c.notify_email %} Gets visit emails{% endif %}{% else %}—{% endif %}
+ {% for p in props if p.active %} +
{{ p.label }}
{{ p.address or p.city or "—" }}{% if p.id in active_holds %} On hold until {{ active_holds[p.id].resume_date | short_date if active_holds[p.id].resume_date else "further notice" }}{% endif %}
+ {% if p.gate_code %}
Gate code
On file · show{{ p.gate_code }}
{% endif %} + {% if p.dog_warning %}
Dog
{{ p.dog_note or "On property" }}
{% endif %} + {% endfor %} +
Notes
{{ c.notes or "—" }}
+
Tags
+
+ {% for t in c.tags %} + {{ t }}{% if can_manage %}
{% endif %}
+ {% else %}None{% endfor %} +
+ {% if can_manage %} +
+ + + +
+ {% endif %} +
+
+
+
+
+

Coming up

+
    +
  • Next visit{% if next_visit %}{{ next_visit.strftime("%A, %b %-d") }}{% if main.assigned_tech %} · {{ main.assigned_tech.name }}{% endif %}{% elif main and main.id in active_holds %}On hold{% else %}None scheduled{% endif %}
  • + {% for j in jobs %} +
  • {{ j.title }}{{ j.status | capitalize }}{% if j.scheduled_date %} · {{ j.scheduled_date | short_date }}{% endif %}
    {% if j.priority == "high" %}High{% endif %}
  • + {% endfor %} +
+
{{ ui.icon("plus") }}New job{% if request.state.user.can("manage_customers") %}{{ ui.icon("plus") }}New quote{% endif %}
+
+ {% if show_money %} +
+

Balance

+

{{ balance_cents | dollars }}

+

{% set open_inv = invoices | selectattr("balance_cents") | list %}{% if open_inv %}{{ open_inv|length }} open invoice{{ "s" if open_inv|length != 1 }}{% else %}Nothing owed{% endif %}

+
+ {% endif %} + {% if qbo_invoices %} +

QuickBooks

{{ qbo_balance_cents | dollars }} outstanding
{% include "billing/_invoices.html" %}
+ {% endif %} +
+

Recent activity

+
    + {% for e in timeline[:8] %} +
  • {{ e.title }}{% if e.detail %}{{ e.detail }} · {% endif %}{{ (e.at | local_date | short_date) if e.date_only else (e.at | stamp) }}
    {% if e.money is not none %}{{ e.money | dollars }}{% endif %}
  • + {% else %} +
  • No activity yet. Visits, jobs, photos and notes appear here once service begins.
  • + {% endfor %} +
+
- Edit - Water
- {% else %} -

No properties yet.

- {% endfor %} -
-