Compare commits

...

4 Commits

Author SHA1 Message Date
188bef2ece Budget setting and all dollar to chf
All checks were successful
Build and Push / build (push) Successful in 1m28s
2026-05-02 23:16:14 +02:00
57258bca92 Budget setting and all dollar to chf
All checks were successful
Build and Push / build (push) Successful in 1m31s
2026-05-02 22:59:51 +02:00
c7ab4c6b4e Budget setting and all dollar to chf
All checks were successful
Build and Push / build (push) Successful in 1m28s
2026-05-02 22:33:35 +02:00
b77dd04b15 EMail templates rework
All checks were successful
Build and Push / build (push) Successful in 1m26s
2026-05-02 22:03:19 +02:00
4 changed files with 410 additions and 15 deletions

View File

@@ -43,6 +43,19 @@ export default async function TenantDetailPage({
// the same page but with edit controls hidden / fields read-only.
const canEdit = canMutate(user);
// TEMP DIAGNOSTIC for budget-card non-rendering. Logs the prop
// values that flow into UsageDisplay so we can see which one is
// turning the editable variant off. Remove once cause is found.
console.log(
"[tenant page] budget edit props",
JSON.stringify({
tenantName: name,
canEdit,
isPlatform: user.isPlatform,
roles: user.roles,
})
);
// Bug 31: customer-side cancel/resume control. Same gate as canEdit
// — only owners (or platform staff) may toggle the subscription.
// The current state comes from spec.suspend on the CR.
@@ -199,7 +212,7 @@ export default async function TenantDetailPage({
<h2 className="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">
{t("usage")}
</h2>
<UsageDisplay tenant={name} />
<UsageDisplay tenant={name} canEditBudget={canEdit} />
</section>
{/* Packages */}

View File

@@ -0,0 +1,283 @@
"use client";
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import { Modal } from "@/components/ui/modal";
/**
* Format remaining budget as CHF. Same adaptive precision rule as the
* usage display: 2 decimals for amounts ≥ 1, 4 for smaller values
* so per-request residuals don't round to zero. The currency comes
* from LiteLLM via our CHF pricing config — see chf() in
* usage-display.tsx for the full reasoning.
*/
function formatRemaining(n: number): string {
const decimals = Math.abs(n) >= 1 ? 2 : 4;
return `CHF ${n.toFixed(decimals)}`;
}
interface Props {
tenantName: string;
maxBudget: number | null;
remaining: number | null;
budgetDuration: string | null;
/** Called after a successful save so the parent re-fetches usage. */
onSaved: () => void;
}
/**
* Clickable Budget StatCard with edit modal (Feature 7).
*
* The display side mirrors the read-only StatCard layout exactly so
* the grid stays uniform. The "click to edit" hint is implicit via
* hover state — a "Set" / "Edit" link in the corner would be louder
* but adds clutter on a tile that's already busy. Customers who
* mouse over discover it.
*
* Important UX note shown in the modal: the budget is org-scoped,
* not per-tenant. All tenants in the same ZITADEL org share the
* underlying LiteLLM team. Without that callout, a customer with
* multiple tenants might think they're capping just one.
*/
export function BudgetEditableCard({
tenantName,
maxBudget,
remaining,
budgetDuration,
onSaved,
}: Props) {
const t = useTranslations("usage");
const tCommon = useTranslations("common");
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
// Form state. Mode = "unlimited" | "capped". When unlimited, the
// duration dropdown is hidden because LiteLLM's reset cadence is
// meaningless without a cap.
const [mode, setMode] = useState<"unlimited" | "capped">(
maxBudget !== null ? "capped" : "unlimited"
);
const [budgetInput, setBudgetInput] = useState<string>(
maxBudget !== null ? String(maxBudget) : ""
);
const [duration, setDuration] = useState<"30d" | "1mo" | "1y">(
(budgetDuration === "30d" ||
budgetDuration === "1mo" ||
budgetDuration === "1y")
? budgetDuration
: "1mo"
);
// Reset form when modal opens — picks up any change made elsewhere
// (e.g. another browser tab) since this card was last re-rendered.
useEffect(() => {
if (open) {
setMode(maxBudget !== null ? "capped" : "unlimited");
setBudgetInput(maxBudget !== null ? String(maxBudget) : "");
setDuration(
(budgetDuration === "30d" ||
budgetDuration === "1mo" ||
budgetDuration === "1y")
? budgetDuration
: "1mo"
);
setError("");
}
}, [open, maxBudget, budgetDuration]);
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setSaving(true);
setError("");
try {
let body: { maxBudget: number | null; budgetDuration: string | null };
if (mode === "unlimited") {
body = { maxBudget: null, budgetDuration: null };
} else {
const parsed = parseFloat(budgetInput);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new Error(t("budgetInvalid"));
}
body = { maxBudget: parsed, budgetDuration: duration };
}
const res = await fetch(
`/api/tenants/${encodeURIComponent(tenantName)}/budget`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}
);
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || t("budgetSaveFailed"));
}
setOpen(false);
onSaved();
} catch (e: any) {
setError(e.message);
} finally {
setSaving(false);
}
};
return (
<>
<button
type="button"
onClick={() => {
// Temporary debug aid — if clicks reach the handler we'll
// see this in the browser console. Remove once confirmed.
console.log("[BudgetEditableCard] open clicked");
setOpen(true);
}}
className="bg-surface-1 border border-accent/40 rounded-xl p-4 text-left hover:border-accent transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-accent/40 group block w-full"
>
<div className="text-xs text-text-muted mb-1 flex items-center justify-between">
<span>{t("budget")}</span>
<span className="text-[10px] text-accent inline-flex items-center gap-1">
{/* Pencil icon — unambiguous "this is editable" affordance.
Visible at all times (was hover-only before, which on
touch devices and at-a-glance scanning gave no
indication the card was clickable). */}
<svg
xmlns="http://www.w3.org/2000/svg"
width="11"
height="11"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
</svg>
{t("budgetEdit")}
</span>
</div>
<div className="text-lg font-semibold text-text-primary tabular-nums">
{remaining !== null ? formatRemaining(remaining) : t("noLimit")}
</div>
</button>
<Modal open={open} onClose={() => setOpen(false)} ariaLabel={t("budgetEditTitle")}>
<h3 className="font-display text-lg font-semibold text-text-primary mb-2">
{t("budgetEditTitle")}
</h3>
<p className="text-sm text-text-secondary mb-4">
{t("budgetEditDescription")}
</p>
<div className="text-xs text-amber-400 bg-amber-400/10 border border-amber-400/20 rounded-lg px-3 py-2 mb-5">
{t("budgetOrgScopeWarning")}
</div>
<form onSubmit={onSubmit} className="space-y-4">
{/* Mode toggle: unlimited vs capped. Two radios are
clearer than a single "max" field where 0 means
unlimited (which would conflict with our zod
validation requiring positive). */}
<div className="space-y-2">
<label className="flex items-start gap-2 text-sm text-text-primary cursor-pointer">
<input
type="radio"
name="budget-mode"
checked={mode === "unlimited"}
onChange={() => setMode("unlimited")}
className="mt-1"
/>
<span>
<span className="font-medium">{t("budgetModeUnlimited")}</span>
<span className="block text-xs text-text-muted">
{t("budgetModeUnlimitedDescription")}
</span>
</span>
</label>
<label className="flex items-start gap-2 text-sm text-text-primary cursor-pointer">
<input
type="radio"
name="budget-mode"
checked={mode === "capped"}
onChange={() => setMode("capped")}
className="mt-1"
/>
<span>
<span className="font-medium">{t("budgetModeCapped")}</span>
<span className="block text-xs text-text-muted">
{t("budgetModeCappedDescription")}
</span>
</span>
</label>
</div>
{mode === "capped" && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
<div>
<label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
{t("budgetAmount")} <span className="text-red-400">*</span>
</label>
<div className="relative">
<span className="absolute left-3 top-2 text-sm text-text-muted font-medium">
CHF
</span>
<input
type="number"
min="0.01"
max="1000000"
step="0.01"
required
value={budgetInput}
onChange={(e) => setBudgetInput(e.target.value)}
className="w-full pl-12 pr-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
/>
</div>
</div>
<div>
<label className="block text-xs uppercase tracking-wider text-text-muted mb-1">
{t("budgetResetCadence")}
</label>
<select
value={duration}
onChange={(e) =>
setDuration(e.target.value as "30d" | "1mo" | "1y")
}
className="w-full px-3 py-2 rounded-lg border border-border bg-surface-2 text-text-primary text-sm focus:outline-none focus:border-text-secondary"
>
<option value="30d">{t("budgetCadence_30d")}</option>
<option value="1mo">{t("budgetCadence_1mo")}</option>
<option value="1y">{t("budgetCadence_1y")}</option>
</select>
</div>
</div>
)}
{error && (
<div className="text-xs text-red-400 bg-red-400/10 border border-red-400/20 rounded-lg px-3 py-2">
{error}
</div>
)}
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={() => setOpen(false)}
disabled={saving}
className="text-sm px-4 py-2 rounded-lg border border-border text-text-secondary hover:text-text-primary transition-colors"
>
{tCommon("cancel")}
</button>
<button
type="submit"
disabled={saving}
className="text-sm px-4 py-2 rounded-lg bg-accent text-white hover:bg-accent/90 transition-colors disabled:opacity-50"
>
{saving ? tCommon("loading") : tCommon("save")}
</button>
</div>
</form>
</Modal>
</>
);
}

