Add note to reactivation request
All checks were successful
Build and Push / build (push) Successful in 1m28s
All checks were successful
Build and Push / build (push) Successful in 1m28s
This commit is contained in:
@@ -272,6 +272,8 @@ export default async function TenantDetailPage({
|
||||
? {
|
||||
id: pendingResumeRequest.id,
|
||||
createdAt: pendingResumeRequest.createdAt,
|
||||
customerNotes:
|
||||
pendingResumeRequest.customerNotes ?? null,
|
||||
}
|
||||
: null
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { getSessionUser, canMutate } from "@/lib/session";
|
||||
import { getTenant, setTenantAnnotation } from "@/lib/k8s";
|
||||
import { canUserSeeTenant } from "@/lib/visibility";
|
||||
@@ -7,8 +8,26 @@ import {
|
||||
getPendingResumeRequestForTenant,
|
||||
getTenantRequestByTenantName,
|
||||
} from "@/lib/db";
|
||||
import { sendResumeRequestAdminNotificationEmail } from "@/lib/email";
|
||||
import { safeError } from "@/lib/errors";
|
||||
|
||||
/**
|
||||
* Body schema. Both fields optional; the customer can submit a
|
||||
* resume request with no body at all (the JS client sends `{}`),
|
||||
* or with a note explaining their reactivation rationale.
|
||||
*
|
||||
* Length cap mirrors `billing_notes` (2000 chars) — same lower
|
||||
* bound for "free-form text we don't want abused".
|
||||
*/
|
||||
const bodySchema = z.object({
|
||||
customerNotes: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(2000)
|
||||
.optional()
|
||||
.transform((v) => (v && v.length > 0 ? v : undefined)),
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/tenants/[name]/resume-request
|
||||
*
|
||||
@@ -82,6 +101,18 @@ export async function POST(
|
||||
);
|
||||
}
|
||||
|
||||
// Body is optional — the customer can submit a resume request
|
||||
// with no payload at all, or attach a free-form note.
|
||||
const rawBody = await req.json().catch(() => ({}));
|
||||
const parsed = bodySchema.safeParse(rawBody ?? {});
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid input", details: parsed.error.flatten() },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const customerNotes = parsed.data.customerNotes;
|
||||
|
||||
// Already a pending request? Don't duplicate.
|
||||
const existing = await getPendingResumeRequestForTenant(name);
|
||||
if (existing) {
|
||||
@@ -110,6 +141,7 @@ export async function POST(
|
||||
contactEmail: user.email,
|
||||
companyName: provision?.companyName ?? tenant.spec.displayName ?? name,
|
||||
agentName: provision?.agentName ?? "Assistant",
|
||||
customerNotes,
|
||||
});
|
||||
|
||||
// Stamp the annotation so the operator pauses its TTL. If this
|
||||
@@ -128,6 +160,20 @@ export async function POST(
|
||||
);
|
||||
}
|
||||
|
||||
// Notify admin distribution. Fire-and-log: failure to email
|
||||
// doesn't roll back the request creation. The customer's note
|
||||
// (if any) is included so admin can triage from the email
|
||||
// without opening the queue.
|
||||
sendResumeRequestAdminNotificationEmail({
|
||||
tenantName: name,
|
||||
companyName: resumeRequest.companyName,
|
||||
contactName: resumeRequest.contactName,
|
||||
contactEmail: resumeRequest.contactEmail,
|
||||
customerNotes,
|
||||
}).catch((e) =>
|
||||
console.error("resume admin notification email failed:", e)
|
||||
);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
message: "Resume request submitted. An admin will review shortly.",
|
||||
|
||||
@@ -384,6 +384,18 @@ export function AdminPanel({ initialTenants }: AdminPanelProps) {
|
||||
{req.tenantName}
|
||||
</div>
|
||||
)}
|
||||
{/* Feature 6: customer's reactivation rationale,
|
||||
shown inline so admin can triage without
|
||||
opening a detail view. Truncated for
|
||||
queue density; full content on hover. */}
|
||||
{req.requestType === "resume" && req.customerNotes && (
|
||||
<div
|
||||
className="text-text-secondary text-xs mt-1 max-w-[280px] line-clamp-2 whitespace-pre-wrap"
|
||||
title={req.customerNotes}
|
||||
>
|
||||
{req.customerNotes}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="text-text-primary text-sm">
|
||||
|
||||
@@ -24,11 +24,16 @@ interface Props {
|
||||
isPlatform: boolean;
|
||||
/**
|
||||
* If a resume request is currently pending for this tenant, its
|
||||
* id and submitted-at. The component renders an info card with
|
||||
* a cancel-request button instead of the request-reactivation
|
||||
* button. Only meaningful when `suspended === true`.
|
||||
* id, when it was submitted, and the customer's optional note.
|
||||
* The component renders an info card with a cancel-request button
|
||||
* instead of the request-reactivation button. Only meaningful when
|
||||
* `suspended === true`.
|
||||
*/
|
||||
pendingResumeRequest: { id: string; createdAt: string } | null;
|
||||
pendingResumeRequest: {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
customerNotes: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,6 +70,10 @@ export function SubscriptionToggle({
|
||||
const [confirmResumeOpen, setConfirmResumeOpen] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
// Feature 6: customer's free-form note attached to the resume
|
||||
// request. Reset when the modal opens/closes so re-opening doesn't
|
||||
// show stale text from a previous abandoned attempt.
|
||||
const [resumeNotes, setResumeNotes] = useState("");
|
||||
|
||||
// Customer-side cancel: PATCH suspend=true. Same path as before.
|
||||
// The 60-day retention copy in the modal is the new bit (Bug 37b);
|
||||
@@ -106,6 +115,13 @@ export function SubscriptionToggle({
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
// Trim and omit on empty so the API stores NULL rather
|
||||
// than empty string. The endpoint's zod transform also
|
||||
// handles this; double-checking on the client lets us
|
||||
// skip the round-trip when there's nothing to send.
|
||||
customerNotes: resumeNotes.trim() || undefined,
|
||||
}),
|
||||
}
|
||||
);
|
||||
if (!res.ok) {
|
||||
@@ -113,6 +129,7 @@ export function SubscriptionToggle({
|
||||
throw new Error(data.error || t("subscriptionUpdateFailed"));
|
||||
}
|
||||
setConfirmResumeOpen(false);
|
||||
setResumeNotes("");
|
||||
router.refresh();
|
||||
} catch (e: any) {
|
||||
setError(e.message);
|
||||
@@ -210,6 +227,15 @@ export function SubscriptionToggle({
|
||||
when: formatRelative(pendingResumeRequest.createdAt, f),
|
||||
})}
|
||||
</div>
|
||||
{/* Feature 6: echo the customer's note back so they can
|
||||
see what they wrote. Useful especially when they
|
||||
later wonder "what did I tell them?" or want to
|
||||
confirm before cancelling and resubmitting. */}
|
||||
{pendingResumeRequest.customerNotes && (
|
||||
<div className="mt-2 text-xs text-text-secondary border-l-2 border-amber-500/30 pl-3 whitespace-pre-wrap">
|
||||
{pendingResumeRequest.customerNotes}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={cancelResumeRequest}
|
||||
@@ -249,10 +275,33 @@ export function SubscriptionToggle({
|
||||
<h3 className="font-display text-lg font-semibold text-text-primary mb-2">
|
||||
{t("requestReactivationConfirmTitle")}
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary mb-5">
|
||||
<p className="text-sm text-text-secondary mb-4">
|
||||
{t("requestReactivationConfirmDescription")}
|
||||
</p>
|
||||
|
||||
{/* Feature 6: optional explanatory note. Useful for
|
||||
customers to tell admin why they want reactivation
|
||||
— e.g. "we paused over winter break, picking back
|
||||
up". Stored on the tenant_request and surfaced in
|
||||
the admin queue. */}
|
||||
<div className="mb-5">
|
||||
<label className="block text-xs uppercase tracking-wider text-text-muted mb-1.5">
|
||||
{t("requestReactivationNoteLabel")}{" "}
|
||||
<span className="text-text-muted normal-case">
|
||||
({tCommon("optional")})
|
||||
</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={resumeNotes}
|
||||
onChange={(e) => setResumeNotes(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={2000}
|
||||
placeholder={t("requestReactivationNotePlaceholder")}
|
||||
disabled={submitting}
|
||||
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 disabled:opacity-50"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-xs text-red-400 bg-red-400/10 border border-red-400/20 rounded-lg px-3 py-2 mb-3">
|
||||
{error}
|
||||
|
||||
@@ -93,6 +93,14 @@ const MIGRATION_SQL = `
|
||||
-- is only meaningful for rejected and cancelled rows.
|
||||
ALTER TABLE tenant_requests ADD COLUMN IF NOT EXISTS dismissed_at TIMESTAMPTZ;
|
||||
|
||||
-- Feature 6: free-form customer note attached to the request.
|
||||
-- Currently surfaced only by resume requests (where the customer
|
||||
-- explains why they want reactivation), but the column is generic
|
||||
-- so future flows could reuse it. Distinct from billing_notes
|
||||
-- (provision-only, accounting-related) and admin_notes (admin's
|
||||
-- reason on reject/approve). Optional — nullable.
|
||||
ALTER TABLE tenant_requests ADD COLUMN IF NOT EXISTS customer_notes TEXT;
|
||||
|
||||
-- Bug 37a: resume requests use the same table as provision requests so
|
||||
-- the customer dashboard and admin queue share rendering. Discriminator
|
||||
-- is request_type. Default 'provision' on backfill keeps existing rows
|
||||
@@ -558,14 +566,21 @@ export async function createResumeRequest(params: {
|
||||
// tenant request for traceability rather than storing dummy values.
|
||||
companyName: string;
|
||||
agentName: string;
|
||||
/**
|
||||
* Feature 6: optional free-form note from the customer explaining
|
||||
* why they want reactivation. Surfaced to admin in the queue and
|
||||
* forwarded to the platform notification email so the admin can
|
||||
* decide before opening the request.
|
||||
*/
|
||||
customerNotes?: string | null;
|
||||
}): Promise<TenantRequest> {
|
||||
await ensureSchema();
|
||||
const result = await getPool().query(
|
||||
`INSERT INTO tenant_requests (
|
||||
zitadel_org_id, zitadel_user_id, company_name,
|
||||
contact_name, contact_email, agent_name,
|
||||
tenant_name, request_type, status
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 'resume', 'pending')
|
||||
tenant_name, request_type, status, customer_notes
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 'resume', 'pending', $8)
|
||||
RETURNING *`,
|
||||
[
|
||||
params.zitadelOrgId,
|
||||
@@ -575,6 +590,7 @@ export async function createResumeRequest(params: {
|
||||
params.contactEmail,
|
||||
params.agentName,
|
||||
params.tenantName,
|
||||
params.customerNotes ?? null,
|
||||
]
|
||||
);
|
||||
return mapRow(result.rows[0]);
|
||||
@@ -876,6 +892,7 @@ function mapRow(row: any): TenantRequest {
|
||||
packages: row.packages ?? [],
|
||||
billingAddress: row.billing_address ?? {},
|
||||
billingNotes: row.billing_notes,
|
||||
customerNotes: row.customer_notes ?? null,
|
||||
status: row.status as TenantRequestStatus,
|
||||
adminNotes: row.admin_notes,
|
||||
tenantName: row.tenant_name,
|
||||
|
||||
@@ -319,6 +319,89 @@ export async function sendAdminNotificationEmail(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Feature 6: resume-request admin notification
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Notify the admin distribution list that a customer has requested
|
||||
* reactivation of a suspended tenant. Distinct from the onboarding
|
||||
* notification because the action consequences differ (admin
|
||||
* approving a resume just unsuspends an existing tenant; no
|
||||
* provisioning runs), and because the customer's note — explaining
|
||||
* why they want reactivation — is meaningful context for the admin
|
||||
* triaging the queue.
|
||||
*
|
||||
* Skipped silently if ADMIN_NOTIFICATION_EMAIL isn't set, matching
|
||||
* the pattern of the other admin notification functions.
|
||||
*/
|
||||
export async function sendResumeRequestAdminNotificationEmail(params: {
|
||||
tenantName: string;
|
||||
companyName: string;
|
||||
contactName: string;
|
||||
contactEmail: string;
|
||||
customerNotes?: string | null;
|
||||
}): Promise<void> {
|
||||
const adminEmail = process.env.ADMIN_NOTIFICATION_EMAIL;
|
||||
if (!adminEmail) return;
|
||||
|
||||
const safeCompany = escapeHtml(params.companyName);
|
||||
const safeName = escapeHtml(params.contactName);
|
||||
const safeEmail = escapeHtml(params.contactEmail);
|
||||
const safeTenant = escapeHtml(params.tenantName);
|
||||
const safeNotes = params.customerNotes ? escapeHtml(params.customerNotes) : "";
|
||||
|
||||
const noteText = params.customerNotes
|
||||
? `\nCustomer's note:\n${params.customerNotes}\n`
|
||||
: "";
|
||||
const noteHtml = safeNotes
|
||||
? `<div style="background: #2a2a2a; border-left: 3px solid #3b82f6; padding: 12px 16px; border-radius: 6px; margin: 16px 0; white-space: pre-wrap;">
|
||||
<p style="color: #ccc; font-size: 13px; margin: 0 0 8px 0;"><strong>Customer's note:</strong></p>
|
||||
<p style="color: #e0e0e0; font-size: 13px; margin: 0;">${safeNotes}</p>
|
||||
</div>`
|
||||
: "";
|
||||
|
||||
try {
|
||||
await getTransporter().sendMail({
|
||||
from: getFrom(),
|
||||
to: adminEmail,
|
||||
subject: `Reactivation request: ${params.companyName}`,
|
||||
text: [
|
||||
`A customer has requested reactivation of a suspended tenant.`,
|
||||
"",
|
||||
`Company: ${params.companyName}`,
|
||||
`Tenant: ${params.tenantName}`,
|
||||
`Contact: ${params.contactName} (${params.contactEmail})`,
|
||||
noteText,
|
||||
`Review at https://app.pieced.ch/admin`,
|
||||
]
|
||||
.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;">Reactivation request</h2>
|
||||
<p>A customer has requested reactivation of a suspended tenant.</p>
|
||||
<table style="color: #ccc; font-size: 14px; margin: 16px 0;">
|
||||
<tr><td style="padding: 4px 12px 4px 0; color: #888;">Company:</td><td>${safeCompany}</td></tr>
|
||||
<tr><td style="padding: 4px 12px 4px 0; color: #888;">Tenant:</td><td style="font-family: monospace;">${safeTenant}</td></tr>
|
||||
<tr><td style="padding: 4px 12px 4px 0; color: #888;">Contact:</td><td>${safeName} (${safeEmail})</td></tr>
|
||||
</table>
|
||||
${noteHtml}
|
||||
<p>
|
||||
<a href="https://app.pieced.ch/admin" style="display: inline-block; padding: 10px 24px; background: #3b82f6; color: #ffffff; text-decoration: none; border-radius: 8px; font-weight: 500;">
|
||||
Review Request
|
||||
</a>
|
||||
</p>
|
||||
<hr style="border: none; border-top: 1px solid #333; margin: 24px 0;" />
|
||||
<p style="color: #666; font-size: 12px;">PieCed IT — Admin notification</p>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Failed to send resume request admin notification:", err);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Feature 5: support ticket emails
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -175,7 +175,9 @@
|
||||
"cancelConfirmRetentionWarning": "Ihre Daten bleiben nach der Kündigung 60 Tage lang erhalten. Danach werden alle Tenant-Daten – Konfiguration, Geheimnisse, Konversationen und Dateien – endgültig gelöscht.",
|
||||
"suspendedSince": "Gekündigt am {date}",
|
||||
"suspendedDeletionIn": "Datenlöschung in {days, plural, one {# Tag} other {# Tagen}} ({date})",
|
||||
"suspendedDeletionImminent": "Daten werden jetzt gelöscht"
|
||||
"suspendedDeletionImminent": "Daten werden jetzt gelöscht",
|
||||
"requestReactivationNoteLabel": "Notiz an unser Team",
|
||||
"requestReactivationNotePlaceholder": "Alles, was unser Team wissen sollte – z. B. Grund der Reaktivierung, Dringlichkeit usw."
|
||||
},
|
||||
"usage": {
|
||||
"inputTokens": "Input-Tokens",
|
||||
|
||||
@@ -175,7 +175,9 @@
|
||||
"cancelConfirmRetentionWarning": "Your data is preserved for 60 days after cancellation. After that, all tenant data — configuration, secrets, conversations, and files — will be permanently deleted.",
|
||||
"suspendedSince": "Suspended on {date}",
|
||||
"suspendedDeletionIn": "data deletion in {days, plural, one {# day} other {# days}} ({date})",
|
||||
"suspendedDeletionImminent": "data is being deleted now"
|
||||
"suspendedDeletionImminent": "data is being deleted now",
|
||||
"requestReactivationNoteLabel": "Note for our team",
|
||||
"requestReactivationNotePlaceholder": "Anything our team should know — e.g. why you want to reactivate, urgency, etc."
|
||||
},
|
||||
"usage": {
|
||||
"inputTokens": "Input Tokens",
|
||||
|
||||
@@ -175,7 +175,9 @@
|
||||
"cancelConfirmRetentionWarning": "Vos données sont conservées pendant 60 jours après l'annulation. Passé ce délai, toutes les données du locataire — configuration, secrets, conversations et fichiers — seront définitivement supprimées.",
|
||||
"suspendedSince": "Suspendu le {date}",
|
||||
"suspendedDeletionIn": "suppression des données dans {days, plural, one {# jour} other {# jours}} ({date})",
|
||||
"suspendedDeletionImminent": "les données sont en cours de suppression"
|
||||
"suspendedDeletionImminent": "les données sont en cours de suppression",
|
||||
"requestReactivationNoteLabel": "Note pour notre équipe",
|
||||
"requestReactivationNotePlaceholder": "Tout ce que notre équipe devrait savoir — par exemple, pourquoi vous voulez réactiver, urgence, etc."
|
||||
},
|
||||
"usage": {
|
||||
"inputTokens": "Tokens d'entrée",
|
||||
|
||||
@@ -175,7 +175,9 @@
|
||||
"cancelConfirmRetentionWarning": "I tuoi dati sono conservati per 60 giorni dopo l'annullamento. Trascorso tale periodo, tutti i dati del tenant — configurazione, segreti, conversazioni e file — verranno eliminati definitivamente.",
|
||||
"suspendedSince": "Sospeso il {date}",
|
||||
"suspendedDeletionIn": "eliminazione dei dati tra {days, plural, one {# giorno} other {# giorni}} ({date})",
|
||||
"suspendedDeletionImminent": "i dati vengono eliminati ora"
|
||||
"suspendedDeletionImminent": "i dati vengono eliminati ora",
|
||||
"requestReactivationNoteLabel": "Nota per il nostro team",
|
||||
"requestReactivationNotePlaceholder": "Qualsiasi cosa il nostro team dovrebbe sapere — ad es. il motivo della riattivazione, l'urgenza, ecc."
|
||||
},
|
||||
"usage": {
|
||||
"inputTokens": "Token di input",
|
||||
|
||||
@@ -273,6 +273,13 @@ export interface TenantRequest {
|
||||
* domain-uniqueness check on subsequent registrations.
|
||||
*/
|
||||
isPersonal?: boolean;
|
||||
/**
|
||||
* Feature 6: free-form note from the customer, attached at request
|
||||
* creation time. Currently used by resume requests (customer's
|
||||
* explanation of why they want reactivation); kept optional and
|
||||
* generic so future flows can reuse without schema work.
|
||||
*/
|
||||
customerNotes?: string | null;
|
||||
/**
|
||||
* Bug 13: when set, the customer has explicitly dismissed a rejected
|
||||
* request from their dashboard. Used by `listActiveTenantRequestsByOrgId`
|
||||
|
||||
Reference in New Issue
Block a user