View File

@@ -2,6 +2,7 @@
import { useTranslations } from "next-intl";
import { useEffect, useState, useCallback } from "react";
import { BudgetEditableCard } from "@/components/dashboard/budget-editable-card";
interface DailyUsage {
date: string;
@@ -18,7 +19,17 @@ interface UsageData {
totalSpend: number;
requestCount: number;
};
budget: { maxBudget: number | null; spend: number; remaining: number | null };
budget: {
maxBudget: number | null;
spend: number;
remaining: number | null;
/**
* Feature 7: budget reset cadence as stored on LiteLLM.
* Strings: "30d" / "1mo" / "1y" / null (no reset). UI maps these
* to user-friendly labels.
*/
budgetDuration: string | null;
};
rateLimits: { rpm: number | null; tpm: number | null };
dailyUsage: DailyUsage[];
}
@@ -29,8 +40,31 @@ function fmt(n: number): string {
return n.toString();
}
function usd(n: number): string {
return `$${n.toFixed(4)}`;
/**
* Format a numeric amount as CHF.
*
* Note on currency labelling: LiteLLM stores raw cost numbers it
* receives from upstream (OpenAI/Anthropic), which originate as USD.
* The PieCed pricing config (Slice 5) converts those numbers to
* CHF before LiteLLM persists them, so the values flowing through
* here are already CHF amounts. We label them as such in the UI;
* "USD" or "$" anywhere in the customer-facing experience would
* be misleading.
*
* Precision is adaptive:
* - Amounts ≥ 1 CHF: 2 decimals (typical money formatting).
* - Smaller amounts: 4 decimals — per-request inference costs are
* routinely sub-rappen, and rounding to 2dp
* would render CHF 0.0042 as "CHF 0.00",
* which obscures real costs from customers
* looking at the daily breakdown.
*
* This is a customer-facing display helper; for storage and
* comparisons keep using the raw number.
*/
function chf(n: number): string {
const decimals = Math.abs(n) >= 1 ? 2 : 4;
return `CHF ${n.toFixed(decimals)}`;
}
function getCurrentMonth(): string {
@@ -69,7 +103,7 @@ function UsageChart({ data }: { data: DailyUsage[] }) {
const x = i * (barW + 2);
return (
<g key={d.date}>
<title>{d.date}: {fmt(d.inputTokens)} in / {fmt(d.outputTokens)} out {usd(d.spend)}</title>
<title>{d.date}: {fmt(d.inputTokens)} in / {fmt(d.outputTokens)} out {chf(d.spend)}</title>
<rect x={x} y={h - totalH} width={barW} height={totalH - inputH} rx={1} fill="var(--color-accent)" opacity={0.3} />
<rect x={x} y={h - inputH} width={barW} height={inputH} rx={1} fill="var(--color-accent)" opacity={0.7} />
{i % 7 === 0 && (
@@ -113,10 +147,18 @@ export function UsageDisplay({
tenant,
teamId,
keyAlias,
canEditBudget = false,
}: {
tenant?: string | null;
teamId?: string | null;
keyAlias?: string | null;
/**
* Feature 7: when true, the Budget StatCard becomes clickable and
* opens the budget editor. Off by default — owners and platform
* admins get it on; `user` role customers see the budget read-only.
* Server component decides this via canMutate(user).
*/
canEditBudget?: boolean;
}) {
const t = useTranslations("usage");
const [month, setMonth] = useState(getCurrentMonth);
@@ -185,11 +227,25 @@ export function UsageDisplay({
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<StatCard label={t("inputTokens")} value={fmt(data.currentPeriod.inputTokens)} />
<StatCard label={t("outputTokens")} value={fmt(data.currentPeriod.outputTokens)} />
<StatCard label={t("totalSpend")} value={usd(data.currentPeriod.totalSpend)} accent />
<StatCard
label={t("budget")}
value={data.budget.remaining !== null ? usd(data.budget.remaining) : t("noLimit")}
/>
<StatCard label={t("totalSpend")} value={chf(data.currentPeriod.totalSpend)} accent />
{canEditBudget && tenant ? (
<BudgetEditableCard
tenantName={tenant}
maxBudget={data.budget.maxBudget}
remaining={data.budget.remaining}
budgetDuration={data.budget.budgetDuration}
onSaved={fetchUsage}
/>
) : (
<StatCard
label={t("budget")}
value={
data.budget.remaining !== null
? chf(data.budget.remaining)
: t("noLimit")
}
/>
)}
</div>
<div className="bg-surface-1 border border-border rounded-xl p-5">

View File

@@ -11,6 +11,17 @@
* SMTP_PASS — App Password
* SMTP_FROM — e.g. "PieCed <noreply@pieced.ch>"
* ADMIN_NOTIFICATION_EMAIL — e.g. admin@pieced.ch (optional)
* SUPPORT_CONTACT_EMAIL — e.g. support@pieced.ch (optional)
* Customer-facing address for "have
* questions?" follow-ups in
* transactional emails. The from
* address itself (SMTP_USER) is
* typically a noreply mailbox, so we
* don't tell customers to "reply to
* this email" — instead we point them
* at this monitored address. If
* unset, the contact-prompt line is
* simply omitted from emails.
*/
import nodemailer from "nodemailer";
@@ -42,6 +53,12 @@ function getFrom(): string {
);
}
/** Returns the customer-facing support email address, or null if unset. */
function getSupportContactEmail(): string | null {
const v = process.env.SUPPORT_CONTACT_EMAIL?.trim();
return v && v.length > 0 ? v : null;
}
/**
* Escape HTML entities to prevent injection in HTML emails.
*/
@@ -125,6 +142,21 @@ export async function sendRejectionEmail(
</div>`
: "";
const supportEmail = getSupportContactEmail();
// The customer here is rejected pre-onboarding — they don't yet
// have a portal account, so we can't send them to /support.
// Instead point at the configured support address (if set).
// If unset (e.g. early pilot before a support inbox exists), we
// omit the follow-up line entirely rather than promise something
// that goes nowhere — telling the customer to "reply to this
// email" would be misleading because we send from a noreply box.
const contactLineText = supportEmail
? `If you have questions or would like to discuss this further, please contact us at ${supportEmail}.`
: "";
const contactLineHtml = supportEmail
? `<p>If you have questions or would like to discuss this further, please contact us at <a href="mailto:${escapeHtml(supportEmail)}" style="color: #3b82f6;">${escapeHtml(supportEmail)}</a>.</p>`
: "";
await getTransporter().sendMail({
from: getFrom(),
to,
@@ -134,18 +166,20 @@ export async function sendRejectionEmail(
"",
`Thank you for your interest in PieCed IT. Unfortunately, we were unable to approve your onboarding request for ${companyName} at this time.`,
notesBlock,
"If you have questions or would like to discuss this further, please reply to this email.",
contactLineText,
"",
"Best regards,",
"PieCed IT",
].join("\n"),
]
.filter((s) => s !== "")
.join("\n"),
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 560px; margin: 0 auto; color: #e0e0e0; background: #1a1a1a; padding: 32px; border-radius: 12px;">
<h2 style="color: #ffffff; margin-top: 0;">Update on your onboarding request</h2>
<p>Hello ${safeName},</p>
<p>Thank you for your interest in PieCed IT. Unfortunately, we were unable to approve your onboarding request for <strong>${safeCompany}</strong> at this time.</p>
${notesHtml}
<p>If you have questions or would like to discuss this further, please reply to this email.</p>
${contactLineHtml}
<hr style="border: none; border-top: 1px solid #333; margin: 24px 0;" />
<p style="color: #666; font-size: 12px;">PieCed IT — Hosted on-premises in Switzerland</p>
</div>
@@ -237,6 +271,15 @@ export async function sendResumeRejectionEmail(
</div>`
: "";
// The customer has portal access (their tenant exists, they
// just had a resume request rejected), so direct them to the
// support ticket system for follow-up. We never tell them to
// "reply to this email" because the from address is a noreply
// mailbox.
const contactLineText =
"If you have questions, open a support ticket at https://app.pieced.ch/support.";
const contactLineHtml = `<p>If you have questions, <a href="https://app.pieced.ch/support" style="color: #3b82f6;">open a support ticket</a>.</p>`;
await getTransporter().sendMail({
from: getFrom(),
to,
@@ -248,7 +291,7 @@ export async function sendResumeRejectionEmail(
notesBlock,
"Your tenant remains suspended. As a reminder, your data is preserved for 60 days from the original cancellation date, after which it will be permanently deleted. You can submit a new reactivation request at any time before then.",
"",
"If you have questions, please reply to this email.",
contactLineText,
"",
"Best regards,",
"PieCed IT",
@@ -260,7 +303,7 @@ export async function sendResumeRejectionEmail(
<p>Thank you for your reactivation request for <strong>${safeCompany}</strong>. Unfortunately, we were unable to approve it at this time.</p>
${notesHtml}
<p>Your tenant remains suspended. As a reminder, your data is preserved for 60 days from the original cancellation date, after which it will be permanently deleted. You can submit a new reactivation request at any time before then.</p>
<p>If you have questions, please reply to this email.</p>
${contactLineHtml}
<hr style="border: none; border-top: 1px solid #333; margin: 24px 0;" />
<p style="color: #666; font-size: 12px;">PieCed IT — Hosted on-premises in Switzerland</p>
</div>