mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-25 00:07:07 +00:00
feat: add an in-app store to buy and renew domains and Google Workspace or Microsoft 365 mailboxes through GraphKit with a one-screen checkout, automatic DNS, tracking, forwarding, photo and signature setup, a shared prepaid balance with a $10 minimum, $100 default and auto top-up, bundled monthly mailbox billing charged before fulfilment, a plan gate that keeps purchased mailboxes readable but stops sending and warmup when the plan lapses, AI overage opt-in, admin, API, CLI, MCP, agency and partner add-on coverage, and a locked store for self-hosts until a GraphKit API key is set
This commit is contained in:
@@ -637,10 +637,15 @@ WORKER_DEV_ENV := \
|
||||
# the docker postgres.
|
||||
# The sandbox's mock inbox vendor API; empty keeps the real vendors.
|
||||
MAILVENDOR_SANDBOX_URL ?=
|
||||
# The store runs against the in-process GraphKit simulator in dev; set both to use a sandbox key.
|
||||
GRAPHKIT_API_URL ?= fake
|
||||
GRAPHKIT_API_KEY ?=
|
||||
backend:
|
||||
$(GO_DEV_ENV) \
|
||||
$(AI_DEV_ENV) \
|
||||
MAILVENDOR_SANDBOX_URL=$(MAILVENDOR_SANDBOX_URL) \
|
||||
GRAPHKIT_API_URL=$(GRAPHKIT_API_URL) \
|
||||
GRAPHKIT_API_KEY=$(GRAPHKIT_API_KEY) \
|
||||
API_HOST=0.0.0.0:8080 \
|
||||
FORMS_DOMAIN=localhost:$(FORMS_PORT) \
|
||||
PORTAL_DOMAIN=localhost:$(PORTAL_PORT) \
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { Activity, ListChecks } from "lucide-react";
|
||||
import { Activity, ListChecks, Plug } from "lucide-react";
|
||||
import { PageHeader } from "@/components/layout/PageHeader";
|
||||
import { PageTabs } from "@/components/layout/PageTabs";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useInstanceHealth } from "@/hooks/useInstanceHealth";
|
||||
import { FindingsTab } from "./health/FindingsTab";
|
||||
import { ServicesTab } from "./health/ServicesTab";
|
||||
import { IntegrationsTab } from "./health/IntegrationsTab";
|
||||
import { InstanceMonitoringPanel } from "./InstanceMonitoringPanel";
|
||||
import { useAdminPerm } from "@/hooks/useAdminPerm";
|
||||
import { AdminPerm } from "@/lib/auth/permissions";
|
||||
|
||||
const TAB_IDS = ["findings", "services", "operations"] as const;
|
||||
const TAB_IDS = ["findings", "services", "operations", "integrations"] as const;
|
||||
type TabId = (typeof TAB_IDS)[number];
|
||||
|
||||
function isTabId(v: string | null): v is TabId {
|
||||
@@ -21,7 +22,8 @@ export default function HealthPage() {
|
||||
const canConfigure = useAdminPerm(AdminPerm.ManageSettings);
|
||||
const [params, setParams] = useSearchParams();
|
||||
const raw = params.get("tab");
|
||||
const tab: TabId = isTabId(raw) ? raw : "findings";
|
||||
// Integrations hold write-only credentials, so the tab exists only for manage-settings.
|
||||
const tab: TabId = isTabId(raw) && (raw !== "integrations" || canConfigure) ? raw : "findings";
|
||||
|
||||
// The findings count comes from the shared cache the sidebar badge reads,
|
||||
// so the tab badge and the nav badge never disagree.
|
||||
@@ -61,12 +63,21 @@ export default function HealthPage() {
|
||||
},
|
||||
{ id: "services", label: "Services", icon: Activity },
|
||||
{ id: "operations", label: "Operations", icon: Activity },
|
||||
...(canConfigure ? [{ id: "integrations", label: "Integrations", icon: Plug }] : []),
|
||||
]}
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
/>
|
||||
|
||||
{tab === "findings" ? <FindingsTab /> : tab === "services" ? <ServicesTab /> : <InstanceMonitoringPanel />}
|
||||
{tab === "findings" ? (
|
||||
<FindingsTab />
|
||||
) : tab === "services" ? (
|
||||
<ServicesTab />
|
||||
) : tab === "integrations" ? (
|
||||
<IntegrationsTab />
|
||||
) : (
|
||||
<InstanceMonitoringPanel />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -278,6 +278,11 @@ function OrgProperties({ org }: { org: AdminOrgDetail }) {
|
||||
</Property>
|
||||
)}
|
||||
<AgencyProperty orgId={org.id} />
|
||||
<Property label="Store">
|
||||
<Link to={`/store/workspaces/${org.id}`} className="underline underline-offset-2">
|
||||
Domains, mailboxes, orders
|
||||
</Link>
|
||||
</Property>
|
||||
</PropertyList>
|
||||
|
||||
<div className="mt-5 mb-1 text-xs font-medium text-muted-foreground">Lifecycle</div>
|
||||
|
||||
@@ -18,11 +18,14 @@ import {
|
||||
getInstanceSettings,
|
||||
putInstanceSettings,
|
||||
type InstanceSettings,
|
||||
type StoreSettings,
|
||||
type UsageSettings,
|
||||
} from "@/lib/api/client/admin/instance";
|
||||
import { getStorePricing } from "@/lib/api/client/admin/store";
|
||||
import { RangeHint, SettingsGroup, SettingsRow } from "./SettingsLayout";
|
||||
|
||||
const SETTINGS_KEY = ["admin", "instance", "settings"];
|
||||
const STORE_PRICING_KEY = ["admin", "store", "pricing"];
|
||||
|
||||
// The backend clamps to the same band; matching it here keeps the operator
|
||||
// from spending a round-trip to learn the range.
|
||||
@@ -430,6 +433,90 @@ function formatUSD(n: number): string {
|
||||
return `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 4 })}`;
|
||||
}
|
||||
|
||||
// Store retail pricing, mirroring the store section of internal/app/instancesettings.
|
||||
const MICROS_PER_USD = 1_000_000;
|
||||
const MICROS_PER_CENT = 10_000;
|
||||
const STORE_USD_MAX = 100;
|
||||
const STORE_PERCENT_MAX = 500;
|
||||
// The preview prices this extension from the live wholesale list.
|
||||
const STORE_PREVIEW_TLD = "com";
|
||||
|
||||
const STORE_LEAD_MIN = 2;
|
||||
const STORE_LEAD_MAX = 10;
|
||||
const STORE_MIN_CARD_FLOOR = 0.5;
|
||||
|
||||
const STORE_DEFAULTS: StoreSettings = {
|
||||
mailbox_monthly_micros: 3_000_000,
|
||||
domain_markup_percent: 0,
|
||||
domain_markup_fixed_micros: 0,
|
||||
mailbox_bill_lead_days: 5,
|
||||
min_card_charge_micros: 10_000_000,
|
||||
};
|
||||
|
||||
interface StoreForm {
|
||||
mailboxMonthly: string;
|
||||
markupPercent: string;
|
||||
markupFixed: string;
|
||||
billLead: string;
|
||||
minCard: string;
|
||||
}
|
||||
|
||||
function microsToDollars(micros: number): string {
|
||||
const usd = micros / MICROS_PER_USD;
|
||||
return micros % MICROS_PER_CENT === 0 ? usd.toFixed(2) : String(usd);
|
||||
}
|
||||
|
||||
function dollarsToMicros(raw: string): number {
|
||||
return Math.round(Number(raw) * MICROS_PER_USD);
|
||||
}
|
||||
|
||||
function toStoreForm(s: StoreSettings | undefined): StoreForm {
|
||||
const store = { ...STORE_DEFAULTS, ...s };
|
||||
return {
|
||||
mailboxMonthly: microsToDollars(store.mailbox_monthly_micros),
|
||||
markupPercent: String(store.domain_markup_percent),
|
||||
markupFixed: microsToDollars(store.domain_markup_fixed_micros),
|
||||
billLead: String(store.mailbox_bill_lead_days ?? 5),
|
||||
minCard: microsToDollars(store.min_card_charge_micros ?? 10_000_000),
|
||||
};
|
||||
}
|
||||
|
||||
// Dollars to at most micro-dollar precision, between zero and max.
|
||||
function dollarsValid(raw: string, max: number): boolean {
|
||||
return /^\d+(\.\d{1,6})?$/.test(raw.trim()) && Number(raw) <= max;
|
||||
}
|
||||
|
||||
function storeFormValid(f: StoreForm): boolean {
|
||||
return (
|
||||
dollarsValid(f.mailboxMonthly, STORE_USD_MAX) &&
|
||||
syncFieldValid(f.markupPercent, 0, STORE_PERCENT_MAX) &&
|
||||
dollarsValid(f.markupFixed, STORE_USD_MAX) &&
|
||||
syncFieldValid(f.billLead, STORE_LEAD_MIN, STORE_LEAD_MAX) &&
|
||||
dollarsValid(f.minCard, STORE_USD_MAX) &&
|
||||
Number(f.minCard) >= STORE_MIN_CARD_FLOOR
|
||||
);
|
||||
}
|
||||
|
||||
// Retail domain price: wholesale plus the percent plus the fixed amount, rounded up to the cent.
|
||||
function retailDomainMicros(wholesale: number, percent: number, fixed: number): number {
|
||||
const exact = wholesale * (100 + percent) + fixed * 100;
|
||||
return Math.ceil(exact / (100 * MICROS_PER_CENT)) * MICROS_PER_CENT;
|
||||
}
|
||||
|
||||
function mailboxPreview(f: StoreForm): string {
|
||||
return `Customers pay ${formatUSD(dollarsToMicros(f.mailboxMonthly) / MICROS_PER_USD)} per mailbox per month`;
|
||||
}
|
||||
|
||||
// What a .com sells for at the form's markup, from the live wholesale price.
|
||||
function domainPreview(f: StoreForm, wholesaleMicros: number): string {
|
||||
const percent = Number(f.markupPercent);
|
||||
const fixed = dollarsToMicros(f.markupFixed);
|
||||
const wholesale = formatUSD(wholesaleMicros / MICROS_PER_USD);
|
||||
if (percent === 0 && fixed === 0) return `a .${STORE_PREVIEW_TLD} costs ${wholesale} at cost`;
|
||||
const retail = formatUSD(retailDomainMicros(wholesaleMicros, percent, fixed) / MICROS_PER_USD);
|
||||
return `a .${STORE_PREVIEW_TLD} that costs ${wholesale} wholesale sells for ${retail}`;
|
||||
}
|
||||
|
||||
interface FormState {
|
||||
linksEnabled: boolean;
|
||||
ttlHours: string;
|
||||
@@ -442,6 +529,7 @@ interface FormState {
|
||||
authGraceHours: string;
|
||||
autoVendorReconnect: boolean;
|
||||
usage: UsageForm;
|
||||
store: StoreForm;
|
||||
}
|
||||
|
||||
function toForm(s: InstanceSettings): FormState {
|
||||
@@ -485,6 +573,7 @@ function toForm(s: InstanceSettings): FormState {
|
||||
authGraceHours: String(s.deliverability.auth_grace_hours),
|
||||
autoVendorReconnect: s.mailbox_signin?.auto_vendor_reconnect ?? true,
|
||||
usage: toUsageForm(s.usage),
|
||||
store: toStoreForm(s.store),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -550,6 +639,10 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
);
|
||||
const usageDirty =
|
||||
!!server && !!form && usageSignature(form.usage) !== usageSignature(toUsageForm(server.usage));
|
||||
const storeDirty =
|
||||
!!server &&
|
||||
!!form &&
|
||||
JSON.stringify(form.store) !== JSON.stringify(toStoreForm(server.store));
|
||||
const dirty =
|
||||
!!server &&
|
||||
!!form &&
|
||||
@@ -563,6 +656,7 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
trackingDirty ||
|
||||
placementDirty ||
|
||||
usageDirty ||
|
||||
storeDirty ||
|
||||
syncDirty);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -592,6 +686,8 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
) &&
|
||||
Object.values(form.usage.units).every(priceValid);
|
||||
|
||||
const storeValid = form !== null && storeFormValid(form.store);
|
||||
|
||||
const authGrace = form ? Number(form.authGraceHours) : NaN;
|
||||
const authGraceValid =
|
||||
form !== null &&
|
||||
@@ -642,6 +738,12 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!storeValid) {
|
||||
toast.error(
|
||||
`The mailbox price and the fixed domain markup must be dollar amounts from $0 to $${STORE_USD_MAX}, and the domain markup a whole percent from 0 to ${STORE_PERCENT_MAX}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!authGraceValid) {
|
||||
toast.error(
|
||||
`The authentication grace period must be a whole number of hours between ${AUTH_GRACE_MIN_HOURS} and ${AUTH_GRACE_MAX_HOURS}`,
|
||||
@@ -698,6 +800,13 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
Object.entries(form.usage.units).map(([k, v]) => [k, Number(v)]),
|
||||
),
|
||||
},
|
||||
store: {
|
||||
mailbox_monthly_micros: dollarsToMicros(form.store.mailboxMonthly),
|
||||
domain_markup_percent: Number(form.store.markupPercent),
|
||||
domain_markup_fixed_micros: dollarsToMicros(form.store.markupFixed),
|
||||
mailbox_bill_lead_days: Number(form.store.billLead),
|
||||
min_card_charge_micros: dollarsToMicros(form.store.minCard),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -923,6 +1032,11 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) {
|
||||
onChange={(usage) => setForm({ ...form, usage })}
|
||||
/>
|
||||
|
||||
<StorePricingGroup
|
||||
store={form.store}
|
||||
onChange={(store) => setForm({ ...form, store })}
|
||||
/>
|
||||
|
||||
<SettingsGroup
|
||||
title="Sending-domain authentication"
|
||||
description="Gmail, Yahoo, and Outlook reject or spam-filter mail from a domain without SPF and DMARC, and one unauthenticated sender damages the reputation of every mailbox in the shared warmup pool. Warmbly checks each sending domain daily and can stop cold sending and warmup from a domain that keeps failing. The grace period is how long a domain may keep failing first, so a DNS outage cannot stop a customer's campaigns and the owner is warned throughout it."
|
||||
@@ -1147,6 +1261,111 @@ function UsagePricingGroup({
|
||||
);
|
||||
}
|
||||
|
||||
// Retail prices for the domains and mailboxes workspaces buy in the dashboard.
|
||||
function StorePricingGroup({
|
||||
store,
|
||||
onChange,
|
||||
}: {
|
||||
store: StoreForm;
|
||||
onChange: (s: StoreForm) => void;
|
||||
}) {
|
||||
const pricingQ = useQuery({
|
||||
queryKey: STORE_PRICING_KEY,
|
||||
queryFn: getStorePricing,
|
||||
retry: false,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
const comWholesale = pricingQ.data?.domains.find((d) => d.tld === STORE_PREVIEW_TLD)?.register_micros;
|
||||
const valid = storeFormValid(store);
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Domains and mailboxes"
|
||||
description={
|
||||
<>
|
||||
What a workspace pays for the domains and mailboxes it buys under Buy mailboxes,
|
||||
charged from its balance. Only used when the store is configured with{" "}
|
||||
<code className="font-mono text-[12px]">GRAPHKIT_API_KEY</code>. A change applies
|
||||
to quotes made after it; a mailbox already bought keeps the monthly price it was
|
||||
bought at. A self-hosted instance with billing off charges workspaces nothing and
|
||||
its partner account pays, so these prices do nothing there.
|
||||
</>
|
||||
}
|
||||
>
|
||||
<NumberRow
|
||||
id="store-mailbox-monthly"
|
||||
label="Mailbox price ($ per month)"
|
||||
help="What one mailbox costs each month, Google or Microsoft alike."
|
||||
range={`Between $0 and $${STORE_USD_MAX}.`}
|
||||
value={store.mailboxMonthly}
|
||||
onChange={(v) => onChange({ ...store, mailboxMonthly: v })}
|
||||
valid={dollarsValid(store.mailboxMonthly, STORE_USD_MAX)}
|
||||
error={`Enter a dollar amount between 0 and ${STORE_USD_MAX}.`}
|
||||
inputMode="decimal"
|
||||
/>
|
||||
<NumberRow
|
||||
id="store-domain-percent"
|
||||
label="Domain markup (%)"
|
||||
help="Added to the wholesale price of every domain, for registration and renewal. With both markups at 0, domains are sold at cost."
|
||||
range={`Between 0 and ${STORE_PERCENT_MAX}.`}
|
||||
value={store.markupPercent}
|
||||
onChange={(v) => onChange({ ...store, markupPercent: v })}
|
||||
valid={syncFieldValid(store.markupPercent, 0, STORE_PERCENT_MAX)}
|
||||
error={`Enter a whole number between 0 and ${STORE_PERCENT_MAX}.`}
|
||||
/>
|
||||
<NumberRow
|
||||
id="store-domain-fixed"
|
||||
label="Domain markup ($ per domain)"
|
||||
help="Added after the percent to every domain price. The result is rounded up to the cent."
|
||||
range={`Between $0 and $${STORE_USD_MAX}.`}
|
||||
value={store.markupFixed}
|
||||
onChange={(v) => onChange({ ...store, markupFixed: v })}
|
||||
valid={dollarsValid(store.markupFixed, STORE_USD_MAX)}
|
||||
error={`Enter a dollar amount between 0 and ${STORE_USD_MAX}.`}
|
||||
inputMode="decimal"
|
||||
/>
|
||||
<NumberRow
|
||||
id="store-bill-lead"
|
||||
label="Mailbox billing lead (days)"
|
||||
help="A workspace's mailboxes are charged together this many days before its monthly billing day, so a failed payment has time to be fixed before the provider bills the next month."
|
||||
range={`Between ${STORE_LEAD_MIN} and ${STORE_LEAD_MAX}.`}
|
||||
value={store.billLead}
|
||||
onChange={(v) => onChange({ ...store, billLead: v })}
|
||||
valid={syncFieldValid(store.billLead, STORE_LEAD_MIN, STORE_LEAD_MAX)}
|
||||
error={`Enter a whole number between ${STORE_LEAD_MIN} and ${STORE_LEAD_MAX}.`}
|
||||
/>
|
||||
<NumberRow
|
||||
id="store-min-card"
|
||||
label="Minimum card charge ($)"
|
||||
help="When a store charge needs the card, it is charged at least this, and the rest stays on the workspace balance. Fewer, larger card charges cost less in card fees."
|
||||
range={`Between $${STORE_MIN_CARD_FLOOR.toFixed(2)} and $${STORE_USD_MAX}.`}
|
||||
value={store.minCard}
|
||||
onChange={(v) => onChange({ ...store, minCard: v })}
|
||||
valid={dollarsValid(store.minCard, STORE_USD_MAX) && Number(store.minCard) >= STORE_MIN_CARD_FLOOR}
|
||||
error={`Enter a dollar amount between ${STORE_MIN_CARD_FLOOR.toFixed(2)} and ${STORE_USD_MAX}.`}
|
||||
inputMode="decimal"
|
||||
/>
|
||||
<div className="px-4 py-3 text-[12.5px] tabular-nums text-muted-foreground" aria-live="polite">
|
||||
{!valid ? (
|
||||
"Fix the values above to see what customers pay."
|
||||
) : pricingQ.isLoading ? (
|
||||
<div className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
|
||||
{mailboxPreview(store)};
|
||||
<Skeleton className="h-3.5 w-40" aria-hidden />
|
||||
<span className="sr-only">loading the live .{STORE_PREVIEW_TLD} price</span>
|
||||
</div>
|
||||
) : comWholesale === undefined ? (
|
||||
<>
|
||||
{mailboxPreview(store)}.{" "}
|
||||
<span className={TONE_TEXT.warning}>Live price unavailable</span>
|
||||
</>
|
||||
) : (
|
||||
`${mailboxPreview(store)}; ${domainPreview(store, comWholesale)}.`
|
||||
)}
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
|
||||
// One numeric setting: the field sits on the right, the range under the help.
|
||||
function NumberRow({
|
||||
id,
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { StoreConnection } from "@/lib/api/client/admin/store";
|
||||
import { StoreConnectionCard } from "./IntegrationsTab";
|
||||
|
||||
const state = vi.hoisted(() => ({ conn: undefined as StoreConnection | undefined }));
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: () => ({ data: state.conn, isLoading: false, isError: false, refetch: vi.fn() }),
|
||||
useMutation: () => ({ mutate: vi.fn(), isPending: false }),
|
||||
useQueryClient: () => ({}),
|
||||
}));
|
||||
vi.mock("@/components/ConfirmDialog", () => ({ useConfirm: () => vi.fn() }));
|
||||
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
function conn(over: Partial<StoreConnection> = {}): StoreConnection {
|
||||
return {
|
||||
source: "settings",
|
||||
configured: true,
|
||||
mode: "live",
|
||||
api_url: "https://gk.example/v1/infrastructure",
|
||||
default_api_url: "https://api.graphkit.com/v1/infrastructure",
|
||||
api_key_set: true,
|
||||
webhook_secret_set: false,
|
||||
webhook_url: "https://api.example/v1/webhooks/graphkit",
|
||||
sealing_available: true,
|
||||
updated_at: "2026-11-01T00:00:00Z",
|
||||
updated_by: "user-1",
|
||||
purchases_without_connection: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function render() {
|
||||
const html = renderToStaticMarkup(<StoreConnectionCard />);
|
||||
return new DOMParser().parseFromString(html, "text/html");
|
||||
}
|
||||
|
||||
const buttons = (doc: Document) => [...doc.querySelectorAll("button")].map((b) => b.textContent?.trim());
|
||||
|
||||
beforeEach(() => {
|
||||
state.conn = conn();
|
||||
});
|
||||
|
||||
describe("GraphKit connection card", () => {
|
||||
it("renders an environment connection read-only", () => {
|
||||
state.conn = conn({ source: "environment" });
|
||||
const doc = render();
|
||||
expect(doc.body.textContent).toContain("Configured by the environment");
|
||||
expect(doc.body.textContent).toContain("https://gk.example/v1/infrastructure");
|
||||
expect(doc.querySelector("input[type=password]")).toBeNull();
|
||||
expect(doc.querySelector("#graphkit-url")).toBeNull();
|
||||
expect(buttons(doc)).not.toContain("Save");
|
||||
expect(buttons(doc)).not.toContain("Disconnect");
|
||||
});
|
||||
|
||||
it("offers Disconnect for stored settings and starts secrets empty", () => {
|
||||
const doc = render();
|
||||
expect(buttons(doc)).toContain("Disconnect");
|
||||
const secrets = [...doc.querySelectorAll<HTMLInputElement>("input[type=password]")];
|
||||
expect(secrets).toHaveLength(2);
|
||||
for (const s of secrets) expect(s.value).toBe("");
|
||||
expect(doc.querySelector<HTMLInputElement>("#graphkit-url")?.value).toBe("https://gk.example/v1/infrastructure");
|
||||
expect(doc.body.textContent).toContain("Not set");
|
||||
});
|
||||
|
||||
it("blocks saving without the credentials key and reports unconnected purchases", () => {
|
||||
state.conn = conn({ source: "none", configured: false, api_key_set: false, sealing_available: false, purchases_without_connection: { mailboxes: 3, domains: 1 } });
|
||||
const doc = render();
|
||||
expect(doc.body.textContent).toContain("CREDENTIALS_ENCRYPTION_KEY must be set");
|
||||
expect(doc.body.textContent).toContain("3 mailboxes and 1 domain were bought here");
|
||||
const save = [...doc.querySelectorAll("button")].find((b) => b.textContent?.includes("Save"));
|
||||
expect(save?.hasAttribute("disabled")).toBe(true);
|
||||
expect(buttons(doc)).not.toContain("Disconnect");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
// Integrations tab of Setup and health: the GraphKit connection behind the domain and mailbox store.
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { AlertTriangle, Check, Copy, FlaskConical, Save, Unplug } from "lucide-react";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Callout, Panel, StatusBadge } from "@/components/ui/kit";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { INSTANCE_HEALTH_KEY } from "@/hooks/useInstanceHealth";
|
||||
import { APIError, ReauthCancelledError } from "@/lib/api/client";
|
||||
import {
|
||||
deleteStoreConnection,
|
||||
getStoreConnection,
|
||||
saveStoreConnection,
|
||||
STORE_CONNECTION_KEY,
|
||||
testStoreConnection,
|
||||
type StoreConnection,
|
||||
type StoreConnectionInput,
|
||||
type StoreConnectionTest,
|
||||
} from "@/lib/api/client/admin/store";
|
||||
import { MODE_TONE } from "../store/format";
|
||||
|
||||
export function IntegrationsTab() {
|
||||
return (
|
||||
<div className="mt-4 space-y-4">
|
||||
<StoreConnectionCard />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ERROR_TEXT: Record<string, string> = {
|
||||
store_configured_by_environment: "GRAPHKIT_* environment variables configure the store, so it cannot be changed here.",
|
||||
store_sealing_unavailable: "Set CREDENTIALS_ENCRYPTION_KEY before saving a GraphKit API key here.",
|
||||
graphkit_url_invalid: "The API URL is not a valid GraphKit URL.",
|
||||
graphkit_key_required: "Enter an API key. None is stored yet.",
|
||||
graphkit_key_reentry_required: "Enter the API key again to use a different API URL.",
|
||||
graphkit_key_rejected: "GraphKit rejected this API key.",
|
||||
graphkit_unreachable: "GraphKit could not be reached at this URL.",
|
||||
};
|
||||
|
||||
function errorText(e: unknown): string {
|
||||
if (e instanceof APIError && e.code && ERROR_TEXT[e.code]) return ERROR_TEXT[e.code];
|
||||
return e instanceof Error && e.message ? e.message : "The request failed";
|
||||
}
|
||||
|
||||
function trimSlash(u: string): string {
|
||||
return u.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function money(micros: number, currency: string): string {
|
||||
try {
|
||||
return new Intl.NumberFormat("en-US", { style: "currency", currency: currency || "USD" }).format(micros / 1_000_000);
|
||||
} catch {
|
||||
return `${(micros / 1_000_000).toFixed(2)} ${currency}`;
|
||||
}
|
||||
}
|
||||
|
||||
const MODE_LABEL: Record<StoreConnection["mode"], string> = {
|
||||
live: "Live",
|
||||
sandbox: "Sandbox",
|
||||
simulator: "Simulator",
|
||||
off: "Off",
|
||||
};
|
||||
|
||||
export function StoreConnectionCard() {
|
||||
const q = useQuery({ queryKey: STORE_CONNECTION_KEY, queryFn: getStoreConnection, retry: false });
|
||||
return (
|
||||
<Panel
|
||||
title="Domains and mailboxes (GraphKit)"
|
||||
description="Buying domains and mailboxes needs only a GraphKit API key. The webhook secret and API URL are optional."
|
||||
actions={q.data && <StatusBadge tone={MODE_TONE[q.data.mode] ?? "neutral"} dot>{MODE_LABEL[q.data.mode] ?? q.data.mode}</StatusBadge>}
|
||||
>
|
||||
{q.isLoading ? (
|
||||
<div className="space-y-3">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-2/3" />
|
||||
</div>
|
||||
) : q.isError || !q.data ? (
|
||||
<ErrorState error={q.error} title="Couldn’t load the GraphKit connection" onRetry={() => void q.refetch()} />
|
||||
) : (
|
||||
// Remount on every server change so the form starts from what is stored.
|
||||
<ConnectionForm key={`${q.data.source}:${q.data.updated_at ?? ""}`} conn={q.data} />
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function SecretStatus({ set }: { set: boolean }) {
|
||||
return <StatusBadge tone={set ? "success" : "neutral"}>{set ? "Set" : "Not set"}</StatusBadge>;
|
||||
}
|
||||
|
||||
function ConnectionForm({ conn }: { conn: StoreConnection }) {
|
||||
const qc = useQueryClient();
|
||||
const confirm = useConfirm();
|
||||
const fromEnv = conn.source === "environment";
|
||||
const [apiUrl, setApiUrl] = useState(conn.api_url);
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [secret, setSecret] = useState("");
|
||||
const [result, setResult] = useState<{ ok: StoreConnectionTest } | { error: string } | null>(null);
|
||||
|
||||
const input = (): StoreConnectionInput => ({
|
||||
api_url: apiUrl.trim() || conn.default_api_url,
|
||||
api_key: apiKey.trim() || undefined,
|
||||
webhook_secret: secret.trim() || undefined,
|
||||
});
|
||||
|
||||
async function refresh(next: StoreConnection) {
|
||||
qc.setQueryData(STORE_CONNECTION_KEY, next);
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: ["admin", "store"] }),
|
||||
qc.invalidateQueries({ queryKey: INSTANCE_HEALTH_KEY }),
|
||||
]);
|
||||
}
|
||||
|
||||
const testMut = useMutation({
|
||||
mutationFn: testStoreConnection,
|
||||
onSuccess: (ok) => setResult({ ok }),
|
||||
onError: (e) => {
|
||||
if (!(e instanceof ReauthCancelledError)) setResult({ error: errorText(e) });
|
||||
},
|
||||
});
|
||||
const saveMut = useMutation({
|
||||
mutationFn: saveStoreConnection,
|
||||
onSuccess: async (next) => {
|
||||
toast.success("GraphKit API key saved");
|
||||
await refresh(next);
|
||||
},
|
||||
onError: (e) => {
|
||||
if (!(e instanceof ReauthCancelledError)) toast.error(errorText(e));
|
||||
},
|
||||
});
|
||||
const deleteMut = useMutation({
|
||||
mutationFn: deleteStoreConnection,
|
||||
onSuccess: async (next) => {
|
||||
toast.success("GraphKit disconnected");
|
||||
await refresh(next);
|
||||
},
|
||||
onError: (e) => {
|
||||
if (!(e instanceof ReauthCancelledError)) toast.error(errorText(e));
|
||||
},
|
||||
});
|
||||
|
||||
const busy = testMut.isPending || saveMut.isPending || deleteMut.isPending;
|
||||
// The stored key is only sent to the URL it was saved with.
|
||||
const urlChanged = conn.api_key_set && trimSlash(apiUrl.trim() || conn.default_api_url) !== trimSlash(conn.api_url);
|
||||
const keyMissing = (!conn.api_key_set || urlChanged) && !apiKey.trim();
|
||||
const saveBlocked = !conn.sealing_available
|
||||
? "Set CREDENTIALS_ENCRYPTION_KEY to save a GraphKit API key here."
|
||||
: keyMissing
|
||||
? urlChanged
|
||||
? "Enter the API key again to use a different API URL."
|
||||
: "Enter an API key to save. None is stored yet."
|
||||
: null;
|
||||
|
||||
function edit(set: (v: string) => void) {
|
||||
return (v: string) => {
|
||||
set(v);
|
||||
setResult(null);
|
||||
};
|
||||
}
|
||||
|
||||
function onSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (fromEnv || saveBlocked || busy) return;
|
||||
saveMut.mutate(input());
|
||||
}
|
||||
|
||||
async function disconnect() {
|
||||
const ok = await confirm({
|
||||
title: "Disconnect GraphKit?",
|
||||
description:
|
||||
"The store stops now. New purchases, renewals, monthly billing and Google mailbox connections pause until an API key is added again. The stored API key and webhook secret are deleted.",
|
||||
confirmLabel: "Disconnect",
|
||||
destructive: true,
|
||||
});
|
||||
if (ok) deleteMut.mutate();
|
||||
}
|
||||
|
||||
const pending = conn.purchases_without_connection;
|
||||
|
||||
return (
|
||||
<form className="space-y-4" onSubmit={onSubmit}>
|
||||
{pending && (
|
||||
<Callout tone="danger" icon={AlertTriangle} title="Store purchases have no GraphKit API key">
|
||||
{pending.mailboxes} {pending.mailboxes === 1 ? "mailbox" : "mailboxes"} and {pending.domains}{" "}
|
||||
{pending.domains === 1 ? "domain" : "domains"} were bought here. Renewals, monthly billing and Google
|
||||
mailbox connections are paused until GraphKit is configured.
|
||||
</Callout>
|
||||
)}
|
||||
|
||||
{fromEnv ? (
|
||||
<div className="flex flex-wrap items-center gap-2 text-[12.5px] text-muted-foreground">
|
||||
<StatusBadge tone="info">Configured by the environment</StatusBadge>
|
||||
<span>GRAPHKIT_* environment variables win over these settings.</span>
|
||||
</div>
|
||||
) : (
|
||||
!conn.sealing_available && (
|
||||
<Callout tone="warning" icon={AlertTriangle} title="Encryption key required">
|
||||
CREDENTIALS_ENCRYPTION_KEY must be set before GraphKit can be saved here, because the API key and
|
||||
webhook secret are stored encrypted with it.
|
||||
</Callout>
|
||||
)
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="graphkit-url">API URL</Label>
|
||||
{fromEnv ? (
|
||||
<div className="break-all font-mono text-[12.5px] text-foreground">{conn.api_url}</div>
|
||||
) : (
|
||||
<Input
|
||||
id="graphkit-url"
|
||||
value={apiUrl}
|
||||
placeholder={conn.default_api_url}
|
||||
onChange={(e) => edit(setApiUrl)(e.target.value)}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="graphkit-key">
|
||||
API key <SecretStatus set={conn.api_key_set} />
|
||||
</Label>
|
||||
{!fromEnv && (
|
||||
<Input
|
||||
id="graphkit-key"
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => edit(setApiKey)(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
placeholder={conn.api_key_set && !urlChanged ? "Leave blank to keep the stored key" : "Required"}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="graphkit-secret">
|
||||
Webhook secret <SecretStatus set={conn.webhook_secret_set} />
|
||||
</Label>
|
||||
{!fromEnv && (
|
||||
<Input
|
||||
id="graphkit-secret"
|
||||
type="password"
|
||||
value={secret}
|
||||
onChange={(e) => edit(setSecret)(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
placeholder={conn.webhook_secret_set ? "Leave blank to keep the stored secret" : "From GraphKit"}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!fromEnv && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Secrets are never shown again once saved. Leave a field blank to keep the stored value.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="graphkit-webhook">Warmbly webhook URL</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input id="graphkit-webhook" value={conn.webhook_url} readOnly className="font-mono text-[12.5px]" onFocus={(e) => e.target.select()} />
|
||||
<CopyButton value={conn.webhook_url} />
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
In GraphKit, register this URL as your webhook endpoint and paste the signing secret it gives you above.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{result && <TestResult result={result} />}
|
||||
|
||||
{!fromEnv && (
|
||||
<div className="flex flex-wrap items-center gap-2 border-t border-border pt-4">
|
||||
<Button type="submit" size="sm" disabled={!!saveBlocked || busy}>
|
||||
<Save />
|
||||
{saveMut.isPending ? "Saving…" : "Save"}
|
||||
</Button>
|
||||
<Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => testMut.mutate(input())}>
|
||||
<FlaskConical />
|
||||
{testMut.isPending ? "Testing…" : "Test connection"}
|
||||
</Button>
|
||||
{conn.source === "settings" && (
|
||||
<Button type="button" size="sm" variant="ghost" className="text-destructive hover:text-destructive" disabled={busy} onClick={() => void disconnect()}>
|
||||
<Unplug />
|
||||
Disconnect
|
||||
</Button>
|
||||
)}
|
||||
{saveBlocked && <span className="text-xs text-muted-foreground">{saveBlocked}</span>}
|
||||
{!saveBlocked && conn.updated_at && (
|
||||
<span className="ml-auto text-xs text-muted-foreground">Saved {new Date(conn.updated_at).toLocaleString()}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function TestResult({ result }: { result: { ok: StoreConnectionTest } | { error: string } }) {
|
||||
if ("error" in result) {
|
||||
return <Callout tone="danger" icon={AlertTriangle} title="Connection test failed">{result.error}</Callout>;
|
||||
}
|
||||
const t = result.ok;
|
||||
const com =
|
||||
t.com_register_micros != null
|
||||
? `.com ${money(t.com_register_micros, t.currency)} to register${t.com_renew_micros != null ? `, ${money(t.com_renew_micros, t.currency)} to renew` : ""}`
|
||||
: null;
|
||||
return (
|
||||
<Callout tone="success" icon={Check} title={t.mode === "live" ? "Connected to a live GraphKit account" : "Connected to a GraphKit test account"}>
|
||||
Balance {money(t.balance_micros, t.currency)}
|
||||
{com && `. ${com}`}
|
||||
</Callout>
|
||||
);
|
||||
}
|
||||
|
||||
function CopyButton({ value }: { value: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(true);
|
||||
toast.success("Webhook URL copied");
|
||||
window.setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
toast.error("Could not copy. Select the URL and copy it instead.");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{copied ? <Check /> : <Copy />}
|
||||
{copied ? "Copied" : "Copy"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
// One partner: its settings, keys, webhook and callback secrets, and the workspaces it manages.
|
||||
// Reading needs view_organizations; every change needs manage_organizations and a fresh confirmation.
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { Copy, KeyRound, Plus } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { PageHeader } from "@/components/layout/PageHeader";
|
||||
import { Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import { DataTable, type Column } from "@/components/data/DataTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { useAdminPerm } from "@/hooks/useAdminPerm";
|
||||
import { AdminPerm } from "@/lib/auth/permissions";
|
||||
import { PartnerStatements } from "./PartnerStatements";
|
||||
import {
|
||||
createPartnerKey,
|
||||
getPartner,
|
||||
listPartnerOrganizations,
|
||||
revokePartnerKey,
|
||||
rotatePartnerWebhookSecret,
|
||||
setPartnerCallbackKey,
|
||||
updatePartner,
|
||||
type AdminPartnerDetail,
|
||||
type AdminPartnerKey,
|
||||
type AdminPartnerOrganization,
|
||||
type AdminPartnerUpdate,
|
||||
type PartnerMode,
|
||||
} from "@/lib/api/client/admin/partners";
|
||||
|
||||
const FIELD_LABEL = "text-xs font-medium text-muted-foreground";
|
||||
const MICROS = 1_000_000;
|
||||
|
||||
function usdFromMicros(m: number): string {
|
||||
return (m / MICROS).toLocaleString(undefined, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 6 });
|
||||
}
|
||||
|
||||
const STATE_TONE = { active: "success", suspended: "warning", cancelled: "danger" } as const;
|
||||
|
||||
const ORG_COLUMNS: Column<AdminPartnerOrganization>[] = [
|
||||
{
|
||||
id: "name",
|
||||
header: "Workspace",
|
||||
cell: (o) =>
|
||||
o.organization_id ? (
|
||||
<Link to={`/organizations/${o.organization_id}`} className="font-medium underline-offset-2 hover:underline">
|
||||
{o.organization_name || o.organization_id}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Deleted</span>
|
||||
),
|
||||
csv: (o) => o.organization_name ?? "",
|
||||
},
|
||||
{ id: "external", header: "Partner's id", cell: (o) => <span className="font-mono text-xs">{o.external_id}</span>, csv: (o) => o.external_id },
|
||||
{ id: "mode", header: "Mode", cell: (o) => <StatusBadge tone={o.mode === "live" ? "info" : "neutral"}>{o.mode}</StatusBadge>, csv: (o) => o.mode },
|
||||
{
|
||||
id: "state",
|
||||
header: "State",
|
||||
cell: (o) => (
|
||||
<StatusBadge tone={STATE_TONE[o.state]} title={o.suspended_reason ?? undefined}>
|
||||
{o.state}
|
||||
</StatusBadge>
|
||||
),
|
||||
csv: (o) => o.state,
|
||||
},
|
||||
{ id: "group", header: "Group", cell: (o) => o.group_name || o.group_external_id || "None", csv: (o) => o.group_external_id ?? "" },
|
||||
{ id: "cap", header: "Sends / mailbox / day", align: "right", cell: (o) => o.campaign_sends_per_mailbox_per_day, csv: (o) => o.campaign_sends_per_mailbox_per_day },
|
||||
{
|
||||
id: "deletes",
|
||||
header: "Deletes",
|
||||
cell: (o) => (o.deletes_at ? new Date(o.deletes_at).toLocaleDateString() : ""),
|
||||
csv: (o) => o.deletes_at ?? "",
|
||||
},
|
||||
];
|
||||
|
||||
export default function PartnerDetailPage() {
|
||||
const { id = "" } = useParams();
|
||||
const q = useQuery({ queryKey: ["admin", "partners", id], queryFn: () => getPartner(id), enabled: !!id });
|
||||
const p = q.data;
|
||||
|
||||
if (q.error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title="Partner" breadcrumbs={[{ label: "Partners", to: "/partners" }]} />
|
||||
<ErrorState error={q.error} onRetry={() => void q.refetch()} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={p?.name ?? "Partner"}
|
||||
breadcrumbs={[{ label: "Partners", to: "/partners" }]}
|
||||
meta={p ? <StatusBadge tone={p.status === "active" ? "success" : "warning"}>{p.status}</StatusBadge> : undefined}
|
||||
/>
|
||||
{p && (
|
||||
<div className="space-y-4">
|
||||
<PartnerStatusCard partner={p} />
|
||||
<PartnerSettingsCard partner={p} />
|
||||
<PartnerKeysCard partner={p} />
|
||||
<PartnerSecretsCard partner={p} />
|
||||
<PartnerStatements partnerId={p.id} />
|
||||
<PartnerOrganizations partnerId={p.id} />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function usePartnerWrite<T>(id: string, fn: (v: T) => Promise<unknown>, done: string) {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: fn,
|
||||
onSuccess: (res) => {
|
||||
if (res && typeof res === "object" && "keys" in res) qc.setQueryData(["admin", "partners", id], res as AdminPartnerDetail);
|
||||
void qc.invalidateQueries({ queryKey: ["admin", "partners"] });
|
||||
toast.success(done);
|
||||
},
|
||||
onError: (e: Error) => toast.error(e.message || "That change did not save."),
|
||||
});
|
||||
}
|
||||
|
||||
function PartnerStatusCard({ partner: p }: { partner: AdminPartnerDetail }) {
|
||||
const confirm = useConfirm();
|
||||
const canManage = useAdminPerm(AdminPerm.ManageOrganizations);
|
||||
const suspended = p.status === "suspended";
|
||||
const toggle = usePartnerWrite(p.id, () => updatePartner(p.id, { status: suspended ? "active" : "suspended" }), suspended ? "Partner resumed" : "Partner suspended");
|
||||
|
||||
async function run() {
|
||||
const ok = await confirm({
|
||||
title: suspended ? `Resume ${p.name}?` : `Suspend ${p.name}?`,
|
||||
description: suspended
|
||||
? "Its keys work again. Workspaces it manages keep their own state."
|
||||
: "Every one of its keys answers partner_suspended until it is resumed. Workspaces it manages keep running as they are.",
|
||||
confirmLabel: suspended ? "Resume" : "Suspend",
|
||||
destructive: !suspended,
|
||||
});
|
||||
if (ok) await toggle.mutateAsync(undefined).catch(() => undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<PropertyList title="Partner">
|
||||
<Property label="Slug">
|
||||
<span className="font-mono text-xs">{p.slug}</span>
|
||||
</Property>
|
||||
<Property label="Members see">Billed through {p.display_name}</Property>
|
||||
<Property label="Plans">{p.allowed_plans.join(", ") || "None"}</Property>
|
||||
<Property label="Status">
|
||||
<span className="inline-flex items-center gap-2">
|
||||
{p.status}
|
||||
{canManage && (
|
||||
<Button size="sm" variant="outline" disabled={toggle.isPending} onClick={() => void run()}>
|
||||
{suspended ? "Resume" : "Suspend"}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
</Property>
|
||||
</PropertyList>
|
||||
);
|
||||
}
|
||||
|
||||
function PartnerSettingsCard({ partner: p }: { partner: AdminPartnerDetail }) {
|
||||
const canManage = useAdminPerm(AdminPerm.ManageOrganizations);
|
||||
const [form, setForm] = useState(() => ({
|
||||
name: p.name,
|
||||
display_name: p.display_name,
|
||||
allowed_hosts: p.allowed_hosts.join(", "),
|
||||
delegation_domains: (p.delegation_domains ?? []).join(", "),
|
||||
webhook_url: p.webhook_url ?? "",
|
||||
callback_base_url: p.callback_base_url ?? "",
|
||||
sending: String(p.wholesale_sending_warmup_day_micros / MICROS),
|
||||
warmup: String(p.wholesale_warmup_only_day_micros / MICROS),
|
||||
rate: String(p.rate_limit_per_second),
|
||||
}));
|
||||
const set = (k: keyof typeof form) => (e: { target: { value: string } }) => setForm((f) => ({ ...f, [k]: e.target.value }));
|
||||
const save = usePartnerWrite(p.id, (body: AdminPartnerUpdate) => updatePartner(p.id, body), "Partner saved");
|
||||
|
||||
function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
const toMicros = (v: string) => Math.round(Number(v || "0") * MICROS);
|
||||
save.mutate({
|
||||
name: form.name.trim(),
|
||||
display_name: form.display_name.trim(),
|
||||
allowed_hosts: form.allowed_hosts.split(/[\s,]+/).filter(Boolean),
|
||||
delegation_domains: form.delegation_domains.split(/[\s,]+/).filter(Boolean),
|
||||
webhook_url: form.webhook_url.trim(),
|
||||
callback_base_url: form.callback_base_url.trim(),
|
||||
wholesale_sending_warmup_day_micros: toMicros(form.sending),
|
||||
wholesale_warmup_only_day_micros: toMicros(form.warmup),
|
||||
rate_limit_per_second: Number(form.rate),
|
||||
});
|
||||
}
|
||||
|
||||
const field = (id: keyof typeof form, label: string, hint?: string, placeholder?: string) => (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`partner-${id}`} className={FIELD_LABEL}>
|
||||
{label}
|
||||
</Label>
|
||||
<Input id={`partner-${id}`} value={form[id]} onChange={set(id)} placeholder={placeholder} disabled={!canManage} />
|
||||
{hint && <p className="text-xs leading-relaxed text-muted-foreground">{hint}</p>}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Panel title="Settings" description="What the partner's workspaces show, where its events go, and what it pays.">
|
||||
<form onSubmit={submit} noValidate className="grid gap-4 sm:grid-cols-2">
|
||||
{field("name", "Name")}
|
||||
{field("display_name", "Display name", 'Members read "Billed through" this name.')}
|
||||
{field("allowed_hosts", "Allowed hosts", "Hosts a return URL the partner sends may point at, separated by commas.", "app.example.com")}
|
||||
{field("rate", "Requests per second", "20 to 1000, across all of the partner's keys.")}
|
||||
{field(
|
||||
"delegation_domains",
|
||||
"Delegation domains",
|
||||
"Domains you have confirmed the partner controls, separated by commas. A mailbox the partner attaches by delegation connects only on one of these, or on a domain its workspace verified.",
|
||||
"mail.example.com",
|
||||
)}
|
||||
{field("webhook_url", "Webhook URL", "HTTPS. Events are signed with the webhook secret below.", "https://api.example.com/webhooks/warmbly")}
|
||||
{field("callback_base_url", "Token callback base", "Where per-mailbox access tokens are requested.", "https://api.example.com/v1/warmbly")}
|
||||
{field("sending", "Wholesale, sending and warmup (USD per mailbox-day)", `Now ${usdFromMicros(p.wholesale_sending_warmup_day_micros)}.`)}
|
||||
{field("warmup", "Wholesale, warmup only (USD per mailbox-day)", `Now ${usdFromMicros(p.wholesale_warmup_only_day_micros)}.`)}
|
||||
{canManage && (
|
||||
<div className="sm:col-span-2 flex justify-end">
|
||||
<Button type="submit" size="sm" disabled={save.isPending}>
|
||||
{save.isPending ? "Saving…" : "Save"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function SecretOnce({ secret, onClose, title, hint }: { secret: string | null; onClose: () => void; title: string; hint: string }) {
|
||||
return (
|
||||
<Dialog open={!!secret} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{hint}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input readOnly value={secret ?? ""} className="font-mono text-xs" onFocus={(e) => e.target.select()} />
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
void navigator.clipboard.writeText(secret ?? "");
|
||||
toast.success("Copied");
|
||||
}}
|
||||
>
|
||||
<Copy className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button onClick={onClose}>Done</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function PartnerKeysCard({ partner: p }: { partner: AdminPartnerDetail }) {
|
||||
const confirm = useConfirm();
|
||||
const canManage = useAdminPerm(AdminPerm.ManageOrganizations);
|
||||
const [secret, setSecret] = useState<string | null>(null);
|
||||
const create = usePartnerWrite(p.id, async (mode: PartnerMode) => {
|
||||
const k = await createPartnerKey(p.id, { mode });
|
||||
setSecret(k.secret);
|
||||
return k;
|
||||
}, "Key created");
|
||||
const revoke = usePartnerWrite(p.id, (keyId: string) => revokePartnerKey(p.id, keyId), "Key revoked");
|
||||
|
||||
async function askRevoke(k: AdminPartnerKey) {
|
||||
const ok = await confirm({
|
||||
title: `Revoke ${k.key_prefix}…${k.key_suffix}?`,
|
||||
description: "Anything using this key stops working at once.",
|
||||
confirmLabel: "Revoke",
|
||||
destructive: true,
|
||||
});
|
||||
if (ok) await revoke.mutateAsync(k.id).catch(() => undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<Panel
|
||||
title="API keys"
|
||||
description="A live key reaches live workspaces only, a test key test workspaces only."
|
||||
actions={
|
||||
canManage && (
|
||||
<>
|
||||
<Button size="sm" variant="outline" disabled={create.isPending} onClick={() => create.mutate("test")}>
|
||||
<Plus className="size-3.5" /> Test key
|
||||
</Button>
|
||||
<Button size="sm" disabled={create.isPending} onClick={() => create.mutate("live")}>
|
||||
<Plus className="size-3.5" /> Live key
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
bodyClassName="p-0"
|
||||
>
|
||||
{p.keys.length === 0 ? (
|
||||
<p className="px-4 py-3 text-[12.5px] text-muted-foreground">No keys yet.</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-border">
|
||||
{p.keys.map((k) => (
|
||||
<li key={k.id} className="flex items-center gap-3 px-4 py-2.5 text-[13px]">
|
||||
<KeyRound className="size-3.5 text-subtle-foreground" />
|
||||
<span className="font-mono text-xs">
|
||||
{k.key_prefix}…{k.key_suffix}
|
||||
</span>
|
||||
<StatusBadge tone={k.mode === "live" ? "info" : "neutral"}>{k.mode}</StatusBadge>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{k.revoked_at
|
||||
? `Revoked ${new Date(k.revoked_at).toLocaleDateString()}`
|
||||
: k.last_used_at
|
||||
? `Used ${new Date(k.last_used_at).toLocaleString()}`
|
||||
: "Never used"}
|
||||
</span>
|
||||
{canManage && !k.revoked_at && (
|
||||
<Button size="sm" variant="outline" className="ml-auto" onClick={() => void askRevoke(k)}>
|
||||
Revoke
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<SecretOnce
|
||||
secret={secret}
|
||||
onClose={() => setSecret(null)}
|
||||
title="Copy the key now"
|
||||
hint="This is the only time the key is shown. Give it to the partner over a secure channel."
|
||||
/>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function PartnerSecretsCard({ partner: p }: { partner: AdminPartnerDetail }) {
|
||||
const confirm = useConfirm();
|
||||
const canManage = useAdminPerm(AdminPerm.ManageOrganizations);
|
||||
const [secret, setSecret] = useState<string | null>(null);
|
||||
const [callbackKey, setCallbackKey] = useState("");
|
||||
const rotate = usePartnerWrite(p.id, async () => {
|
||||
const r = await rotatePartnerWebhookSecret(p.id);
|
||||
setSecret(r.secret);
|
||||
return r;
|
||||
}, "Webhook secret rotated");
|
||||
const saveCallback = usePartnerWrite(p.id, (key: string) => setPartnerCallbackKey(p.id, key), "Callback key saved");
|
||||
|
||||
async function askRotate() {
|
||||
if (p.webhook_secret_set) {
|
||||
const ok = await confirm({
|
||||
title: "Rotate the webhook secret?",
|
||||
description: "Events are signed with both the new and the old secret for a day, then with the new one only.",
|
||||
confirmLabel: "Rotate",
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
await rotate.mutateAsync(undefined).catch(() => undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<Panel title="Secrets" description="Stored encrypted with the instance key and never shown again after they are set.">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<div className={FIELD_LABEL}>Webhook signing secret</div>
|
||||
<div className="text-[13px]">
|
||||
{p.webhook_secret_set
|
||||
? `Set${p.webhook_secret_rotated_at ? `, rotated ${new Date(p.webhook_secret_rotated_at).toLocaleString()}` : ""}`
|
||||
: "Not set: no events are delivered until it is."}
|
||||
</div>
|
||||
{canManage && (
|
||||
<Button size="sm" variant="outline" disabled={rotate.isPending} onClick={() => void askRotate()}>
|
||||
{p.webhook_secret_set ? "Rotate secret" : "Create secret"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className="space-y-1.5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
saveCallback.mutate(callbackKey.trim(), { onSuccess: () => setCallbackKey("") });
|
||||
}}
|
||||
>
|
||||
<Label htmlFor="partner-callback-key" className={FIELD_LABEL}>
|
||||
Token callback key {p.callback_key_set ? "(set)" : "(not set)"}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="partner-callback-key"
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
placeholder={p.callback_key_set ? "Enter a new key to replace it" : "The key the partner issued"}
|
||||
value={callbackKey}
|
||||
onChange={(e) => setCallbackKey(e.target.value)}
|
||||
disabled={!canManage}
|
||||
/>
|
||||
{canManage && (
|
||||
<Button size="sm" type="submit" disabled={saveCallback.isPending || !callbackKey.trim()}>
|
||||
Save
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<SecretOnce
|
||||
secret={secret}
|
||||
onClose={() => setSecret(null)}
|
||||
title="Copy the webhook secret now"
|
||||
hint="The partner verifies every event with it. This is the only time it is shown."
|
||||
/>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function PartnerOrganizations({ partnerId }: { partnerId: string }) {
|
||||
const q = useInfiniteQuery({
|
||||
queryKey: ["admin", "partners", partnerId, "organizations"],
|
||||
queryFn: ({ pageParam }) => listPartnerOrganizations(partnerId, pageParam || undefined),
|
||||
initialPageParam: "",
|
||||
getNextPageParam: (last) => (last.pagination.has_more ? (last.pagination.next_cursor ?? undefined) : undefined),
|
||||
});
|
||||
const rows = q.data?.pages.flatMap((p) => p.data) ?? [];
|
||||
return (
|
||||
<Panel title="Workspaces" description="Every workspace the partner manages, live and test, newest first." bodyClassName="p-0">
|
||||
<DataTable
|
||||
columns={ORG_COLUMNS}
|
||||
rows={rows}
|
||||
getRowId={(o) => o.id}
|
||||
loading={q.isLoading}
|
||||
error={q.error}
|
||||
onRetry={() => void q.refetch()}
|
||||
emptyTitle="No workspaces"
|
||||
emptyHint="The partner creates them through its API."
|
||||
csvName="partner-workspaces"
|
||||
noun="workspaces"
|
||||
/>
|
||||
{q.hasNextPage && (
|
||||
<div className="flex justify-center border-t border-border p-2">
|
||||
<Button size="sm" variant="outline" disabled={q.isFetchingNextPage} onClick={() => void q.fetchNextPage()}>
|
||||
Load more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// A partner's monthly statement: enabled mailbox-days per workspace at its wholesale rates. Closed months are final.
|
||||
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit";
|
||||
import { DataTable, type Column } from "@/components/data/DataTable";
|
||||
import { getPartnerStatement, listPartnerStatements, type AdminPartnerStatementLine } from "@/lib/api/client/admin/partners";
|
||||
|
||||
function usd(m: number): string {
|
||||
return (m / 1_000_000).toLocaleString(undefined, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 6 });
|
||||
}
|
||||
|
||||
function thisMonth(): string {
|
||||
return new Date().toISOString().slice(0, 7);
|
||||
}
|
||||
|
||||
const LINE_COLUMNS: Column<AdminPartnerStatementLine>[] = [
|
||||
{ id: "external", header: "Partner's workspace id", cell: (l) => <span className="font-mono text-xs">{l.external_id}</span>, csv: (l) => l.external_id },
|
||||
{ id: "sw", header: "Sending & warmup days", align: "right", cell: (l) => l.sending_warmup_days, csv: (l) => l.sending_warmup_days },
|
||||
{ id: "wo", header: "Warmup only days", align: "right", cell: (l) => l.warmup_only_days, csv: (l) => l.warmup_only_days },
|
||||
{ id: "amount", header: "Amount", align: "right", cell: (l) => usd(l.amount_micros), csv: (l) => l.amount_micros / 1_000_000 },
|
||||
];
|
||||
|
||||
export function PartnerStatements({ partnerId }: { partnerId: string }) {
|
||||
const [month, setMonth] = useState(thisMonth);
|
||||
const closed = useQuery({ queryKey: ["admin", "partners", partnerId, "statements"], queryFn: () => listPartnerStatements(partnerId) });
|
||||
const st = useQuery({ queryKey: ["admin", "partners", partnerId, "statements", month], queryFn: () => getPartnerStatement(partnerId, month) });
|
||||
const months = Array.from(new Set([thisMonth(), ...(closed.data?.data ?? []).map((s) => s.month)]));
|
||||
const s = st.data;
|
||||
return (
|
||||
<Panel
|
||||
title="Statement"
|
||||
description="Live enabled mailbox-days per workspace at the partner's wholesale rates. A month is final a day after it ends."
|
||||
actions={
|
||||
<select
|
||||
aria-label="Month"
|
||||
value={month}
|
||||
onChange={(e) => setMonth(e.target.value)}
|
||||
className="h-8 rounded-md border border-input bg-background px-2 text-sm"
|
||||
>
|
||||
{months.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{m}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
}
|
||||
bodyClassName="p-0"
|
||||
>
|
||||
{s && (
|
||||
<PropertyList className="border-b border-border">
|
||||
<Property label="Status">
|
||||
<StatusBadge tone={s.closed_at ? "success" : "info"}>{s.closed_at ? "Closed" : "Running"}</StatusBadge>
|
||||
</Property>
|
||||
<Property label="Sending & warmup">
|
||||
{s.sending_warmup_days} days at {usd(s.sending_warmup_day_micros)}
|
||||
</Property>
|
||||
<Property label="Warmup only">
|
||||
{s.warmup_only_days} days at {usd(s.warmup_only_day_micros)}
|
||||
</Property>
|
||||
<Property label="Total">{usd(s.amount_micros)}</Property>
|
||||
</PropertyList>
|
||||
)}
|
||||
<DataTable
|
||||
columns={LINE_COLUMNS}
|
||||
rows={s?.lines ?? []}
|
||||
getRowId={(l) => l.external_id}
|
||||
loading={st.isLoading}
|
||||
error={st.error}
|
||||
onRetry={() => void st.refetch()}
|
||||
emptyTitle="No enabled mailboxes"
|
||||
emptyHint="Days count once the partner turns a mailbox on."
|
||||
csvName={`partner-statement-${month}`}
|
||||
noun="workspaces"
|
||||
/>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// Partners: resellers that create and run workspaces through /v1/partner. The partner API answers
|
||||
// nothing until one exists here (or from `warmblyctl partner create`).
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Plus } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { PageHeader } from "@/components/layout/PageHeader";
|
||||
import { DataTable, type Column } from "@/components/data/DataTable";
|
||||
import { StatusBadge } from "@/components/ui/kit";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { useAdminPerm } from "@/hooks/useAdminPerm";
|
||||
import { AdminPerm } from "@/lib/auth/permissions";
|
||||
import { createPartner, listPartners, type AdminPartner } from "@/lib/api/client/admin/partners";
|
||||
|
||||
const FIELD_LABEL = "text-xs font-medium text-muted-foreground";
|
||||
|
||||
const COLUMNS: Column<AdminPartner>[] = [
|
||||
{ id: "name", header: "Partner", cell: (p) => <span className="font-medium">{p.name}</span>, csv: (p) => p.name },
|
||||
{ id: "slug", header: "Slug", cell: (p) => <span className="font-mono text-xs text-muted-foreground">{p.slug}</span>, csv: (p) => p.slug },
|
||||
{ id: "display", header: "Members see", cell: (p) => `Billed through ${p.display_name}`, csv: (p) => p.display_name },
|
||||
{
|
||||
id: "status",
|
||||
header: "Status",
|
||||
cell: (p) => <StatusBadge tone={p.status === "active" ? "success" : "warning"}>{p.status}</StatusBadge>,
|
||||
csv: (p) => p.status,
|
||||
},
|
||||
{ id: "webhook", header: "Webhook", cell: (p) => (p.webhook_url && p.webhook_secret_set ? "Set" : "Not set"), csv: (p) => p.webhook_url ?? "" },
|
||||
];
|
||||
|
||||
export default function PartnersPage() {
|
||||
const nav = useNavigate();
|
||||
const canManage = useAdminPerm(AdminPerm.ManageOrganizations);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const q = useQuery({ queryKey: ["admin", "partners"], queryFn: listPartners });
|
||||
const rows = q.data?.data ?? [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Partners"
|
||||
description="Resellers that create, sign people in to and bill workspaces through the partner API."
|
||||
meta={rows.length ? rows.length.toLocaleString() : undefined}
|
||||
>
|
||||
{canManage && (
|
||||
<Button size="sm" onClick={() => setCreating(true)}>
|
||||
<Plus className="size-3.5" /> New partner
|
||||
</Button>
|
||||
)}
|
||||
</PageHeader>
|
||||
<NewPartnerDialog open={creating && canManage} onOpenChange={setCreating} />
|
||||
<DataTable
|
||||
columns={COLUMNS}
|
||||
rows={rows}
|
||||
getRowId={(p) => p.id}
|
||||
loading={q.isLoading}
|
||||
error={q.error}
|
||||
onRetry={() => void q.refetch()}
|
||||
onRowClick={(p) => nav(`/partners/${p.id}`)}
|
||||
emptyTitle="No partners"
|
||||
emptyHint="The partner API is off on this instance until a partner exists. Add one only for a reseller you have an agreement with."
|
||||
csvName="partners"
|
||||
noun="partners"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NewPartnerDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New partner</DialogTitle>
|
||||
<DialogDescription>
|
||||
Adds a reseller with no keys yet. Issue a test key on the next page, then a live one when it is ready.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<NewPartnerForm onClose={() => onOpenChange(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function NewPartnerForm({ onClose }: { onClose: () => void }) {
|
||||
const nav = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const [slug, setSlug] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [display, setDisplay] = useState("");
|
||||
const [hosts, setHosts] = useState("");
|
||||
const ready = /^[a-z0-9][a-z0-9-]{1,39}$/.test(slug.trim()) && !!name.trim();
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () =>
|
||||
createPartner({
|
||||
slug: slug.trim(),
|
||||
name: name.trim(),
|
||||
display_name: display.trim() || undefined,
|
||||
allowed_hosts: hosts.split(/[\s,]+/).filter(Boolean),
|
||||
}),
|
||||
onSuccess: (p) => {
|
||||
qc.setQueryData(["admin", "partners", p.id], p);
|
||||
void qc.invalidateQueries({ queryKey: ["admin", "partners"], exact: true });
|
||||
toast.success("Partner created");
|
||||
onClose();
|
||||
nav(`/partners/${p.id}`);
|
||||
},
|
||||
});
|
||||
|
||||
function submit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
if (ready && !create.isPending) create.mutate();
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} noValidate className="grid gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="new-partner-slug" className={FIELD_LABEL}>
|
||||
Slug
|
||||
</Label>
|
||||
<Input id="new-partner-slug" placeholder="graphkit" value={slug} onChange={(e) => setSlug(e.target.value.toLowerCase())} autoFocus />
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">Lowercase letters, digits and dashes. It cannot be changed later.</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="new-partner-name" className={FIELD_LABEL}>
|
||||
Name
|
||||
</Label>
|
||||
<Input id="new-partner-name" placeholder="GraphKit" value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="new-partner-display" className={FIELD_LABEL}>
|
||||
Display name
|
||||
</Label>
|
||||
<Input id="new-partner-display" placeholder={name || "GraphKit"} value={display} onChange={(e) => setDisplay(e.target.value)} />
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">Members of its workspaces read "Billed through {display || name || "…"}".</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="new-partner-hosts" className={FIELD_LABEL}>
|
||||
Allowed hosts
|
||||
</Label>
|
||||
<Input id="new-partner-hosts" placeholder="app.graphkit.com" value={hosts} onChange={(e) => setHosts(e.target.value)} />
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">Hosts a return URL the partner sends may point at, separated by commas.</p>
|
||||
</div>
|
||||
{create.error && (
|
||||
<p role="alert" className="text-[12.5px] leading-relaxed text-[var(--admin-danger)]">
|
||||
{create.error.message || "Failed to create the partner."}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={!ready || create.isPending}>
|
||||
{create.isPending ? "Creating…" : "Create partner"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Store economics: GraphKit's wholesale price against the retail price this
|
||||
// instance charges, per mailbox provider and per domain TLD, and the month's totals.
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Wallet } from "lucide-react";
|
||||
import { EmptyState, Section, Stat, StatGrid } from "@/components/ui/kit";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import { APIError } from "@/lib/api/client";
|
||||
import { getStoreEconomics } from "@/lib/api/client/admin/store";
|
||||
import { relative } from "@/app/dashboard/jobs/format";
|
||||
import { TONE_TEXT } from "@/lib/tones";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { providerLabel, usd } from "./format";
|
||||
|
||||
const TH = "h-9 px-3 text-left text-xs font-medium text-muted-foreground whitespace-nowrap";
|
||||
const TD = "px-3 py-2 tabular-nums whitespace-nowrap";
|
||||
|
||||
function marginPct(retail: number, wholesale: number): string {
|
||||
if (retail <= 0) return "—";
|
||||
return `${Math.round(((retail - wholesale) / retail) * 100)}%`;
|
||||
}
|
||||
|
||||
function Margin({ micros }: { micros: number }) {
|
||||
return <span className={cn(micros < 0 && TONE_TEXT.danger)}>{usd(micros)}</span>;
|
||||
}
|
||||
|
||||
export function EconomicsTab() {
|
||||
const q = useQuery({ queryKey: ["admin", "store", "economics"], queryFn: getStoreEconomics, staleTime: 5 * 60_000, retry: false });
|
||||
if (q.isLoading) return <Skeleton className="h-64 w-full rounded-xl" />;
|
||||
if (q.error instanceof APIError && q.error.code === "store_disabled") {
|
||||
return <EmptyState icon={Wallet} title="The store is off" hint="There are no prices to compare until GRAPHKIT_API_KEY is set." />;
|
||||
}
|
||||
if (q.error || !q.data) return <ErrorState error={q.error} title="Failed to load store economics" onRetry={() => q.refetch()} />;
|
||||
const e = q.data;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<StatGrid>
|
||||
<Stat label="Live mailboxes" value={e.totals.live_mailboxes.toLocaleString()} />
|
||||
<Stat label="Monthly retail" value={usd(e.totals.monthly_retail_micros)} />
|
||||
<Stat label="Monthly wholesale" value={usd(e.totals.monthly_wholesale_micros)} />
|
||||
<Stat label="Monthly margin" value={usd(e.totals.monthly_margin_micros)} tone={e.totals.monthly_margin_micros < 0 ? "danger" : undefined} sub={marginPct(e.totals.monthly_retail_micros, e.totals.monthly_wholesale_micros)} />
|
||||
</StatGrid>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
Prices in {e.currency.toUpperCase()}, read from GraphKit {relative(e.updated_at)}. Mailbox totals only; domain income lands once a year per domain.
|
||||
</p>
|
||||
|
||||
<Section title="Mailboxes" description="Monthly price per mailbox." className="mt-8">
|
||||
<div className="overflow-x-auto rounded-xl border border-border">
|
||||
<table className="w-full border-collapse text-[13px]">
|
||||
<thead className="border-b border-border">
|
||||
<tr>
|
||||
<th className={TH}>Provider</th>
|
||||
<th className={cn(TH, "text-right")}>Wholesale</th>
|
||||
<th className={cn(TH, "text-right")}>Retail</th>
|
||||
<th className={cn(TH, "text-right")}>Margin</th>
|
||||
<th className={cn(TH, "text-right")}>Margin %</th>
|
||||
<th className={TH}>Scheduled change</th>
|
||||
<th className={cn(TH, "text-right")}>Live</th>
|
||||
<th className={cn(TH, "text-right")}>Monthly margin</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/70">
|
||||
{e.mailboxes.map((m) => (
|
||||
<tr key={m.provider}>
|
||||
<td className={cn(TD, "font-medium")}>{providerLabel(m.provider)}</td>
|
||||
<td className={cn(TD, "text-right")}>{usd(m.wholesale_monthly_micros)}</td>
|
||||
<td className={cn(TD, "text-right")}>{usd(m.retail_monthly_micros)}</td>
|
||||
<td className={cn(TD, "text-right")}><Margin micros={m.margin_micros} /></td>
|
||||
<td className={cn(TD, "text-right text-muted-foreground")}>{marginPct(m.retail_monthly_micros, m.wholesale_monthly_micros)}</td>
|
||||
<td className={TD}>
|
||||
{m.scheduled_wholesale_monthly_micros != null ? (
|
||||
<span className={cn(m.scheduled_wholesale_monthly_micros > m.retail_monthly_micros && TONE_TEXT.danger)}>
|
||||
{usd(m.scheduled_wholesale_monthly_micros)}
|
||||
{m.scheduled_from && <span className="text-muted-foreground"> from {new Date(m.scheduled_from).toLocaleDateString()}</span>}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-subtle-foreground">None</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={cn(TD, "text-right")}>{m.live_count.toLocaleString()}</td>
|
||||
<td className={cn(TD, "text-right")}><Margin micros={m.margin_micros * m.live_count} /></td>
|
||||
</tr>
|
||||
))}
|
||||
{e.mailboxes.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-3 py-6 text-center text-muted-foreground">No mailbox prices</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Domains" description="Per year, at the TLD's minimum term.">
|
||||
<div className="overflow-x-auto rounded-xl border border-border">
|
||||
<table className="w-full border-collapse text-[13px]">
|
||||
<thead className="border-b border-border">
|
||||
<tr>
|
||||
<th className={TH}>TLD</th>
|
||||
<th className={cn(TH, "text-right")}>Min years</th>
|
||||
<th className={cn(TH, "text-right")}>Register wholesale</th>
|
||||
<th className={cn(TH, "text-right")}>Register retail</th>
|
||||
<th className={cn(TH, "text-right")}>Register margin</th>
|
||||
<th className={cn(TH, "text-right")}>Renew wholesale</th>
|
||||
<th className={cn(TH, "text-right")}>Renew retail</th>
|
||||
<th className={cn(TH, "text-right")}>Renew margin</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/70">
|
||||
{e.domains.map((d) => (
|
||||
<tr key={d.tld}>
|
||||
<td className={cn(TD, "font-mono")}>.{d.tld.replace(/^\./, "")}</td>
|
||||
<td className={cn(TD, "text-right")}>{d.min_years}</td>
|
||||
<td className={cn(TD, "text-right")}>{usd(d.wholesale_register_micros)}</td>
|
||||
<td className={cn(TD, "text-right")}>{usd(d.retail_register_micros)}</td>
|
||||
<td className={cn(TD, "text-right")}><Margin micros={d.retail_register_micros - d.wholesale_register_micros} /></td>
|
||||
<td className={cn(TD, "text-right")}>{usd(d.wholesale_renew_micros)}</td>
|
||||
<td className={cn(TD, "text-right")}>{usd(d.retail_renew_micros)}</td>
|
||||
<td className={cn(TD, "text-right")}><Margin micros={d.retail_renew_micros - d.wholesale_renew_micros} /></td>
|
||||
</tr>
|
||||
))}
|
||||
{e.domains.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-3 py-6 text-center text-muted-foreground">No domain prices</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// Store health: which GraphKit environment the store talks to, the partner
|
||||
// balance that pays for every order, whether webhooks and the two loops are
|
||||
// keeping up, and the counts an operator acts on, each linking to its list.
|
||||
|
||||
import { Link } from "react-router-dom";
|
||||
import { AlertTriangle, Bell, Wallet } from "lucide-react";
|
||||
import { Callout, EmptyState, Panel, Property, PropertyList, Section, StatusBadge } from "@/components/ui/kit";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import type { StoreHealth, StoreLoopStatus } from "@/lib/api/client/admin/store";
|
||||
import { absolute, humanSeconds, relative } from "@/app/dashboard/jobs/format";
|
||||
import { TONE_TEXT, type Tone } from "@/lib/tones";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { MODE_TONE, storeLink, usd } from "./format";
|
||||
import { useStoreHealth } from "./useStoreHealth";
|
||||
|
||||
// Webhooks only arrive on change, so a quiet day is normal; past this the reconciler is the only source.
|
||||
const WEBHOOK_STALE_MS = 24 * 60 * 60 * 1000;
|
||||
// A loop this far behind has stopped keeping the store current.
|
||||
const LOOP_LAG_WARN_SECONDS = 60 * 60;
|
||||
|
||||
export function HealthTab() {
|
||||
const q = useStoreHealth();
|
||||
if (q.isLoading) return <Skeleton className="h-64 w-full rounded-xl" />;
|
||||
if (q.error || !q.data) return <ErrorState error={q.error} title="Failed to load store health" onRetry={() => q.refetch()} />;
|
||||
const h = q.data;
|
||||
if (!h.enabled || h.mode === "off") {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={Wallet}
|
||||
title="The store is off"
|
||||
hint="It turns on when GRAPHKIT_API_KEY is set on the backend. Nothing is sold and no loop runs until then."
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-5 flex flex-wrap items-center gap-2">
|
||||
<StatusBadge tone={MODE_TONE[h.mode] ?? "neutral"} dot>
|
||||
{h.mode}
|
||||
</StatusBadge>
|
||||
<StatusBadge tone={h.metered ? "neutral" : "warning"}>{h.metered ? "charges workspaces" : "unmetered: charges nothing"}</StatusBadge>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<BalancePanel h={h} />
|
||||
<WebhookPanel h={h} />
|
||||
<LoopPanel title="Reconciler" hint="Re-reads open orders and domains from GraphKit" loop={h.reconciler} />
|
||||
<LoopPanel title="Billing loop" hint="Charges mailbox months and domain renewals" loop={h.billing} />
|
||||
</div>
|
||||
|
||||
<Section title="Needs attention" className="mt-8">
|
||||
<CountGrid h={h} />
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Collected ahead of GraphKit"
|
||||
description="Mailboxes whose GraphKit period started before Warmbly collected it. This should stay at 0."
|
||||
>
|
||||
{(h.uncollected ?? []).length === 0 ? (
|
||||
<div className="rounded-xl border border-border px-4 py-6 text-center text-[13px] text-muted-foreground">
|
||||
Every mailbox period was paid before it started
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-border overflow-hidden rounded-xl border border-border">
|
||||
{(h.uncollected ?? []).map((m) => (
|
||||
<li key={m.id} className="flex items-center gap-3 px-4 py-2.5 text-[13px]">
|
||||
<AlertTriangle className={cn("size-3.5 shrink-0", TONE_TEXT.danger)} />
|
||||
<span className="min-w-0 flex-1 truncate">{m.email}</span>
|
||||
<span className="shrink-0 tabular-nums text-muted-foreground" title={absolute(m.period_end)}>
|
||||
GraphKit to {absolute(m.period_end)}, paid to {absolute(m.paid_through)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<Section title="Recent store alerts" description="store.unavailable operator alerts, newest first.">
|
||||
{h.alerts.length === 0 ? (
|
||||
<div className="rounded-xl border border-border px-4 py-6 text-center text-[13px] text-muted-foreground">No recent alerts</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-border overflow-hidden rounded-xl border border-border">
|
||||
{h.alerts.map((a, i) => (
|
||||
<li key={`${a.at}-${i}`} className="flex items-center gap-3 px-4 py-2.5 text-[13px]">
|
||||
<Bell className="size-3.5 shrink-0 text-subtle-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate">{a.title}</span>
|
||||
<span className="hidden font-mono text-[11.5px] text-subtle-foreground sm:inline">{a.code}</span>
|
||||
<span className="shrink-0 tabular-nums text-muted-foreground" title={absolute(a.at)}>
|
||||
{relative(a.at)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BalancePanel({ h }: { h: StoreHealth }) {
|
||||
const b = h.partner_balance;
|
||||
const low = !!b && b.balance_micros <= b.low_threshold_micros;
|
||||
return (
|
||||
<Panel title="Partner balance" description="What GraphKit draws on for every order and renewal">
|
||||
{!b ? (
|
||||
<Callout tone="warning" icon={AlertTriangle} title="Balance unavailable">
|
||||
{h.partner_balance_error === "store_unavailable" ? "GraphKit did not answer the balance read." : "No balance reported."}
|
||||
</Callout>
|
||||
) : (
|
||||
<>
|
||||
<div className={cn("text-2xl font-semibold tracking-[-0.03em] tabular-nums", low ? TONE_TEXT.danger : "text-foreground")}>
|
||||
{usd(b.balance_micros)}
|
||||
<span className="ml-1.5 text-xs font-normal text-muted-foreground">{b.currency.toUpperCase()}</span>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
Low below {usd(b.low_threshold_micros)}
|
||||
{!b.livemode && ", sandbox funds"}
|
||||
</div>
|
||||
{low && (
|
||||
<Callout tone="danger" icon={AlertTriangle} title="Balance is at or below the low threshold" className="mt-3">
|
||||
Top up the partner account before orders and renewals start failing.
|
||||
</Callout>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function WebhookPanel({ h }: { h: StoreHealth }) {
|
||||
const stale = !h.last_webhook_at || Date.now() - new Date(h.last_webhook_at).getTime() > WEBHOOK_STALE_MS;
|
||||
return (
|
||||
<Panel title="Webhooks" description="GraphKit pushes order, domain and mailbox changes">
|
||||
<PropertyList>
|
||||
<Property label="Last received">
|
||||
<span className={cn("inline-flex items-center gap-1", stale && TONE_TEXT.warning)} title={absolute(h.last_webhook_at)}>
|
||||
{stale && <AlertTriangle className="size-3.5" />}
|
||||
{relative(h.last_webhook_at)}
|
||||
</span>
|
||||
</Property>
|
||||
<Property label="Event cursor">{h.events_cursor_set ? "Set" : <span className={TONE_TEXT.warning}>Not set</span>}</Property>
|
||||
</PropertyList>
|
||||
{stale && <p className="mt-2 text-xs text-muted-foreground">Nothing in the last day. The reconciler still catches changes, more slowly.</p>}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function loopTone(loop: StoreLoopStatus): Tone {
|
||||
const s = loop.last_status.toLowerCase();
|
||||
if (s === "error" || s === "failed") return "danger";
|
||||
if (loop.lag_seconds > LOOP_LAG_WARN_SECONDS) return "warning";
|
||||
return "success";
|
||||
}
|
||||
|
||||
function LoopPanel({ title, hint, loop }: { title: string; hint: string; loop: StoreLoopStatus | null }) {
|
||||
if (!loop) {
|
||||
return (
|
||||
<Panel title={title} description={hint}>
|
||||
<p className="text-[13px] text-muted-foreground">Has not run yet on this instance.</p>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
const tone = loopTone(loop);
|
||||
return (
|
||||
<Panel
|
||||
title={title}
|
||||
description={hint}
|
||||
actions={
|
||||
<StatusBadge tone={tone} dot>
|
||||
{loop.last_status || "unknown"}
|
||||
</StatusBadge>
|
||||
}
|
||||
>
|
||||
<PropertyList>
|
||||
<Property label="Lag">
|
||||
<span className={cn("tabular-nums", tone !== "success" && TONE_TEXT[tone])}>{humanSeconds(loop.lag_seconds)}</span>
|
||||
</Property>
|
||||
<Property label="Last finished">
|
||||
<span title={absolute(loop.last_finished_at)}>{relative(loop.last_finished_at)}</span>
|
||||
</Property>
|
||||
<Property label="Last started">
|
||||
<span title={absolute(loop.last_started_at)}>{relative(loop.last_started_at)}</span>
|
||||
</Property>
|
||||
{loop.last_error && (
|
||||
<Property label="Last error">
|
||||
<span className="font-mono text-[12px] text-[var(--admin-danger)]">{loop.last_error}</span>
|
||||
</Property>
|
||||
)}
|
||||
</PropertyList>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function CountGrid({ h }: { h: StoreHealth }) {
|
||||
const c = h.counts;
|
||||
const items: { label: string; value: number; to: string; tone: Tone }[] = [
|
||||
{ label: "Open orders", value: c.orders_open, to: storeLink("orders", { status: "open" }), tone: "info" },
|
||||
{ label: "Stuck orders", value: c.orders_stuck, to: storeLink("orders", { stuck: "true" }), tone: "danger" },
|
||||
{ label: "Failed orders, 7 days", value: c.orders_failed_7d, to: storeLink("orders", { status: "failed" }), tone: "danger" },
|
||||
{ label: "Failed connects", value: c.connects_failed, to: storeLink("mailboxes", { connect_state: "failed" }), tone: "danger" },
|
||||
{ label: "Billing failures", value: c.mailboxes_billing_failed, to: storeLink("mailboxes", { billing_failed: "true" }), tone: "danger" },
|
||||
{ label: "Renewal failures", value: c.domains_renewal_failed, to: storeLink("domains", { renewal_failed: "true" }), tone: "danger" },
|
||||
{ label: "Expiring in 30 days", value: c.domains_expiring_30d, to: storeLink("domains", { expiring_days: "30" }), tone: "warning" },
|
||||
{ label: "Live mailboxes", value: c.mailboxes_live, to: storeLink("mailboxes", { status: "active" }), tone: "neutral" },
|
||||
{ label: "Live domains", value: c.domains_live, to: storeLink("domains", { status: "active" }), tone: "neutral" },
|
||||
];
|
||||
return (
|
||||
<div className="surface-lit grid grid-cols-2 gap-px overflow-hidden rounded-xl border border-border bg-border md:grid-cols-3">
|
||||
{items.map((it) => (
|
||||
<Link key={it.label} to={it.to} className="bg-card px-4 py-3.5 transition-colors hover:bg-accent/40">
|
||||
<div className="text-xs text-muted-foreground">{it.label}</div>
|
||||
<div className={cn("mt-1.5 text-2xl leading-8 font-semibold tracking-[-0.03em] tabular-nums", it.value > 0 && it.tone !== "neutral" ? TONE_TEXT[it.tone] : "text-foreground")}>
|
||||
{it.value.toLocaleString()}
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// Refunds a store order to the workspace balance: one quote line's charge, or
|
||||
// an amount with a reason, capped at what was charged and not yet refunded.
|
||||
// The idempotency key belongs to the request body, so a retried click after a
|
||||
// timeout reuses it and the server never pays twice.
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Segmented } from "@/components/ui/kit";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { ReauthCancelledError } from "@/lib/api/client";
|
||||
import { refundStoreOrder, type AdminStoreOrder, type StoreRefund } from "@/lib/api/client/admin/store";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { dollarsToMicros, newIdempotencyKey, refundableMicros, usd } from "./format";
|
||||
import { storeErrorText } from "./useStoreAction";
|
||||
|
||||
type Mode = "line" | "amount";
|
||||
|
||||
export function RefundDialog({
|
||||
order,
|
||||
open,
|
||||
onOpenChange,
|
||||
onRefunded,
|
||||
}: {
|
||||
order: AdminStoreOrder;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onRefunded: (order: AdminStoreOrder) => void;
|
||||
}) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
{open && <RefundForm order={order} onDone={onRefunded} onCancel={() => onOpenChange(false)} />}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function RefundForm({
|
||||
order,
|
||||
onDone,
|
||||
onCancel,
|
||||
}: {
|
||||
order: AdminStoreOrder;
|
||||
onDone: (order: AdminStoreOrder) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const cap = refundableMicros(order);
|
||||
const refunded = new Set(order.refunded_lines ?? []);
|
||||
const openLines = order.lines.map((l, i) => ({ line: l, index: i })).filter((x) => !refunded.has(x.index) && x.line.amount_micros > 0);
|
||||
const [mode, setMode] = useState<Mode>(openLines.length > 0 ? "line" : "amount");
|
||||
const [line, setLine] = useState<number | null>(openLines[0]?.index ?? null);
|
||||
const [amount, setAmount] = useState("");
|
||||
const [reason, setReason] = useState("");
|
||||
const keyFor = useRef<{ body: string; key: string } | null>(null);
|
||||
|
||||
const micros = dollarsToMicros(amount);
|
||||
const amountError =
|
||||
mode !== "amount" || micros === null
|
||||
? null
|
||||
: Number.isNaN(micros) || micros <= 0
|
||||
? "Enter an amount in dollars, like 12.50"
|
||||
: micros > cap
|
||||
? `At most ${usd(cap)} is left to refund`
|
||||
: null;
|
||||
|
||||
const body: StoreRefund | null =
|
||||
mode === "line"
|
||||
? line === null
|
||||
? null
|
||||
: { line }
|
||||
: micros && !amountError && reason.trim()
|
||||
? { amount_micros: micros, reason: reason.trim() }
|
||||
: null;
|
||||
|
||||
const refund = useMutation({
|
||||
mutationFn: (req: { body: StoreRefund; key: string }) => refundStoreOrder(order.id, req.body, req.key),
|
||||
onSuccess: (res) => {
|
||||
toast.success(res.refunded_micros > 0 ? `Refunded ${usd(res.refunded_micros)} to the workspace balance` : "Already refunded; nothing more was paid");
|
||||
qc.invalidateQueries({ queryKey: ["admin", "store"] });
|
||||
onDone(res.order);
|
||||
},
|
||||
onError: (e) => {
|
||||
if (!(e instanceof ReauthCancelledError)) toast.error(storeErrorText(e));
|
||||
},
|
||||
});
|
||||
|
||||
function submit() {
|
||||
if (!body) return;
|
||||
const sig = JSON.stringify(body);
|
||||
if (keyFor.current?.body !== sig) keyFor.current = { body: sig, key: newIdempotencyKey() };
|
||||
refund.mutate({ body, key: keyFor.current.key });
|
||||
}
|
||||
|
||||
const lineAmount = line !== null ? order.lines[line]?.amount_micros : undefined;
|
||||
const total = mode === "line" ? lineAmount : micros && !Number.isNaN(micros) ? micros : undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Refund to the workspace balance</DialogTitle>
|
||||
<DialogDescription>
|
||||
{order.organization_name} was charged {usd(order.charged_micros)} and has had {usd(order.refunded_micros)} back.
|
||||
Up to {usd(cap)} can still be refunded. The money goes to the workspace's balance, not the card.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4">
|
||||
<Segmented
|
||||
value={mode}
|
||||
onChange={setMode}
|
||||
ariaLabel="Refund type"
|
||||
options={[
|
||||
{ value: "line", label: "A quote line", disabled: openLines.length === 0 },
|
||||
{ value: "amount", label: "An amount" },
|
||||
]}
|
||||
/>
|
||||
|
||||
{mode === "line" ? (
|
||||
openLines.length === 0 ? (
|
||||
<p className="text-[13px] text-muted-foreground">Every line with a charge has been refunded.</p>
|
||||
) : (
|
||||
<div role="radiogroup" aria-label="Line to refund" className="divide-y divide-border overflow-hidden rounded-lg border border-border">
|
||||
{openLines.map(({ line: l, index }) => (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={line === index}
|
||||
onClick={() => setLine(index)}
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[13px] transition-colors",
|
||||
line === index ? "bg-[var(--admin-accent-weak)]" : "hover:bg-accent/60",
|
||||
)}
|
||||
>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate font-medium text-foreground">{l.domain}</span>
|
||||
<span className="block text-xs text-muted-foreground">
|
||||
{l.type === "domain" ? `Domain, ${l.years ?? 1} year${(l.years ?? 1) === 1 ? "" : "s"}` : `${l.count ?? 0} mailbox${l.count === 1 ? "" : "es"}`}
|
||||
</span>
|
||||
</span>
|
||||
<span className="tabular-nums">{usd(l.amount_micros)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="refund-amount" className="text-xs font-medium text-muted-foreground">
|
||||
Amount (USD)
|
||||
</Label>
|
||||
<Input
|
||||
id="refund-amount"
|
||||
inputMode="decimal"
|
||||
placeholder={`Up to ${usd(cap)}`}
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
aria-invalid={!!amountError}
|
||||
/>
|
||||
{amountError && <p className="text-xs text-[var(--admin-danger)]">{amountError}</p>}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="refund-reason" className="text-xs font-medium text-muted-foreground">
|
||||
Reason
|
||||
</Label>
|
||||
<Textarea
|
||||
id="refund-reason"
|
||||
placeholder="Why this refund (kept in the audit log)"
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={submit} disabled={!body || refund.isPending || cap <= 0}>
|
||||
{refund.isPending ? "Refunding…" : total ? `Refund ${usd(total)}` : "Refund"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
// Detail drawers for one store order, domain or mailbox, with the operator
|
||||
// actions on each. Actions show only to admins holding manage-organizations;
|
||||
// the server enforces the same bit.
|
||||
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Link } from "react-router-dom";
|
||||
import { AlertTriangle, CalendarClock, HandCoins, Pause, Play, PlugZap, RefreshCw, Send } from "lucide-react";
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Callout, Property, PropertyList, StatusBadge } from "@/components/ui/kit";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import {
|
||||
getStoreOrder,
|
||||
placeStoreOrder,
|
||||
refreshStoreOrder,
|
||||
setStoreDomainAutoRenew,
|
||||
storeDomainAction,
|
||||
storeMailboxAction,
|
||||
type AdminStoreDomain,
|
||||
type AdminStoreMailbox,
|
||||
type AdminStoreOrder,
|
||||
} from "@/lib/api/client/admin/store";
|
||||
import { absolute, relative } from "@/app/dashboard/jobs/format";
|
||||
import { label, providerLabel, refundableMicros, statusTone, usd } from "./format";
|
||||
import { RefundDialog } from "./RefundDialog";
|
||||
import { useStoreAction } from "./useStoreAction";
|
||||
|
||||
const linkCls = "underline decoration-border-strong underline-offset-2 hover:text-[var(--admin-accent-strong)]";
|
||||
const mono = "font-mono text-[12px] break-all";
|
||||
|
||||
function Drawer({ open, onClose, children }: { open: boolean; onClose: () => void; children: ReactNode }) {
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<SheetContent side="right" className="w-full gap-0 sm:max-w-xl">
|
||||
{children}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function Header({ title, children }: { title: ReactNode; children?: ReactNode }) {
|
||||
return (
|
||||
<SheetHeader className="gap-1 border-b border-border px-5 py-4 pr-12">
|
||||
<SheetTitle className="truncate">{title}</SheetTitle>
|
||||
<SheetDescription className="text-[12.5px]">{children}</SheetDescription>
|
||||
</SheetHeader>
|
||||
);
|
||||
}
|
||||
|
||||
function Actions({ canManage, children }: { canManage: boolean; children: ReactNode }) {
|
||||
if (!canManage) {
|
||||
return <p className="text-xs text-muted-foreground">Actions need the manage organizations admin permission.</p>;
|
||||
}
|
||||
return <div className="flex flex-wrap gap-1.5">{children}</div>;
|
||||
}
|
||||
|
||||
function When({ ts, empty = "—" }: { ts: string | null | undefined; empty?: string }) {
|
||||
if (!ts) return <span className="text-subtle-foreground">{empty}</span>;
|
||||
return <span title={absolute(ts)}>{relative(ts)}</span>;
|
||||
}
|
||||
|
||||
function Workspace({ id, name }: { id: string; name: string }) {
|
||||
return (
|
||||
<Link to={`/store/workspaces/${id}`} className={linkCls}>
|
||||
{name || id}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Order -------------------------------------------------------------------
|
||||
|
||||
export function OrderDrawer({ order, onClose }: { order: AdminStoreOrder | null; onClose: () => void }) {
|
||||
return (
|
||||
<Drawer open={order !== null} onClose={onClose}>
|
||||
{order && <OrderDetail key={order.id} seed={order} />}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function OrderDetail({ seed }: { seed: AdminStoreOrder }) {
|
||||
const qc = useQueryClient();
|
||||
const key = ["admin", "store", "order", seed.id];
|
||||
const q = useQuery({ queryKey: key, queryFn: () => getStoreOrder(seed.id), initialData: seed, initialDataUpdatedAt: 0 });
|
||||
const o = q.data;
|
||||
const { act, busy, canManage } = useStoreAction();
|
||||
const [refunding, setRefunding] = useState(false);
|
||||
const put = (next: AdminStoreOrder | undefined) => next && qc.setQueryData(key, next);
|
||||
const refundable = refundableMicros(o);
|
||||
const refundedLines = new Set(o.refunded_lines ?? []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header title={`Order ${o.id.slice(0, 8)}`}>
|
||||
<Workspace id={o.organization_id} name={o.organization_name} />, placed <When ts={o.created_at} />
|
||||
</Header>
|
||||
<div className="flex-1 space-y-6 overflow-y-auto px-5 py-4">
|
||||
{q.error && <ErrorState error={q.error} title="Failed to refresh this order" onRetry={() => q.refetch()} />}
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<StatusBadge tone={statusTone(o.status)} dot>
|
||||
{label(o.status)}
|
||||
</StatusBadge>
|
||||
{o.stuck && <StatusBadge tone="warning">stuck</StatusBadge>}
|
||||
<StatusBadge tone={o.placed ? "neutral" : "warning"}>{o.placed ? "placed at GraphKit" : "not placed"}</StatusBadge>
|
||||
</div>
|
||||
|
||||
{o.failure_code && (
|
||||
<Callout tone="danger" icon={AlertTriangle} title="Failure">
|
||||
<span className="font-mono">{o.failure_code}</span>
|
||||
</Callout>
|
||||
)}
|
||||
{o.stuck && (
|
||||
<Callout tone="warning" icon={AlertTriangle} title="This order has not moved">
|
||||
It is open past the point the reconciler expects it to settle. Refresh re-reads it from GraphKit
|
||||
{o.charged_micros > 0 && !o.placed ? "; it was charged but never placed, so retry placing it." : "."}
|
||||
</Callout>
|
||||
)}
|
||||
|
||||
<Actions canManage={canManage}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "refresh",
|
||||
confirm: { title: "Refresh this order?", description: "Re-reads the order from GraphKit and applies what it says.", confirmLabel: "Refresh" },
|
||||
success: "Order refreshed",
|
||||
run: () => refreshStoreOrder(o.id),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<RefreshCw className="size-3.5" />
|
||||
{busy === "refresh" ? "Refreshing…" : "Refresh"}
|
||||
</Button>
|
||||
{o.charged_micros > 0 && !o.placed && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "place",
|
||||
confirm: {
|
||||
title: "Retry placing this order?",
|
||||
description: `The workspace was charged ${usd(o.charged_micros)} and GraphKit never received the order. It is placed under its original key, so it cannot be placed twice.`,
|
||||
confirmLabel: "Place order",
|
||||
},
|
||||
success: "Order placed",
|
||||
run: () => placeStoreOrder(o.id),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Send className="size-3.5" />
|
||||
{busy === "place" ? "Placing…" : "Retry placing"}
|
||||
</Button>
|
||||
)}
|
||||
{refundable > 0 && (
|
||||
<Button size="sm" variant="outline" disabled={busy !== null} onClick={() => setRefunding(true)}>
|
||||
<HandCoins className="size-3.5" />
|
||||
Refund
|
||||
</Button>
|
||||
)}
|
||||
</Actions>
|
||||
|
||||
<PropertyList title="Money">
|
||||
<Property label="Due at checkout">{usd(o.due_now_micros)}</Property>
|
||||
<Property label="Charged">{usd(o.charged_micros)}</Property>
|
||||
<Property label="Refunded">{usd(o.refunded_micros)}</Property>
|
||||
<Property label="Refundable">{usd(refundable)}</Property>
|
||||
</PropertyList>
|
||||
|
||||
<div>
|
||||
<div className="mb-1 text-xs font-medium text-muted-foreground">Lines</div>
|
||||
<div className="divide-y divide-border overflow-hidden rounded-lg border border-border">
|
||||
{o.lines.map((l, i) => (
|
||||
<div key={i} className="flex items-center justify-between gap-3 px-3 py-2 text-[13px]">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium">{l.domain}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{l.type === "domain"
|
||||
? `Domain, ${l.years ?? 1} yr${l.renew_micros ? `, renews at ${usd(l.renew_micros)}` : ""}`
|
||||
: `${l.count ?? 0} ${providerLabel(l.provider ?? "")} mailbox${l.count === 1 ? "" : "es"}${l.monthly_micros ? `, ${usd(l.monthly_micros)}/mo each` : ""}`}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{refundedLines.has(i) && <StatusBadge tone="neutral">refunded</StatusBadge>}
|
||||
<span className="tabular-nums">{usd(l.amount_micros)}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{o.lines.length === 0 && <div className="px-3 py-2 text-[13px] text-muted-foreground">No lines</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-1 text-xs font-medium text-muted-foreground">Steps</div>
|
||||
<ol className="divide-y divide-border overflow-hidden rounded-lg border border-border">
|
||||
{o.steps.map((s) => (
|
||||
<li key={s.key} className="flex items-center justify-between gap-3 px-3 py-2 text-[13px]">
|
||||
<span>{label(s.key)}</span>
|
||||
<span className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
{s.at && <When ts={s.at} />}
|
||||
<StatusBadge tone={statusTone(s.status)}>{s.status}</StatusBadge>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{o.steps.length === 0 && <li className="px-3 py-2 text-[13px] text-muted-foreground">No steps yet</li>}
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<PropertyList title="Record">
|
||||
<Property label="Order id"><span className={mono}>{o.id}</span></Property>
|
||||
<Property label="GraphKit id">{o.upstream_id ? <span className={mono}>{o.upstream_id}</span> : <span className="text-subtle-foreground">Not placed</span>}</Property>
|
||||
<Property label="Created by">{o.created_by ? <Link to={`/users/${o.created_by}`} className={linkCls}>{o.created_by.slice(0, 8)}</Link> : <span className="text-subtle-foreground">API or system</span>}</Property>
|
||||
<Property label="Updated"><When ts={o.updated_at} /></Property>
|
||||
<Property label="Completed"><When ts={o.completed_at} empty="Open" /></Property>
|
||||
</PropertyList>
|
||||
</div>
|
||||
<RefundDialog
|
||||
order={o}
|
||||
open={refunding}
|
||||
onOpenChange={setRefunding}
|
||||
onRefunded={(next) => {
|
||||
put(next);
|
||||
setRefunding(false);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Domain ------------------------------------------------------------------
|
||||
|
||||
export function DomainDrawer({ domain, onClose }: { domain: AdminStoreDomain | null; onClose: () => void }) {
|
||||
return (
|
||||
<Drawer open={domain !== null} onClose={onClose}>
|
||||
{domain && <DomainDetail key={domain.id} seed={domain} />}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function DomainDetail({ seed }: { seed: AdminStoreDomain }) {
|
||||
const [d, setD] = useState(seed);
|
||||
const { act, busy, canManage } = useStoreAction();
|
||||
const put = (next: AdminStoreDomain | undefined) => next && setD(next);
|
||||
const purchased = d.source === "purchased";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header title={d.name}>
|
||||
<Workspace id={d.organization_id} name={d.organization_name} />, {purchased ? "bought here" : "connected"}{" "}
|
||||
<When ts={d.created_at} />
|
||||
</Header>
|
||||
<div className="flex-1 space-y-6 overflow-y-auto px-5 py-4">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<StatusBadge tone={statusTone(d.status)} dot>
|
||||
{label(d.status)}
|
||||
</StatusBadge>
|
||||
<StatusBadge>{purchased ? "purchased" : "connected"}</StatusBadge>
|
||||
{d.renewal_failures > 0 && <StatusBadge tone="danger">{d.renewal_failures} renewal failure{d.renewal_failures === 1 ? "" : "s"}</StatusBadge>}
|
||||
</div>
|
||||
|
||||
<Actions canManage={canManage}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "refresh",
|
||||
confirm: { title: `Refresh ${d.name}?`, description: "Re-reads the domain from GraphKit and applies what it says.", confirmLabel: "Refresh" },
|
||||
success: "Domain refreshed",
|
||||
run: () => storeDomainAction(d.id, "refresh"),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<RefreshCw className="size-3.5" />
|
||||
{busy === "refresh" ? "Refreshing…" : "Refresh"}
|
||||
</Button>
|
||||
{purchased && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "renew",
|
||||
confirm: {
|
||||
title: `Renew ${d.name} now?`,
|
||||
description: `Starts a renewal now instead of waiting for the renewal loop, at the renewal price of ${usd(d.renew_micros)}.`,
|
||||
confirmLabel: "Renew now",
|
||||
destructive: true,
|
||||
},
|
||||
success: "Renewal started",
|
||||
run: () => storeDomainAction(d.id, "renew"),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<CalendarClock className="size-3.5" />
|
||||
{busy === "renew" ? "Renewing…" : "Force renewal"}
|
||||
</Button>
|
||||
)}
|
||||
</Actions>
|
||||
|
||||
<PropertyList title="Registration">
|
||||
<Property label="Expires">
|
||||
{d.expires_at ? (
|
||||
<span className="tabular-nums" title={absolute(d.expires_at)}>
|
||||
{new Date(d.expires_at).toLocaleDateString()} ({relative(d.expires_at)})
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-subtle-foreground">—</span>
|
||||
)}
|
||||
</Property>
|
||||
<Property label="Auto-renew">
|
||||
{purchased ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Switch
|
||||
checked={d.auto_renew}
|
||||
disabled={!canManage || busy !== null}
|
||||
aria-label="Auto-renew"
|
||||
onCheckedChange={async (on) =>
|
||||
put(
|
||||
await act({
|
||||
id: "auto_renew",
|
||||
confirm: {
|
||||
title: on ? `Turn auto-renew on for ${d.name}?` : `Turn auto-renew off for ${d.name}?`,
|
||||
description: on
|
||||
? `The workspace is charged ${usd(d.renew_micros)} each year before it expires.`
|
||||
: "The domain expires at the end of its term unless someone renews it by hand.",
|
||||
confirmLabel: on ? "Turn on" : "Turn off",
|
||||
destructive: !on,
|
||||
},
|
||||
success: on ? "Auto-renew on" : "Auto-renew off",
|
||||
run: () => setStoreDomainAutoRenew(d.id, on),
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{d.auto_renew ? "On" : "Off"}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-subtle-foreground">Registered elsewhere</span>
|
||||
)}
|
||||
</Property>
|
||||
<Property label="Renewal price">{purchased ? usd(d.renew_micros) : "—"}</Property>
|
||||
<Property label="Last renewal try"><When ts={d.renewal_attempt_at} empty="None" /></Property>
|
||||
<Property label="Last notice">{d.last_notice ? label(d.last_notice) : <span className="text-subtle-foreground">None</span>}</Property>
|
||||
</PropertyList>
|
||||
|
||||
<PropertyList title="Mail">
|
||||
<Property label="Provider">{providerLabel(d.provider)}</Property>
|
||||
<Property label="Mailboxes">
|
||||
<Link to={`/store?tab=mailboxes&org=${d.organization_id}&q=${encodeURIComponent(`@${d.name}`)}`} className={linkCls}>
|
||||
{d.mailbox_count}
|
||||
</Link>
|
||||
</Property>
|
||||
<Property label="Tracking host">{d.tracking_host ? <span className={mono}>{d.tracking_host}</span> : <span className="text-subtle-foreground">None</span>}</Property>
|
||||
</PropertyList>
|
||||
|
||||
<PropertyList title="Record">
|
||||
<Property label="Domain id"><span className={mono}>{d.id}</span></Property>
|
||||
<Property label="GraphKit id">{d.upstream_id ? <span className={mono}>{d.upstream_id}</span> : "—"}</Property>
|
||||
<Property label="Updated"><When ts={d.updated_at} /></Property>
|
||||
</PropertyList>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Mailbox -----------------------------------------------------------------
|
||||
|
||||
export function MailboxDrawer({ mailbox, onClose }: { mailbox: AdminStoreMailbox | null; onClose: () => void }) {
|
||||
return (
|
||||
<Drawer open={mailbox !== null} onClose={onClose}>
|
||||
{mailbox && <MailboxDetail key={mailbox.id} seed={mailbox} />}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
function MailboxDetail({ seed }: { seed: AdminStoreMailbox }) {
|
||||
const [m, setM] = useState(seed);
|
||||
const { act, busy, canManage } = useStoreAction();
|
||||
const put = (next: AdminStoreMailbox | undefined) => next && setM(next);
|
||||
const ended = m.status === "cancelled" || m.status === "failed";
|
||||
const canRetryConnect = m.connect_state === "failed" || m.connect_state === "waiting";
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header title={m.email}>
|
||||
<Workspace id={m.organization_id} name={m.organization_name} />, {providerLabel(m.provider)}, bought <When ts={m.created_at} />
|
||||
</Header>
|
||||
<div className="flex-1 space-y-6 overflow-y-auto px-5 py-4">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<StatusBadge tone={statusTone(m.status)} dot>
|
||||
{label(m.status)}
|
||||
</StatusBadge>
|
||||
<StatusBadge tone={statusTone(m.connect_state)}>{m.connect_state === "connected" ? "connected" : `connect ${m.connect_state}`}</StatusBadge>
|
||||
{m.is_admin && <StatusBadge>admin mailbox</StatusBadge>}
|
||||
{m.cancels_at && <StatusBadge tone="warning">cancels {new Date(m.cancels_at).toLocaleDateString()}</StatusBadge>}
|
||||
{m.billing_failures > 0 && <StatusBadge tone="danger">{m.billing_failures} billing failure{m.billing_failures === 1 ? "" : "s"}</StatusBadge>}
|
||||
</div>
|
||||
|
||||
{m.connect_state === "failed" && (
|
||||
<Callout tone="danger" icon={AlertTriangle} title="Connecting it to Warmbly failed">
|
||||
{m.connect_error ? <span className="font-mono">{m.connect_error}</span> : "No reason recorded."} After {m.connect_attempts} attempt
|
||||
{m.connect_attempts === 1 ? "" : "s"}.
|
||||
</Callout>
|
||||
)}
|
||||
|
||||
<Actions canManage={canManage}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "refresh",
|
||||
confirm: { title: `Refresh ${m.email}?`, description: "Re-reads the mailbox from GraphKit and applies what it says.", confirmLabel: "Refresh" },
|
||||
success: "Mailbox refreshed",
|
||||
run: () => storeMailboxAction(m.id, "refresh"),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<RefreshCw className="size-3.5" />
|
||||
{busy === "refresh" ? "Refreshing…" : "Refresh"}
|
||||
</Button>
|
||||
{canRetryConnect && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "connect",
|
||||
confirm: {
|
||||
title: `Retry connecting ${m.email}?`,
|
||||
description: "Resets the connect attempts and tries to connect it to the workspace now.",
|
||||
confirmLabel: "Retry connect",
|
||||
},
|
||||
success: "Connect retried",
|
||||
run: () => storeMailboxAction(m.id, "connect"),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<PlugZap className="size-3.5" />
|
||||
{busy === "connect" ? "Connecting…" : "Retry connect"}
|
||||
</Button>
|
||||
)}
|
||||
{!ended && !m.cancels_at && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "cancel",
|
||||
confirm: {
|
||||
title: `Cancel ${m.email}?`,
|
||||
description: `It keeps working until ${m.paid_through ? new Date(m.paid_through).toLocaleDateString() : "the end of the paid period"}, then it is removed. It can be resumed until then.`,
|
||||
confirmLabel: "Cancel at period end",
|
||||
destructive: true,
|
||||
},
|
||||
success: "Mailbox set to cancel",
|
||||
run: () => storeMailboxAction(m.id, "cancel"),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Pause className="size-3.5" />
|
||||
{busy === "cancel" ? "Cancelling…" : "Cancel"}
|
||||
</Button>
|
||||
)}
|
||||
{!ended && m.cancels_at && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={async () =>
|
||||
put(
|
||||
await act({
|
||||
id: "resume",
|
||||
confirm: {
|
||||
title: `Resume ${m.email}?`,
|
||||
description: `It stays on and the workspace is billed ${usd(m.monthly_micros)} a month again.`,
|
||||
confirmLabel: "Resume",
|
||||
},
|
||||
success: "Mailbox resumed",
|
||||
run: () => storeMailboxAction(m.id, "resume"),
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Play className="size-3.5" />
|
||||
{busy === "resume" ? "Resuming…" : "Resume"}
|
||||
</Button>
|
||||
)}
|
||||
</Actions>
|
||||
|
||||
<PropertyList title="Billing">
|
||||
<Property label="Monthly">{usd(m.monthly_micros)}</Property>
|
||||
<Property label="Paid through">{m.paid_through ? new Date(m.paid_through).toLocaleDateString() : <span className="text-subtle-foreground">—</span>}</Property>
|
||||
<Property label="Cancels">{m.cancels_at ? new Date(m.cancels_at).toLocaleDateString() : <span className="text-subtle-foreground">No</span>}</Property>
|
||||
<Property label="Charge pending">{m.pending_charge ? "Yes" : "No"}</Property>
|
||||
<Property label="Billing failures">{m.billing_failures}</Property>
|
||||
</PropertyList>
|
||||
|
||||
<PropertyList title="Connection">
|
||||
<Property label="State">{label(m.connect_state)}</Property>
|
||||
<Property label="Method">{m.connect_method ? label(m.connect_method) : "—"}</Property>
|
||||
<Property label="Attempts">{m.connect_attempts}</Property>
|
||||
<Property label="Mailbox">
|
||||
{m.email_account_id ? (
|
||||
<Link to={`/mailboxes?mailbox_id=${m.email_account_id}`} className={linkCls}>
|
||||
Open in Mailboxes
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-subtle-foreground">Not connected</span>
|
||||
)}
|
||||
</Property>
|
||||
</PropertyList>
|
||||
|
||||
<PropertyList title="Record">
|
||||
<Property label="Mailbox id"><span className={mono}>{m.id}</span></Property>
|
||||
<Property label="GraphKit id">{m.upstream_id ? <span className={mono}>{m.upstream_id}</span> : "—"}</Property>
|
||||
<Property label="Updated"><When ts={m.updated_at} /></Property>
|
||||
</PropertyList>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
// The instance-wide Orders, Domains and Mailboxes tabs. Filters live in the
|
||||
// query string, so a count on the Health tab links straight to its list.
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { keepPreviousData, useQuery } from "@tanstack/react-query";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { Building2, X } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DataTable } from "@/components/data/DataTable";
|
||||
import { Explorer, FilterGroup, SearchFilter, SegmentedFilter, SelectFilter, ToggleFilter } from "@/components/data/Explorer";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useCursorPager } from "@/lib/useCursorPager";
|
||||
import {
|
||||
listStoreDomains,
|
||||
listStoreMailboxes,
|
||||
listStoreOrders,
|
||||
type AdminStoreDomain,
|
||||
type AdminStoreMailbox,
|
||||
type AdminStoreOrder,
|
||||
} from "@/lib/api/client/admin/store";
|
||||
import { CONNECT_STATES, DOMAIN_STATUSES, MAILBOX_STATUSES, ORDER_STATUSES, label } from "./format";
|
||||
import { domainColumns, mailboxColumns, orderColumns } from "./columns";
|
||||
import { DomainDrawer, MailboxDrawer, OrderDrawer } from "./StoreDrawers";
|
||||
|
||||
const PAGE = 50;
|
||||
|
||||
// Filter state read from and written to ?key=value, keeping ?tab.
|
||||
function useParamFilters(keys: string[]) {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const get = (k: string) => params.get(k) ?? "";
|
||||
const set = (k: string, v: string) =>
|
||||
setParams(
|
||||
(p) => {
|
||||
if (v) p.set(k, v);
|
||||
else p.delete(k);
|
||||
return p;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
const reset = () =>
|
||||
setParams(
|
||||
(p) => {
|
||||
for (const k of keys) p.delete(k);
|
||||
return p;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
const active = keys.filter((k) => params.get(k)).length;
|
||||
const signature = keys.map((k) => `${k}=${params.get(k) ?? ""}`).join("&");
|
||||
return { get, set, reset, active, signature };
|
||||
}
|
||||
|
||||
function anyOption(noun: string, values: readonly string[]) {
|
||||
return [{ value: "any", label: `Any ${noun}` }, ...values.map((v) => ({ value: v, label: label(v) }))];
|
||||
}
|
||||
|
||||
function WorkspaceScope({ onClear }: { onClear: () => void }) {
|
||||
return (
|
||||
<FilterGroup label="Scope">
|
||||
<div className="flex h-7 items-center gap-1.5 rounded-md border border-[color-mix(in_oklab,var(--admin-accent)_30%,transparent)] bg-[var(--admin-accent-weak)] pr-0.5 pl-2 text-[12.5px] text-[var(--admin-accent-strong)]">
|
||||
<Building2 className="size-3.5 shrink-0" />
|
||||
<span className="min-w-0 flex-1 truncate font-medium">One workspace</span>
|
||||
<Button variant="ghost" size="icon-xs" onClick={onClear} title="Clear workspace filter" className="text-[var(--admin-accent-strong)] hover:bg-[var(--admin-accent-soft)]">
|
||||
<X className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</FilterGroup>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Orders ------------------------------------------------------------------
|
||||
|
||||
const ORDER_KEYS = ["q", "org", "status", "failure_code", "stuck"];
|
||||
const ORDER_COLUMNS = orderColumns(true);
|
||||
|
||||
export function OrdersTab() {
|
||||
const f = useParamFilters(ORDER_KEYS);
|
||||
const pager = useCursorPager();
|
||||
const { reset } = pager;
|
||||
const [open, setOpen] = useState<AdminStoreOrder | null>(null);
|
||||
useEffect(() => reset(), [f.signature, reset]);
|
||||
|
||||
const q = useQuery({
|
||||
queryKey: ["admin", "store", "orders", f.signature, pager.cursor],
|
||||
queryFn: () =>
|
||||
listStoreOrders({
|
||||
q: f.get("q").trim() || undefined,
|
||||
org_id: f.get("org") || undefined,
|
||||
status: f.get("status") || undefined,
|
||||
failure_code: f.get("failure_code").trim() || undefined,
|
||||
stuck: f.get("stuck") === "true" || undefined,
|
||||
limit: PAGE,
|
||||
cursor: pager.cursor,
|
||||
}),
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const rows = q.data?.data ?? [];
|
||||
|
||||
return (
|
||||
<Explorer
|
||||
activeCount={f.active}
|
||||
onReset={f.reset}
|
||||
filters={
|
||||
<>
|
||||
<FilterGroup label="Search">
|
||||
<SearchFilter value={f.get("q")} onChange={(v) => f.set("q", v)} placeholder="Order id or workspace…" />
|
||||
</FilterGroup>
|
||||
{f.get("org") && <WorkspaceScope onClear={() => f.set("org", "")} />}
|
||||
<FilterGroup label="Status">
|
||||
<SelectFilter value={f.get("status") || "any"} onChange={(v) => f.set("status", v === "any" ? "" : v)} options={anyOption("status", ORDER_STATUSES)} />
|
||||
<ToggleFilter checked={f.get("stuck") === "true"} onChange={(c) => f.set("stuck", c ? "true" : "")} label="Stuck only" />
|
||||
</FilterGroup>
|
||||
<FilterGroup label="Failure code">
|
||||
<Input value={f.get("failure_code")} onChange={(e) => f.set("failure_code", e.target.value)} placeholder="e.g. domain_unavailable" className="h-8 font-mono text-[12px]" />
|
||||
</FilterGroup>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<DataTable
|
||||
columns={ORDER_COLUMNS}
|
||||
rows={rows}
|
||||
getRowId={(o) => o.id}
|
||||
loading={q.isLoading}
|
||||
error={q.error}
|
||||
onRetry={() => q.refetch()}
|
||||
onRowClick={setOpen}
|
||||
selectedRowId={open?.id ?? null}
|
||||
errorTitle="Failed to load store orders"
|
||||
storageKey="admin.store.orders"
|
||||
csvName="warmbly-store-orders"
|
||||
noun="orders"
|
||||
emptyTitle="No orders"
|
||||
emptyHint="No store orders match these filters."
|
||||
pager={{
|
||||
canPrev: pager.canPrev,
|
||||
canNext: !!q.data?.pagination.has_more,
|
||||
onPrev: pager.prev,
|
||||
onNext: () => pager.next(q.data?.pagination.next_cursor),
|
||||
page: pager.page,
|
||||
shown: rows.length,
|
||||
}}
|
||||
/>
|
||||
<OrderDrawer order={open} onClose={() => setOpen(null)} />
|
||||
</Explorer>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Domains -----------------------------------------------------------------
|
||||
|
||||
const DOMAIN_KEYS = ["q", "org", "status", "auto_renew", "expiring_days", "renewal_failed"];
|
||||
const DOMAIN_COLUMNS = domainColumns(true);
|
||||
const EXPIRING_OPTIONS = [
|
||||
{ value: "any", label: "Any time" },
|
||||
{ value: "7", label: "Within 7 days" },
|
||||
{ value: "30", label: "Within 30 days" },
|
||||
{ value: "60", label: "Within 60 days" },
|
||||
{ value: "90", label: "Within 90 days" },
|
||||
];
|
||||
|
||||
export function DomainsTab() {
|
||||
const f = useParamFilters(DOMAIN_KEYS);
|
||||
const pager = useCursorPager();
|
||||
const { reset } = pager;
|
||||
const [open, setOpen] = useState<AdminStoreDomain | null>(null);
|
||||
useEffect(() => reset(), [f.signature, reset]);
|
||||
|
||||
const autoRenew = f.get("auto_renew");
|
||||
const expiring = Number(f.get("expiring_days"));
|
||||
const q = useQuery({
|
||||
queryKey: ["admin", "store", "domains", f.signature, pager.cursor],
|
||||
queryFn: () =>
|
||||
listStoreDomains({
|
||||
q: f.get("q").trim() || undefined,
|
||||
org_id: f.get("org") || undefined,
|
||||
status: f.get("status") || undefined,
|
||||
auto_renew: autoRenew === "true" || autoRenew === "false" ? autoRenew : undefined,
|
||||
expiring_days: expiring > 0 ? expiring : undefined,
|
||||
renewal_failed: f.get("renewal_failed") === "true" || undefined,
|
||||
limit: PAGE,
|
||||
cursor: pager.cursor,
|
||||
}),
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const rows = q.data?.data ?? [];
|
||||
const expiringValue = f.get("expiring_days");
|
||||
|
||||
return (
|
||||
<Explorer
|
||||
activeCount={f.active}
|
||||
onReset={f.reset}
|
||||
filters={
|
||||
<>
|
||||
<FilterGroup label="Search">
|
||||
<SearchFilter value={f.get("q")} onChange={(v) => f.set("q", v)} placeholder="Domain…" />
|
||||
</FilterGroup>
|
||||
{f.get("org") && <WorkspaceScope onClear={() => f.set("org", "")} />}
|
||||
<FilterGroup label="Status">
|
||||
<SelectFilter value={f.get("status") || "any"} onChange={(v) => f.set("status", v === "any" ? "" : v)} options={anyOption("status", DOMAIN_STATUSES)} />
|
||||
</FilterGroup>
|
||||
<FilterGroup label="Expires">
|
||||
<SelectFilter
|
||||
value={expiringValue || "any"}
|
||||
onChange={(v) => f.set("expiring_days", v === "any" ? "" : v)}
|
||||
options={
|
||||
expiringValue && !EXPIRING_OPTIONS.some((o) => o.value === expiringValue)
|
||||
? [...EXPIRING_OPTIONS, { value: expiringValue, label: `Within ${expiringValue} days` }]
|
||||
: EXPIRING_OPTIONS
|
||||
}
|
||||
/>
|
||||
</FilterGroup>
|
||||
<FilterGroup label="Auto-renew">
|
||||
<SegmentedFilter
|
||||
value={autoRenew === "true" ? "on" : autoRenew === "false" ? "off" : "any"}
|
||||
onChange={(v) => f.set("auto_renew", v === "on" ? "true" : v === "off" ? "false" : "")}
|
||||
options={[
|
||||
{ value: "any", label: "Any" },
|
||||
{ value: "on", label: "On" },
|
||||
{ value: "off", label: "Off" },
|
||||
]}
|
||||
/>
|
||||
<ToggleFilter checked={f.get("renewal_failed") === "true"} onChange={(c) => f.set("renewal_failed", c ? "true" : "")} label="Renewal failed" />
|
||||
</FilterGroup>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<DataTable
|
||||
columns={DOMAIN_COLUMNS}
|
||||
rows={rows}
|
||||
getRowId={(d) => d.id}
|
||||
loading={q.isLoading}
|
||||
error={q.error}
|
||||
onRetry={() => q.refetch()}
|
||||
onRowClick={setOpen}
|
||||
selectedRowId={open?.id ?? null}
|
||||
errorTitle="Failed to load store domains"
|
||||
storageKey="admin.store.domains"
|
||||
csvName="warmbly-store-domains"
|
||||
noun="domains"
|
||||
emptyTitle="No domains"
|
||||
emptyHint="No store domains match these filters."
|
||||
pager={{
|
||||
canPrev: pager.canPrev,
|
||||
canNext: !!q.data?.pagination.has_more,
|
||||
onPrev: pager.prev,
|
||||
onNext: () => pager.next(q.data?.pagination.next_cursor),
|
||||
page: pager.page,
|
||||
shown: rows.length,
|
||||
}}
|
||||
/>
|
||||
<DomainDrawer domain={open} onClose={() => setOpen(null)} />
|
||||
</Explorer>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Mailboxes ---------------------------------------------------------------
|
||||
|
||||
const MAILBOX_KEYS = ["q", "org", "status", "connect_state", "billing_failed"];
|
||||
const MAILBOX_COLUMNS = mailboxColumns(true);
|
||||
|
||||
export function MailboxesTab() {
|
||||
const f = useParamFilters(MAILBOX_KEYS);
|
||||
const pager = useCursorPager();
|
||||
const { reset } = pager;
|
||||
const [open, setOpen] = useState<AdminStoreMailbox | null>(null);
|
||||
useEffect(() => reset(), [f.signature, reset]);
|
||||
|
||||
const q = useQuery({
|
||||
queryKey: ["admin", "store", "mailboxes", f.signature, pager.cursor],
|
||||
queryFn: () =>
|
||||
listStoreMailboxes({
|
||||
q: f.get("q").trim() || undefined,
|
||||
org_id: f.get("org") || undefined,
|
||||
status: f.get("status") || undefined,
|
||||
connect_state: f.get("connect_state") || undefined,
|
||||
billing_failed: f.get("billing_failed") === "true" || undefined,
|
||||
limit: PAGE,
|
||||
cursor: pager.cursor,
|
||||
}),
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const rows = q.data?.data ?? [];
|
||||
|
||||
return (
|
||||
<Explorer
|
||||
activeCount={f.active}
|
||||
onReset={f.reset}
|
||||
filters={
|
||||
<>
|
||||
<FilterGroup label="Search">
|
||||
<SearchFilter value={f.get("q")} onChange={(v) => f.set("q", v)} placeholder="Email address…" />
|
||||
</FilterGroup>
|
||||
{f.get("org") && <WorkspaceScope onClear={() => f.set("org", "")} />}
|
||||
<FilterGroup label="Status">
|
||||
<SelectFilter value={f.get("status") || "any"} onChange={(v) => f.set("status", v === "any" ? "" : v)} options={anyOption("status", MAILBOX_STATUSES)} />
|
||||
</FilterGroup>
|
||||
<FilterGroup label="Connect">
|
||||
<SelectFilter value={f.get("connect_state") || "any"} onChange={(v) => f.set("connect_state", v === "any" ? "" : v)} options={anyOption("connect state", CONNECT_STATES)} />
|
||||
</FilterGroup>
|
||||
<FilterGroup label="Billing">
|
||||
<ToggleFilter checked={f.get("billing_failed") === "true"} onChange={(c) => f.set("billing_failed", c ? "true" : "")} label="Billing failed" />
|
||||
</FilterGroup>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<DataTable
|
||||
columns={MAILBOX_COLUMNS}
|
||||
rows={rows}
|
||||
getRowId={(m) => m.id}
|
||||
loading={q.isLoading}
|
||||
error={q.error}
|
||||
onRetry={() => q.refetch()}
|
||||
onRowClick={setOpen}
|
||||
selectedRowId={open?.id ?? null}
|
||||
errorTitle="Failed to load store mailboxes"
|
||||
storageKey="admin.store.mailboxes"
|
||||
csvName="warmbly-store-mailboxes"
|
||||
noun="mailboxes"
|
||||
emptyTitle="No mailboxes"
|
||||
emptyHint="No store mailboxes match these filters."
|
||||
pager={{
|
||||
canPrev: pager.canPrev,
|
||||
canNext: !!q.data?.pagination.has_more,
|
||||
onPrev: pager.prev,
|
||||
onNext: () => pager.next(q.data?.pagination.next_cursor),
|
||||
page: pager.page,
|
||||
shown: rows.length,
|
||||
}}
|
||||
/>
|
||||
<MailboxDrawer mailbox={open} onClose={() => setOpen(null)} />
|
||||
</Explorer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// The domain and mailbox store, instance-wide: health, every order, domain
|
||||
// and mailbox, and the economics against GraphKit's wholesale prices.
|
||||
// The tab and its filters live in the query string so links deep-link.
|
||||
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { Globe, HeartPulse, Inbox, PiggyBank, Receipt } from "lucide-react";
|
||||
import { PageHeader } from "@/components/layout/PageHeader";
|
||||
import { PageTabs } from "@/components/layout/PageTabs";
|
||||
import { DomainsTab, MailboxesTab, OrdersTab } from "./StoreLists";
|
||||
import { HealthTab } from "./HealthTab";
|
||||
import { useStoreHealth } from "./useStoreHealth";
|
||||
import { EconomicsTab } from "./EconomicsTab";
|
||||
import type { StoreTab } from "./format";
|
||||
|
||||
const TABS: { id: StoreTab; label: string; icon: typeof Globe }[] = [
|
||||
{ id: "health", label: "Health", icon: HeartPulse },
|
||||
{ id: "orders", label: "Orders", icon: Receipt },
|
||||
{ id: "domains", label: "Domains", icon: Globe },
|
||||
{ id: "mailboxes", label: "Mailboxes", icon: Inbox },
|
||||
{ id: "economics", label: "Economics", icon: PiggyBank },
|
||||
];
|
||||
|
||||
function isTab(v: string | null): v is StoreTab {
|
||||
return TABS.some((t) => t.id === v);
|
||||
}
|
||||
|
||||
export default function StorePage() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const raw = params.get("tab");
|
||||
const tab: StoreTab = isTab(raw) ? raw : "health";
|
||||
const health = useStoreHealth();
|
||||
const c = health.data?.counts;
|
||||
|
||||
// A tab starts unfiltered: one list's filters mean nothing on another.
|
||||
const setTab = (next: string) => setParams({ tab: next }, { replace: true });
|
||||
|
||||
const tabs = TABS.map((t) => ({
|
||||
...t,
|
||||
badge: !c
|
||||
? undefined
|
||||
: t.id === "orders"
|
||||
? c.orders_stuck
|
||||
: t.id === "domains"
|
||||
? c.domains_renewal_failed
|
||||
: t.id === "mailboxes"
|
||||
? c.connects_failed + c.mailboxes_billing_failed
|
||||
: undefined,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader title="Store" description="Domains and mailboxes workspaces buy, fulfilled by GraphKit. Refresh, retry, refund and renew from the drawers." />
|
||||
<PageTabs tabs={tabs} value={tab} onChange={setTab} />
|
||||
{tab === "health" && <HealthTab />}
|
||||
{tab === "orders" && <OrdersTab />}
|
||||
{tab === "domains" && <DomainsTab />}
|
||||
{tab === "mailboxes" && <MailboxesTab />}
|
||||
{tab === "economics" && <EconomicsTab />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// One workspace's store: its GraphKit account, balance and spend, and every
|
||||
// order, domain and mailbox it holds, with the same drawers and actions as
|
||||
// the instance-wide lists.
|
||||
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { PageHeader } from "@/components/layout/PageHeader";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Property, PropertyList, Section, StatusBadge } from "@/components/ui/kit";
|
||||
import { DataTable } from "@/components/data/DataTable";
|
||||
import { ErrorState } from "@/components/ErrorState";
|
||||
import {
|
||||
getStoreWorkspace,
|
||||
type AdminStoreDomain,
|
||||
type AdminStoreMailbox,
|
||||
type AdminStoreOrder,
|
||||
} from "@/lib/api/client/admin/store";
|
||||
import { domainColumns, mailboxColumns, orderColumns } from "./columns";
|
||||
import { DomainDrawer, MailboxDrawer, OrderDrawer } from "./StoreDrawers";
|
||||
import { storeLink, usd } from "./format";
|
||||
|
||||
const CRUMBS = [{ label: "Store", to: "/store" }];
|
||||
const ORDER_COLUMNS = orderColumns(false);
|
||||
const DOMAIN_COLUMNS = domainColumns(false);
|
||||
const MAILBOX_COLUMNS = mailboxColumns(false);
|
||||
const linkCls = "underline decoration-border-strong underline-offset-2 hover:text-[var(--admin-accent-strong)]";
|
||||
|
||||
export default function StoreWorkspacePage() {
|
||||
const { orgId = "" } = useParams<{ orgId: string }>();
|
||||
const [order, setOrder] = useState<AdminStoreOrder | null>(null);
|
||||
const [domain, setDomain] = useState<AdminStoreDomain | null>(null);
|
||||
const [mailbox, setMailbox] = useState<AdminStoreMailbox | null>(null);
|
||||
const q = useQuery({ queryKey: ["admin", "store", "workspace", orgId], queryFn: () => getStoreWorkspace(orgId), enabled: !!orgId });
|
||||
|
||||
if (q.isLoading) {
|
||||
return (
|
||||
<div>
|
||||
<PageHeader breadcrumbs={CRUMBS} title={<Skeleton className="h-4 w-40" />} />
|
||||
<Skeleton className="h-64 w-full rounded-xl" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (q.error || !q.data) {
|
||||
return (
|
||||
<div>
|
||||
<PageHeader breadcrumbs={CRUMBS} title="Workspace" />
|
||||
<ErrorState error={q.error} title="Failed to load this workspace's store" onRetry={() => q.refetch()} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const w = q.data;
|
||||
return (
|
||||
<div>
|
||||
<PageHeader breadcrumbs={CRUMBS} title={w.organization.name || "Workspace"} />
|
||||
<div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_17rem] lg:gap-10">
|
||||
<div className="order-2 min-w-0 lg:order-1">
|
||||
<Section title={<Count label="Orders" n={w.orders.length} />} description="The latest 50." className="mt-0">
|
||||
<DataTable
|
||||
columns={ORDER_COLUMNS}
|
||||
rows={w.orders}
|
||||
getRowId={(o) => o.id}
|
||||
onRowClick={setOrder}
|
||||
selectedRowId={order?.id ?? null}
|
||||
storageKey="admin.store.ws.orders"
|
||||
csvName="warmbly-store-orders"
|
||||
noun="orders"
|
||||
emptyTitle="No orders"
|
||||
emptyHint="This workspace has not bought anything."
|
||||
/>
|
||||
</Section>
|
||||
<Section title={<Count label="Domains" n={w.domains.length} />}>
|
||||
<DataTable
|
||||
columns={DOMAIN_COLUMNS}
|
||||
rows={w.domains}
|
||||
getRowId={(d) => d.id}
|
||||
onRowClick={setDomain}
|
||||
selectedRowId={domain?.id ?? null}
|
||||
storageKey="admin.store.ws.domains"
|
||||
csvName="warmbly-store-domains"
|
||||
noun="domains"
|
||||
emptyTitle="No domains"
|
||||
emptyHint="No purchased or connected domains."
|
||||
/>
|
||||
</Section>
|
||||
<Section title={<Count label="Mailboxes" n={w.mailboxes.length} />}>
|
||||
<DataTable
|
||||
columns={MAILBOX_COLUMNS}
|
||||
rows={w.mailboxes}
|
||||
getRowId={(m) => m.id}
|
||||
onRowClick={setMailbox}
|
||||
selectedRowId={mailbox?.id ?? null}
|
||||
storageKey="admin.store.ws.mailboxes"
|
||||
csvName="warmbly-store-mailboxes"
|
||||
noun="mailboxes"
|
||||
emptyTitle="No mailboxes"
|
||||
emptyHint="No purchased mailboxes."
|
||||
/>
|
||||
</Section>
|
||||
</div>
|
||||
|
||||
<aside className="order-1 min-w-0 lg:order-2">
|
||||
<div className="lg:sticky lg:top-16">
|
||||
<PropertyList title="Account" className="border-b border-border">
|
||||
<Property label="GraphKit account">
|
||||
{w.account.exists ? (
|
||||
<span title={w.account.created_at ? new Date(w.account.created_at).toLocaleString() : undefined}>
|
||||
Created {w.account.created_at ? new Date(w.account.created_at).toLocaleDateString() : ""}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-subtle-foreground">None yet</span>
|
||||
)}
|
||||
</Property>
|
||||
<Property label="Registrant">{w.account.has_registrant ? "Saved" : <span className="text-subtle-foreground">Not saved</span>}</Property>
|
||||
<Property label="Plan">
|
||||
{w.plan_active ? <StatusBadge tone="success" dot>active</StatusBadge> : <StatusBadge tone="warning" dot>inactive</StatusBadge>}
|
||||
</Property>
|
||||
<Property label="Managed by partner">{w.managed_by_partner ? "Yes" : "No"}</Property>
|
||||
</PropertyList>
|
||||
<PropertyList title="Money" className="mt-5 border-b border-border">
|
||||
<Property label="Balance">{w.balance_micros == null ? <span className="text-subtle-foreground">—</span> : usd(w.balance_micros)}</Property>
|
||||
<Property label="Monthly spend">{usd(w.monthly_spend_micros)}</Property>
|
||||
</PropertyList>
|
||||
<div className="mt-4 flex flex-col gap-1.5 text-[13px]">
|
||||
<Link to={`/organizations/${w.organization.id}`} className={linkCls}>
|
||||
Open organization
|
||||
</Link>
|
||||
<Link to={storeLink("orders", { org: w.organization.id })} className={linkCls}>
|
||||
All orders in the store list
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<OrderDrawer order={order} onClose={() => setOrder(null)} />
|
||||
<DomainDrawer domain={domain} onClose={() => setDomain(null)} />
|
||||
<MailboxDrawer mailbox={mailbox} onClose={() => setMailbox(null)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Count({ label, n }: { label: string; n: number }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{label}
|
||||
<span className="font-normal tabular-nums text-muted-foreground">{n}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// Table columns for store orders, domains and mailboxes, shared by the
|
||||
// instance-wide tabs and the workspace drill-down (which drops the workspace column).
|
||||
|
||||
import { Link } from "react-router-dom";
|
||||
import type { Column } from "@/components/data/DataTable";
|
||||
import { StatusBadge } from "@/components/ui/kit";
|
||||
import type { AdminStoreDomain, AdminStoreMailbox, AdminStoreOrder } from "@/lib/api/client/admin/store";
|
||||
import { absolute, relative } from "@/app/dashboard/jobs/format";
|
||||
import { TONE_TEXT } from "@/lib/tones";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { label, providerLabel, statusTone, usd } from "./format";
|
||||
|
||||
const linkCls = "truncate text-foreground decoration-border-strong underline-offset-2 hover:text-[var(--admin-accent-strong)] hover:underline";
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
function workspaceColumn<T extends { organization_id: string; organization_name: string }>(): Column<T> {
|
||||
return {
|
||||
id: "workspace",
|
||||
header: "Workspace",
|
||||
cell: (r) => (
|
||||
<Link to={`/store/workspaces/${r.organization_id}`} className={linkCls} onClick={(e) => e.stopPropagation()}>
|
||||
{r.organization_name || r.organization_id.slice(0, 8)}
|
||||
</Link>
|
||||
),
|
||||
csv: (r) => r.organization_name,
|
||||
};
|
||||
}
|
||||
|
||||
function when(ts: string | null | undefined) {
|
||||
if (!ts) return <span className="text-subtle-foreground">—</span>;
|
||||
return (
|
||||
<span className="whitespace-nowrap tabular-nums text-muted-foreground" title={absolute(ts)}>
|
||||
{relative(ts)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function orderSummary(o: AdminStoreOrder): string {
|
||||
const domains = o.lines.filter((l) => l.type === "domain").length;
|
||||
const mailboxes = o.lines.reduce((n, l) => n + (l.type === "mailboxes" ? (l.count ?? 0) : 0), 0);
|
||||
const parts = [];
|
||||
if (domains) parts.push(`${domains} domain${domains === 1 ? "" : "s"}`);
|
||||
if (mailboxes) parts.push(`${mailboxes} mailbox${mailboxes === 1 ? "" : "es"}`);
|
||||
return parts.join(", ") || "Empty";
|
||||
}
|
||||
|
||||
export function orderColumns(withWorkspace: boolean): Column<AdminStoreOrder>[] {
|
||||
const cols: Column<AdminStoreOrder>[] = [
|
||||
{
|
||||
id: "order",
|
||||
header: "Order",
|
||||
cell: (o) => (
|
||||
<div className="min-w-0 py-1">
|
||||
<div className="truncate font-medium">{o.lines[0]?.domain ?? o.id.slice(0, 8)}</div>
|
||||
<div className="text-xs text-muted-foreground">{orderSummary(o)}</div>
|
||||
</div>
|
||||
),
|
||||
csv: (o) => o.id,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "Status",
|
||||
cell: (o) => (
|
||||
<span className="inline-flex flex-wrap items-center gap-1">
|
||||
<StatusBadge tone={statusTone(o.status)} dot>
|
||||
{label(o.status)}
|
||||
</StatusBadge>
|
||||
{o.stuck && <StatusBadge tone="warning">stuck</StatusBadge>}
|
||||
</span>
|
||||
),
|
||||
csv: (o) => (o.stuck ? `${o.status} (stuck)` : o.status),
|
||||
},
|
||||
{
|
||||
id: "failure",
|
||||
header: "Failure",
|
||||
cell: (o) => (o.failure_code ? <span className="font-mono text-[12px] text-[var(--admin-danger)]">{o.failure_code}</span> : <span className="text-subtle-foreground">—</span>),
|
||||
csv: (o) => o.failure_code,
|
||||
},
|
||||
{ id: "charged", header: "Charged", align: "right", cell: (o) => <span className="tabular-nums">{usd(o.charged_micros)}</span>, csv: (o) => o.charged_micros / 1e6 },
|
||||
{
|
||||
id: "refunded",
|
||||
header: "Refunded",
|
||||
align: "right",
|
||||
cell: (o) => <span className={cn("tabular-nums", o.refunded_micros ? "" : "text-subtle-foreground")}>{usd(o.refunded_micros)}</span>,
|
||||
csv: (o) => o.refunded_micros / 1e6,
|
||||
},
|
||||
{ id: "created", header: "Created", cell: (o) => when(o.created_at), csv: (o) => o.created_at },
|
||||
];
|
||||
if (withWorkspace) cols.splice(1, 0, workspaceColumn<AdminStoreOrder>());
|
||||
return cols;
|
||||
}
|
||||
|
||||
export function domainColumns(withWorkspace: boolean): Column<AdminStoreDomain>[] {
|
||||
const cols: Column<AdminStoreDomain>[] = [
|
||||
{
|
||||
id: "name",
|
||||
header: "Domain",
|
||||
cell: (d) => (
|
||||
<div className="min-w-0 py-1">
|
||||
<div className="truncate font-medium">{d.name}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{d.source === "purchased" ? "Purchased" : "Connected"}, {providerLabel(d.provider)}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
csv: (d) => d.name,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "Status",
|
||||
cell: (d) => (
|
||||
<span className="inline-flex flex-wrap items-center gap-1">
|
||||
<StatusBadge tone={statusTone(d.status)} dot>
|
||||
{label(d.status)}
|
||||
</StatusBadge>
|
||||
{d.renewal_failures > 0 && <StatusBadge tone="danger">renewal failed</StatusBadge>}
|
||||
</span>
|
||||
),
|
||||
csv: (d) => d.status,
|
||||
},
|
||||
{
|
||||
id: "expires",
|
||||
header: "Expires",
|
||||
cell: (d) => {
|
||||
if (!d.expires_at) return <span className="text-subtle-foreground">—</span>;
|
||||
const soon = new Date(d.expires_at).getTime() - Date.now() < 30 * DAY_MS;
|
||||
return (
|
||||
<span className={cn("whitespace-nowrap tabular-nums", soon ? TONE_TEXT.warning : "text-muted-foreground")} title={absolute(d.expires_at)}>
|
||||
{new Date(d.expires_at).toLocaleDateString()}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
csv: (d) => d.expires_at ?? "",
|
||||
},
|
||||
{
|
||||
id: "auto_renew",
|
||||
header: "Auto-renew",
|
||||
cell: (d) =>
|
||||
d.source !== "purchased" ? (
|
||||
<span className="text-subtle-foreground">—</span>
|
||||
) : d.auto_renew ? (
|
||||
<span className="text-muted-foreground">On</span>
|
||||
) : (
|
||||
<StatusBadge tone="warning">Off</StatusBadge>
|
||||
),
|
||||
csv: (d) => (d.source === "purchased" ? (d.auto_renew ? "on" : "off") : ""),
|
||||
},
|
||||
{ id: "renew", header: "Renews at", align: "right", cell: (d) => <span className="tabular-nums">{d.source === "purchased" ? usd(d.renew_micros) : "—"}</span>, csv: (d) => d.renew_micros / 1e6 },
|
||||
{ id: "mailboxes", header: "Mailboxes", align: "right", cell: (d) => <span className="tabular-nums">{d.mailbox_count}</span>, csv: (d) => d.mailbox_count },
|
||||
];
|
||||
if (withWorkspace) cols.splice(1, 0, workspaceColumn<AdminStoreDomain>());
|
||||
return cols;
|
||||
}
|
||||
|
||||
export function mailboxColumns(withWorkspace: boolean): Column<AdminStoreMailbox>[] {
|
||||
const cols: Column<AdminStoreMailbox>[] = [
|
||||
{
|
||||
id: "email",
|
||||
header: "Mailbox",
|
||||
cell: (m) => (
|
||||
<div className="min-w-0 py-1">
|
||||
<div className="truncate font-medium">{m.email}</div>
|
||||
<div className="text-xs text-muted-foreground">{providerLabel(m.provider)}</div>
|
||||
</div>
|
||||
),
|
||||
csv: (m) => m.email,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "Status",
|
||||
cell: (m) => (
|
||||
<span className="inline-flex flex-wrap items-center gap-1">
|
||||
<StatusBadge tone={statusTone(m.status)} dot>
|
||||
{label(m.status)}
|
||||
</StatusBadge>
|
||||
{m.cancels_at && m.status !== "cancelled" && <StatusBadge tone="warning">cancelling</StatusBadge>}
|
||||
</span>
|
||||
),
|
||||
csv: (m) => m.status,
|
||||
},
|
||||
{
|
||||
id: "connect",
|
||||
header: "Connect",
|
||||
cell: (m) => <StatusBadge tone={statusTone(m.connect_state)}>{label(m.connect_state)}</StatusBadge>,
|
||||
csv: (m) => m.connect_state,
|
||||
},
|
||||
{
|
||||
id: "billing",
|
||||
header: "Billing",
|
||||
cell: (m) =>
|
||||
m.billing_failures > 0 ? (
|
||||
<StatusBadge tone="danger">{m.billing_failures} failed</StatusBadge>
|
||||
) : m.pending_charge ? (
|
||||
<StatusBadge tone="info">charge pending</StatusBadge>
|
||||
) : (
|
||||
<span className="text-muted-foreground">OK</span>
|
||||
),
|
||||
csv: (m) => m.billing_failures,
|
||||
},
|
||||
{ id: "monthly", header: "Monthly", align: "right", cell: (m) => <span className="tabular-nums">{usd(m.monthly_micros)}</span>, csv: (m) => m.monthly_micros / 1e6 },
|
||||
{
|
||||
id: "paid_through",
|
||||
header: "Paid through",
|
||||
cell: (m) => (m.paid_through ? <span className="whitespace-nowrap tabular-nums text-muted-foreground">{new Date(m.paid_through).toLocaleDateString()}</span> : <span className="text-subtle-foreground">—</span>),
|
||||
csv: (m) => m.paid_through ?? "",
|
||||
},
|
||||
];
|
||||
if (withWorkspace) cols.splice(1, 0, workspaceColumn<AdminStoreMailbox>());
|
||||
return cols;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Money, labels and tones shared by the Store section.
|
||||
|
||||
import type { Tone } from "@/lib/tones";
|
||||
import type { AdminStoreOrder } from "@/lib/api/client/admin/store";
|
||||
|
||||
export const MICROS_PER_USD = 1_000_000;
|
||||
|
||||
// Micro-USD as dollars; sub-cent wholesale prices keep their precision.
|
||||
export function usd(micros: number | null | undefined): string {
|
||||
if (micros == null) return "—";
|
||||
const cents = micros % 10_000 === 0;
|
||||
return (micros / MICROS_PER_USD).toLocaleString("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: cents ? 2 : 4,
|
||||
});
|
||||
}
|
||||
|
||||
// A typed dollar amount as micros: null when empty, NaN when it is not a positive amount with at most cents.
|
||||
export function dollarsToMicros(raw: string): number | null {
|
||||
const text = raw.replace(/[,\s$]/g, "");
|
||||
if (text === "") return null;
|
||||
if (!/^\d+(\.\d{1,2})?$/.test(text)) return NaN;
|
||||
return Math.round(Number(text) * 100) * 10_000;
|
||||
}
|
||||
|
||||
export function refundableMicros(o: Pick<AdminStoreOrder, "charged_micros" | "refunded_micros">): number {
|
||||
return Math.max(0, o.charged_micros - o.refunded_micros);
|
||||
}
|
||||
|
||||
// randomUUID only exists on a secure origin; a plain-http panel still needs a key.
|
||||
export function newIdempotencyKey(): string {
|
||||
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
|
||||
return Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
export const label = (s: string) => (s ? (s.charAt(0).toUpperCase() + s.slice(1)).replace(/_/g, " ") : s);
|
||||
|
||||
export const PROVIDER_LABEL: Record<string, string> = {
|
||||
google: "Google",
|
||||
gmail: "Google",
|
||||
microsoft: "Microsoft",
|
||||
outlook: "Microsoft",
|
||||
};
|
||||
export const providerLabel = (p: string) => PROVIDER_LABEL[p] ?? (p ? label(p) : "—");
|
||||
|
||||
export const ORDER_STATUSES = ["open", "charging", "processing", "completed", "partially_failed", "failed"] as const;
|
||||
export const DOMAIN_STATUSES = [
|
||||
"registering",
|
||||
"connecting",
|
||||
"active",
|
||||
"expired",
|
||||
"redemption",
|
||||
"transferring_out",
|
||||
"transferred_out",
|
||||
"removed",
|
||||
"failed",
|
||||
] as const;
|
||||
export const MAILBOX_STATUSES = ["provisioning", "active", "suspended", "cancelling", "cancelled", "failed"] as const;
|
||||
export const CONNECT_STATES = ["waiting", "connecting", "connected", "failed"] as const;
|
||||
|
||||
const STATUS_TONE: Record<string, Tone> = {
|
||||
charging: "info",
|
||||
processing: "info",
|
||||
completed: "success",
|
||||
partially_failed: "warning",
|
||||
failed: "danger",
|
||||
registering: "info",
|
||||
connecting: "info",
|
||||
provisioning: "info",
|
||||
active: "success",
|
||||
connected: "success",
|
||||
expired: "warning",
|
||||
redemption: "danger",
|
||||
transferring_out: "info",
|
||||
transferred_out: "neutral",
|
||||
removed: "neutral",
|
||||
suspended: "warning",
|
||||
cancelling: "warning",
|
||||
cancelled: "neutral",
|
||||
waiting: "neutral",
|
||||
done: "success",
|
||||
running: "info",
|
||||
pending: "neutral",
|
||||
skipped: "neutral",
|
||||
};
|
||||
export const statusTone = (s: string): Tone => STATUS_TONE[s] ?? "neutral";
|
||||
|
||||
export const MODE_TONE: Record<string, Tone> = {
|
||||
live: "success",
|
||||
sandbox: "info",
|
||||
simulator: "warning",
|
||||
off: "neutral",
|
||||
};
|
||||
|
||||
// The store view a filtered link from Health lands on.
|
||||
export type StoreTab = "health" | "orders" | "domains" | "mailboxes" | "economics";
|
||||
export function storeLink(tab: StoreTab, filters: Record<string, string> = {}): string {
|
||||
const p = new URLSearchParams({ tab, ...filters });
|
||||
return `/store?${p.toString()}`;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type * as StoreAPI from "@/lib/api/client/admin/store";
|
||||
import type { AdminStoreOrder } from "@/lib/api/client/admin/store";
|
||||
import { RefundDialog } from "./RefundDialog";
|
||||
import { dollarsToMicros, usd } from "./format";
|
||||
|
||||
const request = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/lib/api/client", async (original) => ({ ...(await original<object>()), Request: request }));
|
||||
|
||||
const api = vi.hoisted(() => ({ refund: vi.fn() }));
|
||||
vi.mock("@/lib/api/client/admin/store", async (original) => {
|
||||
const real = await original<typeof StoreAPI>();
|
||||
return { ...real, refundStoreOrder: api.refund };
|
||||
});
|
||||
|
||||
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
function order(over: Partial<AdminStoreOrder> = {}): AdminStoreOrder {
|
||||
return {
|
||||
id: "ord-1",
|
||||
organization_id: "org-1",
|
||||
organization_name: "Northwind",
|
||||
status: "completed",
|
||||
failure_code: "",
|
||||
due_now_micros: 20_000_000,
|
||||
charged_micros: 20_000_000,
|
||||
refunded_micros: 5_000_000,
|
||||
refunded_lines: [],
|
||||
placed: true,
|
||||
upstream_id: "ord_x",
|
||||
stuck: false,
|
||||
steps: [],
|
||||
lines: [{ type: "domain", domain: "northwind.com", years: 1, amount_micros: 20_000_000 }],
|
||||
created_by: null,
|
||||
created_at: "2026-11-01T00:00:00Z",
|
||||
updated_at: "2026-11-01T00:00:00Z",
|
||||
completed_at: "2026-11-01T00:00:00Z",
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function type(el: Element | null, value: string) {
|
||||
const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(el, value);
|
||||
el?.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
const button = (text: RegExp) => Array.from(document.querySelectorAll("button")).find((b) => text.test(b.textContent ?? "")) as HTMLButtonElement;
|
||||
|
||||
describe("store API client", () => {
|
||||
beforeEach(() => request.mockReset().mockResolvedValue({}));
|
||||
|
||||
it("sends false auto-renew as a filter and drops unset ones", async () => {
|
||||
const { listStoreDomains } = await vi.importActual<typeof StoreAPI>("@/lib/api/client/admin/store");
|
||||
await listStoreDomains({ auto_renew: "false", renewal_failed: true, expiring_days: 30, q: "" });
|
||||
expect(request).toHaveBeenLastCalledWith({
|
||||
method: "GET",
|
||||
url: "/admin/store/domains?auto_renew=false&renewal_failed=true&expiring_days=30",
|
||||
authorization: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("sends the idempotency key on a refund", async () => {
|
||||
const { refundStoreOrder } = await vi.importActual<typeof StoreAPI>("@/lib/api/client/admin/store");
|
||||
await refundStoreOrder("ord-1", { amount_micros: 1_500_000, reason: "goodwill" }, "key-1");
|
||||
expect(request).toHaveBeenLastCalledWith({
|
||||
method: "POST",
|
||||
url: "/admin/store/orders/ord-1/refund",
|
||||
authorization: true,
|
||||
data: { amount_micros: 1_500_000, reason: "goodwill" },
|
||||
headers: { "Idempotency-Key": "key-1" },
|
||||
});
|
||||
});
|
||||
|
||||
it("reads money as micros", () => {
|
||||
expect(dollarsToMicros("12.50")).toBe(12_500_000);
|
||||
expect(dollarsToMicros("$1,000")).toBe(1_000_000_000);
|
||||
expect(dollarsToMicros("1.234")).toBeNaN();
|
||||
expect(dollarsToMicros("")).toBeNull();
|
||||
expect(usd(1_500_000)).toBe("$1.50");
|
||||
expect(usd(1_234_500)).toBe("$1.2345");
|
||||
});
|
||||
});
|
||||
|
||||
describe("refund dialog", () => {
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
api.refund.mockReset();
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
host.remove();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
async function render(o: AdminStoreOrder) {
|
||||
const client = new QueryClient({ defaultOptions: { mutations: { retry: 0 } } });
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<RefundDialog order={o} open onOpenChange={() => {}} onRefunded={() => {}} />
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it("reuses the key when a failed refund is retried and takes a new one when the amount changes", async () => {
|
||||
api.refund.mockRejectedValueOnce(new Error("timeout")).mockResolvedValue({ order: order(), refunded_micros: 1_000_000 });
|
||||
await render(order());
|
||||
await act(async () => button(/An amount/).click());
|
||||
await act(async () => type(document.querySelector("#refund-amount"), "10"));
|
||||
await act(async () => type(document.querySelector("#refund-reason"), "goodwill"));
|
||||
await act(async () => button(/Refund \$10\.00/).click());
|
||||
await act(async () => button(/Refund \$10\.00/).click());
|
||||
expect(api.refund).toHaveBeenCalledTimes(2);
|
||||
const [first, second] = api.refund.mock.calls;
|
||||
expect(first[1]).toEqual({ amount_micros: 10_000_000, reason: "goodwill" });
|
||||
expect(second[2]).toBe(first[2]);
|
||||
|
||||
await act(async () => type(document.querySelector("#refund-amount"), "11"));
|
||||
await act(async () => button(/Refund \$11\.00/).click());
|
||||
expect(api.refund.mock.calls[2][2]).not.toBe(first[2]);
|
||||
});
|
||||
|
||||
it("refuses an amount above what is left to refund", async () => {
|
||||
await render(order());
|
||||
await act(async () => button(/An amount/).click());
|
||||
await act(async () => type(document.querySelector("#refund-amount"), "15.01"));
|
||||
await act(async () => type(document.querySelector("#refund-reason"), "goodwill"));
|
||||
expect(document.body.textContent).toContain("At most $15.00 is left to refund");
|
||||
expect(button(/^Refund/).disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
// One path for every Store operator action: confirm, call, toast the server's
|
||||
// own message on refusal, and refresh every store view.
|
||||
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { useConfirm, type ConfirmOptions } from "@/components/ConfirmDialog";
|
||||
import { ReauthCancelledError } from "@/lib/api/client";
|
||||
import { useAdminPerm } from "@/hooks/useAdminPerm";
|
||||
import { AdminPerm } from "@/lib/auth/permissions";
|
||||
|
||||
export interface StoreActionJob<T> {
|
||||
id: string;
|
||||
confirm: ConfirmOptions;
|
||||
success: string;
|
||||
run: () => Promise<T>;
|
||||
}
|
||||
|
||||
export function storeErrorText(e: unknown): string {
|
||||
return e instanceof Error && e.message ? e.message : "The action failed";
|
||||
}
|
||||
|
||||
export function useStoreAction() {
|
||||
const confirm = useConfirm();
|
||||
const qc = useQueryClient();
|
||||
const canManage = useAdminPerm(AdminPerm.ManageOrganizations);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const mutation = useMutation({ mutationFn: (run: () => Promise<unknown>) => run() });
|
||||
|
||||
async function act<T>(job: StoreActionJob<T>): Promise<T | undefined> {
|
||||
if (!(await confirm(job.confirm))) return undefined;
|
||||
setBusy(job.id);
|
||||
try {
|
||||
const out = (await mutation.mutateAsync(job.run)) as T;
|
||||
toast.success(job.success);
|
||||
await qc.invalidateQueries({ queryKey: ["admin", "store"] });
|
||||
return out;
|
||||
} catch (e) {
|
||||
if (!(e instanceof ReauthCancelledError)) toast.error(storeErrorText(e));
|
||||
return undefined;
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
return { act, busy, canManage };
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getStoreHealth } from "@/lib/api/client/admin/store";
|
||||
|
||||
// Shared by the Health tab and the tab badges, so the page reads it once.
|
||||
export function useStoreHealth() {
|
||||
return useQuery({ queryKey: ["admin", "store", "health"], queryFn: getStoreHealth, staleTime: 30_000, refetchInterval: 60_000 });
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
Network,
|
||||
Send,
|
||||
SlidersHorizontal,
|
||||
Store,
|
||||
Terminal,
|
||||
TicketPercent,
|
||||
UserCog,
|
||||
@@ -110,8 +111,14 @@ export const NAV_GROUPS: NavGroup[] = [
|
||||
{ to: "/organizations", label: "Organizations", perm: AdminPerm.ViewOrganizations },
|
||||
{ to: "/limit-requests", label: "Limit requests", perm: AdminPerm.ViewOrganizations },
|
||||
{ to: "/agencies", label: "Agencies", perm: AdminPerm.ViewOrganizations },
|
||||
{ to: "/partners", label: "Partners", perm: AdminPerm.ViewOrganizations },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Store",
|
||||
icon: Store,
|
||||
pages: [{ to: "/store", label: "Store", title: "Domain and mailbox store", perm: AdminPerm.ViewOrganizations }],
|
||||
},
|
||||
{
|
||||
label: "Growth",
|
||||
icon: TicketPercent,
|
||||
|
||||
@@ -205,6 +205,22 @@ export interface InstanceSettings {
|
||||
// What a workspace's balance is charged for usage: the provider price
|
||||
// below plus the markup. Absent on a backend from before the balance.
|
||||
usage?: UsageSettings;
|
||||
// Retail prices for domains and mailboxes bought in the dashboard. Absent
|
||||
// on a backend from before the store.
|
||||
store?: StoreSettings;
|
||||
}
|
||||
|
||||
export interface StoreSettings {
|
||||
/** What a workspace pays per mailbox per month, any provider, in micro-USD. */
|
||||
mailbox_monthly_micros: number;
|
||||
/** Added to the wholesale domain price, as a whole percent. */
|
||||
domain_markup_percent: number;
|
||||
/** Added to every domain price after the percent, in micro-USD. */
|
||||
domain_markup_fixed_micros: number;
|
||||
/** Days before a workspace's billing day its mailbox months are collected, 2 to 10. */
|
||||
mailbox_bill_lead_days?: number;
|
||||
/** The least a store charge puts on a card, topping the balance up, in micro-USD. */
|
||||
min_card_charge_micros?: number;
|
||||
}
|
||||
|
||||
export interface UsageSettings {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
// /admin/partners: resellers that create and run workspaces through the partner API, their keys and webhook.
|
||||
|
||||
import { Request } from "@/lib/api/client";
|
||||
|
||||
export type PartnerMode = "live" | "test";
|
||||
|
||||
export interface AdminPartner {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
display_name: string;
|
||||
status: "active" | "suspended";
|
||||
service_user_id: string;
|
||||
allowed_plans: string[];
|
||||
allowed_hosts: string[];
|
||||
delegation_domains: string[];
|
||||
webhook_url: string | null;
|
||||
webhook_secret_set: boolean;
|
||||
webhook_secret_rotated_at?: string;
|
||||
callback_base_url: string | null;
|
||||
callback_key_set: boolean;
|
||||
wholesale_sending_warmup_day_micros: number;
|
||||
wholesale_warmup_only_day_micros: number;
|
||||
rate_limit_per_second: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AdminPartnerKey {
|
||||
id: string;
|
||||
mode: PartnerMode;
|
||||
name: string;
|
||||
key_prefix: string;
|
||||
key_suffix: string;
|
||||
last_used_at?: string;
|
||||
revoked_at?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AdminPartnerDetail extends AdminPartner {
|
||||
keys: AdminPartnerKey[];
|
||||
}
|
||||
|
||||
export interface AdminPartnerOrganization {
|
||||
id: string;
|
||||
mode: PartnerMode;
|
||||
external_id: string;
|
||||
organization_id: string | null;
|
||||
organization_name?: string;
|
||||
plan_key: string;
|
||||
state: "active" | "suspended" | "cancelled";
|
||||
suspended_reason: string | null;
|
||||
campaign_sends_per_mailbox_per_day: number;
|
||||
group_external_id: string | null;
|
||||
group_name: string | null;
|
||||
deletes_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AdminPartnerUpdate {
|
||||
name?: string;
|
||||
display_name?: string;
|
||||
status?: "active" | "suspended";
|
||||
allowed_hosts?: string[];
|
||||
delegation_domains?: string[];
|
||||
webhook_url?: string;
|
||||
callback_base_url?: string;
|
||||
wholesale_sending_warmup_day_micros?: number;
|
||||
wholesale_warmup_only_day_micros?: number;
|
||||
rate_limit_per_second?: number;
|
||||
}
|
||||
|
||||
export function listPartners(): Promise<{ data: AdminPartner[] }> {
|
||||
return Request({ method: "GET", url: "/admin/partners", authorization: true });
|
||||
}
|
||||
|
||||
export function getPartner(id: string): Promise<AdminPartnerDetail> {
|
||||
return Request({ method: "GET", url: `/admin/partners/${id}`, authorization: true });
|
||||
}
|
||||
|
||||
export function createPartner(body: { slug: string; name: string; display_name?: string; allowed_hosts?: string[] }): Promise<AdminPartnerDetail> {
|
||||
return Request({ method: "POST", url: "/admin/partners", authorization: true, data: body });
|
||||
}
|
||||
|
||||
export function updatePartner(id: string, body: AdminPartnerUpdate): Promise<AdminPartnerDetail> {
|
||||
return Request({ method: "PATCH", url: `/admin/partners/${id}`, authorization: true, data: body });
|
||||
}
|
||||
|
||||
/** The new signing secret, shown once. The previous one keeps signing for a day. */
|
||||
export function rotatePartnerWebhookSecret(id: string): Promise<{ secret: string }> {
|
||||
return Request({ method: "POST", url: `/admin/partners/${id}/webhook-secret`, authorization: true });
|
||||
}
|
||||
|
||||
export function setPartnerCallbackKey(id: string, key: string): Promise<AdminPartnerDetail> {
|
||||
return Request({ method: "PUT", url: `/admin/partners/${id}/callback-key`, authorization: true, data: { key } });
|
||||
}
|
||||
|
||||
/** A partner API key; `secret` exists only in this answer. */
|
||||
export function createPartnerKey(id: string, body: { mode: PartnerMode; name?: string }): Promise<AdminPartnerKey & { secret: string }> {
|
||||
return Request({ method: "POST", url: `/admin/partners/${id}/keys`, authorization: true, data: body });
|
||||
}
|
||||
|
||||
export function revokePartnerKey(id: string, keyId: string): Promise<void> {
|
||||
return Request({ method: "DELETE", url: `/admin/partners/${id}/keys/${keyId}`, authorization: true });
|
||||
}
|
||||
|
||||
export function listPartnerOrganizations(
|
||||
id: string,
|
||||
cursor?: string,
|
||||
): Promise<{ data: AdminPartnerOrganization[]; pagination: { next_cursor: string | null; has_more: boolean } }> {
|
||||
const qs = new URLSearchParams({ limit: "50" });
|
||||
if (cursor) qs.set("cursor", cursor);
|
||||
return Request({ method: "GET", url: `/admin/partners/${id}/organizations?${qs}`, authorization: true });
|
||||
}
|
||||
|
||||
/** One workspace's enabled mailbox-days in a statement. */
|
||||
export interface AdminPartnerStatementLine {
|
||||
external_id: string;
|
||||
sending_warmup_days: number;
|
||||
warmup_only_days: number;
|
||||
amount_micros: number;
|
||||
}
|
||||
|
||||
/** A month of a partner's live enabled mailbox-days at its wholesale rates; closed_at is null while the month runs. */
|
||||
export interface AdminPartnerStatement {
|
||||
id: string;
|
||||
month: string;
|
||||
sending_warmup_days: number;
|
||||
warmup_only_days: number;
|
||||
sending_warmup_day_micros: number;
|
||||
warmup_only_day_micros: number;
|
||||
amount_micros: number;
|
||||
closed_at: string | null;
|
||||
lines: AdminPartnerStatementLine[] | null;
|
||||
}
|
||||
|
||||
export function listPartnerStatements(id: string): Promise<{ data: AdminPartnerStatement[] }> {
|
||||
return Request({ method: "GET", url: `/admin/partners/${id}/statements`, authorization: true });
|
||||
}
|
||||
|
||||
/** month is YYYY-MM: a closed statement, or the running month at today's rates. */
|
||||
export function getPartnerStatement(id: string, month: string): Promise<AdminPartnerStatement> {
|
||||
return Request({ method: "GET", url: `/admin/partners/${id}/statements/${month}`, authorization: true });
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// /admin/store/*: the domain and mailbox store. Pricing is the live wholesale list proxied
|
||||
// from GraphKit for the settings preview; the rest is the Store section.
|
||||
|
||||
import { Request } from "@/lib/api/client";
|
||||
import { buildSearchQuery } from "@/lib/api/client/admin/query";
|
||||
|
||||
export interface StoreDomainPrice {
|
||||
tld: string;
|
||||
/** Wholesale first-year price, micro-USD. */
|
||||
register_micros: number;
|
||||
/** Wholesale renewal price, micro-USD. */
|
||||
renew_micros: number;
|
||||
}
|
||||
|
||||
export interface StoreRetailPrice {
|
||||
tld: string;
|
||||
/** First-year price at the instance's saved markup, micro-USD. */
|
||||
register_micros: number;
|
||||
/** Renewal price at the instance's saved markup, micro-USD. */
|
||||
renew_micros: number;
|
||||
}
|
||||
|
||||
export interface StorePricing {
|
||||
currency: string;
|
||||
updated_at: string;
|
||||
domains: StoreDomainPrice[];
|
||||
mailboxes?: { provider: string; monthly_micros: number }[] | null;
|
||||
limits?: { mailboxes_per_domain_max: number; mailboxes_per_domain_recommended: number };
|
||||
/** The same TLDs at the saved settings; the preview computes from the form's unsaved values instead. */
|
||||
retail: StoreRetailPrice[];
|
||||
}
|
||||
|
||||
export function getStorePricing(): Promise<StorePricing> {
|
||||
return Request({
|
||||
method: "GET",
|
||||
url: "/admin/store/pricing",
|
||||
authorization: true,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Store operations: health, economics, instance-wide lists and actions ----
|
||||
// Reads need the view-organizations bit, actions the manage-organizations bit.
|
||||
// Every action is audited and converges, so a retried click changes nothing twice.
|
||||
|
||||
export type StoreMode = "live" | "sandbox" | "simulator" | "off";
|
||||
export type StoreOrderStatus = "charging" | "processing" | "completed" | "partially_failed" | "failed";
|
||||
export type StoreConnectState = "waiting" | "connecting" | "connected" | "failed";
|
||||
|
||||
export interface AdminStoreOrderStep {
|
||||
key: string;
|
||||
status: string;
|
||||
at?: string | null;
|
||||
}
|
||||
|
||||
export interface AdminStoreOrderLine {
|
||||
type: "domain" | "mailboxes";
|
||||
domain: string;
|
||||
years?: number;
|
||||
provider?: string;
|
||||
count?: number;
|
||||
amount_micros: number;
|
||||
renew_micros?: number;
|
||||
monthly_micros?: number;
|
||||
}
|
||||
|
||||
export interface AdminStoreOrder {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
status: StoreOrderStatus;
|
||||
/** Empty, or a Warmbly code. Upstream wording never reaches the panel. */
|
||||
failure_code: string;
|
||||
due_now_micros: number;
|
||||
charged_micros: number;
|
||||
refunded_micros: number;
|
||||
/** Line indexes already refunded. */
|
||||
refunded_lines: number[];
|
||||
placed: boolean;
|
||||
upstream_id: string;
|
||||
stuck: boolean;
|
||||
steps: AdminStoreOrderStep[];
|
||||
lines: AdminStoreOrderLine[];
|
||||
created_by: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
completed_at: string | null;
|
||||
}
|
||||
|
||||
export interface AdminStoreDomain {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
name: string;
|
||||
status: string;
|
||||
source: "purchased" | "connected";
|
||||
provider: string;
|
||||
expires_at: string | null;
|
||||
auto_renew: boolean;
|
||||
renew_micros: number;
|
||||
renewal_failures: number;
|
||||
renewal_attempt_at: string | null;
|
||||
last_notice: string;
|
||||
mailbox_count: number;
|
||||
tracking_host: string;
|
||||
upstream_id: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface AdminStoreMailbox {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
domain_id: string;
|
||||
email: string;
|
||||
provider: string;
|
||||
status: string;
|
||||
is_admin: boolean;
|
||||
monthly_micros: number;
|
||||
paid_through: string | null;
|
||||
cancels_at: string | null;
|
||||
email_account_id: string | null;
|
||||
connect_method: string;
|
||||
connect_state: StoreConnectState;
|
||||
connect_error: string;
|
||||
connect_attempts: number;
|
||||
billing_failures: number;
|
||||
pending_charge: boolean;
|
||||
upstream_id: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface StoreList<T> {
|
||||
data: T[];
|
||||
pagination: { next_cursor: string | null; has_more: boolean };
|
||||
}
|
||||
|
||||
export interface StoreLoopStatus {
|
||||
last_started_at: string | null;
|
||||
last_finished_at: string | null;
|
||||
last_status: string;
|
||||
last_error: string;
|
||||
lag_seconds: number;
|
||||
}
|
||||
|
||||
export interface StoreHealthCounts {
|
||||
orders_open: number;
|
||||
orders_stuck: number;
|
||||
orders_failed_7d: number;
|
||||
connects_failed: number;
|
||||
mailboxes_live: number;
|
||||
mailboxes_billing_failed: number;
|
||||
domains_live: number;
|
||||
domains_renewal_failed: number;
|
||||
domains_expiring_30d: number;
|
||||
}
|
||||
|
||||
export interface StoreHealth {
|
||||
enabled: boolean;
|
||||
mode: StoreMode;
|
||||
metered: boolean;
|
||||
partner_balance: {
|
||||
balance_micros: number;
|
||||
low_threshold_micros: number;
|
||||
currency: string;
|
||||
livemode: boolean;
|
||||
} | null;
|
||||
partner_balance_error: "" | "store_unavailable";
|
||||
last_webhook_at: string | null;
|
||||
events_cursor_set: boolean;
|
||||
reconciler: StoreLoopStatus | null;
|
||||
billing: StoreLoopStatus | null;
|
||||
counts: StoreHealthCounts;
|
||||
alerts: { code: string; title: string; at: string }[];
|
||||
/** Mailboxes whose GraphKit period started without Warmbly having collected it. Should stay empty. */
|
||||
uncollected?: StoreUncollectedMailbox[];
|
||||
}
|
||||
|
||||
export interface StoreUncollectedMailbox {
|
||||
id: string;
|
||||
organization_id: string;
|
||||
email: string;
|
||||
/** GraphKit's current period end. */
|
||||
period_end: string;
|
||||
/** How far Warmbly collected. */
|
||||
paid_through: string;
|
||||
}
|
||||
|
||||
export interface StoreEconomics {
|
||||
currency: string;
|
||||
updated_at: string;
|
||||
mailboxes: {
|
||||
provider: string;
|
||||
wholesale_monthly_micros: number;
|
||||
retail_monthly_micros: number;
|
||||
margin_micros: number;
|
||||
scheduled_wholesale_monthly_micros: number | null;
|
||||
scheduled_from: string | null;
|
||||
live_count: number;
|
||||
}[];
|
||||
domains: {
|
||||
tld: string;
|
||||
min_years: number;
|
||||
wholesale_register_micros: number;
|
||||
retail_register_micros: number;
|
||||
wholesale_renew_micros: number;
|
||||
retail_renew_micros: number;
|
||||
}[];
|
||||
totals: {
|
||||
live_mailboxes: number;
|
||||
monthly_retail_micros: number;
|
||||
monthly_wholesale_micros: number;
|
||||
monthly_margin_micros: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface StoreWorkspace {
|
||||
organization: { id: string; name: string };
|
||||
account: { exists: boolean; created_at: string | null; has_registrant: boolean };
|
||||
plan_active: boolean;
|
||||
managed_by_partner: boolean;
|
||||
balance_micros: number | null;
|
||||
monthly_spend_micros: number;
|
||||
orders: AdminStoreOrder[];
|
||||
domains: AdminStoreDomain[];
|
||||
mailboxes: AdminStoreMailbox[];
|
||||
}
|
||||
|
||||
interface Paging {
|
||||
q?: string;
|
||||
org_id?: string;
|
||||
limit?: number;
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
export interface StoreOrderFilters extends Paging {
|
||||
status?: string;
|
||||
failure_code?: string;
|
||||
stuck?: boolean;
|
||||
}
|
||||
|
||||
export interface StoreDomainFilters extends Paging {
|
||||
status?: string;
|
||||
/** Sent as text so false is a filter rather than an omission. */
|
||||
auto_renew?: "true" | "false";
|
||||
expiring_days?: number;
|
||||
renewal_failed?: boolean;
|
||||
}
|
||||
|
||||
export interface StoreMailboxFilters extends Paging {
|
||||
status?: string;
|
||||
connect_state?: string;
|
||||
billing_failed?: boolean;
|
||||
}
|
||||
|
||||
/** A line refund pays that line's charge at most once; an amount refund needs a reason and an idempotency key. */
|
||||
export type StoreRefund = { line: number } | { amount_micros: number; reason: string };
|
||||
|
||||
const get = <T>(url: string): Promise<T> => Request({ method: "GET", url, authorization: true });
|
||||
const post = <T>(url: string): Promise<T> => Request({ method: "POST", url, authorization: true });
|
||||
|
||||
export const getStoreHealth = () => get<StoreHealth>("/admin/store/health");
|
||||
export const getStoreEconomics = () => get<StoreEconomics>("/admin/store/economics");
|
||||
export const getStoreWorkspace = (orgId: string) => get<StoreWorkspace>(`/admin/store/workspaces/${orgId}`);
|
||||
|
||||
export const listStoreOrders = (f: StoreOrderFilters = {}) =>
|
||||
get<StoreList<AdminStoreOrder>>(`/admin/store/orders${buildSearchQuery({ ...f })}`);
|
||||
export const getStoreOrder = (id: string) => get<AdminStoreOrder>(`/admin/store/orders/${id}`);
|
||||
export const listStoreDomains = (f: StoreDomainFilters = {}) =>
|
||||
get<StoreList<AdminStoreDomain>>(`/admin/store/domains${buildSearchQuery({ ...f })}`);
|
||||
export const listStoreMailboxes = (f: StoreMailboxFilters = {}) =>
|
||||
get<StoreList<AdminStoreMailbox>>(`/admin/store/mailboxes${buildSearchQuery({ ...f })}`);
|
||||
|
||||
export const refreshStoreOrder = (id: string) => post<AdminStoreOrder>(`/admin/store/orders/${id}/refresh`);
|
||||
/** Places a charged order that never reached GraphKit, under its original key. */
|
||||
export const placeStoreOrder = (id: string) => post<AdminStoreOrder>(`/admin/store/orders/${id}/place`);
|
||||
|
||||
/** The key is sent on every refund, so a retried submission of the same dialog never pays twice. */
|
||||
export function refundStoreOrder(
|
||||
id: string,
|
||||
body: StoreRefund,
|
||||
idempotencyKey: string,
|
||||
): Promise<{ order: AdminStoreOrder; refunded_micros: number }> {
|
||||
return Request({
|
||||
method: "POST",
|
||||
url: `/admin/store/orders/${id}/refund`,
|
||||
authorization: true,
|
||||
data: body,
|
||||
headers: { "Idempotency-Key": idempotencyKey },
|
||||
});
|
||||
}
|
||||
|
||||
export type StoreMailboxAction = "refresh" | "connect" | "cancel" | "resume";
|
||||
export const storeMailboxAction = (id: string, action: StoreMailboxAction) =>
|
||||
post<AdminStoreMailbox>(`/admin/store/mailboxes/${id}/${action}`);
|
||||
|
||||
export type StoreDomainAction = "refresh" | "renew";
|
||||
export const storeDomainAction = (id: string, action: StoreDomainAction) =>
|
||||
post<AdminStoreDomain>(`/admin/store/domains/${id}/${action}`);
|
||||
|
||||
export function setStoreDomainAutoRenew(id: string, autoRenew: boolean): Promise<AdminStoreDomain> {
|
||||
return Request({
|
||||
method: "PATCH",
|
||||
url: `/admin/store/domains/${id}`,
|
||||
authorization: true,
|
||||
data: { auto_renew: autoRenew },
|
||||
});
|
||||
}
|
||||
|
||||
// ---- GraphKit connection: manage-settings; writes also need a fresh authentication ----
|
||||
|
||||
export interface StoreConnection {
|
||||
/** Environment GRAPHKIT_* variables win over stored settings. */
|
||||
source: "environment" | "settings" | "none";
|
||||
configured: boolean;
|
||||
mode: StoreMode;
|
||||
api_url: string;
|
||||
default_api_url: string;
|
||||
api_key_set: boolean;
|
||||
webhook_secret_set: boolean;
|
||||
/** What GraphKit must call. */
|
||||
webhook_url: string;
|
||||
/** False when CREDENTIALS_ENCRYPTION_KEY is unset; saving is refused. */
|
||||
sealing_available: boolean;
|
||||
updated_at: string | null;
|
||||
updated_by: string | null;
|
||||
/** Set when nothing is configured but live purchases exist. */
|
||||
purchases_without_connection: { mailboxes: number; domains: number } | null;
|
||||
}
|
||||
|
||||
/** An omitted or empty secret keeps the stored one. */
|
||||
export interface StoreConnectionInput {
|
||||
api_url: string;
|
||||
api_key?: string;
|
||||
webhook_secret?: string;
|
||||
}
|
||||
|
||||
export interface StoreConnectionTest {
|
||||
mode: "live" | "test";
|
||||
balance_micros: number;
|
||||
currency: string;
|
||||
com_register_micros: number | null;
|
||||
com_renew_micros: number | null;
|
||||
}
|
||||
|
||||
export const STORE_CONNECTION_KEY = ["admin", "store", "connection"] as const;
|
||||
|
||||
export function getStoreConnection(): Promise<StoreConnection> {
|
||||
return Request({ method: "GET", url: "/admin/store/connection", authorization: true });
|
||||
}
|
||||
|
||||
export function saveStoreConnection(body: StoreConnectionInput): Promise<StoreConnection> {
|
||||
return Request({ method: "PUT", url: "/admin/store/connection", data: body, authorization: true });
|
||||
}
|
||||
|
||||
export function testStoreConnection(body: StoreConnectionInput): Promise<StoreConnectionTest> {
|
||||
return Request({ method: "POST", url: "/admin/store/connection/test", data: body, authorization: true });
|
||||
}
|
||||
|
||||
export function deleteStoreConnection(): Promise<StoreConnection> {
|
||||
return Request({ method: "DELETE", url: "/admin/store/connection", authorization: true });
|
||||
}
|
||||
@@ -51,6 +51,8 @@ import SendsPage from "@/app/dashboard/SendsPage";
|
||||
import LimitRequestsPage from "@/app/dashboard/LimitRequestsPage";
|
||||
import AgenciesPage from "@/app/dashboard/agencies/AgenciesPage";
|
||||
import AgencyDetailPage from "@/app/dashboard/agencies/AgencyDetailPage";
|
||||
import PartnersPage from "@/app/dashboard/partners/PartnersPage";
|
||||
import PartnerDetailPage from "@/app/dashboard/partners/PartnerDetailPage";
|
||||
import DiscountsPage from "@/app/dashboard/DiscountsPage";
|
||||
import OutreachPage from "@/app/dashboard/OutreachPage";
|
||||
import MailboxesPage from "@/app/dashboard/MailboxesPage";
|
||||
@@ -60,6 +62,8 @@ import JobsPage from "@/app/dashboard/JobsPage";
|
||||
import HealthPage from "@/app/dashboard/HealthPage";
|
||||
import ConfigurationPage from "@/app/dashboard/ConfigurationPage";
|
||||
import TransfersPage from "@/app/dashboard/TransfersPage";
|
||||
import StorePage from "@/app/dashboard/store/StorePage";
|
||||
import StoreWorkspacePage from "@/app/dashboard/store/StoreWorkspacePage";
|
||||
import NotFoundPage from "@/app/dashboard/NotFoundPage";
|
||||
import RealtimeManager from "@/lib/realtime/RealtimeManager";
|
||||
import { RequirePermission } from "@/components/layout/RequirePermission";
|
||||
@@ -173,6 +177,8 @@ const router = createBrowserRouter([
|
||||
{ path: "limit-requests", element: gated(AdminPerm.ViewOrganizations, <LimitRequestsPage />) },
|
||||
{ path: "agencies", element: gated(AdminPerm.ViewOrganizations, <AgenciesPage />) },
|
||||
{ path: "agencies/:id", element: gated(AdminPerm.ViewOrganizations, <AgencyDetailPage />) },
|
||||
{ path: "partners", element: gated(AdminPerm.ViewOrganizations, <PartnersPage />) },
|
||||
{ path: "partners/:id", element: gated(AdminPerm.ViewOrganizations, <PartnerDetailPage />) },
|
||||
{ path: "developer-apps", element: gated(AdminPerm.ViewOrganizations, <DeveloperAppsPage />) },
|
||||
{ path: "app-listings", element: <Navigate to="/developer-apps?tab=directory" replace /> },
|
||||
{ path: "discounts", element: gated(AdminPerm.ViewOrganizations, <DiscountsPage />) },
|
||||
@@ -189,6 +195,8 @@ const router = createBrowserRouter([
|
||||
{ path: "health", element: gated(AdminPerm.ViewAnalytics, <HealthPage />) },
|
||||
{ path: "configuration", element: gated(AdminPerm.ManageSettings, <ConfigurationPage />) },
|
||||
{ path: "transfers", element: gated(AdminPerm.ViewOrganizations, <TransfersPage />) },
|
||||
{ path: "store", element: gated(AdminPerm.ViewOrganizations, <StorePage />) },
|
||||
{ path: "store/workspaces/:orgId", element: gated(AdminPerm.ViewOrganizations, <StoreWorkspacePage />) },
|
||||
|
||||
// Retired paths that docs still link.
|
||||
{ path: "analytics", element: <Redirect to="/" /> },
|
||||
|
||||
+137
-3
@@ -34,6 +34,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/appattest"
|
||||
"github.com/warmbly/warmbly/internal/app/attachmentdownload"
|
||||
"github.com/warmbly/warmbly/internal/app/unsublink"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/observability/errs"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -112,6 +113,7 @@ import (
|
||||
orgrisk "github.com/warmbly/warmbly/internal/app/orgrisk"
|
||||
"github.com/warmbly/warmbly/internal/app/orgtransfer"
|
||||
"github.com/warmbly/warmbly/internal/app/owndomain"
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/app/partners"
|
||||
"github.com/warmbly/warmbly/internal/app/passkey"
|
||||
"github.com/warmbly/warmbly/internal/app/pipedrive"
|
||||
@@ -133,6 +135,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/slackapp"
|
||||
"github.com/warmbly/warmbly/internal/app/socialauth"
|
||||
"github.com/warmbly/warmbly/internal/app/socket"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/app/stripe"
|
||||
"github.com/warmbly/warmbly/internal/app/subscription"
|
||||
"github.com/warmbly/warmbly/internal/app/sysstatus"
|
||||
@@ -268,12 +271,15 @@ func main() {
|
||||
var aiSettingsRepository repository.AISettingsRepository
|
||||
var creditService credits.CreditService
|
||||
var balanceService *balance.Service
|
||||
var storeService *store.Service
|
||||
var aiDraftRepo repository.AIDraftRepository
|
||||
var writingGenerator generation.WritingGenerator
|
||||
var aiProvider generation.Provider
|
||||
var aiSearch generation.SearchClient
|
||||
var webReader webread.Reader
|
||||
var aiToolRegistry *aitools.Registry
|
||||
// Set once the partner and store services exist; the AI tools read it per call.
|
||||
var aiMailboxLock func(ctx context.Context, orgID, accountID uuid.UUID) *errx.Error
|
||||
var aiAgentService aiagent.Service
|
||||
var slackService *slackapp.Service
|
||||
var researchService research.Service
|
||||
@@ -398,6 +404,8 @@ func main() {
|
||||
var brandService *brandkit.Service
|
||||
// A portal session is held to its agency's clients; sign-in on the main address hands a portal its session.
|
||||
var portalHandoffService *portalhandoff.Service
|
||||
// partnerService runs the reseller API; it does nothing until an operator creates a partner.
|
||||
var partnerService *partner.Service
|
||||
var portalClients middleware.PortalClients
|
||||
// agencyMembers holds keyed requests on agency routes to the agency's staff.
|
||||
var agencyMembers middleware.AgencyMembers
|
||||
@@ -934,6 +942,8 @@ func main() {
|
||||
}); ok {
|
||||
g.WireLimitOverrides(organizationRepository)
|
||||
}
|
||||
// Mailboxes bought in the store keep their inbox when the plan lapses.
|
||||
featureGateService = feature.WithPurchasedMailboxes(featureGateService, feature.StoreMailboxes{Repo: repository.NewStoreRepository(primaryDB)})
|
||||
workerAssignmentService = worker.NewAssignmentService(workerRepository, subscriptionRepository, planRepository)
|
||||
subscriptionService = subscription.NewService(subscriptionRepository, planRepository)
|
||||
planOfferService = planoffer.New(repository.NewPlanOfferRepository(primaryDB.Pool), planRepository)
|
||||
@@ -1810,6 +1820,7 @@ func main() {
|
||||
// never exceed the caller's permissions. Built once here with the same
|
||||
// service instances the HTTP handlers use.
|
||||
aiToolRegistry = aitools.BuildRegistry(aitools.Deps{
|
||||
MailboxLock: &aiMailboxLock,
|
||||
Contacts: contactService,
|
||||
CRM: crmService,
|
||||
Campaigns: campaignService,
|
||||
@@ -2169,6 +2180,65 @@ func main() {
|
||||
}
|
||||
go delegationService.StartHealth(ctx)
|
||||
|
||||
// The store: domains and mailboxes bought through GraphKit. GRAPHKIT_* wins; otherwise the API key saved in the admin panel turns it on.
|
||||
storeCfg := config.LoadGraphKit()
|
||||
if err := storeCfg.Validate(); err != nil {
|
||||
errs.CaptureFatal(err)
|
||||
log.Fatal("Store: ", err)
|
||||
}
|
||||
storeDeps := store.Deps{
|
||||
Repo: repository.NewStoreRepository(primaryDB), Credits: creditService, Retail: instanceSettings,
|
||||
Billing: store.StripeBilling{Subs: subscriptionRepository, Customers: stripeService},
|
||||
People: store.Directory{Users: userRepostory, Orgs: organizationRepository},
|
||||
Delegator: delegationService, Mailboxes: emailService, Publisher: streamingPublisher,
|
||||
// Buying needs a paid plan; the gate answers yes on a self-host.
|
||||
Plans: featureGateService, Ops: opsNotifier,
|
||||
// Mailbox photos are private objects; a new domain forwards to the workspace's brand website by default.
|
||||
Blobs: s3ForHandler, Websites: brandRepository,
|
||||
// Only a self-host shows an unconfigured store as locked; hosted keeps it hidden until the key is added.
|
||||
SelfHosted: config.SelfHosted(),
|
||||
}
|
||||
if balanceService != nil {
|
||||
storeDeps.Cards = balanceService
|
||||
}
|
||||
if notificationService != nil {
|
||||
storeDeps.Notifier = notificationService
|
||||
}
|
||||
storeService = store.New(storeDeps)
|
||||
storeService.WireConnectionSettings(repository.NewStoreConnectionRepository(primaryDB.Pool, credEncrypter), storeCfg)
|
||||
delegationService.WirePurchasedTokens(storeService)
|
||||
// A card saved after a refused store charge pays what is unpaid at once.
|
||||
if cs, ok := stripeService.(interface {
|
||||
WireCardSaved(func(context.Context, uuid.UUID))
|
||||
}); ok {
|
||||
cs.WireCardSaved(func(ctx context.Context, orgID uuid.UUID) {
|
||||
if err := storeService.RetryUnpaid(ctx, orgID); err != nil {
|
||||
log.Printf("Store: retrying unpaid charges after a card update failed: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
storeService.Start(ctx)
|
||||
if storeCfg.Enabled() {
|
||||
if err := storeService.Connect(storeCfg, store.SourceEnvironment); err != nil {
|
||||
errs.CaptureFatal(err)
|
||||
log.Fatal("Store: ", err)
|
||||
}
|
||||
if storeCfg.Fake() {
|
||||
log.Printf("Store: using the in-process GraphKit simulator")
|
||||
}
|
||||
} else if err := storeService.LoadConnection(ctx); err != nil {
|
||||
log.Printf("Store: reading the GraphKit connection saved in the admin panel failed: %v", err)
|
||||
}
|
||||
go storeService.WatchConnection(ctx)
|
||||
aitools.RegisterStoreTools(aiToolRegistry, storeService, auditService)
|
||||
if storeService.Enabled() {
|
||||
log.Printf("Store: on (%s, from the %s)", storeService.Mode(), storeService.Source())
|
||||
} else if live, err := storeService.PurchasesWithoutConnection(ctx, nil); err == nil && live != nil {
|
||||
log.Printf("WARNING Store: GraphKit is not configured, but %d purchased mailboxes and %d domains bought here are still live. "+
|
||||
"Their renewals, monthly billing and Google mailbox connections are paused until GraphKit is configured: set GRAPHKIT_API_KEY "+
|
||||
"or add the API key under Setup and health > Integrations in the admin panel.", live.Mailboxes, live.Domains)
|
||||
}
|
||||
|
||||
// Inbox vendor accounts: keys sealed per workspace, mailboxes imported by API.
|
||||
var sandboxVendors func(string, map[string]string) (mailvendor.Client, error)
|
||||
if u := config.MailvendorSandboxURL(); u != "" {
|
||||
@@ -2245,6 +2315,8 @@ func main() {
|
||||
if s3ForHandler != nil {
|
||||
mailboxAvatars := mailboxavatar.New(repository.NewMailboxAvatarRepository(primaryDB), s3ForHandler, delegationService, vendorConnService)
|
||||
emailService.WireAvatars(mailboxAvatars)
|
||||
// A purchased mailbox's chosen photo shows in the dashboard as soon as it connects.
|
||||
storeService.WireAvatars(mailboxAvatars)
|
||||
go mailboxAvatars.Start(ctx)
|
||||
}
|
||||
vendorConnService.SetImporter(mailboxImportService)
|
||||
@@ -2252,7 +2324,13 @@ func main() {
|
||||
vendorConnService.WireSigninSwitch(auditService, func(ctx context.Context) bool {
|
||||
return instanceSettings == nil || instanceSettings.AutoVendorReconnect(ctx)
|
||||
})
|
||||
sendingDomainService.WireVendors(vendorConnService)
|
||||
if storeService != nil {
|
||||
// Store domains are a vendor too: their tracking CNAME and forwarding go through the store's DNS.
|
||||
sendingDomainService.WireVendors(sendingdomain.Vendors{vendorConnService, store.DomainVendor{S: storeService}})
|
||||
storeService.WireSendingDomains(sendingDomainService)
|
||||
} else {
|
||||
sendingDomainService.WireVendors(vendorConnService)
|
||||
}
|
||||
go vendorConnService.StartReconnect(ctx)
|
||||
go mailboxImportService.Start(ctx)
|
||||
tasksService.SetAISearch(aiSearch)
|
||||
@@ -2423,6 +2501,56 @@ func main() {
|
||||
dangerZoneBilling(stripeService),
|
||||
)
|
||||
dangerZoneJob := jobs.NewDangerZoneJob(dangerZoneService)
|
||||
|
||||
// Resellers: managed workspaces, their people and their events.
|
||||
partnerDeps := partner.Deps{
|
||||
Repo: repository.NewPartnerRepository(primaryDB.Pool), Orgs: organizationRepository, Counts: organizationService,
|
||||
Balances: creditRepository, APIKeys: apiKeyService, Sessions: tokenService, Bans: userRepostory,
|
||||
Deletions: dangerZoneService, Audit: auditService, Codes: portalhandoff.RedisStore{Cache: cache}, Cache: cache,
|
||||
Seeders: []func(context.Context, uuid.UUID){inboxtag.SeedLabels(repository.NewTagCategoryStore(primaryDB.Pool))},
|
||||
}
|
||||
if credEncrypter != nil {
|
||||
partnerDeps.Sealer = credEncrypter
|
||||
}
|
||||
partnerService = partner.NewService(partnerDeps)
|
||||
aiMailboxLock = handler.MailboxLock(partnerService, storeService)
|
||||
feature.WithPartnerHold(featureGateService, partnerService)
|
||||
// A partner-managed workspace buys through its partner, so the store is off there.
|
||||
storeService.WireManaged(store.ManagedBy(partnerService.IsPartnerManaged))
|
||||
go jobrun.Loop(ctx, "partner_webhooks", 5*time.Second, true, partnerService.DeliverDue)
|
||||
go jobrun.Loop(ctx, "partner_deleted_sweep", 10*time.Minute, true, partnerService.SweepDeleted)
|
||||
// The mailbox half: attach, per-mailbox enablement, connect links, usage and the group brand.
|
||||
partnerMailboxes := partner.MailboxDeps{
|
||||
Repo: repository.NewPartnerMailboxRepository(primaryDB.Pool), Emails: emailService, Accounts: emailRepostory,
|
||||
Warmup: tasksService, Credits: creditService,
|
||||
}
|
||||
if delegationService != nil {
|
||||
partnerMailboxes.Delegator = delegationService
|
||||
}
|
||||
if connectLinkService != nil {
|
||||
partnerMailboxes.Links = connectLinkService
|
||||
connectLinkService.WirePartnerLinks(partnerService)
|
||||
}
|
||||
if customHosts != nil {
|
||||
partnerMailboxes.Portals = customHosts
|
||||
}
|
||||
if brandService != nil {
|
||||
partnerMailboxes.BrandsChanged = brandService.Resolver().InvalidateAll
|
||||
brandService.Resolver().WireGroups(partnerService)
|
||||
}
|
||||
partnerService.WireMailboxes(partnerMailboxes)
|
||||
if delegationService != nil {
|
||||
// One token source for purchased Google mailboxes: a partner's callback for what it attached, else the store.
|
||||
tokens := partner.TokenRouter{Partners: partnerService}
|
||||
if storeService != nil {
|
||||
tokens.Fallback = storeService
|
||||
}
|
||||
delegationService.WirePurchasedTokens(tokens)
|
||||
}
|
||||
go jobrun.Loop(ctx, "partner_mailboxes", 20*time.Second, true, partnerService.SyncMailboxes)
|
||||
go jobrun.Loop(ctx, "partner_connects", 10*time.Second, true, partnerService.ConnectDue)
|
||||
go jobrun.Loop(ctx, "partner_portals", 5*time.Minute, true, partnerService.CheckPortals)
|
||||
go jobrun.Loop(ctx, "partner_statements", time.Hour, true, partnerService.CloseStatements)
|
||||
dangerZoneScheduler := jobs.NewDangerZoneScheduler(dangerZoneJob, 1*time.Hour)
|
||||
go dangerZoneScheduler.Start(ctx)
|
||||
|
||||
@@ -2758,14 +2886,18 @@ func main() {
|
||||
Policy: authPolicy,
|
||||
WebsocketURL: os.Getenv("WEBSOCKET_URL"),
|
||||
}
|
||||
instanceChecks := instancecheck.New(instancecheck.Deps{
|
||||
checkDeps := instancecheck.Deps{
|
||||
Runtime: instanceRuntime,
|
||||
Transport: mailTransport,
|
||||
Policy: authPolicy,
|
||||
DB: instanceChecksDB,
|
||||
Cache: authCache,
|
||||
Updates: updatesService,
|
||||
})
|
||||
}
|
||||
if storeService != nil {
|
||||
checkDeps.Store = storeService
|
||||
}
|
||||
instanceChecks := instancecheck.New(checkDeps)
|
||||
|
||||
h := &handler.Handler{
|
||||
AuthService: authService,
|
||||
@@ -2890,6 +3022,7 @@ func main() {
|
||||
// AI writing assistant + credit ledger
|
||||
CreditService: creditService,
|
||||
BalanceService: balanceService,
|
||||
StoreService: storeService,
|
||||
WritingGenerator: writingGenerator,
|
||||
AIProvider: aiProvider,
|
||||
TypeSafe: typeSafeAsker(typeSafeClient),
|
||||
@@ -2953,6 +3086,7 @@ func main() {
|
||||
CustomHosts: customHosts,
|
||||
BrandService: brandService,
|
||||
PortalHandoffs: portalHandoffService,
|
||||
Partners: partnerService,
|
||||
WebsiteTrackingService: websiteTrackingService,
|
||||
UserRepo: userRepoForHandler,
|
||||
OrgRepo: organizationRepoForHandler,
|
||||
|
||||
+10
-2
@@ -60,8 +60,16 @@ func TestEverySpecPathMatchesItsArguments(t *testing.T) {
|
||||
t.Errorf("%s %s path %q must be /v1-relative", r.Name, e.Name, e.Path)
|
||||
}
|
||||
placeholders := strings.Count(e.Path, "{")
|
||||
if placeholders != len(e.Args) {
|
||||
t.Errorf("%s %s has %d placeholders and %d arguments", r.Name, e.Name, placeholders, len(e.Args))
|
||||
pathArgs := 0
|
||||
for _, a := range e.Args {
|
||||
if a.Field == "" {
|
||||
pathArgs++
|
||||
} else if a.Toggle && e.Method == http.MethodGet {
|
||||
t.Errorf("%s %s toggles a query parameter", r.Name, e.Name)
|
||||
}
|
||||
}
|
||||
if placeholders != pathArgs {
|
||||
t.Errorf("%s %s has %d placeholders and %d path arguments", r.Name, e.Name, placeholders, pathArgs)
|
||||
}
|
||||
args := make([]string, len(e.Args))
|
||||
for i := range e.Args {
|
||||
|
||||
+8
-2
@@ -116,13 +116,19 @@ func (f *Factory) Printer() *output.Printer {
|
||||
// wire. Without a terminal it refuses rather than sending, because a script
|
||||
// that forgot --yes must not discover the omission by mailing strangers.
|
||||
func (f *Factory) ConfirmSend(what string) error {
|
||||
return f.ConfirmConsequence(what, "sends real mail")
|
||||
}
|
||||
|
||||
// ConfirmConsequence is ConfirmSend for any consequence worth a yes: spending
|
||||
// money, revealing a secret. It refuses without a terminal for the same reason.
|
||||
func (f *Factory) ConfirmConsequence(what, consequence string) error {
|
||||
if f.AssumeYes {
|
||||
return nil
|
||||
}
|
||||
if !f.IO.IsStdinTTY() {
|
||||
return fmt.Errorf("%s sends real mail, and there is no terminal to confirm on.\nPass --yes to go ahead.", what)
|
||||
return fmt.Errorf("%s %s, and there is no terminal to confirm on.\nPass --yes to go ahead.", what, consequence)
|
||||
}
|
||||
ok, err := f.IO.Confirm(f.IO.Yellow("! ")+what+" sends real mail. Continue?", false)
|
||||
ok, err := f.IO.Confirm(f.IO.Yellow("! ")+what+" "+consequence+". Continue?", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -40,6 +40,10 @@ const (
|
||||
type argSpec struct {
|
||||
Name string
|
||||
Help string
|
||||
// Field sends the argument as this body field (a query parameter on a GET) instead of a path segment.
|
||||
Field string
|
||||
// Toggle reads the argument as on or off and sends a boolean.
|
||||
Toggle bool
|
||||
}
|
||||
|
||||
// flagSpec is one flag. Query flags become query parameters; the rest become
|
||||
@@ -78,6 +82,9 @@ type endpoint struct {
|
||||
|
||||
// Sends marks a command that puts real mail on the wire. Those confirm.
|
||||
Sends bool
|
||||
// Confirm names what the command does that needs a yes, such as
|
||||
// "charges the workspace balance". It confirms the way Sends does.
|
||||
Confirm string
|
||||
// Paginate offers --all, which walks the cursor.
|
||||
Paginate bool
|
||||
// Idempotent offers --idempotency-key.
|
||||
@@ -97,6 +104,8 @@ type resource struct {
|
||||
Endpoints []endpoint
|
||||
// Children are nested resources, such as `agency clients`.
|
||||
Children []resource
|
||||
// Commands adds hand-written subcommands the table cannot express.
|
||||
Commands func(*Factory) []*cobra.Command
|
||||
}
|
||||
|
||||
func resourceCommands(f *Factory) []*cobra.Command {
|
||||
@@ -124,6 +133,9 @@ func buildResource(f *Factory, r resource, parent string) *cobra.Command {
|
||||
for _, child := range r.Children {
|
||||
cmd.AddCommand(buildResource(f, child, name))
|
||||
}
|
||||
if r.Commands != nil {
|
||||
cmd.AddCommand(r.Commands(f)...)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -147,6 +159,9 @@ func buildEndpoint(f *Factory, resourceName string, e endpoint) *cobra.Command {
|
||||
if e.Sends {
|
||||
long += "\n\nThis command sends real mail. It asks before doing so; --yes skips the question."
|
||||
}
|
||||
if e.Confirm != "" {
|
||||
long += "\n\nThis command " + e.Confirm + ". It asks before doing so; --yes skips the question."
|
||||
}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: use,
|
||||
@@ -232,6 +247,26 @@ func buildEndpoint(f *Factory, resourceName string, e endpoint) *cobra.Command {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i, a := range e.Args {
|
||||
if a.Field == "" {
|
||||
continue
|
||||
}
|
||||
var value any = strings.TrimSpace(args[i])
|
||||
if a.Toggle {
|
||||
on, terr := parseToggle(args[i])
|
||||
if terr != nil {
|
||||
return fmt.Errorf("<%s>: %w", a.Name, terr)
|
||||
}
|
||||
value = on
|
||||
}
|
||||
if e.Method == http.MethodGet {
|
||||
query.Set(a.Field, queryString(value))
|
||||
continue
|
||||
}
|
||||
if err := assign(body, a.Field, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
raw, err := bodyFromArg(f.IO.In, input)
|
||||
if err != nil {
|
||||
@@ -270,6 +305,10 @@ func buildEndpoint(f *Factory, resourceName string, e endpoint) *cobra.Command {
|
||||
if err := f.ConfirmSend(fmt.Sprintf("`warmbly %s %s`", resourceName, e.Name)); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if e.Confirm != "" {
|
||||
if err := f.ConfirmConsequence(fmt.Sprintf("`warmbly %s %s`", resourceName, e.Name), e.Confirm); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if e.Method == http.MethodDelete {
|
||||
if err := f.ConfirmMutation(fmt.Sprintf("Run `warmbly %s %s`", resourceName, e.Name)); err != nil {
|
||||
return err
|
||||
@@ -314,8 +353,12 @@ func buildEndpoint(f *Factory, resourceName string, e endpoint) *cobra.Command {
|
||||
}
|
||||
|
||||
// fillPath substitutes positional arguments into the {} markers, in order.
|
||||
// Arguments sent as a field fill no marker.
|
||||
func fillPath(path string, specs []argSpec, args []string) (string, error) {
|
||||
for i, spec := range specs {
|
||||
if spec.Field != "" {
|
||||
continue
|
||||
}
|
||||
marker := "{" + spec.Name + "}"
|
||||
if !strings.Contains(path, marker) {
|
||||
return "", fmt.Errorf("internal: path %q has no %s", path, marker)
|
||||
@@ -332,6 +375,17 @@ func fillPath(path string, specs []argSpec, args []string) (string, error) {
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// parseToggle reads on/off, the words a person types for a switch.
|
||||
func parseToggle(raw string) (bool, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "on", "true", "yes", "enable", "enabled":
|
||||
return true, nil
|
||||
case "off", "false", "no", "disable", "disabled":
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("say on or off, not %q", raw)
|
||||
}
|
||||
|
||||
func queryString(v any) string {
|
||||
switch t := v.(type) {
|
||||
case string:
|
||||
|
||||
+291
-1
@@ -32,7 +32,7 @@ func withPaging(extra ...flagSpec) []flagSpec {
|
||||
|
||||
func resourceSpecs() []resource {
|
||||
out := []resource{}
|
||||
out = append(out, campaignSpec(), contactSpec(), suppressionSpec(), mailboxSpec(), inboxSpec())
|
||||
out = append(out, campaignSpec(), contactSpec(), suppressionSpec(), mailboxSpec(), inboxSpec(), storeSpec())
|
||||
out = append(out, segmentSpec(), templateSpec(), automationSpec(), formSpec())
|
||||
out = append(out, dealSpec(), pipelineSpec(), taskSpec())
|
||||
out = append(out, analyticsSpec(), placementSpec(), auditSpec(), advisorSpec())
|
||||
@@ -2551,3 +2551,293 @@ An agency key needs AGENCY_MIGRATE.`,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func storeSpec() resource {
|
||||
idArg := func(what string) []argSpec { return []argSpec{{Name: "id", Help: "The " + what + "'s id"}} }
|
||||
orderColumns := []output.Column{
|
||||
col("ID", "id"), col("STATUS", "status"), colf("DUE", "due_now_micros", "micros"),
|
||||
colf("CHARGED", "charged_micros", "micros"), colf("REFUNDED", "refunded_micros", "micros"),
|
||||
colf("CREATED", "created_at", "time"), colf("COMPLETED", "completed_at", "time"),
|
||||
}
|
||||
domainColumns := []output.Column{
|
||||
col("ID", "id"), colt("DOMAIN", "name", 34), col("SOURCE", "source"), col("STATUS", "status"),
|
||||
colf("EXPIRES", "expires_at", "date"), colf("AUTO-RENEW", "auto_renew", "bool"),
|
||||
colf("RENEWS AT", "renew_micros", "micros"), col("MAILBOXES", "mailbox_count"),
|
||||
}
|
||||
dnsColumns := []output.Column{
|
||||
col("ID", "id"), col("TYPE", "type"), colt("NAME", "name", 30), colt("CONTENT", "content", 44),
|
||||
col("TTL", "ttl"), col("PRIORITY", "priority"), colf("MANAGED", "managed", "bool"), col("PURPOSE", "purpose"),
|
||||
}
|
||||
mailboxColumns := []output.Column{
|
||||
col("ID", "id"), colt("MAILBOX", "email", 34), col("PROVIDER", "provider"), col("STATUS", "status"),
|
||||
col("CONNECTED", "connect_state"), colf("MONTHLY", "monthly_micros", "micros"),
|
||||
colf("PAID THROUGH", "paid_through", "date"), colf("CANCELS", "cancels_at", "date"),
|
||||
}
|
||||
return resource{
|
||||
Name: "store",
|
||||
Aliases: []string{"shop"},
|
||||
Short: "Buy domains and mailboxes, and manage what you bought",
|
||||
Group: groupWork,
|
||||
Long: `Buy sending domains and mailboxes for this workspace, and look after them:
|
||||
orders, renewals, DNS records, forwarding and mailbox sign-ins.
|
||||
|
||||
Reading needs a key with READ_STORE; changing anything needs MANAGE_STORE.
|
||||
Buying, renewing, auto-renew, cancelling or resuming a mailbox, a transfer
|
||||
code and the registrant also need the member behind the key to hold
|
||||
manage_billing. Buying spends the workspace balance, so ` + "`store buy`" + ` and every
|
||||
other command that charges ask first; --yes skips the question.`,
|
||||
Commands: storeCommands,
|
||||
Endpoints: []endpoint{
|
||||
{
|
||||
Name: "status", Short: "Whether the store is open here, prices, limits and the balance",
|
||||
Method: http.MethodGet, Path: "/store/status",
|
||||
Table: output.Table{Columns: []output.Column{
|
||||
colf("ENABLED", "enabled", "bool"), colf("PLAN", "plan_active", "bool"),
|
||||
colf("BALANCE", "balance.balance_micros", "micros"), colf("MAILBOX / MONTH", "mailbox_monthly_micros", "micros"),
|
||||
col("PROVIDERS", "providers"), col("PER DOMAIN", "limits.mailboxes_per_domain_recommended"),
|
||||
}},
|
||||
},
|
||||
{
|
||||
Name: "search", Short: "Search for domains to register, with prices",
|
||||
Method: http.MethodGet, Path: "/store/domains/search",
|
||||
Args: []argSpec{{Name: "query", Help: "A name or keyword, such as getacme", Field: "q"}},
|
||||
Example: " $ warmbly store search getacme\n $ warmbly store search getacme --tlds com,io",
|
||||
Flag: []flagSpec{{Name: "tlds", Help: "Only these endings, comma separated (com,io)", Kind: flagStrings, Query: true}},
|
||||
Table: output.Table{Root: "data", Columns: []output.Column{
|
||||
col("DOMAIN", "domain"), colf("AVAILABLE", "available", "bool"), col("YEARS", "years"),
|
||||
colf("PRICE", "price_micros", "micros"), colf("RENEWS / YEAR", "renew_micros", "micros"), col("WHY NOT", "reason"),
|
||||
}, Empty: "Nothing matched. Try another name."},
|
||||
},
|
||||
{
|
||||
Name: "orders", Short: "List orders, newest first",
|
||||
Method: http.MethodGet, Path: "/store/orders", Paginate: true, Flag: withPaging(),
|
||||
Table: output.Table{Root: "data", Columns: orderColumns, Empty: "No orders yet. `warmbly store buy --help` shows how to place one."},
|
||||
},
|
||||
},
|
||||
Children: []resource{
|
||||
{
|
||||
Name: "order",
|
||||
Short: "One order and its progress",
|
||||
Commands: storeOrderCommands,
|
||||
Endpoints: []endpoint{
|
||||
{
|
||||
Name: "view", Aliases: []string{"get", "show"}, Short: "Show one order, its steps, domains and mailboxes",
|
||||
Method: http.MethodGet, Path: "/store/orders/{id}", Args: idArg("order"),
|
||||
Table: output.Table{Columns: orderColumns},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "domains",
|
||||
Aliases: []string{"domain"},
|
||||
Short: "Domains bought here or connected from another registrar",
|
||||
Endpoints: []endpoint{
|
||||
{
|
||||
Name: "list", Aliases: []string{"ls"}, Short: "List the workspace's domains",
|
||||
Method: http.MethodGet, Path: "/store/domains", Paginate: true, Flag: withPaging(),
|
||||
Table: output.Table{Root: "data", Columns: domainColumns, Empty: "No domains yet."},
|
||||
},
|
||||
{
|
||||
Name: "view", Aliases: []string{"get", "show"}, Short: "Show one domain, its mail records and DNS",
|
||||
Method: http.MethodGet, Path: "/store/domains/{id}", Args: idArg("domain"),
|
||||
Table: output.Table{Columns: domainColumns},
|
||||
},
|
||||
{
|
||||
Name: "renew", Short: "Renew a purchased domain for another year now",
|
||||
Method: http.MethodPost, Path: "/store/domains/{id}/renew", Args: idArg("domain"), Idempotent: true,
|
||||
Confirm: "charges the workspace balance for a year of the domain",
|
||||
Table: output.Table{Columns: domainColumns},
|
||||
},
|
||||
{
|
||||
Name: "auto-renew", Short: "Turn a purchased domain's automatic renewal on or off",
|
||||
Method: http.MethodPatch, Path: "/store/domains/{id}", Idempotent: true,
|
||||
Args: []argSpec{
|
||||
{Name: "id", Help: "The domain's id"},
|
||||
{Name: "state", Help: "on or off", Field: "auto_renew", Toggle: true},
|
||||
},
|
||||
Example: " $ warmbly store domains auto-renew DOMAIN_ID on",
|
||||
Success: "Auto-renew updated.",
|
||||
},
|
||||
{
|
||||
Name: "forwarding", Short: "Send the domain's website visitors to a URL",
|
||||
Long: `Forward visitors of the domain's website to an https URL.
|
||||
An empty URL ("") turns forwarding off.`,
|
||||
Method: http.MethodPatch, Path: "/store/domains/{id}", Idempotent: true,
|
||||
Args: []argSpec{
|
||||
{Name: "id", Help: "The domain's id"},
|
||||
{Name: "url", Help: "An https URL, or \"\" to stop forwarding", Field: "forwarding_url"},
|
||||
},
|
||||
Example: " $ warmbly store domains forwarding DOMAIN_ID https://acme.com",
|
||||
Success: "Forwarding updated.",
|
||||
},
|
||||
{
|
||||
Name: "transfer-out", Short: "Get the transfer code to move a purchased domain to another registrar",
|
||||
Method: http.MethodPost, Path: "/store/domains/{id}/transfer-out", Args: idArg("domain"), Idempotent: true,
|
||||
Confirm: "unlocks the domain for transfer and prints its transfer code",
|
||||
Table: output.Table{Columns: []output.Column{col("TRANSFER CODE", "auth_code")}},
|
||||
},
|
||||
{
|
||||
Name: "connect", Short: "Connect a domain registered elsewhere",
|
||||
Long: `Connect a domain the workspace already owns at another registrar, so
|
||||
mailboxes can be bought on it. --method nameservers moves its DNS here;
|
||||
--method manual lists records to add at its current DNS provider.`,
|
||||
Method: http.MethodPost, Path: "/store/domains/connect", Idempotent: true,
|
||||
Args: []argSpec{{Name: "domain", Help: "The domain name, such as acme.com", Field: "domain"}},
|
||||
Flag: []flagSpec{{Name: "method", Help: "nameservers or manual"}},
|
||||
Example: " $ warmbly store domains connect acme.com --method nameservers",
|
||||
Table: output.Table{Columns: domainColumns},
|
||||
},
|
||||
{
|
||||
Name: "check-connection", Short: "Check a connected domain's nameservers or records now",
|
||||
Method: http.MethodPost, Path: "/store/domains/{id}/connection/check", Args: idArg("domain"), Idempotent: true,
|
||||
Table: output.Table{Columns: domainColumns},
|
||||
},
|
||||
{
|
||||
Name: "regenerate-connection", Short: "Start a lapsed domain connection again",
|
||||
Method: http.MethodPost, Path: "/store/domains/{id}/connection/regenerate", Args: idArg("domain"), Idempotent: true,
|
||||
Table: output.Table{Columns: domainColumns},
|
||||
},
|
||||
{
|
||||
Name: "remove", Aliases: []string{"rm"}, Short: "Remove a connected domain from the workspace",
|
||||
Method: http.MethodDelete, Path: "/store/domains/{id}", Args: idArg("domain"), Idempotent: true,
|
||||
Success: "Domain removed.",
|
||||
},
|
||||
},
|
||||
Children: []resource{
|
||||
{
|
||||
Name: "dns",
|
||||
Short: "DNS records on a store domain",
|
||||
Endpoints: []endpoint{
|
||||
{
|
||||
Name: "list", Aliases: []string{"ls"}, Short: "List the domain's DNS records",
|
||||
Long: "List the domain's DNS records. With --json this prints the whole domain, its records under dns.",
|
||||
Method: http.MethodGet, Path: "/store/domains/{id}", Args: idArg("domain"),
|
||||
Table: output.Table{Root: "dns", Columns: dnsColumns, Empty: "No DNS records on this domain."},
|
||||
},
|
||||
{
|
||||
Name: "add", Short: "Add a DNS record",
|
||||
Method: http.MethodPost, Path: "/store/domains/{id}/dns", Args: idArg("domain"), Body: bodyRequired, Idempotent: true,
|
||||
Example: " $ warmbly store domains dns add DOMAIN_ID --type TXT --name @ --content \"v=spf1 -all\"\n $ warmbly store domains dns add DOMAIN_ID --type MX --name @ --content mx.acme.com --priority 10",
|
||||
Flag: []flagSpec{
|
||||
{Name: "type", Help: "Record type: A, AAAA, CNAME, MX, TXT, ..."},
|
||||
{Name: "name", Help: "Host name, @ for the domain itself"},
|
||||
{Name: "content", Help: "The record's value"},
|
||||
{Name: "ttl", Help: "Time to live in seconds", Kind: flagInt},
|
||||
{Name: "priority", Help: "Priority, for MX and SRV", Kind: flagInt},
|
||||
},
|
||||
Table: output.Table{Columns: dnsColumns},
|
||||
},
|
||||
{
|
||||
Name: "edit", Aliases: []string{"update"}, Short: "Change a DNS record",
|
||||
Method: http.MethodPatch, Path: "/store/domains/{id}/dns/{record}", Body: bodyRequired, Idempotent: true,
|
||||
Args: []argSpec{{Name: "id", Help: "The domain's id"}, {Name: "record", Help: "The record's id"}},
|
||||
Flag: []flagSpec{
|
||||
{Name: "name", Help: "Host name, @ for the domain itself"},
|
||||
{Name: "content", Help: "The record's value"},
|
||||
{Name: "ttl", Help: "Time to live in seconds", Kind: flagInt},
|
||||
{Name: "priority", Help: "Priority, for MX and SRV", Kind: flagInt},
|
||||
},
|
||||
Table: output.Table{Columns: dnsColumns},
|
||||
},
|
||||
{
|
||||
Name: "delete", Aliases: []string{"rm"}, Short: "Delete a DNS record",
|
||||
Method: http.MethodDelete, Path: "/store/domains/{id}/dns/{record}", Idempotent: true,
|
||||
Args: []argSpec{{Name: "id", Help: "The domain's id"}, {Name: "record", Help: "The record's id"}},
|
||||
Success: "DNS record deleted.",
|
||||
},
|
||||
{
|
||||
Name: "check", Short: "Look the domain's records up in public DNS",
|
||||
Method: http.MethodPost, Path: "/store/domains/{id}/dns/check", Args: idArg("domain"),
|
||||
Table: output.Table{Root: "records", Columns: []output.Column{
|
||||
col("TYPE", "type"), colt("NAME", "name", 30), colt("CONTENT", "content", 44), col("STATUS", "status"),
|
||||
}, Empty: "No records to check."},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "mailboxes",
|
||||
Aliases: []string{"mailbox"},
|
||||
Short: "Mailboxes bought here, billed monthly",
|
||||
Endpoints: []endpoint{
|
||||
{
|
||||
Name: "list", Aliases: []string{"ls"}, Short: "List purchased mailboxes",
|
||||
Method: http.MethodGet, Path: "/store/mailboxes", Paginate: true, Flag: withPaging(),
|
||||
Table: output.Table{Root: "data", Columns: mailboxColumns, Empty: "No purchased mailboxes yet."},
|
||||
},
|
||||
{
|
||||
Name: "rename", Short: "Change the name a purchased mailbox sends as",
|
||||
Method: http.MethodPatch, Path: "/store/mailboxes/{id}", Args: idArg("mailbox"), Body: bodyRequired, Idempotent: true,
|
||||
Example: " $ warmbly store mailboxes rename MAILBOX_ID --first Ada --last Lovelace",
|
||||
Flag: []flagSpec{
|
||||
{Name: "first", Help: "First name", Key: "first_name"},
|
||||
{Name: "last", Help: "Last name", Key: "last_name"},
|
||||
},
|
||||
Table: output.Table{Columns: mailboxColumns},
|
||||
},
|
||||
{
|
||||
Name: "cancel", Short: "Cancel a mailbox at the end of the month it is paid for",
|
||||
Method: http.MethodDelete, Path: "/store/mailboxes/{id}", Args: idArg("mailbox"), Idempotent: true,
|
||||
Confirm: "cancels the mailbox, which stops working when its paid month ends",
|
||||
Table: output.Table{Columns: mailboxColumns},
|
||||
},
|
||||
{
|
||||
Name: "resume", Short: "Keep a cancelled mailbox, billing it monthly again",
|
||||
Method: http.MethodPost, Path: "/store/mailboxes/{id}/resume", Args: idArg("mailbox"), Idempotent: true,
|
||||
Confirm: "bills the mailbox every month again",
|
||||
Table: output.Table{Columns: mailboxColumns},
|
||||
},
|
||||
{
|
||||
Name: "sign-in", Short: "Show a purchased mailbox's username and password",
|
||||
Method: http.MethodPost, Path: "/store/mailboxes/{id}/sign-in", Args: idArg("mailbox"),
|
||||
Confirm: "prints the mailbox's password",
|
||||
Table: output.Table{Columns: []output.Column{
|
||||
col("EMAIL", "email"), col("USERNAME", "username"), col("PASSWORD", "password"), col("SIGN IN AT", "login_url"),
|
||||
}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "registrant",
|
||||
Short: "The domain owner's contact details, which registering a domain needs",
|
||||
Endpoints: []endpoint{
|
||||
{
|
||||
Name: "view", Aliases: []string{"get", "show"}, Short: "Show the saved registrant",
|
||||
Method: http.MethodGet, Path: "/store/status",
|
||||
Table: output.Table{Root: "registrant", Columns: registrantColumns(), Empty: "No registrant saved. Set one with `warmbly store registrant set`."},
|
||||
},
|
||||
{
|
||||
Name: "set", Short: "Save the registrant for domains bought from now on",
|
||||
Long: `Save the domain owner's contact details. The whole record is replaced, so
|
||||
pass every field (or a JSON body with --input). --phone is +<country code>.<number>,
|
||||
such as +44.2071234567, and --country is a two-letter code.`,
|
||||
Method: http.MethodPut, Path: "/store/registrant", Body: bodyRequired, Idempotent: true,
|
||||
Example: " $ warmbly store registrant set --first-name Ada --last-name Lovelace --email ada@acme.com \\\n --phone +44.2071234567 --address1 \"1 Main St\" --city London --postal-code N1 --country GB",
|
||||
Flag: []flagSpec{
|
||||
{Name: "first-name", Help: "First name"},
|
||||
{Name: "last-name", Help: "Last name"},
|
||||
{Name: "organization", Help: "Company, if the domain belongs to one"},
|
||||
{Name: "email", Help: "Email address"},
|
||||
{Name: "phone", Help: "Phone as +<country code>.<number>"},
|
||||
{Name: "address1", Help: "Street address"},
|
||||
{Name: "address2", Help: "Second address line"},
|
||||
{Name: "city", Help: "City"},
|
||||
{Name: "state", Help: "State or region"},
|
||||
{Name: "postal-code", Help: "Postal code"},
|
||||
{Name: "country", Help: "Two-letter country code, such as GB"},
|
||||
},
|
||||
Table: output.Table{Columns: registrantColumns()},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func registrantColumns() []output.Column {
|
||||
return []output.Column{
|
||||
col("FIRST", "first_name"), col("LAST", "last_name"), col("ORGANIZATION", "organization"),
|
||||
col("EMAIL", "email"), col("PHONE", "phone"), col("CITY", "city"), col("COUNTRY", "country"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/cli/api"
|
||||
"github.com/warmbly/warmbly/internal/cli/iostreams"
|
||||
"github.com/warmbly/warmbly/internal/cli/output"
|
||||
)
|
||||
|
||||
// The store commands the spec table cannot express: building a cart from
|
||||
// flags, the buy flow that confirms a price and charges, and watching an
|
||||
// order's steps until it settles.
|
||||
|
||||
// minWatchInterval keeps `order watch` from polling the API in a tight loop.
|
||||
var minWatchInterval = time.Second
|
||||
|
||||
func storeCommands(f *Factory) []*cobra.Command {
|
||||
return []*cobra.Command{newStoreQuoteCmd(f), newStoreBuyCmd(f)}
|
||||
}
|
||||
|
||||
func storeOrderCommands(f *Factory) []*cobra.Command {
|
||||
return []*cobra.Command{newStoreOrderWatchCmd(f)}
|
||||
}
|
||||
|
||||
// storeCart is the flags that name what to buy.
|
||||
type storeCart struct {
|
||||
domains []string
|
||||
years int
|
||||
mailboxes []string
|
||||
providers []string
|
||||
first string
|
||||
last string
|
||||
admins []string
|
||||
input string
|
||||
}
|
||||
|
||||
const storeCartHelp = `Name what to buy with flags, or pass the whole body with --input:
|
||||
|
||||
--domain NAME[:YEARS] register a new domain (repeatable)
|
||||
--mailbox ADDRESS[:FIRST:LAST] create a mailbox, such as ada@getacme.com (repeatable)
|
||||
--provider google|microsoft who hosts the mailboxes; DOMAIN=PROVIDER sets one domain
|
||||
--first-name, --last-name the name on mailboxes that do not carry their own
|
||||
--admin ADDRESS the mailbox that administers its domain (one per domain)
|
||||
|
||||
Mailboxes can go on a domain registered in the same order, or on one the
|
||||
workspace already has. --input takes {"items": [...]} as JSON, @file or - for
|
||||
stdin, in the shape POST /v1/store/quotes documents.`
|
||||
|
||||
func (c *storeCart) bind(cmd *cobra.Command) {
|
||||
fl := cmd.Flags()
|
||||
fl.StringArrayVar(&c.domains, "domain", nil, "Register this domain, NAME[:YEARS] (repeatable)")
|
||||
fl.IntVar(&c.years, "years", 0, "Years for every --domain without its own (default: the shortest term)")
|
||||
fl.StringArrayVar(&c.mailboxes, "mailbox", nil, "Create this mailbox, ADDRESS[:FIRST:LAST] (repeatable)")
|
||||
fl.StringArrayVar(&c.providers, "provider", nil, "google or microsoft; DOMAIN=PROVIDER for one domain (repeatable)")
|
||||
fl.StringVar(&c.first, "first-name", "", "First name on mailboxes without their own")
|
||||
fl.StringVar(&c.last, "last-name", "", "Last name on mailboxes without their own")
|
||||
fl.StringArrayVar(&c.admins, "admin", nil, "The mailbox that administers its domain (repeatable, one per domain)")
|
||||
fl.StringVar(&c.input, "input", "", "Request body instead of the flags: JSON, @file, or - for stdin")
|
||||
}
|
||||
|
||||
type storeNewMailbox struct {
|
||||
LocalPart string `json:"local_part"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Admin bool `json:"admin,omitempty"`
|
||||
}
|
||||
|
||||
type storeQuoteItem struct {
|
||||
Type string `json:"type"`
|
||||
Domain string `json:"domain"`
|
||||
Years int `json:"years,omitempty"`
|
||||
Provider string `json:"provider,omitempty"`
|
||||
Mailboxes []storeNewMailbox `json:"mailboxes,omitempty"`
|
||||
}
|
||||
|
||||
// body is the POST /store/quotes payload: --input as given, or the items the flags name.
|
||||
func (c *storeCart) body(stdin io.Reader) ([]byte, error) {
|
||||
flagsUsed := len(c.domains)+len(c.mailboxes)+len(c.providers)+len(c.admins) > 0 || c.years != 0 || c.first != "" || c.last != ""
|
||||
raw, err := bodyFromArg(stdin, c.input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if raw != nil {
|
||||
if flagsUsed {
|
||||
return nil, fmt.Errorf("pass --input or the cart flags, not both")
|
||||
}
|
||||
if !json.Valid(raw) {
|
||||
return nil, fmt.Errorf("the request body is not valid JSON")
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
items, err := c.items()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(map[string]any{"items": items})
|
||||
}
|
||||
|
||||
func (c *storeCart) items() ([]storeQuoteItem, error) {
|
||||
if len(c.domains) == 0 && len(c.mailboxes) == 0 {
|
||||
return nil, fmt.Errorf("name something to buy: --domain, --mailbox, or a body with --input.\n\n%s", storeCartHelp)
|
||||
}
|
||||
|
||||
defaultProvider := ""
|
||||
providerFor := map[string]string{}
|
||||
for _, p := range c.providers {
|
||||
domain, provider, scoped := strings.Cut(p, "=")
|
||||
if !scoped {
|
||||
provider, domain = domain, ""
|
||||
}
|
||||
provider = strings.ToLower(strings.TrimSpace(provider))
|
||||
if provider != "google" && provider != "microsoft" {
|
||||
return nil, fmt.Errorf("--provider %q: the provider is google or microsoft", p)
|
||||
}
|
||||
if domain == "" {
|
||||
defaultProvider = provider
|
||||
} else {
|
||||
providerFor[cleanDomain(domain)] = provider
|
||||
}
|
||||
}
|
||||
|
||||
admins := map[string]bool{}
|
||||
for _, a := range c.admins {
|
||||
admins[strings.ToLower(strings.TrimSpace(a))] = true
|
||||
}
|
||||
|
||||
// Items keep the order domains were named in, each domain's mailboxes right after it.
|
||||
var order []string
|
||||
seen := map[string]bool{}
|
||||
note := func(domain string) {
|
||||
if !seen[domain] {
|
||||
seen[domain] = true
|
||||
order = append(order, domain)
|
||||
}
|
||||
}
|
||||
register := map[string]int{}
|
||||
for _, d := range c.domains {
|
||||
name, yearsRaw, hasYears := strings.Cut(d, ":")
|
||||
name = cleanDomain(name)
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("--domain %q has no domain name", d)
|
||||
}
|
||||
years := c.years
|
||||
if hasYears {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(yearsRaw))
|
||||
if err != nil || n < 1 {
|
||||
return nil, fmt.Errorf("--domain %q: the years after the colon must be a whole number, 1 or more", d)
|
||||
}
|
||||
years = n
|
||||
}
|
||||
if _, dup := register[name]; dup {
|
||||
return nil, fmt.Errorf("--domain %s is named twice", name)
|
||||
}
|
||||
register[name] = years
|
||||
note(name)
|
||||
}
|
||||
|
||||
mailboxes := map[string][]storeNewMailbox{}
|
||||
addresses := map[string]bool{}
|
||||
for _, m := range c.mailboxes {
|
||||
parts := strings.Split(m, ":")
|
||||
address := strings.ToLower(strings.TrimSpace(parts[0]))
|
||||
local, domain, ok := strings.Cut(address, "@")
|
||||
domain = cleanDomain(domain)
|
||||
if !ok || local == "" || domain == "" {
|
||||
return nil, fmt.Errorf("--mailbox %q: start with the full address, such as ada@getacme.com", m)
|
||||
}
|
||||
first, last := c.first, c.last
|
||||
switch len(parts) {
|
||||
case 1:
|
||||
case 3:
|
||||
first, last = parts[1], parts[2]
|
||||
default:
|
||||
return nil, fmt.Errorf("--mailbox %q: use ADDRESS or ADDRESS:FIRST:LAST", m)
|
||||
}
|
||||
first, last = strings.TrimSpace(first), strings.TrimSpace(last)
|
||||
if first == "" || last == "" {
|
||||
return nil, fmt.Errorf("--mailbox %s needs a name: add :FIRST:LAST, or pass --first-name and --last-name", address)
|
||||
}
|
||||
if addresses[local+"@"+domain] {
|
||||
return nil, fmt.Errorf("--mailbox %s is named twice", address)
|
||||
}
|
||||
addresses[local+"@"+domain] = true
|
||||
mailboxes[domain] = append(mailboxes[domain], storeNewMailbox{LocalPart: local, FirstName: first, LastName: last, Admin: admins[local+"@"+domain]})
|
||||
note(domain)
|
||||
}
|
||||
for a := range admins {
|
||||
if !addresses[a] {
|
||||
return nil, fmt.Errorf("--admin %s is not one of the --mailbox addresses", a)
|
||||
}
|
||||
}
|
||||
|
||||
var items []storeQuoteItem
|
||||
for _, domain := range order {
|
||||
if years, ok := register[domain]; ok {
|
||||
items = append(items, storeQuoteItem{Type: "domain", Domain: domain, Years: years})
|
||||
}
|
||||
if len(mailboxes[domain]) == 0 {
|
||||
continue
|
||||
}
|
||||
provider := providerFor[domain]
|
||||
if provider == "" {
|
||||
provider = defaultProvider
|
||||
}
|
||||
if provider == "" {
|
||||
return nil, fmt.Errorf("the mailboxes on %s need a provider: pass --provider google or --provider microsoft", domain)
|
||||
}
|
||||
items = append(items, storeQuoteItem{Type: "mailboxes", Domain: domain, Provider: provider, Mailboxes: mailboxes[domain]})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func cleanDomain(s string) string {
|
||||
return strings.TrimSuffix(strings.ToLower(strings.TrimSpace(s)), ".")
|
||||
}
|
||||
|
||||
// The parts of a quote the CLI prints and acts on.
|
||||
type storeQuote struct {
|
||||
ID string `json:"id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
Lines []storeQuoteRow `json:"lines"`
|
||||
DueNowMicros int64 `json:"due_now_micros"`
|
||||
RecurringMonthlyMicros int64 `json:"recurring_monthly_micros"`
|
||||
YearlyDomainRenewalMicros int64 `json:"yearly_domain_renewal_micros"`
|
||||
Payment struct {
|
||||
BalanceMicros int64 `json:"balance_micros"`
|
||||
FromBalanceMicros int64 `json:"from_balance_micros"`
|
||||
CardChargeMicros int64 `json:"card_charge_micros"`
|
||||
NeedsPaymentMethod bool `json:"needs_payment_method"`
|
||||
Card *struct {
|
||||
Brand string `json:"brand"`
|
||||
Last4 string `json:"last4"`
|
||||
} `json:"card"`
|
||||
} `json:"payment"`
|
||||
}
|
||||
|
||||
type storeQuoteRow struct {
|
||||
Type string `json:"type"`
|
||||
Domain string `json:"domain"`
|
||||
Years int `json:"years"`
|
||||
Provider string `json:"provider"`
|
||||
Count int `json:"count"`
|
||||
AmountMicros int64 `json:"amount_micros"`
|
||||
RenewMicros int64 `json:"renew_micros"`
|
||||
MonthlyMicros int64 `json:"monthly_micros"`
|
||||
AdminEmail *string `json:"admin_email"`
|
||||
NameserversChange bool `json:"nameservers_change"`
|
||||
}
|
||||
|
||||
func plural(n int, one, many string) string {
|
||||
if n == 1 {
|
||||
return "1 " + one
|
||||
}
|
||||
return fmt.Sprintf("%d %s", n, many)
|
||||
}
|
||||
|
||||
// printQuote writes the itemised lines and the totals a buyer agrees to.
|
||||
func printQuote(w io.Writer, s *iostreams.IOStreams, q *storeQuote) {
|
||||
fmt.Fprintf(w, "%s %s\n", s.Bold("Quote"), s.Gray(q.ID+", prices held until "+q.ExpiresAt.Local().Format("15:04")))
|
||||
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
|
||||
for _, l := range q.Lines {
|
||||
switch l.Type {
|
||||
case "domain":
|
||||
then := ""
|
||||
if l.RenewMicros > 0 {
|
||||
then = "then " + output.Dollars(l.RenewMicros) + "/year"
|
||||
}
|
||||
fmt.Fprintf(tw, " %s\tregister for %s\t%s\t%s\n", l.Domain, plural(l.Years, "year", "years"), output.Dollars(l.AmountMicros), then)
|
||||
case "mailboxes":
|
||||
then := ""
|
||||
if l.MonthlyMicros > 0 {
|
||||
then = "then " + output.Dollars(l.MonthlyMicros) + "/month"
|
||||
}
|
||||
fmt.Fprintf(tw, " %s\t%s %s\t%s\t%s\n", l.Domain, plural(l.Count, "mailbox", "mailboxes"), l.Provider, output.Dollars(l.AmountMicros), then)
|
||||
if l.AdminEmail != nil && *l.AdminEmail != "" {
|
||||
fmt.Fprintf(tw, " \t%s\t\t\n", s.Gray("admin: "+*l.AdminEmail))
|
||||
}
|
||||
if l.NameserversChange {
|
||||
fmt.Fprintf(tw, " \t%s\t\t\n", s.Gray("set new nameservers for the domain after the order"))
|
||||
}
|
||||
default:
|
||||
fmt.Fprintf(tw, " %s\t%s\t%s\t\n", l.Domain, l.Type, output.Dollars(l.AmountMicros))
|
||||
}
|
||||
}
|
||||
_ = tw.Flush()
|
||||
|
||||
fmt.Fprintf(w, "%s %s\n", s.Bold("Due now:"), s.Bold(output.Dollars(q.DueNowMicros)))
|
||||
p := q.Payment
|
||||
if q.DueNowMicros > 0 {
|
||||
var from []string
|
||||
if p.FromBalanceMicros > 0 {
|
||||
from = append(from, output.Dollars(p.FromBalanceMicros)+" from the workspace balance")
|
||||
}
|
||||
if p.CardChargeMicros > 0 {
|
||||
card := "the card on file"
|
||||
if p.Card != nil {
|
||||
card = p.Card.Brand + " ending " + p.Card.Last4
|
||||
}
|
||||
from = append(from, output.Dollars(p.CardChargeMicros)+" charged to "+card)
|
||||
}
|
||||
if len(from) > 0 {
|
||||
fmt.Fprintf(w, " %s\n", s.Gray(strings.Join(from, ", ")))
|
||||
}
|
||||
if p.NeedsPaymentMethod {
|
||||
fmt.Fprintf(w, " %s\n", s.Yellow("The balance does not cover this and there is no card on file."))
|
||||
}
|
||||
}
|
||||
if q.RecurringMonthlyMicros > 0 {
|
||||
fmt.Fprintf(w, "Then monthly: %s for mailboxes\n", output.Dollars(q.RecurringMonthlyMicros))
|
||||
}
|
||||
if q.YearlyDomainRenewalMicros > 0 {
|
||||
fmt.Fprintf(w, "Domain renewals: %s a year\n", output.Dollars(q.YearlyDomainRenewalMicros))
|
||||
}
|
||||
}
|
||||
|
||||
func createQuote(ctx context.Context, client *api.Client, body []byte) (*storeQuote, []byte, error) {
|
||||
resp, err := client.Do(ctx, api.Request{Method: http.MethodPost, Path: "/store/quotes", Body: body})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var q storeQuote
|
||||
if err := json.Unmarshal(resp.Body, &q); err != nil || q.ID == "" {
|
||||
return nil, nil, fmt.Errorf("the API answered the quote with something unexpected")
|
||||
}
|
||||
return &q, resp.Body, nil
|
||||
}
|
||||
|
||||
func newStoreQuoteCmd(f *Factory) *cobra.Command {
|
||||
var cart storeCart
|
||||
cmd := &cobra.Command{
|
||||
Use: "quote",
|
||||
Short: "Price a cart of domains and mailboxes without buying it",
|
||||
Long: "Price a cart without buying anything. The quote holds its prices for a few\nminutes; `warmbly store buy` with the same flags quotes again and buys.\n\n" + storeCartHelp,
|
||||
Example: ` $ warmbly store quote --domain getacme.com --mailbox ada@getacme.com --mailbox grace@getacme.com \
|
||||
--provider google --first-name Ada --last-name Lovelace
|
||||
$ warmbly store quote --mailbox ada@acme.com:Ada:Lovelace --provider microsoft
|
||||
$ warmbly store quote --input @cart.json --json`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
body, err := cart.body(f.IO.In)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
q, raw, err := createQuote(c.Context(), client, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printer := f.Printer()
|
||||
if printer.JSON || printer.Template != "" || !f.IO.IsStdoutTTY() {
|
||||
return printer.Print(raw, output.Table{})
|
||||
}
|
||||
printQuote(f.IO.Out, f.IO, q)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cart.bind(cmd)
|
||||
return cmd
|
||||
}
|
||||
|
||||
// storeBuy is one buy: quote, agree, order, and agree again if the price moves.
|
||||
type storeBuy struct {
|
||||
client *api.Client
|
||||
io *iostreams.IOStreams
|
||||
yes bool
|
||||
ask func(question string) (bool, error)
|
||||
forward string
|
||||
idemKey string
|
||||
maxTries int
|
||||
}
|
||||
|
||||
// run places the order and returns the order the API answered with.
|
||||
func (b *storeBuy) run(ctx context.Context, body []byte) ([]byte, error) {
|
||||
q, _, err := createQuote(ctx, b.client, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for attempt := 1; ; attempt++ {
|
||||
printQuote(b.io.ErrOut, b.io, q)
|
||||
if !b.yes {
|
||||
ok, aerr := b.ask(fmt.Sprintf("Buy this and charge %s now?", output.Dollars(q.DueNowMicros)))
|
||||
if aerr != nil {
|
||||
return nil, aerr
|
||||
}
|
||||
if !ok {
|
||||
return nil, errCancelled
|
||||
}
|
||||
}
|
||||
|
||||
order := map[string]any{"quote_id": q.ID, "expected_due_now_micros": q.DueNowMicros}
|
||||
if b.forward != "" {
|
||||
order["forwarding_url"] = b.forward
|
||||
}
|
||||
payload, _ := json.Marshal(order)
|
||||
key := b.idemKey
|
||||
if key != "" && attempt > 1 {
|
||||
// A new total is a different request, which must not replay the first answer.
|
||||
key = fmt.Sprintf("%s-%d", key, attempt)
|
||||
}
|
||||
resp, err := b.client.Do(ctx, api.Request{Method: http.MethodPost, Path: "/store/orders", Body: payload, IdempotencyKey: key})
|
||||
if err == nil {
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
var apiErr *api.Error
|
||||
if !errors.As(err, &apiErr) {
|
||||
return nil, err
|
||||
}
|
||||
switch apiErr.Code {
|
||||
case "price_changed":
|
||||
var env struct {
|
||||
Details struct {
|
||||
Quote *storeQuote `json:"quote"`
|
||||
} `json:"details"`
|
||||
}
|
||||
if json.Unmarshal([]byte(apiErr.Body), &env) != nil || env.Details.Quote == nil || env.Details.Quote.ID == "" {
|
||||
return nil, err
|
||||
}
|
||||
fresh := env.Details.Quote
|
||||
if b.yes {
|
||||
return nil, fmt.Errorf("the price changed after the quote: due now is %s, not %s. Nothing was charged.\nRun the command again to buy at the new price", output.Dollars(fresh.DueNowMicros), output.Dollars(q.DueNowMicros))
|
||||
}
|
||||
if attempt >= b.maxTries {
|
||||
return nil, fmt.Errorf("the price kept changing while you were confirming. Nothing was charged; try again in a minute")
|
||||
}
|
||||
fmt.Fprintf(b.io.ErrOut, "\n%s The price changed from %s to %s. Nothing was charged. Here is the new quote:\n\n",
|
||||
b.io.Yellow("!"), output.Dollars(q.DueNowMicros), output.Dollars(fresh.DueNowMicros))
|
||||
q = fresh
|
||||
case "payment_method_required":
|
||||
var env struct {
|
||||
SetupURL string `json:"setup_url"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(apiErr.Body), &env)
|
||||
where := "in the dashboard's billing settings (`warmbly browse billing`)"
|
||||
if env.SetupURL != "" {
|
||||
where = "at " + env.SetupURL
|
||||
}
|
||||
return nil, fmt.Errorf("the workspace balance does not cover this order and there is no card to charge. Nothing was charged.\nAdd a card %s, then run the command again (request %s)", where, apiErr.RequestID)
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newStoreBuyCmd(f *Factory) *cobra.Command {
|
||||
var (
|
||||
cart storeCart
|
||||
forward string
|
||||
idemKey string
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "buy",
|
||||
Short: "Buy domains and mailboxes, charging the workspace balance",
|
||||
Long: "Quote a cart, show what it costs now and every month after, and buy it once\nyou agree. The workspace balance pays first, then the card on file.\n\n" +
|
||||
"This command spends money. It asks before buying, and refuses with no\nterminal to ask on unless --yes is passed. If the price moves between the\nquote and the order, it shows the new one and asks again; with --yes it\nstops instead, and nothing is charged.\n\n" +
|
||||
"Buying needs MANAGE_STORE, and the member behind the key must hold\nmanage_billing. `warmbly store order watch` follows the order afterwards.\n\n" + storeCartHelp,
|
||||
Example: ` $ warmbly store buy --domain getacme.com --mailbox ada@getacme.com --provider google \
|
||||
--first-name Ada --last-name Lovelace --forwarding-url https://acme.com
|
||||
$ warmbly store buy --input @cart.json --yes --json`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
body, err := cart.body(f.IO.In)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !f.AssumeYes && !f.IO.IsStdinTTY() {
|
||||
return fmt.Errorf("`warmbly store buy` charges the workspace balance, and there is no terminal to confirm on.\nCheck the price with `warmbly store quote`, then pass --yes to buy")
|
||||
}
|
||||
client, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b := &storeBuy{
|
||||
client: client, io: f.IO, yes: f.AssumeYes, forward: strings.TrimSpace(forward), idemKey: idemKey, maxTries: 3,
|
||||
ask: func(q string) (bool, error) { return f.IO.Confirm(f.IO.Yellow("! ")+q, false) },
|
||||
}
|
||||
raw, err := b.run(c.Context(), body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
printer := f.Printer()
|
||||
if printer.JSON || printer.Template != "" || !f.IO.IsStdoutTTY() {
|
||||
return printer.Print(raw, output.Table{})
|
||||
}
|
||||
var o struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &o)
|
||||
f.IO.Printf("%s Ordered (%s). Order %s\n", f.IO.Tick(), o.Status, o.ID)
|
||||
f.IO.Printf("%s\n", f.IO.Gray("Follow it with `warmbly store order watch "+o.ID+"`. Mailbox setup can take a few hours."))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cart.bind(cmd)
|
||||
cmd.Flags().StringVar(&forward, "forwarding-url", "", "Send visitors of newly registered domains to this https URL")
|
||||
cmd.Flags().StringVar(&idemKey, "idempotency-key", "", "Idempotency-Key header for the order")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// storeOrder is what the watch draws.
|
||||
type storeOrder struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Steps []struct {
|
||||
Key string `json:"key"`
|
||||
Status string `json:"status"`
|
||||
At *time.Time `json:"at"`
|
||||
} `json:"steps"`
|
||||
}
|
||||
|
||||
func (o *storeOrder) settled() bool { return o.Status != "processing" && o.Status != "charging" }
|
||||
|
||||
var storeStepLabels = map[string]string{
|
||||
"register": "Register the domains",
|
||||
"dns": "Set up DNS",
|
||||
"mail_auth": "Set up mail authentication",
|
||||
"mailboxes": "Create the mailboxes",
|
||||
"delegation": "Connect the mailboxes to Warmbly",
|
||||
"ready": "Ready",
|
||||
}
|
||||
|
||||
// orderLines renders the step track, each line fitted to width.
|
||||
func orderLines(s *iostreams.IOStreams, o *storeOrder, width int, now time.Time) []string {
|
||||
fit := func(text string, used int) string {
|
||||
limit := width - used - 1
|
||||
if limit < 10 {
|
||||
limit = 10
|
||||
}
|
||||
if r := []rune(text); len(r) > limit {
|
||||
return string(r[:limit-1]) + "…"
|
||||
}
|
||||
return text
|
||||
}
|
||||
lines := []string{fit(fmt.Sprintf("Order %s %s (checked %s)", o.ID, o.Status, now.Local().Format("15:04:05")), 0)}
|
||||
for _, st := range o.Steps {
|
||||
icon := s.Gray("-")
|
||||
switch st.Status {
|
||||
case "done":
|
||||
icon = s.Tick()
|
||||
case "failed":
|
||||
icon = s.Cross()
|
||||
case "running":
|
||||
icon = s.Cyan("*")
|
||||
}
|
||||
label := storeStepLabels[st.Key]
|
||||
if label == "" {
|
||||
label = st.Key
|
||||
}
|
||||
text := label + " " + st.Status
|
||||
if st.At != nil && st.Status != "pending" {
|
||||
text += " " + st.At.Local().Format("15:04")
|
||||
}
|
||||
lines = append(lines, " "+icon+" "+fit(text, 5))
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func newStoreOrderWatchCmd(f *Factory) *cobra.Command {
|
||||
var interval, timeout time.Duration
|
||||
cmd := &cobra.Command{
|
||||
Use: "watch <id>",
|
||||
Short: "Follow an order's steps until it completes or fails",
|
||||
Long: `Check the order every --interval and redraw its steps until it is no longer
|
||||
charging or processing. Creating and connecting mailboxes can take hours, so
|
||||
this stops after --timeout (0 waits as long as it takes). Ctrl-C stops
|
||||
watching at any time; the order carries on without it.
|
||||
|
||||
Exits 0 when the order completes, and 1 when it fails, partly fails, or the
|
||||
watch stops before it settles.
|
||||
|
||||
Arguments:
|
||||
<id> The order's id`,
|
||||
Example: " $ warmbly store order watch ORDER_ID\n $ warmbly store order watch ORDER_ID --interval 30s --timeout 6h",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
id := strings.TrimSpace(args[0])
|
||||
if id == "" {
|
||||
return fmt.Errorf("<id> cannot be empty")
|
||||
}
|
||||
if interval < minWatchInterval {
|
||||
interval = minWatchInterval
|
||||
}
|
||||
client, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return watchOrder(c.Context(), f, client, id, interval, timeout)
|
||||
},
|
||||
}
|
||||
cmd.Flags().DurationVar(&interval, "interval", 5*time.Second, "How often to check the order")
|
||||
cmd.Flags().DurationVar(&timeout, "timeout", time.Hour, "Stop watching after this long; 0 for no limit")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func watchOrder(ctx context.Context, f *Factory, client *api.Client, id string, interval, timeout time.Duration) error {
|
||||
if timeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
}
|
||||
printer := f.Printer()
|
||||
machine := printer.JSON || printer.Template != "" || !f.IO.IsStdoutTTY()
|
||||
path := "/store/orders/" + id
|
||||
|
||||
drawn := 0
|
||||
last := ""
|
||||
var raw []byte
|
||||
var o storeOrder
|
||||
for {
|
||||
resp, err := client.Do(ctx, api.Request{Method: http.MethodGet, Path: path})
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
raw = resp.Body
|
||||
if jerr := json.Unmarshal(raw, &o); jerr != nil {
|
||||
return fmt.Errorf("the API answered the order with something unexpected")
|
||||
}
|
||||
lines := orderLines(f.IO, &o, f.IO.TerminalWidth(), time.Now())
|
||||
if machine {
|
||||
// No redraw off a terminal: one progress line on stderr each time a step moves.
|
||||
if state := strings.Join(lines[1:], "|") + o.Status; state != last {
|
||||
last = state
|
||||
fmt.Fprintln(f.IO.ErrOut, orderProgress(&o))
|
||||
}
|
||||
} else {
|
||||
if drawn > 0 {
|
||||
fmt.Fprintf(f.IO.Out, "\033[%dA", drawn)
|
||||
}
|
||||
for _, l := range lines {
|
||||
fmt.Fprintf(f.IO.Out, "\r\033[K%s\n", l)
|
||||
}
|
||||
drawn = len(lines)
|
||||
}
|
||||
if o.settled() {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(interval):
|
||||
continue
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return fmt.Errorf("order %s is still %s after %s. It carries on; run `warmbly store order watch %s` again later", id, o.Status, timeout, id)
|
||||
}
|
||||
fmt.Fprintf(f.IO.ErrOut, "\nStopped watching. Order %s carries on; `warmbly store order view %s` shows where it is.\n", id, id)
|
||||
return errSilent
|
||||
}
|
||||
|
||||
if machine {
|
||||
if err := printer.Print(raw, output.Table{}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
switch o.Status {
|
||||
case "completed":
|
||||
if !machine {
|
||||
f.IO.Printf("%s Order complete.\n", f.IO.Tick())
|
||||
}
|
||||
return nil
|
||||
case "partially_failed":
|
||||
fmt.Fprintf(f.IO.ErrOut, "%s Part of order %s failed. `warmbly store order view %s` lists what was set up.\n", f.IO.Cross(), id, id)
|
||||
default:
|
||||
fmt.Fprintf(f.IO.ErrOut, "%s Order %s ended %s.\n", f.IO.Cross(), id, o.Status)
|
||||
}
|
||||
return errSilent
|
||||
}
|
||||
|
||||
// orderProgress is the one-line form of the step track, for logs.
|
||||
func orderProgress(o *storeOrder) string {
|
||||
parts := make([]string, 0, len(o.Steps))
|
||||
for _, st := range o.Steps {
|
||||
parts = append(parts, st.Key+"="+st.Status)
|
||||
}
|
||||
return fmt.Sprintf("%s %s %s %s", time.Now().Format("15:04:05"), o.ID, o.Status, strings.Join(parts, " "))
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/cli/api"
|
||||
"github.com/warmbly/warmbly/internal/cli/iostreams"
|
||||
)
|
||||
|
||||
// storeServer records every request and answers each with the handler's reply.
|
||||
type storeServer struct {
|
||||
mu sync.Mutex
|
||||
reqs []capturedRequest
|
||||
keys []string
|
||||
}
|
||||
|
||||
func (s *storeServer) start(t *testing.T, reply func(n int, r *http.Request, body []byte) (int, string)) string {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
s.mu.Lock()
|
||||
s.reqs = append(s.reqs, capturedRequest{method: r.Method, path: r.URL.Path, query: r.URL.Query(), body: body})
|
||||
s.keys = append(s.keys, r.Header.Get("Idempotency-Key"))
|
||||
n := len(s.reqs)
|
||||
s.mu.Unlock()
|
||||
status, payload := reply(n, r, body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(payload))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv.URL
|
||||
}
|
||||
|
||||
// runCLI runs one invocation with no terminal on stdin and no --yes added.
|
||||
func runCLI(t *testing.T, url string, args ...string) (string, error) {
|
||||
t.Helper()
|
||||
t.Setenv("WARMBLY_CONFIG_DIR", t.TempDir())
|
||||
t.Setenv("WARMBLY_TOKEN", "wmbly_test")
|
||||
t.Setenv("WARMBLY_API_URL", url)
|
||||
var out bytes.Buffer
|
||||
f := &Factory{IO: &iostreams.IOStreams{In: strings.NewReader(""), Out: &out, ErrOut: &out}}
|
||||
root := newRootCmd(f)
|
||||
root.SetArgs(args)
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&out)
|
||||
err := root.Execute()
|
||||
return out.String(), err
|
||||
}
|
||||
|
||||
func quoteJSON(id string, due int64) string {
|
||||
return fmt.Sprintf(`{"id":%q,"expires_at":"2026-11-18T12:15:00Z","lines":[{"type":"domain","domain":"getacme.com","years":1,"amount_micros":12000000,"renew_micros":12000000},{"type":"mailboxes","domain":"getacme.com","provider":"google","count":2,"amount_micros":%d,"monthly_micros":6000000}],"due_now_micros":%d,"recurring_monthly_micros":6000000,"yearly_domain_renewal_micros":12000000,"payment":{"balance_micros":50000000,"from_balance_micros":%d}}`, id, due-12000000, due, due)
|
||||
}
|
||||
|
||||
var buyArgs = []string{
|
||||
"store", "buy", "--domain", "getacme.com", "--mailbox", "ada@getacme.com", "--mailbox", "grace@getacme.com:Grace:Hopper",
|
||||
"--provider", "google", "--first-name", "Ada", "--last-name", "Lovelace", "--admin", "ada@getacme.com",
|
||||
"--forwarding-url", "https://acme.com",
|
||||
}
|
||||
|
||||
func TestStoreBuyQuotesThenOrdersAtTheQuotedTotal(t *testing.T) {
|
||||
var s storeServer
|
||||
url := s.start(t, func(n int, r *http.Request, _ []byte) (int, string) {
|
||||
if r.URL.Path == "/v1/store/quotes" {
|
||||
return http.StatusCreated, quoteJSON("11111111-1111-1111-1111-111111111111", 18_000_000)
|
||||
}
|
||||
return http.StatusCreated, `{"id":"o1","status":"charging","steps":[]}`
|
||||
})
|
||||
if out, err := runCLI(t, url, append(buyArgs, "--yes", "--json")...); err != nil {
|
||||
t.Fatalf("buy: %v\n%s", err, out)
|
||||
}
|
||||
if len(s.reqs) != 2 || s.reqs[0].path != "/v1/store/quotes" || s.reqs[1].path != "/v1/store/orders" {
|
||||
t.Fatalf("requests: %+v", s.reqs)
|
||||
}
|
||||
|
||||
var q store.QuoteRequest
|
||||
strictDecode(t, s.reqs[0].body, &q)
|
||||
if len(q.Items) != 2 || q.Items[0].Type != "domain" || q.Items[0].Domain != "getacme.com" || q.Items[1].Type != "mailboxes" || q.Items[1].Provider != "google" {
|
||||
t.Fatalf("quote items: %+v", q.Items)
|
||||
}
|
||||
mbs := q.Items[1].Mailboxes
|
||||
if len(mbs) != 2 || mbs[0].LocalPart != "ada" || mbs[0].FirstName != "Ada" || !mbs[0].Admin ||
|
||||
mbs[1].LocalPart != "grace" || mbs[1].LastName != "Hopper" || mbs[1].Admin {
|
||||
t.Fatalf("mailboxes: %+v", mbs)
|
||||
}
|
||||
|
||||
var o store.OrderRequest
|
||||
strictDecode(t, s.reqs[1].body, &o)
|
||||
if o.QuoteID.String() != "11111111-1111-1111-1111-111111111111" || o.ExpectedDueNowMicros == nil || *o.ExpectedDueNowMicros != 18_000_000 || o.ForwardingURL != "https://acme.com" {
|
||||
t.Fatalf("order: %s", s.reqs[1].body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreBuyRefusesWithoutATerminalOrYes(t *testing.T) {
|
||||
var s storeServer
|
||||
url := s.start(t, func(int, *http.Request, []byte) (int, string) { return http.StatusOK, `{}` })
|
||||
_, err := runCLI(t, url, buyArgs...)
|
||||
if err == nil || !strings.Contains(err.Error(), "--yes") {
|
||||
t.Fatalf("a buy with no terminal and no --yes must refuse, got %v", err)
|
||||
}
|
||||
if len(s.reqs) != 0 {
|
||||
t.Fatalf("a refused buy made %d requests", len(s.reqs))
|
||||
}
|
||||
}
|
||||
|
||||
func priceChanged(id string, due int64) string {
|
||||
return `{"error":"Conflict","code":"price_changed","request_id":"r1","message":"The price changed","details":{"quote":` + quoteJSON(id, due) + `}}`
|
||||
}
|
||||
|
||||
func TestStoreBuyStopsOnAPriceChangeUnderYes(t *testing.T) {
|
||||
var s storeServer
|
||||
url := s.start(t, func(n int, r *http.Request, _ []byte) (int, string) {
|
||||
if r.URL.Path == "/v1/store/quotes" {
|
||||
return http.StatusCreated, quoteJSON("q1", 18_000_000)
|
||||
}
|
||||
return http.StatusConflict, priceChanged("q2", 21_500_000)
|
||||
})
|
||||
_, err := runCLI(t, url, append(buyArgs, "--yes")...)
|
||||
if err == nil || !strings.Contains(err.Error(), "$21.50") || !strings.Contains(err.Error(), "Nothing was charged") {
|
||||
t.Fatalf("want the new total named, got %v", err)
|
||||
}
|
||||
if len(s.reqs) != 2 {
|
||||
t.Fatalf("--yes must not buy at a price nobody saw; made %d requests", len(s.reqs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreBuyAsksAgainAtTheNewPrice(t *testing.T) {
|
||||
var s storeServer
|
||||
url := s.start(t, func(n int, r *http.Request, _ []byte) (int, string) {
|
||||
switch {
|
||||
case r.URL.Path == "/v1/store/quotes":
|
||||
return http.StatusCreated, quoteJSON("q1", 18_000_000)
|
||||
case n == 2:
|
||||
return http.StatusConflict, priceChanged("q2", 21_500_000)
|
||||
}
|
||||
return http.StatusCreated, `{"id":"o1","status":"charging"}`
|
||||
})
|
||||
var asked []string
|
||||
var errOut bytes.Buffer
|
||||
b := &storeBuy{
|
||||
client: api.New(url, "wmbly_test", "test"), io: &iostreams.IOStreams{Out: &errOut, ErrOut: &errOut},
|
||||
idemKey: "k", maxTries: 3,
|
||||
ask: func(q string) (bool, error) { asked = append(asked, q); return true, nil },
|
||||
}
|
||||
if _, err := b.run(context.Background(), []byte(`{"items":[]}`)); err != nil {
|
||||
t.Fatalf("run: %v", err)
|
||||
}
|
||||
if len(asked) != 2 || !strings.Contains(asked[1], "$21.50") {
|
||||
t.Fatalf("questions: %q", asked)
|
||||
}
|
||||
if len(s.reqs) != 3 {
|
||||
t.Fatalf("want quote, order, order; got %d", len(s.reqs))
|
||||
}
|
||||
var second map[string]any
|
||||
_ = json.Unmarshal(s.reqs[2].body, &second)
|
||||
if second["quote_id"] != "q2" || second["expected_due_now_micros"] != float64(21_500_000) {
|
||||
t.Fatalf("second order: %s", s.reqs[2].body)
|
||||
}
|
||||
if s.keys[1] == s.keys[2] || s.keys[1] != "k" {
|
||||
t.Fatalf("a re-priced order must not reuse the first idempotency key: %q", s.keys)
|
||||
}
|
||||
|
||||
// Saying no to the new price buys nothing more.
|
||||
s = storeServer{}
|
||||
url = s.start(t, func(n int, r *http.Request, _ []byte) (int, string) {
|
||||
if r.URL.Path == "/v1/store/quotes" {
|
||||
return http.StatusCreated, quoteJSON("q1", 18_000_000)
|
||||
}
|
||||
return http.StatusConflict, priceChanged("q2", 21_500_000)
|
||||
})
|
||||
answers := []bool{true, false}
|
||||
b.client = api.New(url, "wmbly_test", "test")
|
||||
b.ask = func(string) (bool, error) { a := answers[0]; answers = answers[1:]; return a, nil }
|
||||
if _, err := b.run(context.Background(), []byte(`{"items":[]}`)); err != errCancelled {
|
||||
t.Fatalf("declining the new price must cancel, got %v", err)
|
||||
}
|
||||
if len(s.reqs) != 2 {
|
||||
t.Fatalf("declined buy made %d requests", len(s.reqs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreBuyNamesTheCardSetupURL(t *testing.T) {
|
||||
var s storeServer
|
||||
url := s.start(t, func(n int, r *http.Request, _ []byte) (int, string) {
|
||||
if r.URL.Path == "/v1/store/quotes" {
|
||||
return http.StatusCreated, quoteJSON("q1", 18_000_000)
|
||||
}
|
||||
return http.StatusPaymentRequired, `{"error":"Payment Required","code":"payment_method_required","request_id":"r1","message":"Add a card","setup_url":"https://checkout.example/setup"}`
|
||||
})
|
||||
_, err := runCLI(t, url, append(buyArgs, "--yes")...)
|
||||
if err == nil || !strings.Contains(err.Error(), "https://checkout.example/setup") {
|
||||
t.Fatalf("want the setup URL, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreCartFlags(t *testing.T) {
|
||||
for name, c := range map[string]storeCart{
|
||||
"no provider": {mailboxes: []string{"ada@acme.com:Ada:Lovelace"}},
|
||||
"no name": {mailboxes: []string{"ada@acme.com"}, providers: []string{"google"}},
|
||||
"admin not listed": {mailboxes: []string{"ada@acme.com:Ada:L"}, providers: []string{"google"}, admins: []string{"bob@acme.com"}},
|
||||
"bad provider": {mailboxes: []string{"ada@acme.com:Ada:L"}, providers: []string{"yahoo"}},
|
||||
"nothing": {},
|
||||
"bad years": {domains: []string{"acme.com:0"}},
|
||||
} {
|
||||
if _, err := c.items(); err == nil {
|
||||
t.Errorf("%s: want an error", name)
|
||||
}
|
||||
}
|
||||
|
||||
// A per-domain provider wins, and mailboxes on a domain the workspace already has need no --domain.
|
||||
c := storeCart{
|
||||
domains: []string{"new.io:2"},
|
||||
mailboxes: []string{"a@owned.com:A:B", "c@new.io:C:D"},
|
||||
providers: []string{"google", "owned.com=microsoft"},
|
||||
}
|
||||
items, err := c.items()
|
||||
if err != nil {
|
||||
t.Fatalf("items: %v", err)
|
||||
}
|
||||
if len(items) != 3 || items[0].Type != "domain" || items[0].Years != 2 || items[1].Domain != "new.io" || items[1].Provider != "google" ||
|
||||
items[2].Domain != "owned.com" || items[2].Provider != "microsoft" {
|
||||
t.Fatalf("items: %+v", items)
|
||||
}
|
||||
|
||||
if _, err := (&storeCart{input: `{"items":[]}`, providers: []string{"google"}}).body(strings.NewReader("")); err == nil {
|
||||
t.Error("--input with cart flags must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreCommandBodies(t *testing.T) {
|
||||
t.Run("dns add", func(t *testing.T) {
|
||||
r := runAgainst(t, "store", "domains", "dns", "add", "D", "--type", "MX", "--name", "@", "--content", "mx.acme.com", "--ttl", "300", "--priority", "10")
|
||||
var rec store.DNSRecordInput
|
||||
strictDecode(t, r.body, &rec)
|
||||
if r.method != http.MethodPost || r.path != "/v1/store/domains/D/dns" || rec.Type != "MX" || rec.Name != "@" || rec.Content != "mx.acme.com" ||
|
||||
rec.TTL != 300 || rec.Priority == nil || *rec.Priority != 10 {
|
||||
t.Fatalf("sent %s %s %s", r.method, r.path, r.body)
|
||||
}
|
||||
})
|
||||
|
||||
for state, want := range map[string]bool{"on": true, "off": false} {
|
||||
t.Run("auto-renew "+state, func(t *testing.T) {
|
||||
r := runAgainst(t, "store", "domains", "auto-renew", "D", state)
|
||||
var p store.DomainPatch
|
||||
strictDecode(t, r.body, &p)
|
||||
if r.method != http.MethodPatch || r.path != "/v1/store/domains/D" || p.AutoRenew == nil || *p.AutoRenew != want || p.ForwardingURL != nil {
|
||||
t.Fatalf("sent %s %s %s", r.method, r.path, r.body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("forwarding", func(t *testing.T) {
|
||||
m := bodyKeys(t, runAgainst(t, "store", "domains", "forwarding", "D", "https://acme.com").body)
|
||||
if m["forwarding_url"] != "https://acme.com" || len(m) != 1 {
|
||||
t.Fatalf("sent %v", m)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("connect", func(t *testing.T) {
|
||||
r := runAgainst(t, "store", "domains", "connect", "acme.com", "--method", "manual")
|
||||
var req store.ConnectRequest
|
||||
strictDecode(t, r.body, &req)
|
||||
if r.path != "/v1/store/domains/connect" || req.Domain != "acme.com" || req.Method != "manual" {
|
||||
t.Fatalf("sent %s %s", r.path, r.body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rename", func(t *testing.T) {
|
||||
var p store.MailboxPatch
|
||||
strictDecode(t, runAgainst(t, "store", "mailboxes", "rename", "M", "--first", "Ada", "--last", "Lovelace").body, &p)
|
||||
if p.FirstName == nil || *p.FirstName != "Ada" || p.LastName == nil || *p.LastName != "Lovelace" {
|
||||
t.Fatalf("decoded %+v", p)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("registrant set", func(t *testing.T) {
|
||||
r := runAgainst(t, "store", "registrant", "set", "--first-name", "Ada", "--postal-code", "N1", "--country", "GB")
|
||||
var reg store.Registrant
|
||||
strictDecode(t, r.body, ®)
|
||||
if r.method != http.MethodPut || reg.PostalCode != "N1" || reg.Country != "GB" {
|
||||
t.Fatalf("sent %s %s", r.method, r.body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("search", func(t *testing.T) {
|
||||
r := runAgainst(t, "store", "search", "getacme", "--tlds", "com,io")
|
||||
if r.method != http.MethodGet || r.path != "/v1/store/domains/search" || r.query.Get("q") != "getacme" || r.query.Get("tlds") != "com,io" {
|
||||
t.Fatalf("sent %s %s ?%s", r.method, r.path, r.query.Encode())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cancel", func(t *testing.T) {
|
||||
if r := runAgainst(t, "store", "mailboxes", "cancel", "M"); r.method != http.MethodDelete || r.path != "/v1/store/mailboxes/M" {
|
||||
t.Fatalf("sent %s %s", r.method, r.path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestStoreChargingCommandsConfirm(t *testing.T) {
|
||||
for _, args := range [][]string{
|
||||
{"store", "domains", "renew", "D"},
|
||||
{"store", "domains", "transfer-out", "D"},
|
||||
{"store", "mailboxes", "cancel", "M"},
|
||||
{"store", "mailboxes", "resume", "M"},
|
||||
{"store", "mailboxes", "sign-in", "M"},
|
||||
} {
|
||||
var s storeServer
|
||||
url := s.start(t, func(int, *http.Request, []byte) (int, string) { return http.StatusOK, `{}` })
|
||||
if _, err := runCLI(t, url, args...); err == nil || !strings.Contains(err.Error(), "--yes") {
|
||||
t.Errorf("%v without a terminal or --yes: got %v", args, err)
|
||||
}
|
||||
if len(s.reqs) != 0 {
|
||||
t.Errorf("%v made a request before confirming", args)
|
||||
}
|
||||
}
|
||||
|
||||
var s storeServer
|
||||
url := s.start(t, func(int, *http.Request, []byte) (int, string) { return http.StatusOK, `{}` })
|
||||
if _, err := runCLI(t, url, "store", "domains", "auto-renew", "D", "maybe"); err == nil || len(s.reqs) != 0 {
|
||||
t.Errorf("auto-renew must take on or off, got %v and %d requests", err, len(s.reqs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreOrderWatchPollsUntilSettled(t *testing.T) {
|
||||
minWatchInterval = 0
|
||||
t.Cleanup(func() { minWatchInterval = time.Second })
|
||||
var s storeServer
|
||||
url := s.start(t, func(n int, r *http.Request, _ []byte) (int, string) {
|
||||
status := "processing"
|
||||
if n >= 3 {
|
||||
status = "completed"
|
||||
}
|
||||
return http.StatusOK, `{"id":"O","status":"` + status + `","steps":[{"key":"register","status":"done","at":null},{"key":"mailboxes","status":"running","at":null}]}`
|
||||
})
|
||||
out, err := runCLI(t, url, "store", "order", "watch", "O", "--interval", "1ms", "--json")
|
||||
if err != nil {
|
||||
t.Fatalf("watch: %v\n%s", err, out)
|
||||
}
|
||||
if len(s.reqs) != 3 || s.reqs[0].path != "/v1/store/orders/O" {
|
||||
t.Fatalf("polled %d times: %+v", len(s.reqs), s.reqs)
|
||||
}
|
||||
if !strings.Contains(out, `"completed"`) {
|
||||
t.Fatalf("the final order was not printed: %s", out)
|
||||
}
|
||||
|
||||
s = storeServer{}
|
||||
url = s.start(t, func(int, *http.Request, []byte) (int, string) {
|
||||
return http.StatusOK, `{"id":"O","status":"failed","steps":[]}`
|
||||
})
|
||||
if _, err := runCLI(t, url, "store", "order", "watch", "O", "--json"); err != errSilent {
|
||||
t.Fatalf("a failed order must exit non-zero, got %v", err)
|
||||
}
|
||||
|
||||
s = storeServer{}
|
||||
url = s.start(t, func(int, *http.Request, []byte) (int, string) {
|
||||
return http.StatusOK, `{"id":"O","status":"processing","steps":[]}`
|
||||
})
|
||||
if _, err := runCLI(t, url, "store", "order", "watch", "O", "--interval", "1ms", "--timeout", "30ms"); err == nil || !strings.Contains(err.Error(), "still processing") {
|
||||
t.Fatalf("a watch that times out must say the order carries on, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -543,6 +543,9 @@ func main() {
|
||||
|
||||
cloudLinkC := cloudlink.NewService(repository.NewCloudLinkRepository(primaryDB.Pool, credEncrypter, primaryDB.ConnectSession), emailRepo, nil)
|
||||
|
||||
// Mailboxes bought in the store keep their inbox when the plan lapses.
|
||||
uniboxAccess := feature.WithPurchasedMailboxes(feature.NewService(subscriptionRepoConsumer, planRepoConsumer),
|
||||
feature.StoreMailboxes{Repo: repository.NewStoreRepository(primaryDB)})
|
||||
jobsService := &jobs.JobsService{
|
||||
CampaignIsolationEnabled: config.CampaignSendIsolationEnabled(),
|
||||
DBConns: primaryDB.Pool.Config().MaxConns,
|
||||
@@ -579,7 +582,7 @@ func main() {
|
||||
AdminRepo: repository.NewAdminRepository(primaryDB.Pool),
|
||||
AssignmentService: workerAssignmentSvc,
|
||||
Notifier: notificationService,
|
||||
UniboxAccess: feature.NewService(subscriptionRepoConsumer, planRepoConsumer),
|
||||
UniboxAccess: uniboxAccess,
|
||||
OpsNotifier: opsNotifierC,
|
||||
TaskRepo: taskRepo,
|
||||
CampaignRepo: campaignRepo,
|
||||
|
||||
@@ -88,6 +88,8 @@ func dispatch(ctx context.Context, args []string) error {
|
||||
return runFleet(ctx, args[1:])
|
||||
case "inbox-tag":
|
||||
return runInboxTag(ctx, args[1:])
|
||||
case "partner":
|
||||
return runPartner(ctx, args[1:])
|
||||
case "keys":
|
||||
return runKeys(ctx, args[1:])
|
||||
case "db":
|
||||
@@ -141,6 +143,9 @@ var commands = []command{
|
||||
{"fleet rollout start", "Move the fleet to a tag in stages: one canary, then waves", composeExec + "fleet rollout start v1.4.2 --bake 30m"},
|
||||
{"fleet rollout status", "Show a staged rollout's stage, admitted nodes and halt reason", composeExec + "fleet rollout status"},
|
||||
{"fleet env-status", "Whether every live node has applied the current rendered env", composeExec + "fleet env-status"},
|
||||
{"partner create", "Add a reseller that runs workspaces through the partner API, which is off until one exists", composeExec + "partner create --slug graphkit --name GraphKit --allowed-hosts app.graphkit.com"},
|
||||
{"partner list", "List resellers with their status and webhook", composeExec + "partner list"},
|
||||
{"partner key", "Issue a partner API key for live or test workspaces. Shown once", composeExec + "partner key --partner graphkit --mode live"},
|
||||
{"db load", "Show what the database is busy with: connections by service, costliest queries, largest tables", composeExec + "db load"},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
// Resellers run workspaces through /v1/partner, which answers nothing until a partner exists here.
|
||||
|
||||
func runPartner(ctx context.Context, args []string) error {
|
||||
if len(args) == 0 {
|
||||
partnerUsage(os.Stderr)
|
||||
return errors.New("`partner` needs a subcommand. Pick one from the list above.")
|
||||
}
|
||||
switch args[0] {
|
||||
case "help", "-h", "--help":
|
||||
partnerUsage(os.Stdout)
|
||||
return nil
|
||||
case "create":
|
||||
return runPartnerCreate(ctx, args[1:])
|
||||
case "list":
|
||||
return runPartnerList(ctx, args[1:])
|
||||
case "key":
|
||||
return runPartnerKey(ctx, args[1:])
|
||||
}
|
||||
partnerUsage(os.Stderr)
|
||||
return fmt.Errorf("unknown subcommand `partner %s`. Pick one from the list above.", args[0])
|
||||
}
|
||||
|
||||
func partnerUsage(w *os.File) {
|
||||
fmt.Fprint(w, "Manage resellers that create and run workspaces through the partner API.\n\nUsage:\n warmblyctl partner <subcommand> [flags]\n\nSubcommands:\n")
|
||||
for _, c := range commands {
|
||||
if !strings.HasPrefix(c.name, "partner ") {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(w, " %-28s %s\n %s\n", strings.TrimPrefix(c.name, "partner "), c.summary, c.example)
|
||||
}
|
||||
}
|
||||
|
||||
func partnerService(ctx context.Context) (*partner.Service, func(), error) {
|
||||
c, err := connect(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return partner.NewService(partner.Deps{Repo: repository.NewPartnerRepository(c.db.Pool)}), c.close, nil
|
||||
}
|
||||
|
||||
func runPartnerCreate(ctx context.Context, args []string) error {
|
||||
fs := newFlagSet("partner create")
|
||||
slug := fs.String("slug", "", "short identifier, lowercase letters, digits and dashes")
|
||||
name := fs.String("name", "", "the partner's name")
|
||||
display := fs.String("display-name", "", `what members of its workspaces read, as in "Billed through <display name>" (default: --name)`)
|
||||
hosts := fs.String("allowed-hosts", "", "comma-separated hosts a partner-supplied return URL may point at")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := noExtraArgs(fs); err != nil {
|
||||
return err
|
||||
}
|
||||
if *slug == "" || *name == "" {
|
||||
return errors.New("--slug and --name are required")
|
||||
}
|
||||
svc, done, err := partnerService(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer done()
|
||||
var allowed []string
|
||||
for _, h := range strings.Split(*hosts, ",") {
|
||||
if h = strings.TrimSpace(h); h != "" {
|
||||
allowed = append(allowed, h)
|
||||
}
|
||||
}
|
||||
p, xerr := svc.CreatePartner(ctx, partner.CreatePartnerInput{Slug: *slug, Name: *name, DisplayName: *display, AllowedHosts: allowed}, nil)
|
||||
if xerr != nil {
|
||||
return errors.New(xerr.Message)
|
||||
}
|
||||
fmt.Printf("Created partner %s (%s), id %s.\nIssue a key with: warmblyctl partner key --partner %s --mode test\n", p.Name, p.Slug, p.ID, p.Slug)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runPartnerList(ctx context.Context, args []string) error {
|
||||
fs := newFlagSet("partner list")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := noExtraArgs(fs); err != nil {
|
||||
return err
|
||||
}
|
||||
svc, done, err := partnerService(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer done()
|
||||
list, err := svc.Repo.ListPartners(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(list) == 0 {
|
||||
fmt.Println("No partners. The partner API is off on this instance.")
|
||||
return nil
|
||||
}
|
||||
tw := tabwriter.NewWriter(os.Stdout, 0, 2, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, "SLUG\tNAME\tDISPLAY NAME\tSTATUS\tWEBHOOK\tID")
|
||||
for _, p := range list {
|
||||
hook := "-"
|
||||
if p.WebhookURL != nil {
|
||||
hook = *p.WebhookURL
|
||||
}
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\n", p.Slug, p.Name, p.DisplayName, p.Status, hook, p.ID)
|
||||
}
|
||||
return tw.Flush()
|
||||
}
|
||||
|
||||
func runPartnerKey(ctx context.Context, args []string) error {
|
||||
fs := newFlagSet("partner key")
|
||||
slug := fs.String("partner", "", "the partner's slug")
|
||||
mode := fs.String("mode", "test", "live or test: which workspaces the key reaches")
|
||||
name := fs.String("name", "", "a label for the key")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := noExtraArgs(fs); err != nil {
|
||||
return err
|
||||
}
|
||||
if *slug == "" {
|
||||
return errors.New("--partner is required")
|
||||
}
|
||||
svc, done, err := partnerService(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer done()
|
||||
p, err := svc.Repo.GetPartnerBySlug(ctx, strings.ToLower(strings.TrimSpace(*slug)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p == nil {
|
||||
return fmt.Errorf("no partner with slug %q. `warmblyctl partner list` shows them.", *slug)
|
||||
}
|
||||
k, xerr := svc.CreateKey(ctx, p.ID, models.PartnerMode(*mode), *name, nil)
|
||||
if xerr != nil {
|
||||
return errors.New(xerr.Message)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "Created a %s key for %s. It is shown once; store it now.\n", k.Mode, p.Name)
|
||||
fmt.Println(k.Secret)
|
||||
return nil
|
||||
}
|
||||
@@ -61,6 +61,10 @@ var remoteAdminHelpers = []remoteAdminHelper{
|
||||
{"health instance", "GET", "/admin/instance/health", ""},
|
||||
{"health monitoring", "GET", "/admin/instance/monitoring", ""},
|
||||
{"health limits", "GET", "/admin/instance/limits", ""},
|
||||
{"store health", "GET", "/admin/store/health", ""},
|
||||
{"store orders", "GET", "/admin/store/orders", ""},
|
||||
{"store domains", "GET", "/admin/store/domains", ""},
|
||||
{"store mailboxes", "GET", "/admin/store/mailboxes", ""},
|
||||
}
|
||||
|
||||
func remoteAdminUsage() {
|
||||
@@ -309,7 +313,7 @@ func runRemoteAdminHelper(ctx context.Context, helper remoteAdminHelper, args []
|
||||
query := url.Values{}
|
||||
var limit *int
|
||||
var cursor, q, state, status, level, after, before, mailbox *string
|
||||
if helper.Method == "GET" && (helper.Command == "logs" || helper.Command == "sync list" || helper.Command == "mailbox list" || helper.Command == "sends in-flight" || helper.Command == "recovery dead-letters" || helper.Command == "recovery failures") {
|
||||
if helper.Method == "GET" && (helper.Command == "logs" || helper.Command == "sync list" || helper.Command == "mailbox list" || helper.Command == "sends in-flight" || helper.Command == "recovery dead-letters" || helper.Command == "recovery failures" || storeList(helper.Command)) {
|
||||
limit = fs.Int("limit", 100, "Maximum rows, 1 to 200 (server may apply a lower endpoint cap)")
|
||||
}
|
||||
switch helper.Command {
|
||||
@@ -328,6 +332,10 @@ func runRemoteAdminHelper(ctx context.Context, helper remoteAdminHelper, args []
|
||||
case "recovery dead-letters":
|
||||
status = fs.String("status", "", "pending, replayed or failed")
|
||||
cursor = fs.String("cursor", "", "Cursor UUID from the preceding page")
|
||||
case "store orders", "store domains", "store mailboxes":
|
||||
status = fs.String("status", "", "Exact status, for example processing, active or failed")
|
||||
q = fs.String("q", "", "Order id, workspace name, domain or address substring")
|
||||
cursor = fs.String("cursor", "", "Cursor from the preceding page")
|
||||
}
|
||||
var write bool
|
||||
var confirm string
|
||||
@@ -350,6 +358,9 @@ func runRemoteAdminHelper(ctx context.Context, helper remoteAdminHelper, args []
|
||||
}
|
||||
requestPath = strings.ReplaceAll(requestPath, ":id", id)
|
||||
}
|
||||
if limit != nil && storeList(helper.Command) && *limit > 100 {
|
||||
*limit = 100
|
||||
}
|
||||
if limit != nil {
|
||||
if *limit < 1 || *limit > 200 {
|
||||
return remoteFailure(2, "invalid_limit", "--limit must be between 1 and 200.")
|
||||
@@ -403,3 +414,8 @@ func runRemoteAdminHelper(ctx context.Context, helper remoteAdminHelper, args []
|
||||
}
|
||||
return executeRemoteAdmin(ctx, sel, helper.Method, requestPath, validated, nil, write, confirm, risk)
|
||||
}
|
||||
|
||||
// storeList is a store list helper; those lists page at most 100 rows.
|
||||
func storeList(command string) bool {
|
||||
return command == "store orders" || command == "store domains" || command == "store mailboxes"
|
||||
}
|
||||
|
||||
@@ -42,6 +42,33 @@ var remoteAdminRoutes = []remoteAdminRoute{
|
||||
{"POST", "/admin/agencies/:id/ai-credit", []string{"ManageOrganizations"}, true, ""},
|
||||
{"POST", "/admin/agencies/:id/clients", []string{"ManageOrganizations"}, true, ""},
|
||||
{"DELETE", "/admin/agencies/:id/clients/:orgId", []string{"ManageOrganizations"}, false, ""},
|
||||
{"GET", "/admin/store/pricing", []string{"ManageSettings"}, false, ""},
|
||||
{"GET", "/admin/store/health", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/store/economics", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/store/orders", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/store/orders/:id", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/store/domains", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/store/mailboxes", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/store/workspaces/:orgId", []string{"ViewOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/orders/:id/refresh", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/orders/:id/place", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/orders/:id/refund", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/mailboxes/:id/refresh", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/mailboxes/:id/connect", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/mailboxes/:id/cancel", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/mailboxes/:id/resume", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/domains/:id/refresh", []string{"ManageOrganizations"}, false, ""},
|
||||
{"POST", "/admin/store/domains/:id/renew", []string{"ManageOrganizations"}, false, ""},
|
||||
{"PATCH", "/admin/store/domains/:id", []string{"ManageOrganizations"}, false, ""},
|
||||
{"GET", "/admin/partners", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/partners/:id", []string{"ViewOrganizations"}, false, ""},
|
||||
{"GET", "/admin/partners/:id/organizations", []string{"ViewOrganizations"}, false, ""},
|
||||
{"POST", "/admin/partners", []string{"ManageOrganizations"}, true, ""},
|
||||
{"PATCH", "/admin/partners/:id", []string{"ManageOrganizations"}, true, ""},
|
||||
{"POST", "/admin/partners/:id/webhook-secret", []string{"ManageOrganizations"}, true, ""},
|
||||
{"PUT", "/admin/partners/:id/callback-key", []string{"ManageOrganizations"}, true, ""},
|
||||
{"POST", "/admin/partners/:id/keys", []string{"ManageOrganizations"}, true, ""},
|
||||
{"DELETE", "/admin/partners/:id/keys/:keyId", []string{"ManageOrganizations"}, true, ""},
|
||||
{"GET", "/admin/organizations/:id/agency", []string{"ViewOrganizations"}, false, ""},
|
||||
{"PUT", "/admin/organizations/:id/overrides", []string{"ManageOrganizations"}, false, ""},
|
||||
{"GET", "/admin/plans", []string{"ViewOrganizations"}, false, ""},
|
||||
|
||||
@@ -57,6 +57,10 @@ curl -X GET "https://api.warmbly.com/v1/api-keys" \
|
||||
|
||||
For mutation retries, include an `Idempotency-Key` header with a unique value per logical operation. Warmbly stores completed mutation responses for 24 hours per organization and key, then replays matching retries instead of performing the operation again. A key belongs to the credential and the exact request that first used it, resource ids included; see [retry safety](/api/endpoints/#retry-safety) for how refusals and server errors are handled.
|
||||
|
||||
### Recent confirmation
|
||||
|
||||
Some changes ask a dashboard session to have confirmed the account holder in the last five minutes; see [actions that need a recent confirmation](/api/endpoints/#actions-that-need-a-recent-confirmation). An API key or an OAuth access token presents its credential on every call, so it passes that check. It still needs the route's scope, and the member it acts for still needs the matching role permission. For example, a key with `MANAGE_STORE` can [pay for a store order](/api/endpoints/#domains-and-mailboxes), renew a domain or cancel a mailbox without a confirmation step, but only while the member behind it holds `manage_billing`, which is checked on every request.
|
||||
|
||||
## Verifying a credential
|
||||
|
||||
To check that a credential is valid and see who it belongs to, call `GET /v1/me`. It works with an API key, an OAuth access token, or a dashboard session, requires no specific permission, and returns the caller's identity:
|
||||
|
||||
@@ -242,6 +242,7 @@ Run `warmbly <command> --help` for the flags, and `warmbly <command> <subcommand
|
||||
| `contact` | list, view, create, edit, delete, lookup, timeline, notes, import, export, verify |
|
||||
| `mailbox` | list, view, edit, health checks, sync state, send-as addresses, sending behaviour, warmup, hold, send |
|
||||
| `inbox` | list, view, threads, read, reply, compose, drafts, scheduled sends, snoozes |
|
||||
| `store` | [buy domains and mailboxes](#buying-domains-and-mailboxes): search, status, quote, buy, orders and `order watch`, domains (renew, auto-renew, forwarding, transfer-out, DNS, connect), purchased mailboxes, the registrant |
|
||||
| `suppression` | the addresses and domains that get no campaign mail |
|
||||
| `segment` | live audiences and their conditions |
|
||||
| `template` | reply templates |
|
||||
@@ -335,6 +336,55 @@ warmbly campaign list --organization CLIENT_ID
|
||||
WARMBLY_ORGANIZATION=CLIENT_ID warmbly mailbox list
|
||||
```
|
||||
|
||||
## Buying domains and mailboxes
|
||||
|
||||
`warmbly store` is the [store](/guides/buy-mailboxes/) from the terminal: search for a domain, price a cart, buy it, follow the order, then look after what you bought.
|
||||
|
||||
```bash
|
||||
warmbly store status
|
||||
warmbly store search getacme --tlds com,io
|
||||
warmbly store quote --domain getacme.com --mailbox ada@getacme.com --mailbox grace@getacme.com \
|
||||
--provider google --first-name Ada --last-name Lovelace
|
||||
warmbly store buy --domain getacme.com --mailbox ada@getacme.com --mailbox grace@getacme.com \
|
||||
--provider google --first-name Ada --last-name Lovelace --forwarding-url https://acme.com
|
||||
warmbly store order watch ORDER_ID
|
||||
```
|
||||
|
||||
A cart is built from flags:
|
||||
|
||||
| Flag | What it adds |
|
||||
|---|---|
|
||||
| `--domain NAME[:YEARS]` | registers a new domain; `--years` sets the term for every domain without its own |
|
||||
| `--mailbox ADDRESS[:FIRST:LAST]` | a mailbox, on a domain in the same cart or one the workspace already has |
|
||||
| `--provider google\|microsoft` | who hosts the mailboxes; `DOMAIN=PROVIDER` sets it for one domain |
|
||||
| `--first-name`, `--last-name` | the name on mailboxes that do not carry their own |
|
||||
| `--admin ADDRESS` | the mailbox that administers its domain, at most one per domain |
|
||||
|
||||
For full control, pass the `POST /store/quotes` body instead: `--input @cart.json` or `--input -` for stdin, as `{"items": [...]}`.
|
||||
|
||||
`store buy` quotes the cart, prints every line, the total due now and what recurs each month and year, then asks before it charges. It pays from the workspace balance first, then the card on file, and the order carries the total you agreed to: if the price moved in between, nothing is charged and the CLI shows the new total and asks again. With no terminal it refuses unless `--yes` is passed, and under `--yes` a price change stops the buy rather than paying a total nobody saw. When the balance does not cover the order and there is no card, it prints the link to add one.
|
||||
|
||||
Setting up mailboxes can take a few hours. `store order watch` redraws the order's steps every `--interval` (5 seconds by default) until it completes or fails, and gives up after `--timeout` (one hour by default, `0` for no limit). Ctrl-C stops watching; the order carries on either way.
|
||||
|
||||
```bash
|
||||
warmbly store domains list
|
||||
warmbly store domains renew DOMAIN_ID
|
||||
warmbly store domains auto-renew DOMAIN_ID off
|
||||
warmbly store domains forwarding DOMAIN_ID https://acme.com
|
||||
warmbly store domains dns add DOMAIN_ID --type TXT --name @ --content "v=spf1 include:_spf.google.com ~all"
|
||||
warmbly store domains dns delete DOMAIN_ID RECORD_ID
|
||||
warmbly store domains connect acme.com --method nameservers
|
||||
warmbly store mailboxes list
|
||||
warmbly store mailboxes rename MAILBOX_ID --first Ada --last Lovelace
|
||||
warmbly store mailboxes cancel MAILBOX_ID
|
||||
warmbly store registrant set --first-name Ada --last-name Lovelace --email ada@acme.com \
|
||||
--phone +44.2071234567 --address1 "1 Main St" --city London --postal-code N1 --country GB
|
||||
```
|
||||
|
||||
Like a send, `domains renew`, `domains transfer-out`, `mailboxes cancel`, `mailboxes resume` and `mailboxes sign-in` ask first and refuse without a terminal unless `--yes` is passed: the first four charge the workspace or change what it is charged, and `sign-in` prints the mailbox's password. Every write takes `--idempotency-key`.
|
||||
|
||||
The key needs `READ_STORE` to read and `MANAGE_STORE` to change anything ([permissions](/api/permissions/)). Buying, renewing, turning auto-renew on or off, cancelling or resuming a mailbox, getting a transfer code and saving the registrant also need the member behind the key to hold `manage_billing`, checked on every call.
|
||||
|
||||
## What needs the dashboard
|
||||
|
||||
Three things the CLI deliberately does not do, because the API does not let a key do them:
|
||||
|
||||
@@ -51,6 +51,7 @@ These checks use existing grants on hosted and self-hosted instances and need no
|
||||
| POST | `/emails/bulk/warmup` | `WRITE_EMAILS` |
|
||||
| POST | `/emails/bulk/status` | `WRITE_EMAILS` |
|
||||
| GET | `/emails/allowance` | `READ_EMAILS` |
|
||||
| GET | `/emails/partner` | `READ_EMAILS` |
|
||||
| POST | `/emails/client-links` | `WRITE_EMAILS` |
|
||||
| GET | `/emails/client-links` | `READ_EMAILS` |
|
||||
| GET | `/emails/client-links/:id/uses` | `READ_EMAILS` |
|
||||
@@ -106,6 +107,75 @@ These routes connect mailboxes from the API and are part of the [Partnership pla
|
||||
|
||||
On the Partnership plan, `POST /emails/onboarding/oauth/start`, `POST /emails/onboarding/oauth/reauth/:id`, inbox-vendor sign-in and `POST /emails/grants/google/start`, `/emails/grants/microsoft/start` and `/emails/grants/:id/connect` answer `422` `partnership_oauth_app_required` unless the sign-in can go through the workspace's own app.
|
||||
|
||||
### Domains and mailboxes
|
||||
|
||||
The [Buy mailboxes](/guides/buy-mailboxes/) store. Every `/store/*` route accepts a session, an API key, an OAuth token, or an agency key acting in a client workspace. Each needs a current workspace and counts against the write rate limit. A key or token needs `READ_STORE` to read and `MANAGE_STORE` to change anything, and the member behind it needs `manage_emails`. Anything that charges, or changes what is charged, also needs that member to hold `manage_billing`, checked on every request rather than when the key was made. A session also needs a [recent confirmation](#actions-that-need-a-recent-confirmation) for those, except saving the registrant, and to show a sign-in; API keys and OAuth tokens present their credential on every call, so they skip that confirmation. Buying spends the workspace balance, charging its saved card only for a shortfall; an agency key buying in a client workspace charges that client's balance. An `:id` or `:record_id` that is not a UUID answers `400`. When the instance has no GraphKit API key configured, `GET /store/status` answers `enabled: false` with `reason: not_configured`, the list reads (`GET /store/orders`, `/store/orders/:id`, `/store/domains` and `/store/mailboxes`) still answer from what was bought here, every other route answers `404` `store_disabled`, and on a self-hosted instance the dashboard shows buying as locked; a hosted instance keeps it hidden. In a workspace a partner manages, `GET /store/status` answers `enabled: false` with `reason: partner_managed`, every write answers `403` `store_managed_by_partner`, and the dashboard shows no entry point.
|
||||
|
||||
Buying needs an active paid plan: `POST /store/quotes`, `POST /store/orders` and `POST /store/domains/connect` answer `402` `plan_required` without one. An instance that does not bill its users (the self-host default) has no plan gate, so it never answers `plan_required`.
|
||||
|
||||
| Method | Path | API Permission | Member needs | Session also needs |
|
||||
|--------|------|----------------|--------------|--------------------|
|
||||
| GET | `/store/status` | `READ_STORE` | `manage_emails` | |
|
||||
| GET | `/store/domains/search` | `READ_STORE` | `manage_emails` | |
|
||||
| PUT | `/store/registrant` | `MANAGE_STORE` | `manage_emails`, `manage_billing` | |
|
||||
| POST | `/store/quotes` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| POST | `/store/orders` | `MANAGE_STORE` | `manage_emails`, `manage_billing` | recent confirmation |
|
||||
| GET | `/store/orders` | `READ_STORE` | `manage_emails` | |
|
||||
| GET | `/store/orders/:id` | `READ_STORE` | `manage_emails` | |
|
||||
| GET | `/store/domains` | `READ_STORE` | `manage_emails` | |
|
||||
| GET | `/store/domains/:id` | `READ_STORE` | `manage_emails` | |
|
||||
| PATCH | `/store/domains/:id` | `MANAGE_STORE` | `manage_emails`; a body with `auto_renew` also `manage_billing` | recent confirmation, with `auto_renew` |
|
||||
| POST | `/store/domains/:id/renew` | `MANAGE_STORE` | `manage_emails`, `manage_billing` | recent confirmation |
|
||||
| POST | `/store/domains/:id/transfer-out` | `MANAGE_STORE` | `manage_emails`, `manage_billing` | recent confirmation |
|
||||
| POST | `/store/domains/connect` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| POST | `/store/domains/:id/connection/check` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| POST | `/store/domains/:id/connection/regenerate` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| DELETE | `/store/domains/:id` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| POST | `/store/domains/:id/dns` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| PATCH | `/store/domains/:id/dns/:record_id` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| DELETE | `/store/domains/:id/dns/:record_id` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| POST | `/store/domains/:id/dns/check` | `READ_STORE` | `manage_emails` | |
|
||||
| GET | `/store/mailboxes` | `READ_STORE` | `manage_emails` | |
|
||||
| PATCH | `/store/mailboxes/:id` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| PUT | `/store/mailboxes/:id/photo` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| POST | `/store/photos` | `MANAGE_STORE` | `manage_emails` | |
|
||||
| GET | `/store/photos/:id` | `READ_STORE` | `manage_emails` | |
|
||||
| DELETE | `/store/mailboxes/:id` | `MANAGE_STORE` | `manage_emails`, `manage_billing` | recent confirmation |
|
||||
| POST | `/store/mailboxes/:id/resume` | `MANAGE_STORE` | `manage_emails`, `manage_billing` | recent confirmation |
|
||||
| POST | `/store/mailboxes/:id/sign-in` | `MANAGE_STORE` | `manage_emails` | recent confirmation |
|
||||
|
||||
A key or token without `manage_billing` behind it answers `403` on the routes that need it, the same as a member without it. A `PATCH /store/domains/:id` that changes `auto_renew` from a session that has not confirmed recently answers `403` `reauth_required`; one that only changes `forwarding_url` needs neither. Every `POST`, `PATCH`, `PUT` and `DELETE` accepts an `Idempotency-Key`; send one with each write, and always with an order, a renewal, a cancellation or a resume, so a retry never charges or applies twice. The two exceptions are `POST /store/domains/:id/transfer-out` and `POST /store/mailboxes/:id/sign-in`: each answers with a secret shown once, so no copy of the answer is stored and a key sent with them is ignored. Repeating either charges nothing and returns the secret again.
|
||||
|
||||
Money is integer micro-USD (`1000000` is $1.00) in fields ending `_micros`.
|
||||
|
||||
- `GET /store/status` returns `enabled`, `configured` (whether the instance has a GraphKit API key at all), `reason` when `enabled` is `false` (`not_configured` or `partner_managed`), `locked` (with `not_configured`: `true` only on a self-hosted instance, which shows buying as a feature to set up; `false` on a hosted instance, which hides the store until a key is added), `can_configure` (with `locked`: `true` for a session whose user is an instance admin holding `manage_settings`, never for an API key or OAuth token), `configure_url` with `can_configure` when the admin panel's address is known (the page that takes the key), and `disconnected` with `not_configured` when this workspace still has live purchases, as `{"mailboxes", "domains"}` counts, because their renewals, billing and Google mailbox connections are paused. It also returns `plan_active` (whether the workspace has the paid plan buying needs; always `true` on an instance that does not bill), `metered` (false on an instance that does not bill, where workspaces are charged nothing), `currency`, `mailbox_monthly_micros`, `domain_markup` (`at_cost` when the instance adds nothing to domain prices, otherwise `markup`), `limits` (`mailboxes_per_domain_max` and `mailboxes_per_domain_recommended`), `providers` (`google`, `microsoft`), `balance` (`balance_micros` and the saved `card` brand and last four, or `null`) and the saved `registrant`, or `null`. While `registrant` is `null` it also returns `registrant_prefill`, a draft from the workspace's billing details and its owner for the buyer to confirm. It also returns `default_forwarding_url` (where new domains forward unless the buyer changes it: the workspace's brand website, else the caller's email domain when it is not a free provider, else `""`), `photos` (whether mailbox photos can be uploaded on this instance), `min_card_charge_micros` (the least a store charge puts on the card), `billing_day` (the day of the month, 1 to 28, every mailbox is billed together; `null` before the first mailbox) and `next_bundle`, the next monthly mailbox charge as `{"charge_on", "mailboxes", "amount_micros"}`, or `null` when nothing is due. It never carries domain prices; those come from search and quotes.
|
||||
- `GET /store/domains/search?q=acme&tlds=com,io` returns `query` and `data`: each result's `domain`, `display_name`, `tld`, `available`, `exact`, `years` (the extension's minimum registration term, such as `2` for `.ai`), `price_micros` (the price for those `years`), `renew_micros` (per year) and, for an unavailable one, `reason` (`registered`, `premium`, `reserved` or `tld_unsupported`). A `q` that is not a word or a domain name answers `400` `invalid_query`.
|
||||
- `PUT /store/registrant` saves the registrant a domain is registered to: `first_name`, `last_name`, `organization`, `email`, `phone` (`+CC.NUMBER`), `address1`, `address2`, `city`, `state`, `postal_code` and `country` (ISO 3166-1 alpha-2). A refused field answers `400` `contact_invalid` with `details.fields`.
|
||||
- `POST /store/quotes` answers `201`. It takes `items`: `{"type": "domain", "domain", "years"}` lines, where `years` is the search result's `years`, and `{"type": "mailboxes", "domain", "provider", "mailboxes": [{"local_part", "first_name", "last_name", "admin"}]}` lines. Each mailbox needs both a `first_name` and a `last_name` (1 to 64 characters each; an empty one is `400` `invalid_name`). `admin: true` marks at most one mailbox per line as the domain's Google Workspace or Microsoft 365 admin; without one, the first mailbox is. Leave `admin` out for a domain that already has an admin, or the quote answers `400` `store_items_invalid`. A `mailboxes` line may carry `photo_id`, an uploaded photo for every mailbox on that domain, and each mailbox its own `photo_id`, which wins over the line's. One photo can be named on any number of mailboxes, on one domain or several. A photo the workspace does not have answers `400` `photo_not_found`. Each mailbox may also carry `signature`, `{"html", "plain"}`, the finished signature set on it when it connects, as `PATCH /emails/:id` takes `signature_html` and `signature_plain`. Nothing is filled in on the server, so fill any sender placeholders first; both empty buys the mailbox without a signature. A signature longer than a mailbox keeps (20,000 characters of HTML, 10,000 of plain text), or one for an address the quote does not buy, answers `400` `store_items_invalid`. Google mailboxes also get it as their Gmail signature; Microsoft 365 ones in Warmbly only. A `mailboxes` line with no `domain` line adds mailboxes to a domain the workspace already has in the store: one it bought, or one it connected whose `connection.status` is `active`. Nothing is charged for that domain, and the quote has no domain line for it. A connected domain that is not connected yet answers `409` `domain_not_ready`, and one with records in the way of mail `409` `dns_record_conflict`. A quote with a domain in it needs a saved registrant first (`422` `registrant_required`). The quote holds its prices for 15 minutes (`expires_at`) and returns `id`, `lines` (a mailboxes line adds `admin_email`, the admin mailbox's address, and `nameservers_change`, `true` when the domain is a connected one whose nameservers have to change after the order, to the set shown on the domain), `due_now_micros`, `recurring_monthly_micros`, `yearly_domain_renewal_micros` and `payment`: `balance_micros`, `from_balance_micros`, `card_charge_micros` (at least the minimum card charge, or the automatic reload amount when larger, whenever the balance falls short; `0` when it covers the order), `balance_after_micros` (the balance once the card was charged and the order paid), `card`, `needs_payment_method` and `auto_reload`, the workspace's automatic reload as it will be after the order: `{"enabled", "threshold_micros", "amount_micros", "store_managed"}`, where `store_managed` is a reload the store turns on and keeps sized to the mailboxes until it is changed by hand.
|
||||
- `POST /store/orders` `{"quote_id", "expected_due_now_micros", "forwarding_url", "enable_auto_reload"}` pays the quote from the balance, charging the saved card when it falls short (at least the minimum card charge, the rest staying on the balance), and answers `201` with the order. `enable_auto_reload` (default `true` when the workspace never set automatic reload up) turns the balance's automatic reload on with the first purchase, sized to the mailboxes; `false` leaves it off. `expected_due_now_micros` is the total the buyer was shown. A quote that has expired is priced again; when the total then differs from `expected_due_now_micros`, the answer is `409` `price_changed` with `details.quote`, a fresh quote to show and confirm, and nothing is charged. To go ahead, order again with that quote's `id`, and its `due_now_micros` as `expected_due_now_micros`, once the buyer has confirmed the new total. With no saved card to cover a shortfall it answers `402` `payment_method_required` with `setup_url`, a card-setup page that returns to the dashboard's buy page (an empty string when one could not be made); nothing is charged. A retry with the same `Idempotency-Key` never charges twice. An item the store cannot fulfil is refunded to the balance, exactly that item's line.
|
||||
- An order carries `id`, `status` (`charging`, `processing`, `completed`, `partially_failed` or `failed`), `created_at`, `completed_at`, `due_now_micros`, `charged_micros`, `refunded_micros`, `steps` (`register`, `dns`, `mail_auth`, `mailboxes`, `delegation` and `ready` in that order, each `pending`, `running`, `done`, `failed` or `skipped`, with `at`), and its `domains` and `mailboxes`. An order can stay `charging` for up to about two minutes after the charge when fulfilment did not confirm it at once; it then moves on or is refunded. The `mailboxes` step can stay `running` from a few hours to a couple of days while Google or Microsoft creates the mailboxes; the order moves on by itself, and the workspace is notified when it completes. On a domain the workspace connected, `register` is `skipped`.
|
||||
- A domain carries `id`, `name`, `status` (`registering`, `active`, `expired`, `redemption`, `transferring_out`, `transferred_out`, `failed`, `connecting` or `removed`; treat an unknown value as not ready), `source` (`purchased`, or `connected` for a domain registered elsewhere), `renewable` (a purchased domain that is active or expired: renew, auto-renew and transfer-out apply), `provider`, `expires_at`, `auto_renew`, `renew_micros`, `forwarding_url`, `forwarding_status` (`none`, `pending` or `active`), `mail_auth` (`mx`, `spf`, `dkim`, `dmarc`), `mailbox_count`, `nameservers` (the pair the domain should be delegated to), `connection`, `dns_conflicts`, `owner_verification`, `transfer`, `tracking_host` and `created_at`.
|
||||
- `connection` is `null` on a purchased domain. On a connected one it carries `method` (`nameservers` or `manual`), `status` (`pending`, `active`, `moved` or `expired`), `expires_at` (a pending connection expires 48 hours after it was made), `checked_at` and `current_nameservers` (what public DNS showed at the last check).
|
||||
- `dns_conflicts` lists records that block mail, each with `type`, `name`, `content` and `record_id`: set, the record can be deleted with `DELETE /store/domains/:id/dns/:record_id`; `null`, it has to be removed at the domain's DNS provider. Mailboxes cannot be bought on the domain while the list is not empty.
|
||||
- `owner_verification` is `null` or `{status, email, deadline}`: while `status` is `pending`, the registrant has to confirm `email` before `deadline`. `transfer` is `null` or `{status: "requested", requested_at, auto_approve_at}` when another registrar asked for the domain.
|
||||
- `tracking_host` is the open and click tracking host set up for a purchased domain once its first mailbox connects (`link.` plus the domain), or `""` until then.
|
||||
- `PATCH` takes `auto_renew` and `forwarding_url` (an `https://` address, or empty to stop forwarding; anything else is `400` `forwarding_url_invalid`).
|
||||
- `GET /store/domains/:id` adds `dns`, the domain's records. Each carries `id` (stable per record), `type` (`A`, `AAAA`, `CNAME`, `MX`, `TXT`, `SRV`, `CAA` or another), `name` (relative, `@` is the apex), `content`, `ttl`, `priority` (MX and SRV, otherwise `null`), `managed` (kept by Warmbly for mail and forwarding, so locked) and `purpose` (`mx`, `spf`, `dkim`, `dmarc`, `verification`, `forwarding`, `ownership`, `imported` for a record copied over when the domain was connected, or `custom` for one the workspace added; treat an unknown value as `custom`).
|
||||
- `POST /store/domains/:id/renew` charges and renews the domain for a year now. `POST /store/domains/:id/transfer-out` unlocks the domain and returns its `auth_code`. Both, and `auto_renew`, apply only when `renewable` is `true`; on a connected domain they answer `409` `domain_registered_elsewhere`.
|
||||
- `POST /store/domains/connect` `{"domain": "acme.com", "method": "nameservers"}` adds a domain registered elsewhere and answers `201` with the domain, `dns` included. Nothing is charged. With `method` `nameservers` (recommended), the customer sets the domain's `nameservers` at its registrar with DNSSEC off, and the records the domain serves today are copied over. With `manual`, the customer adds the records in `dns` at the current DNS provider, starting with the one whose `purpose` is `ownership`. A value that is not a domain answers `400` `store_items_invalid`; a domain that cannot be added answers `409` `domain_unavailable` with a top-level `reason`.
|
||||
- `POST /store/domains/:id/connection/check` looks for the nameservers or records now and answers with the domain; Warmbly also checks on its own, every 30 seconds at first. After a connection reaches `expired`, `POST /store/domains/:id/connection/regenerate` issues a new pair of nameservers or a new ownership record and answers with the domain, `dns` included. Each `connection.status`, nameserver or conflict change also arrives as a `STORE_DOMAIN_UPDATED` event.
|
||||
- `DELETE /store/domains/:id` removes a connected domain and answers `204`. A domain that still has mailboxes answers `409` `domain_in_use`, and a purchased one `409` `domain_registered_here` (it leaves by transfer-out).
|
||||
- `POST /store/domains/:id/dns` `{"type", "name", "content", "ttl", "priority"}` adds a record and answers `201` with it (`ttl` and `priority` are optional). `PATCH /store/domains/:id/dns/:record_id` takes any of `name`, `content`, `ttl` and `priority`, and answers with the record; its `type` is fixed. `DELETE /store/domains/:id/dns/:record_id` answers `204`. A `managed` record answers `409` `dns_record_managed`, a record that clashes with a mail record `409` `dns_record_conflict`, a malformed one `400` `dns_record_invalid`, a domain connected with `manual` (its DNS provider holds the zone) `409` `dns_not_hosted`, and an unknown record `404`.
|
||||
- `POST /store/domains/:id/dns/check` looks every record up in public DNS and answers `{"nameservers": [...], "records": [...]}`: the nameservers that answered, and each record with a `status` of `ok` or `missing`. It changes nothing.
|
||||
- A mailbox carries `id`, `email`, `domain_id`, `provider`, `status`, `first_name`, `last_name`, `is_admin` (the domain's Google Workspace or Microsoft 365 admin), `paused` (campaign sending and warmup are paused because the workspace has no active plan; the mailbox still syncs and keeps billing), `monthly_micros`, `paid_through`, `cancels_at`, `cancelled_at` (when a mailbox that ended was switched off in Warmbly, or `null`), `email_account_id` (the connected mailbox, once there is one), `connect_state` (`waiting`, `connecting`, `connected` or `failed`), `photo` (`none`, `pending` or `set`) and `created_at`. `PATCH` takes `first_name` and `last_name` (a refused name is `400` `invalid_name`). `DELETE` cancels it at the end of the paid month and answers with `cancels_at` set; `POST .../resume` clears it.
|
||||
- `POST /store/photos` uploads a profile photo for purchased mailboxes and answers `201` `{"id", "created_at"}`. Send the image as the multipart field `file` (PNG or JPG, up to 2 MB and 2048 px on each side; it is stored as a JPEG), or the JSON body `{"from": "profile"}` to copy the caller's own uploaded profile photo (`404` `profile_photo_missing` when there is none). A refused image answers `400` (`image_unreadable`, `image_format_not_allowed`, `image_too_large`, `image_dimensions_too_large` or `photo_invalid`), more than 200 uploads in a day `429` `photo_limit_reached`, and an instance without file storage `503` `photo_storage_unavailable`. Photos are private to the workspace; one no order or mailbox uses is deleted after 24 hours. `GET /store/photos/:id` answers the JPEG itself, for a preview.
|
||||
- `PUT /store/mailboxes/:id/photo` `{"photo_id"}` makes an uploaded photo the mailbox's Google or Microsoft profile picture and answers with the mailbox. It is sent to the provider at once and retried in the background when the provider does not take it; the mailbox's `photo` reads `none`, `pending` (chosen, not taken yet) or `set`. A photo cannot be removed, only replaced. A mailbox that has ended answers `409` `store_state_conflict`, an unknown photo `400` `photo_not_found`. Photos named on an order's mailbox lines are set the same way as soon as each mailbox exists.
|
||||
- `POST /store/mailboxes/:id/sign-in` answers `{"email", "username", "password", "login_url", "admin_console_url"}`, a fresh sign-in each time, with `Cache-Control: no-store`. For the admin mailbox it is the Google Workspace or Microsoft 365 admin sign-in and `admin_console_url` is set; otherwise `admin_console_url` is `null`. Show it once and do not keep it. A mailbox with no sign-in to show answers `409` `sign_in_unavailable`. Each call is audited.
|
||||
- A mailbox bought here is an ordinary connected mailbox once it is set up. `GET /emails`, `GET /emails/:id` and every other mailbox read carry `purchased: true` for it, and `purchase_cancelled_at` once its subscription ended (absent while it is live).
|
||||
- While a purchased mailbox is live (not cancelled or failed), `DELETE /emails/:id`, `POST /emails/bulk/delete` (per row) and the reconnect routes (`/emails/onboarding/oauth/reauth/:id`, `/emails/onboarding/smtp-imap/:id`, `/emails/onboarding/app-password/:id`) answer `403` `purchased_mailbox`. Cancel it with `DELETE /store/mailboxes/:id` instead, or switch it off with `PATCH /emails/:id` to pause it. Once it is cancelled it is switched off in Warmbly and can be deleted like any other mailbox.
|
||||
|
||||
List routes return `data` and `pagination` with an opaque cursor; a bad `cursor` or a `limit` outside 1 to 100 answers `400` (`invalid_cursor`, `invalid_limit`). Order, domain and mailbox changes reach the dashboard live as `STORE_ORDER_UPDATED`, `STORE_DOMAIN_UPDATED` and `STORE_MAILBOX_UPDATED` events, which members with `manage_emails` receive. Each carries `org_id`, `id` and `status`; a mailbox event adds `domain_id`, `email_account_id` once it is connected, and `connect_state`. Every store error code is listed under [domain and mailbox store refusals](/api/error-codes/#domain-and-mailbox-store-refusals).
|
||||
|
||||
### Campaigns and sequences
|
||||
|
||||
Campaigns, steps and activity logs are scoped to the selected organization for session callers and the key's organization for API-key callers. Access depends on the permissions below, regardless of who created the campaign. Step updates and deletes also require the step to belong to the campaign in the URL. Campaign analytics, including daily, hourly and comparison endpoints, use this same organization boundary and require `READ_ANALYTICS` (or **View analytics** for session callers).
|
||||
@@ -409,6 +479,8 @@ The `/unibox/drafts` endpoints hold autosaved compose drafts, scoped to the call
|
||||
|
||||
The `/emails/client-links` routes manage [client connect links](/guides/agencies/#client-connect-links), each with JWT permission `MANAGE_EMAILS`. `POST /emails/client-links` takes `label` (optional), `providers` (any of `gmail`, `outlook`, `smtp_imap` and `vendor`, an [inbox vendor account](/guides/agencies/#client-connect-links) the client names), `max_mailboxes` (1 to 500), `expires_in_days` (1 to 90, default 7), `tag_ids` (up to 20 of the workspace's mailbox tags) and `warmup`, and answers `201` with the `link` and its `url`, on the agency's verified portal domain when it has one, else on `PORTAL_DOMAIN` (`503 client_links_unavailable` without it). The URL appears in that response only; send an `Idempotency-Key` so a retry replays it instead of minting a second link. `GET /emails/connect-links` lists links newest first with their `status` (`active`, `expired`, `revoked`, `exhausted`) and `mailboxes_connected`, paginated with `cursor` and `limit` (1 to 100). `GET /emails/connect-links/:id/uses` lists the mailboxes a link connected. `POST /emails/connect-links/:id/revoke` turns a link off; a repeat returns the revoked link, so it needs no `Idempotency-Key`.
|
||||
|
||||
`GET /emails/partner` lists, in a workspace a [partner](/development/partners/) manages, each mailbox's `enablement` (`sending_warmup`, `warmup_only` or `off`) and whether the partner holds it (`managed`). The partner sets both; in any other workspace the list is empty.
|
||||
|
||||
`GET /emails/allowance` reports how many mailboxes the workspace holds (`used`), how many it may hold (`allowance`, `null` for unlimited), `remaining`, and the `basis` of the number: `fair_use` (the plan's daily sends divided by `sends_per_mailbox`), `plan`, `override` (an approved request), `free` (no paid plan: `0`, or `10` for a workspace that kept the earlier free plan), or `unlimited`. `pending_request` is the open limit-increase request for mailboxes, if any. Every connect path refuses with `mailbox_allowance_reached` once `remaining` is `0`. See [mailbox allowance](/guides/mailboxes/#mailbox-allowance).
|
||||
|
||||
`GET /emails/:id/identity` reports which addresses the mailbox's provider will let it send as, which one it uses, and whether its signature was imported or written here; it contacts no provider. `POST /emails/:id/identity/refresh` re-reads that list from the provider and stores it, and with `import_signature` also replaces the stored signature with the one configured at the provider. Storing the list is what a `send_as_email` choice is validated against, so the refresh needs `WRITE_EMAILS` rather than `READ_EMAILS`; it takes no `Idempotency-Key` because it writes exactly what the provider currently says. Gmail only. See [sending identity](/guides/mailboxes/#sending-identity).
|
||||
@@ -734,7 +806,9 @@ These changes require the session to have confirmed the account holder within th
|
||||
| Connect, re-key or remove an inbox vendor account an agency holds | `POST /agency/:agencyId/vendors`, `PATCH /agency/:agencyId/vendors/:id`, `DELETE /agency/:agencyId/vendors/:id` |
|
||||
| Schedule a workspace or account for deletion | `POST /organization/current/danger-zone/delete`, `POST /me/danger-zone/delete` |
|
||||
| Approve a self-hosted instance's warmup pool link (always refused with `403` `pool_link_closed`) | `POST /pool-link/codes/:code/approve` |
|
||||
| Start a checkout, open the billing portal, change or cancel the plan, add money to the balance, save a card, change automatic reload or AI spend controls | `POST /subscription/checkout`, `POST /subscription/portal`, `POST /subscription/change-plan`, `POST /subscription/cancel`, `POST /subscription/balance/top-up`, `POST /subscription/balance/checkout`, `POST /subscription/balance/payment-method`, `PATCH /subscription/balance/auto-reload`, `PATCH /subscription/credits/settings`, `POST /pool-link/checkout` (the retired Warmup plan's checkout, which always refuses with `409` `warmup_plan_retired`), `POST /subscription/offers/:planId/checkout` |
|
||||
| Start a checkout, open the billing portal, change or cancel the plan, add money to the balance, save a card, change automatic reload or AI spend controls | `POST /subscription/checkout`, `POST /subscription/portal`, `POST /subscription/change-plan`, `POST /subscription/cancel`, `POST /subscription/balance/top-up`, `POST /subscription/balance/checkout`, `POST /subscription/balance/payment-method`, `POST /subscription/balance/setup-intent`, `POST /subscription/balance/setup-intent/default`, `PATCH /subscription/balance/auto-reload`, `PATCH /subscription/credits/settings`, `POST /pool-link/checkout` (the retired Warmup plan's checkout, which always refuses with `409` `warmup_plan_retired`), `POST /subscription/offers/:planId/checkout` |
|
||||
| Pay for domains and mailboxes, renew a domain or change its auto-renew, cancel or resume a purchased mailbox, get a domain's transfer code | `POST /store/orders`, `POST /store/domains/:id/renew`, `PATCH /store/domains/:id` (with `auto_renew`), `DELETE /store/mailboxes/:id`, `POST /store/mailboxes/:id/resume`, `POST /store/domains/:id/transfer-out` |
|
||||
| Show a purchased mailbox's sign-in, which for a domain's admin mailbox opens its whole Google Workspace or Microsoft 365 account | `POST /store/mailboxes/:id/sign-in` |
|
||||
| Reveal or rotate a signing secret | `POST /webhooks/:id/rotate-secret`, `GET /integrations/connections/:id/webhook-secret`, `POST /oauth/applications/:id/rotate-secret`, `GET /oauth/applications/:id/webhook-secret`, `POST /oauth/applications/:id/webhook-secret/rotate` |
|
||||
| Record, use or remove an admin grant over a whole domain | `POST /emails/grants/google/finish`, `POST /emails/grants/microsoft/finish`, `POST /emails/grants/:id/connect`, `DELETE /emails/grants/:id` |
|
||||
| Admin panel: issue a fleet join token, change the worker fleet's size cap, grant admin permissions, export or import any workspace, issue a tester a new password, change a login-code exemption | `POST /admin/fleet/join-token`, `PATCH /admin/fleet/scale`, `POST /admin/admins/:userId/grant`, `POST /admin/organizations/:id/exports`, `POST /admin/organizations/:id/imports`, `POST /admin/testers/:id/password`, `PUT /admin/users/:id/login-code-exempt` |
|
||||
@@ -935,6 +1009,7 @@ Besides a signed-in session, the routes in the first rows of the table below acc
|
||||
|-----------------------|--------|
|
||||
| `AGENCY_READ` | `GET /agency` (its own agency only), `GET /agency/plans`, `GET /agency/:agencyId`, `GET /agency/:agencyId/members`, `GET /agency/:agencyId/clients`, `GET /agency/:agencyId/overview`, `GET /agency/:agencyId/mailboxes`, `GET /agency/:agencyId/brand` |
|
||||
| `AGENCY_READ` and `READ_UNIBOX` | `GET /agency/:agencyId/inbox`, `/inbox/thread`, `/inbox/messages/:messageId` |
|
||||
| `AGENCY_READ` and `READ_STORE` | `GET /agency/:agencyId/store` |
|
||||
| `AGENCY_MANAGE_CLIENTS` | `POST /agency/:agencyId/clients`, `POST /agency/:agencyId/clients/attach`, `PATCH` and `DELETE /agency/:agencyId/clients/:orgId` |
|
||||
| `AGENCY_READ_USAGE` | `GET /agency/:agencyId/usage`, `GET /agency/:agencyId/ai-balance` |
|
||||
| `AGENCY_TRANSFER_AI` | `POST /agency/:agencyId/clients/:orgId/ai-balance` |
|
||||
@@ -982,6 +1057,7 @@ A key passes the recent-confirmation check the session routes ask for, since it
|
||||
| POST/DELETE | `/agency/:agencyId/brand/icon` | Owner, admin: the square browser tab icon. Multipart `file`, PNG up to 1 MB and 512px on each side |
|
||||
| POST/DELETE | `/agency/:agencyId/brand/sign-in-image` | Owner, admin: the image on the portal's sign-in page. Multipart `file`, PNG or JPG up to 4 MB and 2560px on each side |
|
||||
| GET | `/agency/:agencyId/mailboxes` | Staff: [mailboxes across the clients](/guides/agencies/#mailboxes-across-clients) whose mailbox list the caller reads, newest first, as `data` plus `pagination`. Each carries `organization_id`, `client`, `email`, `name`, `provider`, `status`, `erroring`, `warmup`, `warmup_state` (`watch`, `throttled`, `quarantined` or `blocked` when held), `vendor`, `campaign_limit` and `created_at`. Filters: `client` (comma-separated workspace ids; one that is not a client answers `404 agency_client_not_found`), `attention=true` (disconnected, erroring or held), `q` (part of an address), `limit` (1 to 200, default 50) and `cursor` |
|
||||
| GET | `/agency/:agencyId/store` | Staff: the [purchased infrastructure](/guides/buy-mailboxes/#for-agencies) across the clients where the caller's own membership holds `manage_emails`. See [purchased infrastructure across clients](#purchased-infrastructure-across-clients) |
|
||||
| GET | `/agency/:agencyId/vendors` | Staff, session only: the [inbox vendor accounts the agency holds](/guides/agencies/#vendor-accounts-held-by-the-agency) as `data`, each with `vendor`, `label`, `status`, `mailboxes` and the `clients` it is used in, never a key; and `catalog`, the supported vendors and what each asks for |
|
||||
| POST | `/agency/:agencyId/vendors` | Owner, admin, session only: `vendor`, `fields` (its API key) and an optional `label`. The key is verified with the vendor before it is stored. Accepts `Idempotency-Key`: send the same key again on a retry, or an account is connected twice |
|
||||
| PATCH | `/agency/:agencyId/vendors/:id` | Owner, admin, session only: `label`, and `fields` to replace the key, which every client that uses the account reads from then on |
|
||||
@@ -1004,6 +1080,42 @@ A key passes the recent-confirmation check the session routes ask for, since it
|
||||
|
||||
`POST /agency`, the client creates, adding staff, every checkout, creating an API key and moving AI balance honor `Idempotency-Key`; a move retried with the same key moves the money once. The other writes set a value, so a retry lands on the same state. Moving AI balance, like the billing routes and creating, editing or revoking an agency API key, asks a session for a [recent confirmation](#actions-that-need-a-recent-confirmation). On an instance without billing (`BILLING_PROVIDER=none`) the billing routes and moving AI balance answer `503 agency_billing_disabled`, the pool has no cap and AI is not charged. `GET /organization/current` carries `agency` (`id`, `name`, `can_leave`) on a client workspace, `GET /organization` carries the same `agency` on each membership row whose workspace is a client, and that workspace's `POST /subscription/checkout` answers `409 agency_billed`.
|
||||
|
||||
#### Purchased infrastructure across clients
|
||||
|
||||
`GET /agency/:agencyId/store` sums up what the [store](#domains-and-mailboxes) holds in each client workspace, for the clients where the caller's own membership holds `manage_emails`. A session on the agency's staff can call it, and so can an agency key with `AGENCY_READ` and `READ_STORE`. Money is micro-USD.
|
||||
|
||||
```json
|
||||
{
|
||||
"enabled": true,
|
||||
"clients": [
|
||||
{
|
||||
"organization_id": "2f6b…",
|
||||
"name": "Acme",
|
||||
"avatar_url": "",
|
||||
"domains": 3,
|
||||
"mailboxes_live": 9,
|
||||
"mailboxes_connected": 8,
|
||||
"monthly_spend_micros": 27000000,
|
||||
"renewals_30d": 1,
|
||||
"next_renewal": {"domain_id": "8c1d…", "domain": "getacme.com", "expires_at": "2026-12-04T00:00:00Z", "auto_renew": true},
|
||||
"orders_open": 0,
|
||||
"attention": [{"kind": "connect_failed", "count": 1}]
|
||||
}
|
||||
],
|
||||
"renewals": [
|
||||
{"organization_id": "2f6b…", "organization_name": "Acme", "domain_id": "8c1d…", "domain": "getacme.com", "expires_at": "2026-12-04T00:00:00Z", "auto_renew": true, "renew_micros": 11170000}
|
||||
],
|
||||
"totals": {"domains": 3, "mailboxes_live": 9, "monthly_spend_micros": 27000000, "renewals_30d": 1, "attention": 1}
|
||||
}
|
||||
```
|
||||
|
||||
- `monthly_spend_micros` is what the client's live mailboxes cost each month. `next_renewal` is the client's soonest domain renewal, or `null`.
|
||||
- `attention` counts what needs a person, by `kind`: `connect_failed` (a purchased mailbox that could not be connected), `billing_failed` (a mailbox month not paid), `renewal_failed` (a domain renewal not paid), `auto_renew_off` (a domain with auto-renew turned off) and `order_failed`. Treat an unknown `kind` as needing attention.
|
||||
- `renewals` lists domain renewals across the clients in the next 30 days, soonest first, at most 50.
|
||||
- `enabled` is `false` when the instance has no store; the lists are then empty.
|
||||
|
||||
To act on a client's store, switch to its workspace (`organization_id`) and use the `/store` routes, or, with an agency key, send them with `Warmbly-Organization`. In the dashboard the client's purchased domains are on `/app/emails/domains?tab=purchased`, its mailboxes on `/app/emails`, and its orders on `/app/emails/buy/orders`.
|
||||
|
||||
#### Portal theme
|
||||
|
||||
The agency's [portal theme](/guides/white-label/#portal-theme) is the `theme` object on its brand, plus two uploaded images. It is available on every agency plan. Every `theme` field is optional, and an empty string or a missing field means the default:
|
||||
@@ -1064,24 +1176,27 @@ The workspace balance, adding money, automatic reload, spend controls, the activ
|
||||
|
||||
| Method | Path | JWT permission |
|
||||
|--------|------|----------------|
|
||||
| GET | `/subscription/balance` | `manage_billing` |
|
||||
| GET | `/subscription/balance` (optional `include=burn`) | `manage_billing` |
|
||||
| POST | `/subscription/balance/top-up` | `manage_billing` |
|
||||
| POST | `/subscription/balance/checkout` | `manage_billing` |
|
||||
| POST | `/subscription/balance/payment-method` | `manage_billing` |
|
||||
| POST | `/subscription/balance/setup-intent` | `manage_billing` |
|
||||
| POST | `/subscription/balance/setup-intent/default` | `manage_billing` |
|
||||
| PATCH | `/subscription/balance/auto-reload` | `manage_billing` |
|
||||
| GET | `/subscription/balance/invoices` | `manage_billing` |
|
||||
| GET | `/subscription/credits` | `manage_billing` |
|
||||
| GET | `/subscription/credits/transactions` | `manage_billing` |
|
||||
| GET | `/subscription/credits/transactions` (optional `category=store`) | `manage_billing` |
|
||||
| GET | `/subscription/credits/usage` | `manage_billing` |
|
||||
| GET | `/subscription/credits/settings` | `manage_billing` |
|
||||
| PATCH | `/subscription/credits/settings` | `manage_billing` |
|
||||
|
||||
- `GET /subscription/balance` is everything the Balance tab shows: `balance_usd`, `monthly_usd`, `purchased_usd`, `monthly_allowance_usd`, `monthly_used_usd`, `next_reset_at`, the saved card (`payment_method`), `auto_reload`, `low_balance_usd`, `charge_in_progress`, and the `top_up` bounds and presets. On an [agency](/guides/agencies/#the-shared-ai-balance) client it adds `agency_usd`, what the agency's shared AI balance would pay once the workspace's own runs out (absent when that is nothing). On a deployment with `BILLING_PROVIDER=none` it answers only `{"unlimited": true}`.
|
||||
- `GET /subscription/balance` is everything the Balance tab shows: `balance_usd`, `monthly_usd`, `purchased_usd`, `monthly_allowance_usd`, `monthly_used_usd`, `next_reset_at`, the saved card (`payment_method`), `auto_reload`, `low_balance_usd`, `charge_in_progress`, the `top_up` bounds and presets, and, only with `?include=burn`, `burn`: what the balance pays for a day (`per_day_usd`, split into `mailboxes_per_day_usd`, `renewals_per_day_usd` and `ai_per_day_usd`), with `mailboxes_monthly_usd`, `renewals_due_usd` (auto-renewing domains charged in the next 60 days) and the mailboxes' `billing_day` (null before the first one). With Stripe billing it also carries `stripe_publishable_key`, which the page loads Stripe.js with to save a card in place. Mailboxes count a month's price over 30 days, each renewal its price over the days until it is charged, and AI its average over the last 30 days. On an [agency](/guides/agencies/#the-shared-ai-balance) client it adds `agency_usd`, what the agency's shared AI balance would pay once the workspace's own runs out (absent when that is nothing). On a deployment with `BILLING_PROVIDER=none` it answers only `{"unlimited": true}`.
|
||||
- `POST /subscription/balance/top-up` `{"amount_usd": 25}` charges the saved card now (from $5 to $5,000) and is billed as a Stripe invoice. It answers `200` with `status` `paid`, or `202` with `status` `processing` and `charge_in_progress` `true` while the payment is still going through and Warmbly finishes it in the background. It honors `Idempotency-Key`; without one, a retry while the first payment is pending answers `409` `charge_in_progress`, so it never charges twice. A decline answers `402` with `card_declined`, `authentication_required` or `payment_failed`, which tells a client to offer Checkout instead; no saved card is `409` `payment_method_required`, and another payment still going through is `409` `charge_in_progress`. Needs an active paid plan.
|
||||
- `POST /subscription/balance/checkout` `{"amount_usd": 25}` returns a Stripe Checkout `checkout_url` for the amount; the payment saves the card for next time. `POST /subscription/balance/payment-method` returns a Checkout `checkout_url` that saves or replaces the card without charging it. Money is added only in the Stripe webhook, never in the call, and exactly once.
|
||||
- `POST /subscription/balance/checkout` `{"amount_usd": 25}` returns a Stripe Checkout `checkout_url` for the amount; the payment saves the card for next time. `POST /subscription/balance/payment-method` returns a Checkout `checkout_url` that saves or replaces the card without charging it. `POST /subscription/balance/setup-intent` saves a card without leaving the page instead: it answers `client_secret` (a Stripe SetupIntent on the workspace's customer, for off-session charges, card only) and `publishable_key`, which the dashboard hands to Stripe.js to confirm, 3-D Secure included. `POST /subscription/balance/setup-intent/default` `{"setup_intent_id": "seti_..."}` then makes the confirmed card the workspace's default, replacing an older one, before anything is charged; it answers `204`, `404` for a SetupIntent that is not on the workspace's customer and `409` for one that has not succeeded, and a retry sets the same default. Money is added only in the Stripe webhook, never in the call, and exactly once.
|
||||
- `PATCH /subscription/balance/auto-reload` takes `enabled`, `threshold_usd` ($0.01 to $1,000), `amount_usd` ($5 to $5,000, more than the threshold) and `monthly_limit_usd` (at least the amount, at most $50,000), and answers with the same body as `GET /subscription/balance`. An amount not above the threshold is `422` `recharge_too_small`, a monthly limit out of range is `422` `monthly_limit_too_small`, and turning it on with no saved card is `409` `payment_method_required`.
|
||||
- `GET /subscription/balance/invoices` returns `data`: the latest Stripe invoices for the workspace, subscription and balance alike, each with `kind` (`subscription`, `top_up` or `auto_reload`), `status`, `amount_cents`, `currency`, `hosted_url` and `pdf_url`.
|
||||
- `GET /subscription/credits`, `/credits/transactions`, `/credits/usage` and `/credits/settings` keep their legacy credit fields for older clients and carry the dollar figures next to them: `balance_usd`, `monthly_usd`, `purchased_usd`, `monthly_allowance_usd` and `total_purchased_usd` on the balance; `amount_usd`, `cost_usd` (the provider price before the markup), `input_tokens`, `output_tokens`, `quantity`, `balance_after_usd` and `agency_delta_usd` (the part of the amount the agency's shared AI balance paid, or got back) on each transaction; `spent_today_usd`, `spent_week_usd`, `spent_month_usd`, the `limit_*_usd` caps and `amount_usd` on each `series` and `by_reason` or `by_model` entry in usage; and the `spend_limit_*_usd`, `member_limit_*_usd` and `low_balance_usd` settings, which `PATCH /subscription/credits/settings` also accepts. `GET /subscription/credits` carries `unlimited` (boolean): `true` on a deployment with `BILLING_PROVIDER=none`, where the balance is bypassed and every amount is zero and meaningless.
|
||||
- `GET /subscription/credits`, `/credits/transactions`, `/credits/usage` and `/credits/settings` keep their legacy credit fields for older clients and carry the dollar figures next to them: `balance_usd`, `monthly_usd`, `purchased_usd`, `monthly_allowance_usd` and `total_purchased_usd` on the balance; `amount_usd`, `cost_usd` (the provider price before the markup), `input_tokens`, `output_tokens`, `quantity`, `balance_after_usd` and `agency_delta_usd` (the part of the amount the agency's shared AI balance paid, or got back) on each transaction; `spent_today_usd`, `spent_week_usd`, `spent_month_usd`, `ai_from_balance_month_usd` (what metered usage took from money the workspace added this calendar month), the `limit_*_usd` caps and `amount_usd` on each `series` and `by_reason` or `by_model` entry in usage; and the `spend_limit_*_usd`, `member_limit_*_usd`, `low_balance_usd`, `ai_overage_enabled` and `ai_overage_monthly_limit_usd` settings, which `PATCH /subscription/credits/settings` also accepts. `GET /subscription/credits` carries `unlimited` (boolean): `true` on a deployment with `BILLING_PROVIDER=none`, where the balance is bypassed and every amount is zero and meaningless.
|
||||
- `GET /subscription/credits/transactions?category=store` returns only the [store](#domains-and-mailboxes) lines of the ledger (domain registrations, mailbox months, renewals and their refunds), in the same shape and with the same paging as without it. Any other `category` answers `400` `invalid_category`.
|
||||
|
||||
`POST /subscription/credits/checkout`, which bought a fixed credit pack, is removed; add money with `POST /subscription/balance/top-up` or `/balance/checkout` instead.
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ Admission denial before dispatch releases the send reservation without spending
|
||||
|------|-------|-------------|
|
||||
| 400 | Bad Request | Invalid request syntax or parameters, or a quota that would be passed (`storage_limit_reached`) |
|
||||
| 401 | Unauthorized | Missing or invalid authentication |
|
||||
| 402 | Payment Required | The workspace balance is too low (`insufficient_credits`), a card was not charged when adding money (`card_declined`, `authentication_required`, `payment_failed`), or no free placement tests left this month (`placement_quota_exceeded`, `placement_not_entitled`) |
|
||||
| 402 | Payment Required | The workspace balance is too low (`insufficient_credits`), the plan's included AI usage is used up and the workspace keeps its balance for other charges (`ai_allowance_used`) or AI reached the workspace's monthly limit on using the balance (`ai_overage_limit_reached`), a card was not charged when adding money (`card_declined`, `authentication_required`, `payment_failed`), or no free placement tests left this month (`placement_quota_exceeded`, `placement_not_entitled`) |
|
||||
| 403 | Forbidden | Authenticated but lacks permission, the workspace's mailbox allowance is full (`mailbox_allowance_reached`), or new contacts would pass its contact limit (`contact_limit_reached`) |
|
||||
| 404 | Not Found | Resource doesn't exist |
|
||||
| 409 | Conflict | Resource already exists |
|
||||
@@ -785,6 +785,78 @@ A session signed in on an agency's [portal domain](/guides/white-label/#where-cl
|
||||
|--------|--------|---------|
|
||||
| `action_provider_mismatch` | 400 | `POST /automations`, `PATCH /automations/:id` or `POST /integrations/connections/:id/events` paired an action with a connection whose provider does not run it, such as a Slack message on a HubSpot connection. Each action runs only on the integration it belongs to; the provider's actions are listed under `capability.actions` in `GET /integrations/catalog` |
|
||||
|
||||
#### Domain and mailbox store refusals
|
||||
|
||||
The [Buy mailboxes](/guides/buy-mailboxes/) routes (`/store/*`, see [domains and mailboxes](/api/endpoints/#domains-and-mailboxes)) answer these codes, in the usual `{error, message, code, request_id}` shape. Nothing is charged when one of them comes back from `POST /store/quotes` or `POST /store/orders`, except where a row says so, and nothing changes when one comes back from any other store route.
|
||||
|
||||
| `code` | Status | Meaning |
|
||||
|--------|--------|---------|
|
||||
| `contact_invalid` | 400 | The registrant is incomplete or a field is malformed: `phone` must be `+CC.NUMBER` and `country` an ISO 3166-1 alpha-2 code. `details.fields` names the refused fields |
|
||||
| `store_items_invalid` | 400 | The quote's `items` are empty, too many, or malformed: an unknown `type` or `provider`, a domain name that is not one, mailbox names that cannot be used, more than one `admin` mailbox on a line, `admin` on a domain that already has an admin, or a mailbox `signature` with an unknown `template`, a phone or website that cannot be used, or an address the quote does not buy. `POST /store/domains/connect` answers it for a `domain` that is not a domain name. The `message` says which |
|
||||
| `invalid_query` | 400 | `GET /store/domains/search` with a `q` that is not a word or a domain name |
|
||||
| `invalid_cursor` | 400 | A store list route was sent a `cursor` it did not issue |
|
||||
| `invalid_limit` | 400 | A store list route was sent a `limit` outside 1 to 100 |
|
||||
| `forwarding_url_invalid` | 400 | `forwarding_url` is not a full `https://` address |
|
||||
| `local_part_invalid` | 400 | A mailbox address (the part before `@`) is empty, too long, or uses characters an address cannot hold. Use letters, digits, dots, dashes or underscores |
|
||||
| `invalid_name` | 400 | A mailbox's first or last name broke the naming rules, or one of them is empty: every mailbox needs both. See [name refusals](#name-refusals) |
|
||||
| `dns_record_invalid` | 400 | `POST /store/domains/:id/dns` or `PATCH .../dns/:record_id` with a record that cannot be published: check its `type`, `name`, `content`, `ttl` and, for MX and SRV, `priority` |
|
||||
| `payment_method_required` | 402 | `POST /store/orders` when the balance does not cover the order and the workspace has no saved card. The body carries `setup_url`, a card-setup page that returns to the dashboard's buy page (an empty string when one could not be made); order again from a fresh quote afterwards |
|
||||
| `card_declined` | 402 | The saved card was refused while covering the order's shortfall. Nothing is charged |
|
||||
| `authentication_required` | 402 | The card's bank asked to confirm the payment, which cannot happen on a saved card. Nothing is charged |
|
||||
| `payment_failed` | 402 | The saved card could not be charged for another reason. Nothing is charged |
|
||||
| `insufficient_balance` | 402 | The balance cannot cover the order or a renewal and no card could cover the rest |
|
||||
| `plan_required` | 402 | `POST /store/quotes`, `POST /store/orders` or `POST /store/domains/connect` from a workspace without an active paid plan, which buying needs. `GET /store/status` shows it in advance as `plan_active: false`. Choose a plan under **Settings > Billing** and try again. An instance that does not bill its users, the self-host default, never answers it |
|
||||
| `reauth_required` | 403 | The change needs a recent confirmation: paying, renewing, transferring out, cancelling or resuming a mailbox, showing a mailbox's sign-in, or changing a domain's `auto_renew`. Confirm with `POST /auth/reauth` and retry. Only a dashboard session gets it; an API key or OAuth token passes this check |
|
||||
| `store_managed_by_partner` | 403 | A write to the store from a workspace a partner manages. Its domains and mailboxes are bought through the partner, and `GET /store/status` answers `enabled: false` |
|
||||
| `store_disabled` | 404 | The instance has no GraphKit API key configured, so nothing can be bought or changed. The message says an instance admin adds the key under **Setup and health > Integrations** in the admin panel. `GET /store/status` answers `enabled: false` with `reason: not_configured` instead, and the list reads keep answering |
|
||||
| `store_configured_by_environment` | 409 | `PUT`, `DELETE /admin/store/connection` or `POST /admin/store/connection/test` while `GRAPHKIT_API_KEY` (or `GRAPHKIT_API_URL=fake`) is set. The environment takes precedence; change it there |
|
||||
| `store_sealing_unavailable` | 409 | `PUT /admin/store/connection` on an instance without `CREDENTIALS_ENCRYPTION_KEY`. The GraphKit API key is stored sealed under it, so set it first |
|
||||
| `graphkit_url_invalid` | 400 | The GraphKit API URL given to `/admin/store/connection` is not an `https` address |
|
||||
| `graphkit_key_required` | 400 | `PUT` or `POST /admin/store/connection/test` with no API key, and none stored |
|
||||
| `graphkit_key_reentry_required` | 400 | `PUT` or `POST /admin/store/connection/test` with a different API URL from the stored one and no API key. The stored key is only sent to the URL it was saved with; enter it again |
|
||||
| `graphkit_key_rejected` | 400 | GraphKit refused the API key when it was tested or saved. Nothing was stored |
|
||||
| `graphkit_unreachable` | 503 | GraphKit could not be reached at the API URL when the key was tested or saved. Nothing was stored |
|
||||
| `quote_not_found` | 404 | `POST /store/orders` with a `quote_id` this workspace does not hold: never issued to it, or expired long enough ago to be cleared. Request a new quote |
|
||||
| `price_changed` | 409 | `POST /store/orders` when the total, priced again for an expired quote, differs from `expected_due_now_micros`. Nothing is charged. `details.quote` is a fresh quote at the current prices: show its total and, once the person confirms, order again with its `id` |
|
||||
| `payment_processing` | 409 | The card payment for the shortfall has not settled yet. Nothing was ordered; try again in a minute |
|
||||
| `charge_in_progress` | 409 | Another payment for this workspace is still going through, or `POST /store/mailboxes/:id/resume` while the mailbox's own monthly payment is. Try again in a minute |
|
||||
| `domain_unavailable` | 409 | The domain was registered by someone else after the search, or cannot be registered. Pick another. From `POST /store/domains/connect`, the body carries a top-level `reason` when one is known: `already_added` (the domain is already in this workspace), `registered` (another workspace bought it here) or `connected_elsewhere` (another workspace is connecting it) |
|
||||
| `domain_registered_elsewhere` | 409 | Renewing, transferring out or changing `auto_renew` on a domain the workspace connected. It is registered elsewhere, so renew or transfer it at its registrar |
|
||||
| `domain_registered_here` | 409 | `DELETE /store/domains/:id` on a domain bought here. A purchased domain leaves by `POST /store/domains/:id/transfer-out` |
|
||||
| `domain_in_use` | 409 | `DELETE /store/domains/:id` on a connected domain that still has mailboxes. Cancel them first |
|
||||
| `dns_record_conflict` | 409 | From a DNS write: the record clashes with one Warmbly keeps for mail, so change its name or type. From a quote or order: the domain has records in the way of mail, listed in its `dns_conflicts`; remove them first |
|
||||
| `dns_record_managed` | 409 | Editing or deleting a `managed` DNS record, which Warmbly keeps for mail delivery and forwarding |
|
||||
| `dns_not_hosted` | 409 | A DNS write on a domain connected with `method` `manual`. Its DNS provider holds the records, so change them there |
|
||||
| `sign_in_unavailable` | 409 | `POST /store/mailboxes/:id/sign-in` for a mailbox that has no sign-in to show |
|
||||
| `photo_invalid` | 400 | `POST /store/photos`: the upload is not a PNG or JPG photo the store can use (up to 2 MB and 2048 px on each side) |
|
||||
| `photo_not_found` | 400 | A quote's `photo_id`, or `PUT /store/mailboxes/:id/photo`, names a photo this workspace does not have, or one deleted because nothing used it for 24 hours. Upload it again |
|
||||
| `profile_photo_missing` | 404 | `POST /store/photos` with `{"from": "profile"}` when the caller has no uploaded profile photo |
|
||||
| `photo_limit_reached` | 429 | More than 200 photos uploaded in a day |
|
||||
| `photo_storage_unavailable` | 503 | The instance has no file storage, so it cannot keep photos |
|
||||
| `store_state_conflict` | 409 | The domain or mailbox is not in a state that allows the change right now. Refresh it and try again |
|
||||
| `mailbox_exists` | 409 | An address in the order already exists on that domain |
|
||||
| `domain_not_ready` | 409 | Mailboxes were added to a purchased domain that is still being set up, or to a connected domain whose `connection.status` is not `active` yet, or a change was asked of a domain in a state that does not allow it. Try again once it is active |
|
||||
| `domain_not_renewable` | 409 | `POST /store/domains/:id/renew` for a domain in a state that cannot be renewed, such as one transferred out |
|
||||
| `renewal_in_progress` | 409 | The domain is already being renewed |
|
||||
| `transfer_locked` | 409 | The domain cannot be transferred out yet, typically because it was registered or transferred within the last 60 days |
|
||||
| `mailbox_not_cancellable` | 409 | `DELETE /store/mailboxes/:id` for a mailbox that cannot be cancelled now, or `POST .../resume` for one that is not set to cancel |
|
||||
| `purchased_mailbox` | 403 | Removing a mailbox bought in the store (`DELETE /emails/:id`, a row of `POST /emails/bulk/delete`) or signing it in again (`/emails/onboarding/oauth/reauth/:id`, `/emails/onboarding/smtp-imap/:id`, `/emails/onboarding/app-password/:id`) while it is still live. Removing it would not stop its billing: cancel it with `DELETE /store/mailboxes/:id`, which ends it at the end of the paid month, or switch it off to pause it. Once it is cancelled it can be removed. While the instance has no GraphKit API key it cannot be cancelled either, and the message says so |
|
||||
| `registrant_required` | 422 | `POST /store/quotes` with a domain in it before a registrant is saved. Save one with `PUT /store/registrant` |
|
||||
| `domain_premium` | 422 | The domain is a premium name, priced by its registry above the standard rate. Premium names are not sold |
|
||||
| `tld_unsupported` | 422 | The store does not sell that domain extension |
|
||||
| `provider_mixed` | 422 | A domain's mailboxes must all use one provider, Google or Microsoft |
|
||||
| `mailbox_limit` | 422 | The order would put more mailboxes on one domain than `limits.mailboxes_per_domain_max` |
|
||||
| `renewal_not_due` | 422 | `POST /store/domains/:id/renew` before the domain's renewal window opens |
|
||||
| `renewal_window_closed` | 422 | The domain can no longer be renewed. Any charge for the attempt was refunded to the balance |
|
||||
| `rate_limited` | 429 | The store is taking too many requests. Wait for `Retry-After` and try again |
|
||||
| `store_unavailable` | 503 | The store could not complete the request right now. Nothing changed; retry in a few minutes, with the same `Idempotency-Key` where the route takes one |
|
||||
|
||||
`payment_method_required` from the store is a `402`, while the same code from `POST /subscription/balance/top-up` is a `409` (see [409 Conflict](#409-conflict)). Both mean save a card first.
|
||||
|
||||
Store charges and refunds also appear on the balance ledger, and `GET /subscription/credits/transactions?category=store` lists only those. A `category` other than `store` answers `400` `invalid_category`.
|
||||
|
||||
A key or OAuth token whose member lacks `manage_billing` gets `403` `forbidden` on the routes that charge, the same answer the member gets in the dashboard.
|
||||
|
||||
#### `google_personal_app_password`
|
||||
|
||||
A `400` with `code: "google_personal_app_password"` comes from `POST /emails/onboarding/oauth/start` with `provider: "gmail"` and a `login_hint` on `gmail.com` or `googlemail.com`. Personal Gmail connects with an app password, not with Google sign-in. Nothing was started and nothing was stored.
|
||||
@@ -856,6 +928,24 @@ Returned when an AI action, or a placement test paid from the balance, is reques
|
||||
- Add money to the balance, turn on automatic reload, or wait for the monthly allowance to reset (see [Balance and usage](/guides/ai-credits/))
|
||||
- Related: a `429` with code `usage_cap_exceeded` means a spend limit or a short-term AI usage cap was hit; retry when the window rolls over
|
||||
|
||||
Two more `402` codes come from the workspace's own choice about AI spending money it added, not from an empty balance. Nothing is charged for either.
|
||||
|
||||
| Code | Meaning | How to fix |
|
||||
|------|---------|------------|
|
||||
| `ai_allowance_used` | This month's included AI usage is spent and **Let AI use my balance** is off, so AI does not touch money the workspace added | Turn **Let AI use my balance** on under **Settings > Billing > Balance** (`PATCH /subscription/credits/settings` with `ai_overage_enabled: true`), or wait for the allowance to reset |
|
||||
| `ai_overage_limit_reached` | AI took the workspace's monthly limit from money it added (`ai_overage_monthly_limit_usd`) | Raise or remove the limit, or wait for the next calendar month (UTC) |
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Payment Required",
|
||||
"message": "This month's included AI usage is used up. To keep using AI, let it use your balance under Settings > Billing > Balance.",
|
||||
"code": "ai_allowance_used",
|
||||
"request_id": "req_..."
|
||||
}
|
||||
```
|
||||
|
||||
The same two codes reach Remie's stream as an `error` event and MCP tool calls as an `isError` result carrying the message.
|
||||
|
||||
`POST /subscription/balance/top-up` answers `402` when the saved card was not charged: `card_declined` (the card was refused), `authentication_required` (the bank asked to confirm the payment) or `payment_failed`. Nothing was added. Offer Stripe Checkout instead with `POST /subscription/balance/checkout`. See [balance and usage](/api/endpoints/#balance-and-usage).
|
||||
|
||||
Placement tests answer `402` too, with `placement_not_entitled` or `placement_quota_exceeded`; see [placement test refusals](#placement-test-refusals). A paid placement test past the balance answers `insufficient_credits`, and one past a spend limit answers `429` with `usage_cap_exceeded`; neither charges anything.
|
||||
@@ -956,6 +1046,19 @@ Signup and invitation refusals carry their own `code`, so a client can branch on
|
||||
|
||||
**How to fix:** on a self-hosted deployment these are configuration, not faults. See [accounts and access](/development/accounts-and-access/#registration-modes).
|
||||
|
||||
#### Workspaces a partner manages
|
||||
|
||||
A workspace a [partner](/development/partners/) manages and bills has its own refusals. They answer dashboard sessions and API keys alike.
|
||||
|
||||
| `code` | Status | Meaning |
|
||||
|--------|--------|---------|
|
||||
| `organization_suspended` | 403 | The partner paused the workspace. It is read-only until the partner resumes it: reads work, changes and sending wait |
|
||||
| `organization_cancelled` | 403 | The partner cancelled the workspace. It is read-only and is deleted after 30 days unless the partner restores it |
|
||||
| `partner_managed` | 403 | A billing change (checkout, plan change, cancellation, top-up) in a workspace the partner bills. It is made with the partner |
|
||||
| `partner_account` | 403 | An account the partner signs in tried to set a password or add a passkey or second factor. It signs in only through the partner |
|
||||
| `partner_login_invalid` | 400 | `POST /auth/partner/exchange` with a sign-in link that expired, was already used, or is not one. Open it again from the partner |
|
||||
| `partner_managed_mailbox` | 403 | Removing a mailbox (`DELETE /emails/:id`, `POST /emails/bulk/delete`) or signing it in again (`/emails/onboarding/oauth/reauth/:id`, `/emails/onboarding/smtp-imap/:id`, `/emails/onboarding/app-password/:id`) while the partner holds it. It is removed or reconnected through the partner |
|
||||
|
||||
#### Account and workspace standing
|
||||
|
||||
An account or workspace that support or the instance's administrators have restricted answers with its own `code`. These are not permission problems, and a role change does not lift them.
|
||||
|
||||
@@ -181,6 +181,14 @@ Six tools give a client the same understanding of the product a person gets from
|
||||
| `list_migrations` / `get_migration` | Read migrations, their inventory, progress and follow-up | `IMPORT_TOOLS` |
|
||||
| `start_migration` | Start a scanned migration. Imported campaigns are drafts and never launch | `IMPORT_TOOLS` |
|
||||
| `cancel_migration` / `link_migration_senders` | Cancel a migration, or link its draft campaigns to senders connected since | `IMPORT_TOOLS` |
|
||||
| `get_store_status` / `search_store_domains` | Whether the store is open to the workspace, its prices and balance; search domains with their prices | `READ_STORE` |
|
||||
| `list_store_orders` / `get_store_order` | Read store orders and their setup progress | `READ_STORE` |
|
||||
| `list_store_domains` / `get_store_domain` / `list_store_mailboxes` | Read purchased and connected domains, their DNS records, and purchased mailboxes | `READ_STORE` |
|
||||
| `create_store_quote` | Price domains and mailboxes for 15 minutes. Charges nothing | `MANAGE_STORE` |
|
||||
| `add_store_dns_record` / `delete_store_dns_record` | Add or delete a DNS record on a store domain | `MANAGE_STORE` |
|
||||
| `place_store_order` | Pay for a quote from the workspace balance. Needs `expected_due_now_micros`, the total that was shown | `MANAGE_STORE` |
|
||||
| `renew_store_domain` / `set_store_domain_auto_renew` | Renew a domain now, or turn its auto-renew on or off | `MANAGE_STORE` |
|
||||
| `cancel_store_mailbox` / `resume_store_mailbox` | Cancel a purchased mailbox at the end of its paid month, or undo that | `MANAGE_STORE` |
|
||||
| `search_web` / `fetch_url` | Search and read public pages | `AI_AGENT` |
|
||||
| `load_skill` | Read one of your playbooks | `AI_AGENT` |
|
||||
| `search_docs` / `read_doc` | Search and read the Warmbly docs | none beyond MCP access |
|
||||
@@ -195,6 +203,8 @@ Tools that return a secret (`create_webhook` and `rotate_webhook_secret`) return
|
||||
|
||||
The migration tools also need the member behind the credential to hold the manage contacts permission, and bringing campaigns or mailboxes over needs the matching campaign or mailbox permission. Mailbox passwords a source tool returns are only used when a signed-in member started the migration, so a migration started over MCP asks for every mailbox to be reconnected.
|
||||
|
||||
The [store](/guides/buy-mailboxes/) tools appear only when the instance has a store. Every one needs the member behind the credential to hold the manage mailboxes permission, and the five that charge or change what is charged (`place_store_order`, `renew_store_domain`, `set_store_domain_auto_renew`, `cancel_store_mailbox`, `resume_store_mailbox`) also need the manage billing permission, checked on every call; in the dashboard's assistant they also ask for a recent sign-in. Buying spends the workspace balance. When prices moved since the quote, `place_store_order` answers `price_changed` with a fresh quote and charges nothing; show the new total and order that quote once it is confirmed. The in-product assistant always pauses `place_store_order` for your approval. Getting a domain's transfer code and showing a mailbox's sign-in are not tools, because each returns a credential; use the [store routes](/api/endpoints/#domains-and-mailboxes) for those.
|
||||
|
||||
## Agencies
|
||||
|
||||
An [agency](/guides/agencies/) API key (`wmagency_...`) connects to the same URL and works across the agency's client workspaces:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Permissions reference
|
||||
description: Complete reference for the 27 workspace and 5 agency API permissions available in Warmbly.
|
||||
description: Complete reference for the 29 workspace and 5 agency API permissions available in Warmbly.
|
||||
---
|
||||
|
||||
Warmbly uses a bitmask system for API permissions. Each permission is one bit in a `uint64`, so a single integer can express any combination of the permissions below.
|
||||
@@ -43,6 +43,8 @@ These same permissions are the [OAuth](/api/oauth/) scopes, lowercased: `READ_EM
|
||||
| `AGENCY_TRANSFER_AI` | 29 | 536870912 | agency | Move AI balance from the agency into a client workspace |
|
||||
| `IMPORT_TOOLS` | 30 | 1073741824 | bulk | Migrate data in from another outreach tool |
|
||||
| `AGENCY_MIGRATE` | 31 | 2147483648 | agency | Migrate client accounts in from another outreach tool |
|
||||
| `READ_STORE` | 32 | 4294967296 | read | View purchased domains, mailboxes, orders and store prices |
|
||||
| `MANAGE_STORE` | 33 | 8589934592 | write | Buy, renew and cancel domains and mailboxes, and edit their DNS |
|
||||
|
||||
Bits 26 to 29 and bit 31 exist only on [agency API keys](/api/authentication/#agency-api-keys). A workspace key or OAuth app never holds them, and `POST /api-keys` refuses them as unknown bits.
|
||||
|
||||
@@ -56,6 +58,8 @@ Bits 26 to 29 and bit 31 exist only on [agency API keys](/api/authentication/#ag
|
||||
|
||||
`SEND_CAMPAIGNS` is intentionally separate from `WRITE_CAMPAIGNS`: editing a campaign draft and starting one that actually transmits mail are different blast radii, so a key can be granted the first without the second. An [inbox placement test](/guides/placement-tests/) sends real mail from a real mailbox too, so starting or cancelling one, and scheduling a campaign's placement monitor, takes `SEND_CAMPAIGNS`, while reading results takes `READ_ANALYTICS`.
|
||||
|
||||
`READ_STORE` and `MANAGE_STORE` cover the [store](/guides/buy-mailboxes/), the `/store` routes where the workspace buys domains and mailboxes. `READ_STORE` reads the store status and domain search, orders, purchased and connected domains, their DNS checks, and purchased mailboxes. `MANAGE_STORE` covers asking for a quote, connecting a domain the workspace already owns, editing DNS records, renaming a mailbox and changing a forwarding URL. Anything that charges the workspace or changes what it is charged (placing an order, renewing a domain, turning auto-renew on or off, cancelling or resuming a mailbox, getting a transfer code, and saving the registrant) also needs the member behind the key to hold `manage_billing`, checked on every request rather than when the key was made, so a key stops paying the moment that member loses it. Buying spends the workspace balance. `MANAGE_STORE` can also fetch a purchased mailbox's sign-in (`POST /store/mailboxes/:id/sign-in`), which reveals its username and password, so treat a key holding it like one that can read mailbox credentials. See the [store routes](/api/endpoints/#domains-and-mailboxes) for each route's scope.
|
||||
|
||||
## Categories
|
||||
|
||||
### Read
|
||||
@@ -80,7 +84,7 @@ The agency's own endpoints under `/v1/agency/:agencyId`. Only an agency API key
|
||||
|
||||
| Agency permission | Endpoints |
|
||||
|-------------------|-----------|
|
||||
| `AGENCY_READ` | `GET /agency`, `GET /agency/plans`, `GET /agency/:agencyId`, its staff, clients, overview and brand; with `READ_UNIBOX` also the cross-client inbox |
|
||||
| `AGENCY_READ` | `GET /agency`, `GET /agency/plans`, `GET /agency/:agencyId`, its staff, clients, overview and brand; with `READ_UNIBOX` also the cross-client inbox, and with `READ_STORE` the [purchased infrastructure overview](/api/endpoints/#agencies) (`GET /agency/:agencyId/store`) |
|
||||
| `AGENCY_MANAGE_CLIENTS` | Create, attach, update (send and AI caps) and detach clients |
|
||||
| `AGENCY_READ_USAGE` | `GET /agency/:agencyId/usage` and `GET /agency/:agencyId/ai-balance` |
|
||||
| `AGENCY_TRANSFER_AI` | `POST /agency/:agencyId/clients/:orgId/ai-balance` |
|
||||
@@ -98,7 +102,7 @@ An API key or an OAuth grant acts for a member of the workspace, so it never hol
|
||||
| `READ_CONTACTS`, `READ_CRM` | `view_contacts` |
|
||||
| `READ_UNIBOX`, `WRITE_UNIBOX` | `access_unibox` |
|
||||
| `READ_ANALYTICS`, `READ_AUDIT_LOGS` | `view_analytics` |
|
||||
| `WRITE_EMAILS`, `CONNECT_EMAILS` | `manage_emails` |
|
||||
| `WRITE_EMAILS`, `CONNECT_EMAILS`, `READ_STORE`, `MANAGE_STORE` | `manage_emails` |
|
||||
| `WRITE_CAMPAIGNS`, `WRITE_TEMPLATES`, `BULK_CAMPAIGNS` | `manage_campaigns` |
|
||||
| `WRITE_CONTACTS`, `WRITE_CRM`, `BULK_CONTACTS`, `IMPORT_TOOLS` | `manage_contacts` |
|
||||
| `SEND_CAMPAIGNS` | `send_campaigns` |
|
||||
@@ -123,31 +127,31 @@ Where it applies:
|
||||
|
||||
Both presets are returned by `GET /api-keys/permissions` for convenience. The same response carries `grantable`, the mask the caller may put on a key (its role's reach, or the calling key's own permissions), and `app_scopes`, the mask an OAuth app may request.
|
||||
|
||||
### Read only (688159)
|
||||
### Read only (4295655455)
|
||||
|
||||
All read permissions combined:
|
||||
|
||||
```
|
||||
READ_EMAILS | READ_CAMPAIGNS | READ_CONTACTS | READ_UNIBOX | READ_ANALYTICS
|
||||
| READ_TEMPLATES | READ_CRM | READ_AUDIT_LOGS
|
||||
= 1 | 2 | 4 | 8 | 16 | 32768 | 131072 | 524288
|
||||
= 688159
|
||||
| READ_TEMPLATES | READ_CRM | READ_AUDIT_LOGS | READ_STORE
|
||||
= 1 | 2 | 4 | 8 | 16 | 32768 | 131072 | 524288 | 4294967296
|
||||
= 4295655455
|
||||
```
|
||||
|
||||
### Full access (1124073471)
|
||||
### Full access (14008975359)
|
||||
|
||||
Every workspace permission except `CONNECT_EMAILS`, which is granted by hand:
|
||||
|
||||
```
|
||||
(((1 << 26) - 1) & ~16777216) | 1073741824 = 1124073471
|
||||
(((1 << 26) - 1) & ~16777216) | (1 << 30) | (1 << 32) | (1 << 33) = 14008975359
|
||||
```
|
||||
|
||||
### Agency key presets
|
||||
|
||||
`GET /agency/:agencyId/api-keys/permissions` returns the bits an agency key may hold, grouped as `workspace` and `agency`, with two presets:
|
||||
|
||||
- **Read only (336232479)**: the workspace read set plus `AGENCY_READ` and `AGENCY_READ_USAGE`, `688159 | 67108864 | 268435456`.
|
||||
- **Full access (4278179839)**: every bit an agency key may hold, which is every workspace bit except `API_KEYS`, `REALTIME_SUBSCRIBE` and `CONNECT_EMAILS` (1124063231) plus the five agency bits (3154116608).
|
||||
- **Read only (4631199775)**: the workspace read set plus `AGENCY_READ` and `AGENCY_READ_USAGE`, `4295655455 | 67108864 | 268435456`.
|
||||
- **Full access (17163081727)**: every bit an agency key may hold, which is every workspace bit except `API_KEYS`, `REALTIME_SUBSCRIBE` and `CONNECT_EMAILS` (14008965119) plus the five agency bits (3154116608).
|
||||
|
||||
## Working with bitmasks
|
||||
|
||||
@@ -173,9 +177,28 @@ hasPermission(16387, 16384); // true: SEND_CAMPAIGNS granted
|
||||
hasPermission(16387, 64); // false: WRITE_CAMPAIGNS missing
|
||||
```
|
||||
|
||||
### Values above 2^31
|
||||
|
||||
JavaScript's bitwise operators (`&`, `|`, `~`, `<<`) work on 32-bit integers, so they give wrong answers for `AGENCY_MIGRATE` (bit 31), `READ_STORE` (bit 32), `MANAGE_STORE` (bit 33) and any mask that contains them, such as the presets. Use `BigInt` for masks in JavaScript and TypeScript:
|
||||
|
||||
```javascript
|
||||
const READ_STORE = 1n << 32n; // 4294967296n
|
||||
const MANAGE_STORE = 1n << 33n; // 8589934592n
|
||||
|
||||
function hasPermission(permissions, required) {
|
||||
const p = BigInt(permissions);
|
||||
const r = BigInt(required);
|
||||
return (p & r) === r;
|
||||
}
|
||||
|
||||
hasPermission(14008975359, MANAGE_STORE); // true: full access holds it
|
||||
```
|
||||
|
||||
Every value fits in a JSON number exactly (all are below 2^53), so only the arithmetic needs `BigInt`. Python and Go integers have no such limit.
|
||||
|
||||
### Rejecting unknown bits
|
||||
|
||||
`POST /api-keys` rejects any request whose `permissions` field has bits outside the known set, so a stale client can't accidentally request a future permission. The current mask of valid bits is `1140850687`. `POST /agency/:agencyId/api-keys` does the same against `4278179839` and answers `400` `invalid_agency_key_permissions`.
|
||||
`POST /api-keys` rejects any request whose `permissions` field has bits outside the known set, so a stale client can't accidentally request a future permission. The current mask of valid bits is `14025752575`. `POST /agency/:agencyId/api-keys` does the same against `17163081727` and answers `400` `invalid_agency_key_permissions`.
|
||||
|
||||
## Common permission sets
|
||||
|
||||
@@ -268,6 +291,9 @@ export const Permissions = {
|
||||
IMPORT_TOOLS: 1073741824,
|
||||
// Agency API keys only
|
||||
AGENCY_MIGRATE: 2147483648,
|
||||
// Store (workspace permissions); above 2^31, so use BigInt for bitwise math
|
||||
READ_STORE: 4294967296,
|
||||
MANAGE_STORE: 8589934592,
|
||||
} as const;
|
||||
```
|
||||
|
||||
@@ -312,6 +338,9 @@ class Permissions:
|
||||
IMPORT_TOOLS = 1073741824
|
||||
# Agency API keys only
|
||||
AGENCY_MIGRATE = 2147483648
|
||||
# Store (workspace permissions)
|
||||
READ_STORE = 4294967296
|
||||
MANAGE_STORE = 8589934592
|
||||
```
|
||||
|
||||
</Tab>
|
||||
@@ -355,6 +384,9 @@ const (
|
||||
APIPermImportTools // 1073741824
|
||||
// Agency API keys only
|
||||
APIPermAgencyMigrate // 2147483648
|
||||
// Store (workspace permissions)
|
||||
APIPermReadStore // 4294967296
|
||||
APIPermManageStore // 8589934592
|
||||
)
|
||||
```
|
||||
|
||||
|
||||
@@ -2386,6 +2386,8 @@ The workspace balance in US dollars: the plan's monthly allowance plus money the
|
||||
|
||||
`GET /subscription/balance`
|
||||
|
||||
`burn` is included only with `?include=burn`, because it sums a month of the ledger; the example below asks for it.
|
||||
|
||||
```json
|
||||
{
|
||||
"unlimited": false,
|
||||
@@ -2410,10 +2412,21 @@ The workspace balance in US dollars: the plan's monthly allowance plus money the
|
||||
"failure_code": null,
|
||||
"failed_at": null
|
||||
},
|
||||
"top_up": { "min_usd": 5, "max_usd": 5000, "presets_usd": [10, 25, 50, 100, 250], "default_usd": 25 }
|
||||
"top_up": { "min_usd": 5, "max_usd": 5000, "presets_usd": [10, 25, 50, 100, 250], "default_usd": 25 },
|
||||
"burn": {
|
||||
"per_day_usd": 1.12,
|
||||
"mailboxes_per_day_usd": 0.3,
|
||||
"renewals_per_day_usd": 0.62,
|
||||
"ai_per_day_usd": 0.2,
|
||||
"mailboxes_monthly_usd": 9,
|
||||
"renewals_due_usd": 11.17,
|
||||
"billing_day": 17
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`burn` is what the balance pays for a day, for a "lasts about N days" estimate: a month of [bought mailboxes](/guides/buy-mailboxes/) over 30 days, each auto-renewing domain charged in the next 60 days over the days until its charge, and the average daily AI spend over the last 30 days. `billing_day` is the day of the month the mailboxes are billed, `null` before the first one.
|
||||
|
||||
`payment_method` is `null` with no saved card. `retry_at` and `retry_reason` are set while a declined automatic reload waits for its next try (1, 6 and 18 hours after the attempts before it). `failure_code` and `failed_at` record why automatic reload last turned itself off: `card_declined`, `authentication_required`, `no_payment_method`, `payment_failed`, or `unavailable` when Stripe could not be reached after 8 tries. A reload waiting for its next try is canceled when automatic reload is turned off or the balance is back above `threshold_usd`.
|
||||
|
||||
#### Add money on the saved card
|
||||
@@ -2444,6 +2457,18 @@ Takes the same `amount_usd` and returns `{"session_id": "cs_...", "checkout_url"
|
||||
|
||||
No body. Returns a Checkout `checkout_url` in setup mode, which saves a card without charging it.
|
||||
|
||||
#### Save a card in the page
|
||||
|
||||
`POST /subscription/balance/setup-intent`
|
||||
|
||||
No body. Returns `{"client_secret": "seti_..._secret_...", "publishable_key": "pk_..."}`: a Stripe SetupIntent on the workspace's customer, card only, for off-session charges. Confirm it with Stripe.js (`stripe.confirmSetup`), which runs any 3-D Secure check in the page; the card is saved without a charge. A workspace with no Stripe customer yet gets one. `409` when the workspace has no billing account at all, in which case use `POST /subscription/balance/payment-method`.
|
||||
|
||||
#### Make a saved card the default
|
||||
|
||||
`POST /subscription/balance/setup-intent/default`
|
||||
|
||||
`{"setup_intent_id": "seti_..."}`. Makes the card a confirmed SetupIntent from `POST /subscription/balance/setup-intent` saved the workspace's default, so the next top-up, automatic reload or store charge uses it, including when it replaces an older card. Call it after `stripe.confirmSetup` succeeds and before charging. Answers `204`. `404` when the SetupIntent is not on the workspace's Stripe customer, `409` while it has not succeeded. Setting the same default again changes nothing, so a retry is safe.
|
||||
|
||||
#### Change automatic reload
|
||||
|
||||
`PATCH /subscription/balance/auto-reload`
|
||||
@@ -2492,7 +2517,7 @@ The endpoints from before the dollar balance remain and carry dollar figures nex
|
||||
| `GET /subscription/credits` | `balance_usd`, `monthly_usd`, `purchased_usd`, `monthly_allowance_usd`, `total_purchased_usd` |
|
||||
| `GET /subscription/credits/transactions` | Per row: `amount_usd` (negative for a charge), `cost_usd` (the provider price before the markup), `input_tokens`, `output_tokens`, `quantity` (units such as web searches), `balance_after_usd`, `monthly_after_usd`, `purchased_after_usd`, `purchased_delta_usd`. Keyset paginated with an opaque `cursor`. |
|
||||
| `GET /subscription/credits/usage?days=30` | `spent_today_usd`, `spent_week_usd`, `spent_month_usd`, `limit_daily_usd`, `limit_weekly_usd`, `limit_monthly_usd`, and `amount_usd` on each `series`, `by_reason` and `by_model` entry. `days` is 1 to 90. |
|
||||
| `GET` and `PATCH /subscription/credits/settings` | `spend_limit_daily_usd`, `spend_limit_weekly_usd`, `spend_limit_monthly_usd`, `member_limit_daily_usd`, `member_limit_weekly_usd`, `member_limit_monthly_usd`, `low_balance_usd`, and read-only `auto_reload_enabled`. A limit left out of the `PATCH` body is removed. |
|
||||
| `GET` and `PATCH /subscription/credits/settings` | `spend_limit_daily_usd`, `spend_limit_weekly_usd`, `spend_limit_monthly_usd`, `member_limit_daily_usd`, `member_limit_weekly_usd`, `member_limit_monthly_usd`, `low_balance_usd`, `ai_overage_enabled` (whether AI may use money the workspace added once the plan's included usage is spent; default `true`), `ai_overage_monthly_limit_usd` and `ai_overage_monthly_limit_micros` (the most AI may take from that money per calendar month, UTC; `null` is no cap; the `PATCH` accepts either, micros first), and read-only `auto_reload_enabled`. A spend limit left out of the `PATCH` body is removed; the two `ai_overage_*` fields left out are kept, and a `null` limit removes it. |
|
||||
|
||||
`POST /subscription/credits/checkout`, which bought a fixed credit pack, is removed.
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ The sidebar lists sections. A section with more than one page shows its pages as
|
||||
| **Warmup** | Pool (the Warmup page below), Appeals, Content, Seed panel |
|
||||
| **Sending** | Campaigns, Sends |
|
||||
| **Organizations** | Organizations, Limit requests |
|
||||
| **Store** | Store (the [Store](#store) page below), with a page per workspace |
|
||||
| **Growth** | Promo codes, Outreach |
|
||||
| **Admins** | Admins, Testers |
|
||||
| **Activity** | Audit log, Live events, Jobs |
|
||||
@@ -97,6 +98,10 @@ An organization's page has two cards that decide what the workspace may buy, bes
|
||||
|
||||
Each grant, renewal and withdrawal is written to the **Audit log** with the reason. Reading the cards needs `view_organizations`; changing them needs `manage_organizations`.
|
||||
|
||||
### Partners
|
||||
|
||||
**Partners** lists the resellers that run workspaces through the [partner API](/development/partners/), which is off until one exists. **New partner** adds one. Its page sets the display name its workspaces show, its allowed hosts, webhook and token callback addresses, wholesale prices and rate limit; issues and revokes live and test keys, each shown once; creates or rotates the webhook signing secret, shown once; stores the token callback key; suspends or resumes the partner; shows its **Statement** for any month (enabled mailbox-days per workspace at its wholesale prices, the running month at today's prices, a closed month as it was written); and lists every workspace it manages with its state. Reading needs `view_organizations`; every change needs `manage_organizations` and a recent confirmation of your identity, and is written to the **Audit log**.
|
||||
|
||||
### Agencies
|
||||
|
||||
An [agency](/guides/agencies/) is not a workspace: it is one billing account over many client workspaces, and one account can own up to five agencies and be staff in any number of them. So an agency's plan is set on the agency, under **Agencies**, and its client workspaces receive it. The **Managed plan** card on a workspace leaves agency plans out and the API refuses one there (`agency_plan_needs_agency`). A workspace that is a client shows **Client of** and its agency on its own page.
|
||||
@@ -167,6 +172,34 @@ Three tabs.
|
||||
|
||||
Reading the tabs needs `view_organizations`; every action needs `manage_organizations`.
|
||||
|
||||
## Store
|
||||
|
||||
**Store** is the operator side of the [domain and mailbox store](/guides/buy-mailboxes/): whether it is working, what every workspace bought, the actions that repair an order, a domain or a mailbox, and what the store earns. It reads from Warmbly's own records and from GraphKit, the store's supplier; it is turned on by adding a GraphKit API key under **Setup and health > Integrations**, or by `GRAPHKIT_API_KEY` (see [configuration](/development/configuration/#domain-and-mailbox-store)). When the store is off, the page says so and nothing else.
|
||||
|
||||
| Tab | What it answers |
|
||||
|---|---|
|
||||
| **Health** | Whether the store runs against GraphKit's live service, its sandbox, or the built-in simulator (development only), and whether workspaces are charged. The GraphKit account balance against its low-balance threshold, when the last webhook arrived, and the reconciler's and the billing pass's last run, lag and last error. Counts of open, stuck and recently failed orders, failed connects, mailboxes behind on payment, failed renewals and domains expiring within 30 days, and the recent `store.unavailable` [operator alerts](/development/operator-notifications/) |
|
||||
| **Orders** | Every order on the instance, filtered by status, workspace, failure code or **Stuck only**, or searched by order id or workspace name. An order opens a drawer with its lines, its setup steps, what was charged and refunded, and whether it was placed with GraphKit |
|
||||
| **Domains** | Every purchased and connected domain, filtered by status, workspace, auto-renew, expiry within some days or a failed renewal, or searched by name |
|
||||
| **Mailboxes** | Every purchased mailbox, filtered by status, workspace, connect state (waiting, connecting, connected, failed) or a failed monthly payment, or searched by address |
|
||||
| **Economics** | What each mailbox and domain costs from GraphKit against what the instance charges for it: per mailbox provider the wholesale and retail monthly price, the margin, any scheduled wholesale change and how many are live; per domain extension the wholesale and retail registration and renewal prices; and the instance's monthly retail, wholesale and margin totals |
|
||||
|
||||
Any workspace name opens that workspace's store page: whether it has a store account and a saved registrant, whether its plan is active, whether a partner manages it, its balance and monthly store spend, and its latest orders, its domains and its mailboxes, with the same actions.
|
||||
|
||||
### Store actions
|
||||
|
||||
| Where | Action | What it does |
|
||||
|---|---|---|
|
||||
| Order | **Refresh** | Re-reads the order from GraphKit and applies what it says |
|
||||
| Order | **Retry placing** | Places an order that was charged but never reached GraphKit, under its original key, so it can never be placed twice |
|
||||
| Order | **Refund** | Refunds one line's charge, or an amount with a reason, to the workspace balance |
|
||||
| Domain | **Refresh**, **Force renewal**, **Auto-renew** | Re-reads the domain, renews it now, or turns its auto-renew on or off |
|
||||
| Mailbox | **Refresh**, **Retry connect**, **Cancel**, **Resume** | Re-reads the mailbox, retries a failed connect now (resetting its attempts), cancels it at the end of its paid month, or undoes that |
|
||||
|
||||
Every action is written to the **Audit log** (`store_order_refresh`, `store_order_place`, `store_order_refund`, `store_mailbox_refresh`, `store_mailbox_connect`, `store_mailbox_cancel`, `store_mailbox_resume`, `store_domain_refresh`, `store_domain_renew` and `store_domain_auto_renew`), and every action is safe to repeat: a second **Retry placing** on a placed order answers `409` `store_state_conflict`, and a line refunded once refunds nothing more. A refund by amount needs an `Idempotency-Key` (`400` `idempotency_key_required` without one, and the panel sends one), is capped at what was charged less what was already refunded (`422` `refund_exceeds_charge`), and is refused with `409` `store_unmetered` on an instance that charges workspaces nothing. Errors use Warmbly codes; GraphKit's wording never appears.
|
||||
|
||||
Reading the Store pages needs `view_organizations`; every action needs `manage_organizations`. Like every admin route, both need a session that verified a second factor. The API behind them is `/admin/store/*` (`health`, `economics`, `orders`, `domains`, `mailboxes` and `workspaces/:orgId`), with lists in the usual `data` and `pagination` shape, `limit` 1 to 100 (50 by default).
|
||||
|
||||
## Activity
|
||||
|
||||
| Page | What it answers |
|
||||
@@ -179,7 +212,7 @@ Reading the tabs needs `view_organizations`; every action needs `manage_organiza
|
||||
|
||||
| Page | What it answers |
|
||||
|---|---|
|
||||
| **Setup and health** | Three tabs. **Findings** is the [instance health](/development/instance-health/) check list, and the sidebar badge counts its errors and warnings, not operational signals. **Services** holds scoped service reachability probes and the platform mail card. **Operations** holds read-only measurements, coverage, affected counts, evidence age, waits and permission-gated investigation links |
|
||||
| **Setup and health** | Four tabs. **Findings** is the [instance health](/development/instance-health/) check list, and the sidebar badge counts its errors and warnings, not operational signals. **Services** holds scoped service reachability probes and the platform mail card. **Operations** holds read-only measurements, coverage, affected counts, evidence age, waits and permission-gated investigation links. **Integrations**, shown with `manage_settings`, holds the **Domains and mailboxes (GraphKit)** card: the GraphKit API key, optional webhook secret and API URL that turn the [store](#store) on, with **Test connection**, **Save** and **Disconnect**, and the webhook URL to register with GraphKit. Secrets are write-only, a changed API URL needs the API key entered again, a replaced webhook secret keeps verifying for 24 hours, every change needs a recent confirmation of your identity, and the card is read-only when `GRAPHKIT_*` in the environment configures the store. See [adding the key in the admin panel](/development/configuration/#adding-the-key-in-the-admin-panel) |
|
||||
| **Configuration** | Five tabs. **Settings** is the database-backed settings document; **Notifications** is the [operator notification](/development/operator-notifications/) channels; **Environment** is the read-only [configuration reference](/development/configuration/) view of what the backend resolved; **Effective limits** lists the compiled pacing constants; **Keys** shows whether a [key rotation](/development/configuration/#rotate-instance-keys) can be finished: sealed values still opening only under a read key or under no key, open overlap windows for previous tokens and unsubscribe secrets, and live nodes that have not applied the current env. It is read only; rotation runs where the keys are stored |
|
||||
| **Transfers** | Workspace export and import for any organization, from the operator side, with the same archives as `warmblyctl org export` and `org import`. A whole-instance backup stays `warmblyctl backup` and `restore` |
|
||||
|
||||
@@ -193,7 +226,7 @@ Reading the tabs needs `view_organizations`; every action needs `manage_organiza
|
||||
| Warmup, Warmup content, Seed panel | `view_warmup_pool` (changing seeds or running a test needs `manage_warmup_bans`) |
|
||||
| Warmup appeals | `review_appeals` |
|
||||
| Campaigns, Sends | `view_campaigns` |
|
||||
| Organizations, Agencies, Limit requests, Developer apps, Promo codes, Outreach, Transfers | `view_organizations` |
|
||||
| Organizations, Agencies, Limit requests, Developer apps, Promo codes, Outreach, Transfers, Store | `view_organizations` (Store actions need `manage_organizations`) |
|
||||
| Admins | `grant_admin_access` |
|
||||
| Audit log | `view_audit_logs` |
|
||||
| Jobs, Setup and health | `view_analytics` |
|
||||
|
||||
@@ -159,6 +159,7 @@ Every emailed link (password reset, invitation, the first-run claim link) is bui
|
||||
| `API_HOST` | The listen address | `0.0.0.0:8080` | yes |
|
||||
| `PUBLIC_HOST` | Compose only. A hostname or LAN IP that every other URL derives from | `localhost` | yes |
|
||||
| `CORS_ALLOW_ORIGINS` | Comma separated origins allowed to call the API. Anything not listed gets `403` on preflight | derived from `PUBLIC_HOST` under compose | yes |
|
||||
| `ADMIN_URL` | The admin panel's origin. The dashboard links an instance admin to it, for example to [add the GraphKit API key](#adding-the-key-in-the-admin-panel), and `warmblyctl` prints it | guessed from the `CORS_ALLOW_ORIGINS` entry on an `admin.` host or port `5174`, else unset (no link) | no (read per request) |
|
||||
| `WEBSOCKET_URL` | The websocket URL the dashboard connects to | derived under compose | yes (container start) |
|
||||
| `PHX_HOST` | The realtime service's own hostname | `localhost` | yes |
|
||||
| `TRACKING_DOMAIN` | The host that serves open pixels, click links and the unsubscribe pages for workspaces that verified their own domain against it, and the `CNAME` value those customers point their tracking subdomain at. Use a separate, neutral domain in production. Unset means campaign mail ships with no pixel and unwrapped links, no custom tracking domain can verify, and every opt-out is served from `API_PUBLIC_URL` | `localhost:3000` under compose, otherwise unset | no |
|
||||
@@ -929,7 +930,7 @@ Add a Tax registration only after the business is registered with that tax autho
|
||||
|
||||
Stripe Checkout always requests the billing address needed for tax and lets business buyers provide a legal name and business tax ID. The active default billing portal configuration must allow updates to payment methods, billing email, billing address, name, and tax ID, and must show invoice history. This lets a customer correct its tax location or registration before a renewal.
|
||||
|
||||
Point the webhook endpoint at `/webhook/stripe` using API version `2026-08-26.dahlia`, matching stripe-go v86. Subscribe to `checkout.session.completed`, `checkout.session.async_payment_succeeded`, `checkout.session.expired`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid`, `invoice.payment_failed`, `invoice.finalization_failed`, `payment_intent.succeeded` and `charge.refunded`. If you replace the endpoint, update `STRIPE_WEBHOOK_SECRET` to the new endpoint's signing secret before disabling the old endpoint. The handler accepts the previous webhook shape during an endpoint upgrade, but new endpoints should use the matching version.
|
||||
Point the webhook endpoint at `/webhook/stripe` using API version `2026-08-26.dahlia`, matching stripe-go v86. Subscribe to `checkout.session.completed`, `checkout.session.async_payment_succeeded`, `checkout.session.expired`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid`, `invoice.payment_failed`, `invoice.finalization_failed`, `payment_intent.succeeded`, `charge.refunded` and `setup_intent.succeeded`. The last one makes a card saved in the mailbox checkout the workspace's default and retries anything unpaid at once; without it the newest saved card is still used. If you replace the endpoint, update `STRIPE_WEBHOOK_SECRET` to the new endpoint's signing secret before disabling the old endpoint. The handler accepts the previous webhook shape during an endpoint upgrade, but new endpoints should use the matching version.
|
||||
|
||||
Turning on Stripe Tax does not update existing subscriptions. Review and migrate them from **Tax > Migrations** after setting the prices' tax behavior. Stripe applies the tax change from the next billing cycle without prorating it. The Dashboard migration does not operate on sandbox subscriptions, so update those individually when testing.
|
||||
|
||||
@@ -955,6 +956,74 @@ Dub's Stripe app then reads the payments from the Stripe account: each paid invo
|
||||
|
||||
The key is a Dub workspace API key with conversion tracking write access. Rotate it in Dub and restart the backend; nothing stored depends on it. The referral table never travels with a [workspace export](/guides/workspace-export-import/), because the click and the customer belong to this instance's Dub workspace.
|
||||
|
||||
## Domain and mailbox store
|
||||
|
||||
The [Buy mailboxes](/guides/buy-mailboxes/) store lets workspaces buy domains and Google Workspace or Microsoft 365 mailboxes in the dashboard. It is fulfilled through the GraphKit infrastructure API: an operator with a GraphKit partner account gives the backend its API key, and GraphKit registers the domains, publishes their mail records and provisions the mailboxes. The API key is the only requirement. Add it in the admin panel, or set `GRAPHKIT_API_KEY`; with neither, the store is off and nothing is ever called. An existing self-host is unaffected by upgrading.
|
||||
|
||||
While no key is configured, `GET /store/status` answers `enabled: false` with `reason: not_configured`, every other store route answers `404` `store_disabled`, and the dashboard shows buying as locked: **Add account** lists **Buy new mailboxes** with a lock, and the buy page says a GraphKit API key is needed. An instance admin holding `manage_settings` sees a button to the admin panel there (when [`ADMIN_URL`](#addresses) is known); everyone else is asked to send their operator a note. A workspace a partner manages never shows it. This locked state is self-host only: with `DEPLOYMENT_MODE=cloud` the status carries `locked: false` and the dashboard shows no store until a key is added.
|
||||
|
||||
### Adding the key in the admin panel
|
||||
|
||||
Open **Setup and health > Integrations** in the admin panel. The **Domains and mailboxes (GraphKit)** card takes:
|
||||
|
||||
- **API key**, required: the partner key (`gk_live_...`, or `gk_test_...` against GraphKit's sandbox).
|
||||
- **Webhook secret**, optional: the signing secret of the webhook endpoint you register with GraphKit. The card shows the URL to register, `<backend public address>/v1/webhooks/graphkit` (from `BACKEND_PUBLIC_URL`, else `API_PUBLIC_URL`), with a copy button.
|
||||
- **API URL**, optional: `https://api.graphkit.com/v1/infrastructure` unless GraphKit gave you another. It must be `https`. A stored key is only sent to the URL it was saved with, so changing the URL means entering the API key again; testing or saving a new URL with the key left blank answers `400` `graphkit_key_reentry_required`.
|
||||
|
||||
**Test connection** asks GraphKit for the partner balance and the price list with what you typed and saves nothing; it shows whether the key is live or test, the balance, and the `.com` price. **Save** runs the same check, refuses a key GraphKit does not accept, and then turns the store on at once, with no restart. **Disconnect** deletes the stored key and secrets and turns the store off at once. Purchases already made stay recorded and resume with the next key. Other backend replicas pick a change up within 30 seconds.
|
||||
|
||||
The key and the secrets are write-only: the card and `GET /admin/store/connection` only say whether each is set. They are stored sealed under `CREDENTIALS_ENCRYPTION_KEY` in the `store_graphkit_connection` table, so saving is refused (`409` `store_sealing_unavailable`) on an instance without that key, and a key rotation reseals them like every other instance secret. A new webhook secret keeps the previous one verifying for 24 hours from the save, matching GraphKit's own overlap, so rotating it does not drop deliveries. After that only the current secret verifies. They are never logged, and the audit log records `store_connection_saved` and `store_connection_removed` without them.
|
||||
|
||||
The routes behind the card need the `manage_settings` admin permission, and every change needs a recent confirmation of your identity: `GET`, `PUT` and `DELETE /admin/store/connection`, and `POST /admin/store/connection/test`.
|
||||
|
||||
**The environment wins.** When `GRAPHKIT_API_KEY` is set (or `GRAPHKIT_API_URL=fake`), the card shows **Configured by the environment** read-only, and saving, testing or disconnecting there answers `409` `store_configured_by_environment`. A key saved in the panel is kept but unused until the variables are removed.
|
||||
|
||||
### Purchases with no key
|
||||
|
||||
If the key is removed while purchased mailboxes or unexpired domains exist, their renewals, monthly billing and Google mailbox connections are paused until a key is configured again. The backend logs a warning at boot, **Setup and health** lists an error (`store_purchases_without_graphkit`) with the counts, and each affected workspace sees a banner on its **Purchased** domains tab and in its purchased mailboxes' drawers. Their purchases stay listed. A Google mailbox whose access comes through GraphKit's token broker stops syncing and sending until then.
|
||||
|
||||
### Rolling back
|
||||
|
||||
The store and the partner API are off until an operator adds a key or a partner, so an instance that never turned them on has no purchased mailboxes and can roll back as before.
|
||||
|
||||
Once purchases exist, the release that introduced the store is the oldest one you can roll back to without an interruption. An older release does not know about purchased grants. On it, a Google mailbox whose access comes through GraphKit's token broker stops syncing and sending, and its grant shows as not working. Purchases, billing records, Microsoft mailboxes and Google mailboxes connected through this instance's own service account carry on. Nothing is lost: when you roll forward again, the hourly grant check marks every purchased grant active again and reconnects each of its mailboxes that the token broker still reaches. To speed that up, open the grant in Settings and choose **Check again**.
|
||||
|
||||
### Environment variables
|
||||
|
||||
| Variable | What it does | Default |
|
||||
|---|---|---|
|
||||
| `GRAPHKIT_API_KEY` | The partner API key (`gk_live_...`, or `gk_test_...` against a sandbox). Setting it turns the store on. With `APP_ENV=development`, a `gk_test_` key is treated like the simulator when a Google mailbox connects: sandbox tokens are opaque placeholders, so the backend skips the Gmail check it makes on a real token. Outside development the check always runs | unset |
|
||||
| `GRAPHKIT_API_URL` | The infrastructure API's base URL. `fake` selects an in-process simulator that needs no key, for tests, `make dev`, the sandbox and proof recordings: search, quotes, orders whose steps finish over about 20 seconds, renewals and cancellation, with nothing bought. `make backend` sets `fake` unless you pass another value. The backend refuses to boot with `fake` unless `APP_ENV=development` | `https://api.graphkit.com/v1/infrastructure` |
|
||||
| `GRAPHKIT_WEBHOOK_SECRET` | The signing secret of the webhook endpoint you registered with GraphKit. Signed events are posted to `/v1/webhooks/graphkit` on the backend's public address; anything not signed with this secret (or the previous one), or more than five minutes old, is refused with `401`. With the store off the route answers `404` | unset |
|
||||
| `GRAPHKIT_WEBHOOK_SECRET_PREVIOUS` | The secret before a rotation, accepted alongside the current one for as long as it is set. Set it when you rotate, and remove it once the 24-hour overlap has passed and GraphKit signs only with the new secret | unset |
|
||||
|
||||
The webhook endpoint is not registered for you. In your GraphKit partner account, add `https://<backend public address>/v1/webhooks/graphkit` as the endpoint, then paste the secret GraphKit gives you into the admin card, or set it as `GRAPHKIT_WEBHOOK_SECRET` and restart the backend. The secret is stable: GraphKit returns the same one every time the endpoint is registered or updated, so registering it again does not change it. Only a rotation does. When you rotate, GraphKit keeps signing with the old secret alongside the new one for 24 hours: move the old value to `GRAPHKIT_WEBHOOK_SECRET_PREVIOUS`, set the new one as `GRAPHKIT_WEBHOOK_SECRET`, restart, and clear the previous one after the overlap.
|
||||
|
||||
Webhooks only make updates arrive sooner. The store's two loops run in the backend, not the consumer, because connecting a mailbox needs the backend's mailbox, delegation and billing services; with several backend replicas, one runs each loop at a time. `store_reconcile` runs every minute: it reads GraphKit's event feed (its cursor is kept in the database), refreshes any order still processing after two minutes, places or refunds an order left `charging` when GraphKit did not answer the charge, and connects mailboxes that are waiting. `store_billing` runs hourly: renewal notices, renewal charges, monthly mailbox charges and their retries. So an order never stalls on a missed delivery, and an instance that cannot receive webhooks (one with no public address) still works with `GRAPHKIT_WEBHOOK_SECRET` unset.
|
||||
|
||||
Purchased mailboxes connect on their own, with warmup started on the workspace's defaults where its plan includes warmup:
|
||||
|
||||
- **Google.** The mailbox is connected as a delegated mailbox under a grant marked as purchased, in one of two ways:
|
||||
- **Through this instance's service account**, when `GOOGLE_WORKSPACE_DELEGATION_KEY` (or `_FILE`) is set, as for [whole-domain connects](#whole-domain-connects). The backend registers the key's `client_id` with GraphKit at boot and daily, with every scope a delegated mailbox and its grant check use, including the directory scope, and GraphKit authorizes it for domain-wide delegation in every purchased Workspace. The grant reads through the domain's admin mailbox, like any administrator's grant, and its **Users** picker in Settings works.
|
||||
- **Through GraphKit's token broker** otherwise. Each mailbox's access tokens are minted by GraphKit, limited to the Gmail scopes a purchased mailbox runs on, which the backend registers per workspace. No service account is needed. A brokered grant cannot list its directory, so the grant's **Users** picker does not work for it; the store connects its mailboxes instead.
|
||||
- **Microsoft.** The mailbox is connected through the instance's own Microsoft application with a grant on the domain's tenant, so it needs `BOX_OUTLOOK_CLIENT_ID` and `BOX_OUTLOOK_CLIENT_SECRET`, with the app registration set up as for [whole-domain connects](#whole-domain-connects). The backend sends GraphKit the app id and the `Mail.ReadWrite`, `Mail.Send` and `User.Read.All` permissions at boot and daily.
|
||||
- **Otherwise**, a purchased mailbox connects over IMAP and SMTP, with credentials fetched once and sealed like any other mailbox password (an app password on Google). Microsoft has turned off password IMAP for most tenants, so on Microsoft this fallback usually fails.
|
||||
|
||||
A connection that fails is retried up to five times with a growing wait; after that the workspace sees the mailbox as failed to connect, with a neutral message.
|
||||
|
||||
Creating Google Workspace and Microsoft 365 mailboxes can take from a few hours to a couple of days at the provider. The order's `mailboxes` step stays running meanwhile and the reconciler carries the rest on; members are notified when the order completes.
|
||||
|
||||
When GraphKit refuses this instance's partner account itself (the partner is suspended, `GRAPHKIT_API_KEY` is refused, or the partner balance is too low for orders and renewals), every workspace sees the store as unavailable (`503` `store_unavailable`, with nothing charged) and never the cause. The operator is told instead, through the `store.unavailable` [operator notification](/development/operator-notifications/), at most once an hour per cause, and the backend logs the same summary.
|
||||
|
||||
With `BILLING_PROVIDER=stripe`, buying also needs a paid plan (`402` `plan_required` without one), and a workspace whose plan ends keeps its purchased mailboxes and the unified inbox while campaign sending and warmup follow the usual plan gates and the mailboxes keep billing. With `BILLING_PROVIDER=none` there is no plan gate and `GET /store/status` always reports `plan_active: true`. Workspaces a partner manages buy through the partner and see the store as off.
|
||||
|
||||
What workspaces pay is decided by `BILLING_PROVIDER`:
|
||||
|
||||
- **`stripe` (Warmbly Cloud, or a self-host that bills its users).** Each purchase, renewal and monthly mailbox charge is taken from the workspace balance, with the saved card covering a shortfall at checkout. Retail prices are the three `store.*` [settings stored in the database](#settings-stored-in-the-database). The partner balance at GraphKit pays GraphKit.
|
||||
- **`none` (the self-host default).** Workspaces are charged nothing. The operator's own GraphKit partner balance pays for every domain and mailbox anyone on the instance buys, so enable the store only where you are willing to pay for what members order.
|
||||
|
||||
Purchased domains and mailbox subscriptions belong to this instance's partner account and do not travel in a [workspace export](/guides/workspace-export-import/). See [data control](/development/data-control/#purchased-domains-and-mailboxes) for what is stored.
|
||||
|
||||
## Observability
|
||||
|
||||
### Error reporting
|
||||
@@ -1263,6 +1332,11 @@ These are the only settings a browser can change, and no environment variable ow
|
||||
| `placement.batch_sender_concurrency` | integer, 1 to 500 | `20` | How many of one workspace's batch mailboxes may be sending their copies at the same time, across all its batches. The next mailbox starts when one has sent every copy; each mailbox keeps its own daily limit and minimum gap |
|
||||
| `placement.batch_instance_concurrency` | integer, 1 to 5000 | `200` | The same limit across every workspace together. It bounds how much batch mail the instance seed panel takes in at once, so a seed never receives enough in an hour to trip the sync flood rule, which deactivates a mailbox |
|
||||
| `placement.batch_starts_per_minute` | integer, 1 to 600 | `10` | How many mailboxes one batch starts per minute, so a large batch ramps up instead of starting its whole concurrency at once |
|
||||
| `store.mailbox_monthly_micros` | integer micro-USD, 0 to 100000000 ($0 to $100) | `3000000` | What a workspace pays per [purchased mailbox](/guides/buy-mailboxes/) per month, Google or Microsoft alike ($3.00 by default). Applies to quotes made after the change; a mailbox already bought keeps the price it was bought at. See [domain and mailbox store](#domain-and-mailbox-store) |
|
||||
| `store.domain_markup_percent` | integer, 0 to 500 (0 to 500%) | `0` | Added to the wholesale price of every domain, for registration and renewal |
|
||||
| `store.domain_markup_fixed_micros` | integer micro-USD, 0 to 100000000 ($0 to $100) | `0` | Added to every domain price after the percent. The retail price is wholesale times (1 + percent / 100) plus this, rounded up to the cent. With both markups at `0` the dashboard shows domains as sold at cost |
|
||||
| `store.mailbox_bill_lead_days` | integer, 2 to 10 | `5` | How many days before a workspace's monthly billing day all its mailboxes are charged together. Each mailbox is paid before GraphKit starts its next month, and a payment that keeps failing cancels the unpaid mailboxes at GraphKit a day before that month would start, so a longer lead gives a failed card more time to be fixed |
|
||||
| `store.min_card_charge_micros` | integer micro-USD, 500000 to 100000000 ($0.50 to $100) | `10000000` | The least a store charge puts on a card when the balance falls short. The card tops the balance up by at least this (or by the workspace's automatic reload amount when that is larger), the store charge comes out of the balance, and the rest stays there for the next one. Fewer, larger card charges cost less in card fees. No card is charged when the balance covers the charge |
|
||||
| `usage.markup_percent` | integer, 0 to 500 | `25` | The markup added to every provider price when a workspace balance is charged. See [usage pricing](#usage-pricing) |
|
||||
| `usage.models` | list of `{model, input_per_mtok, output_per_mtok}` | Sonnet 4 class $3 / $15, Haiku 4 class $1 / $5, Claude 3.5 Haiku $0.80 / $4, `gpt-6-luna` $0.10 / $0.50, `*` $3 / $15 | Provider price per million input and output tokens, in dollars before the markup. A `*` row is required and is added back if missing |
|
||||
| `usage.units` | map of unit to dollars | `web_search` $0.01, `placement_test` $0.40, `lead_website_read` $0.016, `lead_person_email` $0.016, `lead_search_page` $0.032 | Provider price of one unit, in dollars before the markup. `0` for `placement_test` turns paid placement tests off |
|
||||
@@ -1283,6 +1357,8 @@ The two `deliverability.*` values are read on every scheduling pass and every wa
|
||||
|
||||
The `placement.*` allowance, seed and spacing values are read when a test starts, so a change applies to the next test and never to one already sending. The four `placement.batch_*` values are read on every pass of the batch runner, about every 30 seconds, so a change reaches running batches within a minute; lowering the concurrency never stops a mailbox already sending, it only delays the next start. A value of zero or below resolves to the default, and one above the range to its ceiling. Which mailboxes form the instance seed panel is not a setting: an administrator marks them from the admin panel.
|
||||
|
||||
The three `store.*` values are read when a quote is made, so a change applies to the next quote and never to one a workspace is already paying from. A value outside its range is clamped to the nearest end rather than refused. They only charge anything on an instance that bills (`BILLING_PROVIDER=stripe`); with billing off, workspaces pay nothing whatever they say. The admin panel edits them in dollars and percent and previews what a customer pays.
|
||||
|
||||
Changing them is audited, and every value is validated and clamped server side on write as well as on read, so a row written by an older version still resolves.
|
||||
|
||||
### Usage pricing
|
||||
|
||||
@@ -191,6 +191,42 @@ Vendor connections and redirects travel in a [workspace export](/guides/workspac
|
||||
|
||||
Forwarding a domain through an inbox vendor, and a tracking `CNAME` written through one, are stored at the vendor, not here. Warmbly keeps only the vendor's domain list, in memory for five minutes.
|
||||
|
||||
### Purchased domains and mailboxes
|
||||
|
||||
Only an instance with the [domain and mailbox store](/development/configuration/#domain-and-mailbox-store) configured writes these. Each row is kept until the workspace is deleted, except quotes, which are cleared a day after they expire unless an order was paid from them, and applied webhook event ids, which are kept 31 days.
|
||||
|
||||
| Table | Holds | Secrets |
|
||||
|---|---|---|
|
||||
| `store_accounts` | The workspace's account id at GraphKit and the registrant its domains are registered to (name, organization, email, phone and postal address) | None |
|
||||
| `store_quotes` | Each quote's retail prices as shown to the buyer, so an order charges exactly what was on screen | None |
|
||||
| `store_orders` | Each order: the quote it was paid from, its setup steps, what was charged and refunded, and who placed it | None |
|
||||
| `store_domains` | Each purchased domain: its status, expiry, auto-renew, renewal price, forwarding URL and mail record checks | None |
|
||||
| `store_mailboxes` | Each purchased mailbox: its address, names, provider, monthly price, the date it is paid through, any pending cancellation, and the Warmbly mailbox it connected | None. A mailbox that connects over IMAP and SMTP stores its password on the connected mailbox, sealed like any other |
|
||||
| `store_webhook_events` | The id and arrival time of each GraphKit event already applied, so a redelivery is applied once | None |
|
||||
| `store_graphkit_connection` | The GraphKit API URL, API key and webhook secrets an operator added under **Setup and health > Integrations**, and who saved them last. At most one row, kept until **Disconnect** removes it; unused while `GRAPHKIT_API_KEY` is set | The API key and both webhook secrets, sealed under `CREDENTIALS_ENCRYPTION_KEY` |
|
||||
|
||||
The registrant also lives at GraphKit, which registers domains with it and keeps WHOIS privacy on wherever the extension allows. None of these tables travel in a [workspace export](/guides/workspace-export-import/), because what they describe is bought and billed through this instance's partner account. The mailboxes they connected do travel, and a domain leaves through transfer-out.
|
||||
|
||||
### Partners
|
||||
|
||||
Only an instance where an operator added a [partner](/development/partners/) writes these.
|
||||
|
||||
| Table | Holds | Kept | Secrets |
|
||||
|---|---|---|---|
|
||||
| `partners` | Each partner's names, status, allowed hosts, webhook and token callback addresses, wholesale prices and rate limit | Until removed | The webhook signing secrets and the token callback key, sealed with `CREDENTIALS_ENCRYPTION_KEY` |
|
||||
| `partner_api_keys` | Each partner key's mode, name and display ends | Until the partner is removed | Only a SHA-256 hash of the key |
|
||||
| `partner_organizations` | Which workspace a partner manages under which of its ids, its state, per-mailbox send limit and group | Until the workspace is deleted, then until the partner is told | None |
|
||||
| `partner_identities` | Which account a partner signs a person in as, with the address and name the partner gave | Until the account is deleted | None |
|
||||
| `partner_idempotency_keys` | The answer to each partner write, for a retry with the same key | 24 hours | The whole answer, sealed with `CREDENTIALS_ENCRYPTION_KEY`, since some carry an API key |
|
||||
| `partner_events` | Events for the partner and how their delivery went | 30 days | None |
|
||||
| `partner_mailboxes` | Each mailbox of a managed workspace: the partner's id for it, its source, enablement, how it connects and whether it was detached | Until the partner is removed, so billed days stay reportable after the mailbox or workspace is gone | None; a password a partner sends is sealed on the mailbox like any other and never stored here |
|
||||
| `partner_mailbox_enablements` | When each mailbox was enabled for sending and warmup or warmup only, the history mailbox-days are counted from | As long as its mailbox row | None |
|
||||
| `partner_connect_links` | Which mailbox a partner's connect link connects, as what, and where it returns | Until the workspace is deleted | None; the link's secret is a hash on `client_connect_links` |
|
||||
| `partner_groups` | Each partner group's brand (name, logo URL, accent colour, website, "Powered by"), its portal domain and whether it resolved | Until the partner is removed | None |
|
||||
| `partner_statements`, `partner_statement_lines` | Each closed month of a partner's enabled mailbox-days, per workspace, at the wholesale prices in force when it closed | Until the partner is removed | None |
|
||||
|
||||
None of these travel in a [workspace export](/guides/workspace-export-import/). A cancelled workspace is deleted 30 days after the partner cancels it, through the same delayed deletion an owner schedules.
|
||||
|
||||
### Disconnecting a mailbox
|
||||
|
||||
Disconnecting a mailbox, or deleting the workspace holding it, removes its rows from Postgres straight away through the database's own cascades. Two things cannot be done in that instant and are queued instead, then worked off within about a minute:
|
||||
@@ -376,6 +412,10 @@ These are made only when a workspace uses the feature behind them, so an instanc
|
||||
|
||||
Everything else is you: mail through the mailboxes you connect, DNS lookups for the domains you check, and whatever integrations you configure. There is no telemetry, no phone-home, and no license check.
|
||||
|
||||
### Domain and mailbox store
|
||||
|
||||
With `GRAPHKIT_API_KEY` unset, the default, the backend never contacts GraphKit. With it set, the backend calls the GraphKit API it is pointed at to search domains, quote and place orders, renew, cancel and transfer out, sending the workspace id, its name, the registrant and the names and addresses of the mailboxes ordered. No mail content and no mailbox credential is sent. The backend also tells GraphKit, at boot and daily, which Gmail scopes and which Microsoft application id and permissions purchased mailboxes should grant, and asks it for short-lived access tokens for purchased Google mailboxes. GraphKit calls back on `/v1/webhooks/graphkit`, once the operator registers that endpoint, with the current state of orders, domains and mailboxes.
|
||||
|
||||
### Error reporting
|
||||
|
||||
An instance reports errors nowhere unless you point it somewhere. Every service reads its own credentials and none of them ship with any, so a default install sends no crash, no stack trace and no browser error to anybody, including us.
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"accounts-and-access",
|
||||
"admin-panel",
|
||||
"warmblyctl",
|
||||
"partners",
|
||||
"data-control",
|
||||
"configuration",
|
||||
"warmup-generation",
|
||||
|
||||
@@ -69,6 +69,7 @@ A chat webhook URL is a bearer credential: anyone holding it can post to that ch
|
||||
| Warmup dispatch is overdue | Active, sending-enabled mailboxes have pending warmup tasks at least an hour past their intended schedule; this is not a provider-error diagnosis |
|
||||
| Warmup ban appealed | A blocked mailbox asks to rejoin the warmup pool |
|
||||
| Workspace risk escalated | Risk scoring moves a workspace into a different posture |
|
||||
| Domain and mailbox store unavailable | GraphKit refuses this instance's partner account: the partner is suspended, `GRAPHKIT_API_KEY` is refused, or the partner balance is too low for orders and renewals. Workspaces only see the store as unavailable, so this is how you learn the cause. Sent at most once an hour per cause; event key `store.unavailable`. See [domain and mailbox store](/development/configuration/#domain-and-mailbox-store) |
|
||||
| Admin signed in | An account holding platform admin access starts a new session, in the admin panel or the dashboard. The alert names the account, sign-in method, whether a second factor was presented, the device (flagged when it is new), the location and the IP address. Sent only to channels that tick it |
|
||||
| Admin access changed | Admin permissions are granted to, changed for, or revoked from an account in the admin panel, with who made the change. Saving permissions unchanged sends nothing. A change made with `warmblyctl` on the server is not reported |
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
---
|
||||
title: Partners
|
||||
description: Resellers that create, sign people in to and bill Warmbly workspaces through the partner API. Off until an operator adds one.
|
||||
---
|
||||
|
||||
A partner is a reseller that sells Warmbly inside its own product. Through the partner API it creates a Warmbly workspace for each of its customers, signs that customer's people in without a Warmbly password, issues the workspace an API key for its own integration, and bills the customer itself. GraphKit is one such partner on Warmbly Cloud.
|
||||
|
||||
The partner API is off on every instance until an operator adds a partner. A self-hosted instance needs nothing for it: no setting, no external account, and no change to an upgrade. With no partner, every request to `/v1/partner` answers `401`.
|
||||
|
||||
## Adding a partner
|
||||
|
||||
From the [admin panel](/development/admin-panel/), **Accounts > Organizations > Partners > New partner** (manage organizations, and a fresh confirmation). Or from the backend container:
|
||||
|
||||
```bash
|
||||
docker compose -p warmbly exec backend warmblyctl partner create --slug graphkit --name GraphKit --allowed-hosts app.graphkit.com
|
||||
docker compose -p warmbly exec backend warmblyctl partner key --partner graphkit --mode test
|
||||
docker compose -p warmbly exec backend warmblyctl partner list
|
||||
```
|
||||
|
||||
A partner has:
|
||||
|
||||
| Setting | What it decides |
|
||||
|---|---|
|
||||
| Slug | A short, permanent identifier |
|
||||
| Display name | What its workspaces' members read, as in "Billed through GraphKit" |
|
||||
| Status | `active`, or `suspended`, which makes every one of its keys answer `403 partner_suspended` |
|
||||
| Allowed hosts | Hosts a return URL the partner sends may point at |
|
||||
| Delegation domains | Domains you have confirmed the partner controls. A mailbox it attaches by `delegation` connects only on one of these, or on a domain its workspace verified itself. Empty by default; set it from the partner's page in the admin panel |
|
||||
| Webhook URL and signing secret | Where its events are delivered, and the secret they are signed with |
|
||||
| Token callback base and key | Where Warmbly asks the partner for short-lived mailbox access tokens, and the key it presents |
|
||||
| Wholesale per mailbox-day | What the partner pays per enabled mailbox-day, for sending and warmup and for warmup only. Both start at zero |
|
||||
| Requests per second | The rate limit across all of the partner's keys, 20 to 1,000 (50 by default) |
|
||||
|
||||
The webhook secret and callback key are stored encrypted with `CREDENTIALS_ENCRYPTION_KEY` and are never shown again once set. A partner owns a service account that owns its workspaces and that its workspace API keys act for. The account has no password and an address under the reserved `.invalid` domain, so nobody signs in as it and no mail is sent to it.
|
||||
|
||||
### Keys
|
||||
|
||||
A partner key is `wmbp_live_…` or `wmbp_test_…`, shown once and stored only as a SHA-256 hash. The prefix is the mode: a live key reaches only live workspaces and a test key only test ones, and the same id under the other mode is a different workspace. A test workspace is classified Test like an operator's [tester workspace](/development/accounts-and-access/). Revoke a key from the partner's page; anything using it stops at once.
|
||||
|
||||
## Managed workspaces
|
||||
|
||||
A workspace a partner creates runs on the private **Managed** plan: every feature (the API and webhooks, the unified inbox, CRM, placement tests, roles and the audit log), no plan tiers or send caps of its own, and no included AI allowance. Its members see **Billed through** the partner's display name instead of the billing page: no checkout, plan change, cancellation, balance top-up or workspace deletion. Those requests answer `403 partner_managed`.
|
||||
|
||||
The [store](/guides/buy-mailboxes/) is off in a managed workspace, because its customers buy in the partner's product: the dashboard shows no buy button, store link, **Purchased** tab, balance or **Add money**, and an empty **Mailboxes** page says mailboxes are added through the partner. Members with **Manage mailboxes** can still connect a mailbox they already have; it starts **off** (see [Enablement](#enablement)). An agency whose every client is managed has no **Store** page either.
|
||||
|
||||
People reach the workspace only through the partner's one-time login links. Each person is a separate Warmbly account bound to the partner's id for them and the key's mode, never to an existing account with the same email: a test key naming a person creates a test person and never reaches the live one. Their role comes from the partner on every sign-in (`admin` as Admin, `member` as Manager, `viewer` as Viewer). Such an account cannot set a password, add a passkey, a second factor or another sign-in method (`403 partner_account`), and a person the partner removes loses the membership and every session.
|
||||
|
||||
The account signs in under an unguessable address in the reserved `.invalid` domain, which no other sign-in can match and which never receives mail. The person's `email` from the partner is kept as their **contact email**: it is what the dashboard and the API show for them (the user menu, profile, member, team and agency staff lists, Slack and app authorizations, the audit log and `GET /v1/me`), and it is refreshed on the upsert that creates the workspace and on every login link. The contact email is never a sign-in and never a mail destination; platform mail to these accounts is dropped. It is optional: without one the person is shown by name only, never under the `.invalid` address. An address that does not parse, or one under `.invalid`, is `400 invalid_request`. A name the [display-name rules](/api/error-codes/#name-refusals) refuse is cleaned rather than refused, so a reconcile loop never sticks on it.
|
||||
|
||||
When the partner **suspends** a workspace, campaign sending and warmup stop, campaigns stay active and resume on their own when it is reactivated, and the workspace is read-only: members still sign in and read everything, while every change answers `403 organization_suspended` and a banner says the workspace is paused by the partner. The dashboard holds its write controls (connecting a mailbox, new campaigns, launching, importing contacts, new automations, composing, workspace settings, invitations) with the banner's explanation, and a change that still reaches the API is explained in the same words. When the partner **cancels** one, the same happens, the partner's API keys in it are revoked, and the workspace is deleted 30 days later through the normal workspace deletion unless the partner restores it first.
|
||||
|
||||
## The partner API
|
||||
|
||||
Base URL: `https://<your api host>/v1/partner`. Every request carries `Authorization: Bearer wmbp_…`.
|
||||
|
||||
| Method and path | What it does |
|
||||
|---|---|
|
||||
| `PUT /organizations/{external_id}` | Create (`201`) or update (`200`) a workspace under the partner's id for it |
|
||||
| `GET /organizations/{external_id}` | The workspace, with usage and warmup summaries |
|
||||
| `GET /organizations` | Every workspace in the key's mode, newest first |
|
||||
| `DELETE /organizations/{external_id}` | Cancel: suspend now, delete after 30 days |
|
||||
| `POST /organizations/{external_id}/login-links` | A one-time sign-in URL for a person, valid for 60 seconds |
|
||||
| `DELETE /organizations/{external_id}/people/{person_external_id}` | Remove a person and end their sessions |
|
||||
| `POST /organizations/{external_id}/api-keys` | A `wmbly_` workspace key for the partner's integration, shown once |
|
||||
| `DELETE /organizations/{external_id}/api-keys/{id}` | Revoke a key the partner created |
|
||||
| `GET /organizations/{external_id}/mailboxes` | The workspace's mailboxes, oldest first (detached ones left out) |
|
||||
| `PUT /organizations/{external_id}/mailboxes/{partner_mailbox_id}` | Attach a mailbox under the partner's id for it (`201`), or bring an attached one up to date (`200`) |
|
||||
| `DELETE /organizations/{external_id}/mailboxes/{partner_mailbox_id}` | Detach it: it stops and turns off, its history stays |
|
||||
| `PUT /organizations/{external_id}/enablements/{mailbox_id}` | Set what one mailbox may do: `sending_warmup`, `warmup_only` or `off` |
|
||||
| `POST /organizations/{external_id}/connect-links` | A one-time, hour-long page that connects an outside Google or Microsoft mailbox |
|
||||
| `GET /organizations/{external_id}/balance` | The workspace's balance for AI and usage |
|
||||
| `POST /organizations/{external_id}/balance/credits` | Add money the partner charged its customer for, once per `reference` |
|
||||
| `GET /usage/mailbox-days?month=YYYY-MM` | Enabled mailbox-days per mailbox in a month, for reconciliation |
|
||||
| `GET /usage?month=YYYY-MM` | Enabled mailbox-days and the wholesale amount per workspace in a month |
|
||||
| `GET /events?after=evt_…&limit=100` | The partner's events in order, kept 30 days |
|
||||
|
||||
The upsert body takes `name`, `plan` (`graphkit_managed`), `state` (`active` or `suspended`), `suspended_reason` (`billing`, `admin` or `reseller`), `limits.campaign_sends_per_mailbox_per_day`, `group`, `owner` (used only when the workspace is created) and `timezone`. A `PUT` on a cancelled workspace within its 30 days restores it. Unknown fields are ignored.
|
||||
|
||||
A login link body is `{"person": {"external_id", "email", "name", "role"}, "return_to"}`. `return_to` is a path inside the app, or an HTTPS URL on one of the partner's allowed hosts; anything else is `400 invalid_request`. The link opens `/auth/partner` on the dashboard, signs the person in once, selects the workspace and lands on `return_to`. A cancelled workspace issues no links (`409 organization_cancelled`); a suspended one does, read-only.
|
||||
|
||||
### Writes and retries
|
||||
|
||||
Every `POST`, `PUT`, `PATCH` and `DELETE` needs an `Idempotency-Key` of 1 to 255 visible characters (`400 idempotency_key_required` without one). Keys are kept 24 hours per partner and mode. The same key with the same body returns the first answer with `Idempotent-Replayed: true`, the API key secret included: answers are stored encrypted with `CREDENTIALS_ENCRYPTION_KEY`. The same key with another body is `409 idempotency_conflict`, and a key whose first request is still running is `409 idempotency_in_progress`. A request that has not finished after two minutes is treated as abandoned and the same request may run again; the abandoned one can no longer store or clear an answer under the key. A server error or a `401`, `403` or `429` frees the key, so a retry with it runs again.
|
||||
|
||||
### Errors and limits
|
||||
|
||||
Errors are `{"error": {"code", "message", "request_id"}}`: `invalid_request`, `idempotency_key_required`, `idempotency_conflict`, `idempotency_in_progress`, `unauthorized`, `partner_suspended`, `not_found`, `plan_unknown`, `permission_not_allowed`, `organization_suspended`, `organization_cancelled`, `mailbox_exists`, `connection_failed`, `delegation_not_allowed`, `provider_unavailable`, `rate_limited` and `internal`. An unknown path under `/v1/partner` answers `404 not_found` in the same shape. Over the partner's rate limit the answer is `429` with `Retry-After`. Lists are `{"data": […], "pagination": {"next_cursor", "has_more"}}` with `?cursor=&limit=` (at most 100). Timestamps are RFC 3339 in UTC and money is integer micro-USD.
|
||||
|
||||
### Webhooks
|
||||
|
||||
With a webhook URL and secret set, every event is posted to the URL with `X-Warmbly-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<unix>." + body)>`, the same scheme as [customer webhooks](/guides/webhooks/), plus `X-Warmbly-Event` and `X-Warmbly-Event-Id`. For a day after a rotation the header carries a second `v1=` signed with the previous secret. The body is `{"id", "type", "created_at", "organization_external_id", "livemode", "data"}`, where `data` is the current state of what the event is about. Delivery is at least once and in no guaranteed order, retried with backoff for 72 hours; a `2xx` within 10 seconds counts as delivered. The webhook URL must be HTTPS and public, unless the instance allows unsafe webhook URLs (`WARMBLY_ALLOW_UNSAFE_WEBHOOK_URLS`, development and self-hosted only).
|
||||
|
||||
Events: `organization.updated` (state, plan or limit changed, and on cancellation), `organization.deleted` (the workspace is gone), `mailbox.created` (a mailbox was connected inside the workspace or through a connect link), `mailbox.updated` (its status, enablement or warmup state changed, not on every send) and `mailbox.deleted` (it was removed inside Warmbly). `data` is the mailbox. A reader ignores types it does not know.
|
||||
|
||||
## Mailboxes
|
||||
|
||||
Every mailbox of a managed workspace has an id in the partner API (`id`, a UUID) and, when the partner attached it, the partner's own id for it (`partner_mailbox_id`). A mailbox answer carries `email`, `provider` (`google`, `microsoft` or `smtp`), `source`, `status` (`connecting` until its first sync, `connected`, `error` with `status_error`, or `disconnected`), `enablement`, `sends_today`, `daily_send_limit` and `warmup` (`state` is `off`, `ramping` or the mailbox's warmup health band, with `reason`, `daily_target`, `sent_7d`, `inbox_rate_7d` and `score`).
|
||||
|
||||
### Attaching
|
||||
|
||||
`PUT /organizations/{external_id}/mailboxes/{partner_mailbox_id}` takes `source`, `email`, `provider`, `first_name`, `last_name`, `enablement` and `connection`:
|
||||
|
||||
| `source` | `connection.method` | How Warmbly connects it |
|
||||
|---|---|---|
|
||||
| `graphkit_infrastructure` (bought through the partner) | `token` (Google) | Through the same purchased-mailbox path as the [store](/guides/buy-mailboxes/), with short-lived tokens from the partner's token callback (`POST {callback base}/mailboxes/{id}/access-token`). The token has to open exactly the attached address. Connects in the background a few seconds after the attach, retried with backoff |
|
||||
| `graphkit_infrastructure` | `delegation` (Google or Microsoft) | This instance's own Google service account or Microsoft app. Only for a domain the workspace already holds an active grant for (it verified the domain, or the store bought it), or one of the partner's delegation domains; anything else is `422 delegation_not_allowed`. Also in the background |
|
||||
| `graphkit_infrastructure` or `partner` | `password` | `connection.credentials` (`username`, `password` or Google's `app_password`, and `imap` and `smtp` host, port and `security` of `ssl` or `starttls`). Checked live during the call and sealed like any mailbox password; never kept anywhere else, logged or returned. A refusal is `422 connection_failed` |
|
||||
|
||||
A bought mailbox shows as **Purchased** in the workspace. An address the workspace already has is adopted under the partner's id instead of connected again. Attaching again applies the body's enablement and sender name, brings a detached mailbox back, and retries a connect that failed. A suspended or cancelled workspace refuses an attach (`409 organization_suspended` or `organization_cancelled`), and nothing a suspended partner attached connects until it is active again.
|
||||
|
||||
While the partner holds a mailbox it attached, the workspace's members cannot remove it or sign it in again: those requests answer `403 partner_managed_mailbox`, and the mailbox says it is managed by the partner. `DELETE …/mailboxes/{partner_mailbox_id}` detaches it: it turns off, stops connecting, keeps its history, and the members may then remove it themselves.
|
||||
|
||||
### Enablement
|
||||
|
||||
What a mailbox may do is its **enablement**, set by `PUT …/enablements/{mailbox_id}` with `{"enablement": "…"}` and on attach:
|
||||
|
||||
| Enablement | Campaigns | Warmup |
|
||||
|---|---|---|
|
||||
| `sending_warmup` | Yes | Yes |
|
||||
| `warmup_only` | Skipped, like a resting mailbox: its leads move to the campaign's other mailboxes | Yes |
|
||||
| `off` | No | No, and it leaves the warmup pools |
|
||||
|
||||
A mailbox someone connects inside a managed workspace starts **off**, and the partner hears about it as `mailbox.created`; the workspace shows it with "Turn it on" in the partner's product. Turning a mailbox on in a suspended or cancelled workspace is `409`; turning it off always works. Cancelling a workspace turns every mailbox off.
|
||||
|
||||
Enablement is enforced where every send is already decided, not in a parallel check: the scheduler's send admission skips a mailbox campaigns may not use, the dispatch gate refuses a campaign, warmup or placement send from it, and the warmup entitlement (the same one a lapsed plan turns off) is read per mailbox, so the task runner, the pool reconciler and pool membership all agree. The workspace's members see each mailbox's enablement read-only in **Mailboxes**.
|
||||
|
||||
### Daily campaign cap
|
||||
|
||||
`limits.campaign_sends_per_mailbox_per_day` on the workspace upsert caps each mailbox's campaign emails per UTC day (1 to 5,000; 50 by default). It applies with the mailbox's own daily limit, and the lower one binds. At the cap the mailbox stops until the next UTC midnight and campaigns move on to the workspace's other mailboxes; the dispatch gate refuses anything past it. Warmup, placement tests and replies do not count. `sends_today` and `daily_send_limit` on each mailbox show where it stands.
|
||||
|
||||
### Connect links
|
||||
|
||||
`POST /organizations/{external_id}/connect-links` with `provider` (`google` or `microsoft`), `partner_mailbox_id`, `enablement`, an optional `login_hint` and `return_url` answers `{"url", "expires_at"}`. The page is the [client connect page](/guides/agencies/#client-connect-links), in the group's brand, for that one provider. It works once and for an hour: the first mailbox connected spends it, and a used or expired link opens an explanation instead. The person signs in at Google or Microsoft (whose consent screen names this instance's OAuth app), the mailbox joins the workspace as `source: partner` under `partner_mailbox_id` with the requested enablement, the partner gets `mailbox.created`, and the browser returns to `return_url` with `?partner_mailbox_id=…&status=connected`, `cancelled` or `error`. `return_url` must be HTTPS on one of the partner's allowed hosts (`400 invalid_request` otherwise). An instance without Google or Microsoft sign-in, or without a portal address (`PORTAL_DOMAIN`), answers `422 provider_unavailable`.
|
||||
|
||||
### Group branding
|
||||
|
||||
`group.branding` on the workspace upsert (`product_name`, `logo_url`, `accent_color`, `website`, `hide_powered_by`, `portal_domain`) is the brand of every workspace sent with that group: its connect pages, shared reports and other public pages show it, and `hide_powered_by` is honoured on every plan. A workspace's own brand still wins. The group is not an agency: balances, limits and billing stay per workspace. A `portal_domain` is checked every few minutes for a CNAME to the portal address and the TXT record listed in `group.portal.dns_records`; `group.portal.status` turns `verified` once both resolve. Pages and sign-in links stay on the shared portal and app hosts for now.
|
||||
|
||||
## Usage and billing
|
||||
|
||||
A **mailbox-day** is a UTC day on which a mailbox had `sending_warmup` or `warmup_only` at any moment; it counts once, under the higher of the two it had. Days come from each mailbox's enablement history, so detached mailboxes and cancelled workspaces count for the days they were on.
|
||||
|
||||
- `GET /usage/mailbox-days?month=YYYY-MM` lists each mailbox with days in the month (`external_id`, `mailbox_id`, `partner_mailbox_id`, `email`, `sending_warmup_days`, `warmup_only_days`) and the month's `totals`, up to 1,000 rows a page with `?cursor=&limit=`.
|
||||
- `GET /usage?month=YYYY-MM` adds them up per workspace with `amount_micros` at the partner's wholesale prices, and `total_micros`. `final` is true once the month is closed.
|
||||
|
||||
A month closes one day after it ends: its days and amounts are written once at the prices in force then, and never change after that. Test-mode workspaces are counted but bill nothing. The admin panel's partner page shows the statement for any month, the running one at today's prices.
|
||||
|
||||
`GET …/balance` reads the workspace's balance for AI and usage (`owner` is always `organization`; the Managed plan includes no allowance). `POST …/balance/credits` with `amount_micros` (5 to 5,000 USD), `reference` and `description` adds money the partner charged its customer for; a `reference` already credited adds nothing and answers the current balance.
|
||||
|
||||
## Test mode
|
||||
|
||||
A workspace created with a test key sends no real mail: campaign, warmup and placement sends are refused at dispatch, its mailboxes never join the warmup pools, and manual sends are refused too. Everything else, enablement and mailbox-days included, works as in live mode.
|
||||
|
||||
## Data
|
||||
|
||||
Partners, their keys, the link between a partner and a workspace, its mailbox enablements and connect links, group brands and monthly statements belong to the instance. A [workspace archive](/guides/workspace-export-import/) never carries them, so an imported workspace is an ordinary one: its mailboxes travel, unmanaged. Partner events are kept 30 days and idempotency answers 24 hours. See [data control](/development/data-control/).
|
||||
@@ -183,6 +183,15 @@ warmblyctl admin recovery replay --id <dead-letter-uuid> --server laptop \
|
||||
|
||||
Acknowledging risk does not prove the message was not delivered or override server recovery guards. Never replay an uncertain send solely because a CLI diagnostic has no evidence. Webhook lease recovery is separately available as `admin recovery reclaim-webhooks`, with exact confirmation for `POST /admin/webhooks/reclaim`.
|
||||
|
||||
### Store diagnostics
|
||||
|
||||
The store's admin views have read helpers: `admin store health` (mode, partner balance, last webhook, reconciler and billing loops, stuck orders, failed connects, recent alerts) and `admin store orders`, `admin store domains` and `admin store mailboxes`, which take `--status`, `--q`, `--limit` (at most 100) and `--cursor`. Repairs such as a refund or a retried connect go through `admin api` with `--write` and an exact `--confirm`; an amount refund also needs an `Idempotency-Key`, so run it from the admin panel's Store section.
|
||||
|
||||
```bash
|
||||
warmblyctl admin store health --server laptop
|
||||
warmblyctl admin store orders --server laptop --status open
|
||||
```
|
||||
|
||||
### Cataloged admin API requests
|
||||
|
||||
```bash
|
||||
@@ -679,6 +688,18 @@ The input path must resolve to a regular file before opening, and the opened des
|
||||
|
||||
This is an inventory observation, not malware certification, import approval or send eligibility. It does not change archives, stored rows, private bytes, MIME metadata, duplication, restore or queued sends. It does not inspect live storage, retained queue messages, orphan objects, other archives or concurrent writes. Any later eligibility transition needs its own compatible migration stage covering old readers, retained messages, portability and rollback.
|
||||
|
||||
## partner
|
||||
|
||||
Adds and lists the [partners](/development/partners/) that run workspaces through the partner API, which answers nothing until one exists, and issues their keys.
|
||||
|
||||
```bash
|
||||
docker compose -p warmbly exec backend warmblyctl partner create --slug graphkit --name GraphKit --allowed-hosts app.graphkit.com
|
||||
docker compose -p warmbly exec backend warmblyctl partner list
|
||||
docker compose -p warmbly exec backend warmblyctl partner key --partner graphkit --mode live
|
||||
```
|
||||
|
||||
`partner key` prints the key once on standard output and nothing else there, so it can be piped into a secret store. `--display-name` sets what the partner's workspaces show as "Billed through"; it defaults to `--name`. Webhook, token callback and price settings are in the admin panel's **Partners** page.
|
||||
|
||||
## The API commands
|
||||
|
||||
Everything in this section talks to the public REST API with an API key, so it runs from anywhere: your laptop, a CI job, an agent's sandbox. It needs no database access and works against the hosted service and self-hosted instances alike.
|
||||
|
||||
@@ -11,28 +11,31 @@ AI and other metered features are paid from the workspace balance, in US dollars
|
||||
|
||||
<Step>
|
||||
|
||||
Open the **Balance** tab of **Settings > Billing** (it needs the **Manage billing** permission).
|
||||
Open the **Balance** tab of **Settings > Billing** (it needs the **Manage billing** permission) and select **Add funds**.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
Pick an amount: **$10**, **$25**, **$50**, **$100**, **$250**, or any other amount from $5 to $5,000.
|
||||
On **One-time**, pick **$10**, **$25**, **$50**, **$100** or **$250** ($25 is picked first), or enter another amount from $5 to $5,000; the arrows step by $10. Where [buying domains and mailboxes](/guides/buy-mailboxes/) is on, the amounts are **$100**, **$250**, **$500**, **$1,000**, **$2,500** and **$5,000** ($100 first), and the least is the store's minimum card charge, $10 unless it sets another. The dialog shows how long the balance would last with it.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
With a saved card, confirm **Pay** and the money is added at once. Without one, or to use another card, choose **Pay another way** to finish in Stripe Checkout, which saves the card for next time.
|
||||
Select **Pay**. The saved card is charged and the money is added at once. With no saved card, or after **Change**, enter a card right in the dialog; it is saved for next time and becomes the card charged from then on, before anything is charged, with any check your bank asks for shown there. **Pay another way** finishes in Stripe Checkout instead.
|
||||
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
The top of the Balance tab shows the balance and about how many days it lasts at what it pays for each day: a month of [bought mailboxes](/guides/buy-mailboxes/) spread over 30 days, domain renewals due in the next 60 days spread over the days until each is charged, and your average daily AI spend over the last 30 days. Where the store is on, **Your rates** beside it lists the mailbox and domain prices and the day of the month mailboxes are billed.
|
||||
|
||||
## Good to know
|
||||
|
||||
- The balance is in US dollars. A charge is the provider's price for what a call used plus a markup (25% by default).
|
||||
- Spending draws the monthly allowance first, then money you added.
|
||||
- Spending draws the monthly allowance first, then money you added, unless you keep AI to the allowance (see [after the included usage](#after-the-included-usage)).
|
||||
- Domains and mailboxes are paid only from money you added or your card, never from the monthly allowance.
|
||||
- Unused allowance does not roll over. Money you add never expires.
|
||||
- Before work starts, Warmbly checks the balance covers a typical call. Running out stops work before it starts, and a result you already received never fails.
|
||||
- Automatic reload adds money on your saved card when the balance runs low, up to a monthly limit you set.
|
||||
@@ -73,6 +76,17 @@ The allowance resets to the plan amount at the start of each billing cycle, and
|
||||
|
||||
Spending draws the allowance first and only touches money you added once the allowance is used up, so what you added is held back for heavy months.
|
||||
|
||||
### After the included usage
|
||||
|
||||
**Let AI use my balance after the included $X runs out**, in the AI spend section of the Balance tab, decides what happens once the month's allowance is spent. It is on unless you turn it off, which is how every workspace worked before the setting existed.
|
||||
|
||||
- **On**: AI keeps working and is paid from money you added. Tick **Use at most** to cap what AI takes from it each calendar month (UTC); at the cap, AI stops with `ai_overage_limit_reached` until the next month. Domain and mailbox charges never count toward the cap.
|
||||
- **Off**: AI stops for the rest of the month once the allowance is spent, with `ai_allowance_used`, and money you added is kept for [domains and mailboxes](/guides/buy-mailboxes/) and other charges. A client workspace in an agency still draws on the agency's [shared AI balance](/guides/agencies/#the-shared-ai-balance).
|
||||
|
||||
The setting covers everything the allowance pays for: AI features, the web searches they make and paid placement tests. The AI spend section shows both halves for the month: **Included AI: $X of $Y used** and **From your balance: $Z this month**.
|
||||
|
||||
Domains and mailboxes are the other way round: they are paid only from money you added (or your card), never from the allowance or an agency's shared AI balance.
|
||||
|
||||
A balance held in credits before Warmbly switched to dollars was converted to dollars, and purchased credits carry over as money you added, so they still never expire.
|
||||
|
||||
</Fold>
|
||||
@@ -137,11 +151,13 @@ The usage card above it shows spend today, this week and this month, a graph ove
|
||||
|
||||
## Adding money and your saved card
|
||||
|
||||
You can add any amount from **$5 to $5,000**, in whole cents. Adding money needs an active paid plan.
|
||||
You can add any amount from **$5 to $5,000** ($10 or the store's minimum card charge where the store is on), in whole cents. Adding money needs an active paid plan.
|
||||
|
||||
- **One click on the saved card.** The card is charged at once and the money is added as soon as the payment goes through. If the payment is still going through when the page answers, the Balance tab says so and updates when it lands; Warmbly finishes it in the background, and another payment cannot start until it does. Each charge is billed as a Stripe invoice, so it has its own invoice and receipt.
|
||||
- **Pay another way.** Opens Stripe Checkout for the amount. Use it when there is no saved card, when you want another card, or when the saved card is declined or your bank asks to confirm the payment. Checkout saves the card for next time. Money arrives only after Stripe confirms the payment, so closing the checkout tab charges nothing, and a completed payment is added exactly once even if Stripe retries.
|
||||
- **Change the card.** Opens Stripe Checkout to save a new card, without charging anything.
|
||||
- **A new card in the dialog.** With no saved card, or after **Change**, the card is entered in the dialog, saved and made the workspace's card before it is charged, so a replaced card is never the one billed. If your bank asks to confirm, the check opens in the page.
|
||||
- **Pay another way.** With a saved card, opens Stripe Checkout for the amount, to pay with another card or method.
|
||||
- **Stripe Checkout as a fallback.** When the saved card is declined or your bank asks to confirm a one-click payment, or when the card field cannot load, the payment carries on in Stripe Checkout, which saves the card for next time. Money arrives only after Stripe confirms the payment, so closing the checkout tab charges nothing, and a completed payment is added exactly once even if Stripe retries.
|
||||
- **Payment method.** Saves a new card in place, without charging anything.
|
||||
|
||||
The card shown is the one on the workspace's Stripe billing account (brand and last four digits). Card details are held by Stripe and never touch Warmbly.
|
||||
|
||||
@@ -151,7 +167,7 @@ The card shown is the one on the workspace's Stripe billing account (brand and l
|
||||
|
||||
## Automatic reload
|
||||
|
||||
Automatic reload adds money on the saved card when the balance falls below a threshold, so AI never pauses for an empty balance. It needs a saved card and an active paid plan.
|
||||
Automatic reload adds money on the saved card when the balance falls below a threshold, so AI never pauses for an empty balance. Turning it on needs a saved card and an active paid plan; turning it off never does, so a workspace whose plan lapsed can still switch it off. Set it on the **Auto top-up** tab of **Add funds**, which starts from the values below.
|
||||
|
||||
| Setting | Default | Range |
|
||||
|---------|---------|-------|
|
||||
@@ -159,6 +175,8 @@ Automatic reload adds money on the saved card when the balance falls below a thr
|
||||
| **Add** | $25 | $5 to $5,000, and more than the threshold |
|
||||
| **Monthly limit** | $250 | at least one reload, up to $50,000 |
|
||||
|
||||
Where the store is on, a first setup starts at next month's mailbox charge (at least $10) for the threshold, $100 for each reload and $500 a month, and each reload adds at least the store's minimum card charge.
|
||||
|
||||
The monthly limit counts every automatic reload in the calendar month. When less than a full reload is left under it, Warmbly adds what is left if that is at least $5, and otherwise waits for next month.
|
||||
|
||||
When a reload is declined:
|
||||
@@ -169,7 +187,11 @@ When a reload is declined:
|
||||
|
||||
A reload waiting for a retry is canceled, never charged, when you turn automatic reload off or the balance is back above the threshold by the time it is due.
|
||||
|
||||
The Balance tab shows the last reload, how much has been reloaded this month, and a pending retry with its time.
|
||||
If you [buy mailboxes](/guides/buy-mailboxes/#automatic-top-ups), Warmbly turns automatic reload on with your first purchase, unless you set it up yourself or untick it at checkout, and keeps it sized to your mailboxes: below what the next monthly mailbox charge needs, it adds at least $10. Once you change those amounts here, Warmbly leaves them as you set them. Store charges also put at least $10 on the card when the balance falls short, and what the charge does not use stays on the balance.
|
||||
|
||||
Domains and mailboxes are paid only from money you added (or your card), never from the monthly allowance or an agency's shared AI balance: those pay for AI usage alone.
|
||||
|
||||
The Balance tab shows the last reload, how much has been reloaded this month, a pending retry with its time and an **Update card** button, and a warning when the saved card expires within about a month.
|
||||
|
||||
</Fold>
|
||||
|
||||
@@ -187,7 +209,7 @@ Everyone with **Manage billing** gets an in-app notice when the balance falls be
|
||||
|
||||
| Control | Behavior |
|
||||
|---------|----------|
|
||||
| **Spend limits** | Optional caps in dollars per calendar day, ISO week and calendar month. At the limit, AI pauses with a clear message until the window rolls over |
|
||||
| **Spend limits** | Optional caps in dollars per calendar day, ISO week and calendar month. At the limit, AI pauses with a clear message until the window rolls over. Domain and mailbox charges never count toward them |
|
||||
| **Per-member limits** | The same three windows per teammate, in dollars, counting only charges they triggered. Workspace-level work (automations, the inbox agent) is attributed to nobody |
|
||||
|
||||
Each limit shows current spend against it, and changes collect into a save bar. Who can use AI at all is separate: the **Use AI** role permission (see [Team and roles](/guides/team-roles/)).
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
---
|
||||
title: Buy mailboxes
|
||||
description: "Buy domains and Google Workspace or Microsoft 365 mailboxes inside Warmbly. Domains at cost, mailboxes $3 a month, set up and connected for you with warmup on."
|
||||
---
|
||||
|
||||
Buy new sending domains and Google Workspace or Microsoft 365 mailboxes on them without leaving Warmbly, or put new mailboxes on a domain you already own. Warmbly registers the domain, publishes its mail records, creates the mailboxes and connects them to your workspace with warmup on.
|
||||
|
||||
## Buy mailboxes
|
||||
|
||||
Buying is one screen: search, your senders and your order across the page, the order summary and **Pay** in a column on the right (on a phone, the summary is a bar at the bottom that opens upward).
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
|
||||
On **Mailboxes**, open **Add** and choose **Buy new mailboxes**.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
Search for a domain and add the ones you want. Each result shows its price and what it costs to renew. To use a domain you already have, open **Use a domain I already own** under the search; see [a domain you already own](#a-domain-you-already-own).
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
Set up your **Senders** once: the people the mailboxes send as, each with a first and last name and a profile photo. It starts with you. Each domain you add appears under **Your order** with mailboxes for your senders, named after them and carrying their photo: three for one sender, two each for two senders, and one each for three or more. One line under the senders sums up what every domain gets; the defaults make a complete order, and **Customize** there changes the addresses, provider, count and signature. Switch a domain between Google and Microsoft on its card, or open **Customize** on the card to change that domain's mailboxes on their own; see [senders](#senders).
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
Check the summary and select **Pay**. Until the order can be paid, a short checklist above the button says what is missing (a domain, a sender's name, the registrant details) and ticks each item off as you complete it. It is paid from the workspace balance, and your saved card covers anything the balance does not. With no saved card, enter one in the summary; it is saved for the monthly charges in the same step, with any check your bank asks for shown right there.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
|
||||
The summary turns into the setup as it happens. The new mailboxes appear on **Mailboxes**, connected and warming up.
|
||||
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Good to know
|
||||
|
||||
- Buying needs a Warmbly plan. Without one, the buy page offers the plans instead of the checkout. See [billing](/guides/billing/).
|
||||
- Domains are sold at cost. Mailboxes are $3 per mailbox per month, Google or Microsoft alike.
|
||||
- Some domain endings register for at least two years, such as `.ai`. The price shown covers that whole first term.
|
||||
- A domain you already own can take mailboxes too, with nothing charged for the domain.
|
||||
- Domain prices can change over time. You always see the price, and what the domain renews at, before you pay.
|
||||
- A renewal charges the renewal price current at the time. A notice 37 days before the domain expires tells you that price, at least 7 days ahead of the charge.
|
||||
- Domains renew automatically by default, charged 30 days before they expire. You can turn this off per domain.
|
||||
- Purchased mailboxes carry a **Purchased** chip on **Mailboxes** and in their drawer.
|
||||
- Mailboxes are billed monthly from the workspace balance.
|
||||
- Cancelling a mailbox takes effect at the end of the month you paid for, and you can resume it until then. When it ends it is switched off in Warmbly and its history stays until you disconnect it.
|
||||
- A purchased mailbox you still pay for has no **Disconnect**: removing it would not stop its billing. Cancel it, or switch it off to pause it.
|
||||
- A domain can leave Warmbly whenever you want: you get its transfer code on request.
|
||||
- If your plan ends, purchased mailboxes stay yours and keep billing. Reading and replying keep working; campaign sending and warmup on them pause until a plan is active again. See [when your plan ends](#when-your-plan-ends).
|
||||
- Viewing needs **Manage mailboxes**. Paying, renewing and cancelling need **Manage billing** and a recent sign-in.
|
||||
- Every purchase is kept under [**Orders**](#orders), and store charges have their own filter in the billing history.
|
||||
- The store works from the [API and the CLI](#managing-by-api-and-cli) too, and agencies get an [overview across clients](#for-agencies).
|
||||
|
||||
<Fold>
|
||||
|
||||
## What you can buy
|
||||
|
||||
| Item | Price | When you pay |
|
||||
|------|-------|--------------|
|
||||
| A domain | At cost, the price shown in search | Its first term when you order, then each yearly renewal |
|
||||
| A Google Workspace mailbox | $3 per month | The first month when you order, then monthly |
|
||||
| A Microsoft 365 mailbox | $3 per month | The first month when you order, then monthly |
|
||||
|
||||
The summary shows what is due today and what you pay each month after it, line by line. It is priced again as you change the order, and each price is held for 15 minutes, so what you see is what you are charged. Domain prices are set by the registries and change from time to time; if one changed before you paid, Warmbly shows the new total and asks you to confirm it, and nothing is charged until you do.
|
||||
|
||||
A domain is registered for its extension's shortest term, which is one year for most and two for some, such as `.ai`. Search shows the term next to the price, the price covers the whole term, and the renewal price is per year after it. Privacy is turned on wherever the extension allows it, so your contact details are not published in the public registration record. Premium names, which a registry prices above its standard rate, are not offered.
|
||||
|
||||
Each domain uses one mail provider. To have both Google and Microsoft mailboxes, buy them on separate domains. You can add more mailboxes to a domain you already bought later, up to 5 on that domain, and nothing is charged for the domain again.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Finding a domain
|
||||
|
||||
Type your brand or a keyword. The exact name comes first, marked **Exact match** when it is available, followed by available variations: the keyword with a short prefix or suffix (`get`, `try`, `hq`, `team` and similar) and on other extensions. Extensions are limited to ones with a good reputation for mail (`.com`, `.co`, `.io`, `.net`, `.org`, `.ai`). A taken exact match is still shown, with the reason it cannot be bought.
|
||||
|
||||
Buy two or three domains per brand rather than one, with about three mailboxes on each. Cold outreach is safer spread across many mailboxes sending a modest amount each than concentrated on a few, and spreading those mailboxes across domains means a problem with one domain's reputation or records does not stop the others. Keep your main company domain out of cold outreach entirely; the bare domain of each new one can forward visitors to your website.
|
||||
|
||||
Neither the number of domains nor how they are named guarantees inbox placement. Mailbox providers judge each sender on how its mail is received, so new mailboxes still need warmup and a gradual start. See [deliverability](/guides/deliverability/).
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## A domain you already own
|
||||
|
||||
A domain registered somewhere else can take Google Workspace or Microsoft 365 mailboxes bought here. The domain stays registered where it is, you keep renewing it there, and nothing is charged for it in Warmbly.
|
||||
|
||||
On **Buy new mailboxes**, open **Use a domain I already own** under the search, type the domain, and pick how to connect it:
|
||||
|
||||
| Method | What you do | What Warmbly does |
|
||||
|--------|-------------|-------------------|
|
||||
| **Change nameservers** (recommended) | At your registrar, replace the domain's nameservers with the two Warmbly shows, and turn DNSSEC off if it is on, or the change does not take | Copies the records the domain serves today, so your website and other services keep working, then keeps every mail record right from then on |
|
||||
| **Add DNS records** | Keep your DNS where it is and add the records Warmbly lists at your DNS provider, starting with the ownership record | Watches for the records and tells you which ones it has seen |
|
||||
|
||||
The domain's page shows where the connection stands and updates live: waiting for the nameservers or records, connected, or moved away. Warmbly checks on its own, often at first, and **Check now** checks straight away. Members with **Manage mailboxes** get a notification when the domain connects.
|
||||
|
||||
The instructions last 48 hours. If the change has not shown up by then, the connection times out, you get a notification, and **Start again** on the domain gives you a fresh set of nameservers or a fresh ownership record. Anything you already changed for the old set has to be changed again.
|
||||
|
||||
Once the domain is connected, add it to your order and set its mailboxes as you would for a new domain. Mailboxes can be bought on it when both of these are true:
|
||||
|
||||
- **It is connected.** A domain still waiting for its nameservers or records is not ready yet.
|
||||
- **Nothing on it clashes with mail.** A record that conflicts with the mail records the domain needs, such as another provider's MX record, is listed on the domain as in the way. Delete it there when Warmbly holds the domain's DNS; otherwise remove it at your DNS provider. Mailboxes cannot be ordered until every one is gone.
|
||||
|
||||
Some mail setups need the mail provider to hold the domain's DNS. When that applies, the summary says so: after the order, set the new nameservers shown on the domain at your registrar.
|
||||
|
||||
If the nameservers or records later change so they no longer point at Warmbly, the domain shows as moved away and you get a notification, because its mail records may stop working. Put them back as the domain's page shows.
|
||||
|
||||
To stop using a connected domain, choose **Remove domain** on its page. Cancel its mailboxes first; a domain that still has mailboxes cannot be removed. Removing it stops Warmbly looking after its records, and the domain stays registered where it is. A domain you bought here leaves by [transfer](#taking-a-domain-elsewhere) instead.
|
||||
|
||||
A domain that another workspace bought or is already connecting cannot be added, and neither can one already in your workspace; the message says which.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Senders
|
||||
|
||||
A sender is a person the mailboxes send as: a name and a photo. You set the senders once for the whole order, and every domain in it follows them:
|
||||
|
||||
- **Names.** Each sender needs a first and a last name; Google and Microsoft both require one for every account. Names that look like a link, a web address or an email address are refused, as everywhere else in Warmbly. The addresses are made from these names, so to get `matt@` type Matt as the first name, or type the address you want under the domain's **Customize**.
|
||||
- **Photo.** Each sender has one profile photo, used on every mailbox of theirs on every domain. The first sender starts with your own profile photo when you have uploaded one.
|
||||
- **Add sender.** Up to 5 senders.
|
||||
|
||||
Under the senders, one line sums up what every domain following them gets, for example `3 mailboxes per domain · matt@, matt.m@, matt.meszaros@ · Google · Signature: Default`. Nothing there needs changing to place an order. Select **Customize** on that line to change it; the page remembers whether you left it open:
|
||||
|
||||
- **Per sender.** How many mailboxes each sender gets on every domain. Until you change it, it follows the number of senders: 3 for one sender (each in a different [address pattern](#address-patterns), such as `matt@`, `matt.m@` and `matt.meszaros@`), 2 each for two senders, and 1 each for three to five. Once you set it yourself, your number stays. A domain holds at most 5 mailboxes, so when your number times the senders would pass that, it is lowered to fit and the page says so; your number comes back when there are fewer senders. **Use the suggested** returns to the automatic count. Adding a sender is never blocked by this.
|
||||
- **Addresses.** The [address patterns](#address-patterns) that turn each name into an address, for every domain at once.
|
||||
- **Provider.** Google or Microsoft for every domain. A domain card can switch its own; the rest follow the order's choice. A domain you already own that has mailboxes keeps their provider.
|
||||
- **Signature.** **Default**, **None** or **Custom**; see [signatures](#signatures).
|
||||
|
||||
Changing a sender's name or photo, or anything under **Customize**, updates every domain that follows the senders.
|
||||
|
||||
### Address patterns
|
||||
|
||||
A pattern is how a name becomes the part before the `@`. Each one shows an example made from your first sender's name:
|
||||
|
||||
| Pattern | Matt Meszaros gets |
|
||||
|---------|--------------------|
|
||||
| first | `matt@` |
|
||||
| first.l | `matt.m@` |
|
||||
| first.last | `matt.meszaros@` |
|
||||
| firstlast | `mattmeszaros@` |
|
||||
| first_last | `matt_meszaros@` |
|
||||
| first-last | `matt-meszaros@` |
|
||||
| f.last | `m.meszaros@` |
|
||||
| flast | `mmeszaros@` |
|
||||
| firstl | `mattm@` |
|
||||
| last | `meszaros@` |
|
||||
| last.first | `meszaros.matt@` |
|
||||
| lastf | `meszarosm@` |
|
||||
|
||||
Open **Addresses** to tick the patterns you want and put them in order with the arrows (or Alt and the arrow keys). Each sender's mailboxes on a domain take the patterns in that order: with `first`, `first.l` and `first.last`, a sender with three mailboxes gets `matt@`, `matt.m@` and `matt.meszaros@`. A sender with more mailboxes than patterns continues with the patterns you did not tick, in the order of the table.
|
||||
|
||||
Until you choose, one sender uses `first`, `first.l` and `first.last`, and two or more senders use `first.last`. **Use the suggested** in the list goes back to that.
|
||||
|
||||
Names are turned into plain letters first: accents are dropped (`José` makes `jose`, `Müller` makes `muller`) and letters such as `ß`, `æ`, `ø`, `ł`, `đ` and `þ` are spelled out (`ss`, `ae`, `o`, `l`, `d`, `th`). Only the first word of a first name is used, so Mary Ann makes `mary@`. A last name of several words is joined (`van der Berg` makes `vanderberg`), and a hyphenated one keeps its hyphen where the last name stands as its own word (`jose.nunez-ortiz@`) and is joined elsewhere (`josenunezortiz@`). Anything else that cannot be in an address is left out, and an address is at most 64 characters.
|
||||
|
||||
No two mailboxes on a domain get the same address. When two senders would, the second moves on to its next pattern, and the domain card says so. Only when every pattern is taken, as with two senders of the same name, does an address get a number at the end; type another address for it under the domain's **Customize** to avoid it.
|
||||
|
||||
### Customizing one domain
|
||||
|
||||
Select **Customize** on a domain card to change that domain alone: how many mailboxes it has (1 to 5), which sender each one belongs to, and its addresses. The card is marked **Customized**, and later changes to the number of senders no longer change it. Addresses you have not typed there still follow the sender's name and the address patterns. Select **Follow the senders** to undo the customization.
|
||||
|
||||
An address that is not allowed, or that appears twice on one domain, is flagged as you type, and the card stays open until it is fixed.
|
||||
|
||||
### Website forward
|
||||
|
||||
Anyone who visits a new domain's bare address (`getacme.com`) is sent to your company website. The card shows it as "Visitors to getacme.com go to acme.com". It starts as:
|
||||
|
||||
- the workspace's own website, the one set under **Settings > Branding**, when there is one
|
||||
- otherwise the domain of your own email address, when it is a company domain rather than a free provider such as Gmail or Outlook
|
||||
- otherwise nothing, so the domain does not forward
|
||||
|
||||
Select **Change** to type another address, or remove it so the domain does not forward. One forward applies to every new domain in the order. A domain you already own keeps its own website. You can change the forward later from the domain on the **Purchased** tab of **Domains**.
|
||||
|
||||
### Profile photos
|
||||
|
||||
The photo of each sender becomes the real Google or Microsoft profile picture of every mailbox of theirs, the one recipients see next to the sender name in Gmail and Outlook. Choose a PNG or JPG, crop it to a square, and it is saved for the order; remove it to buy that sender's mailboxes without a photo. One upload serves all of a sender's mailboxes.
|
||||
|
||||
Warmbly sets the photo as soon as each mailbox exists, while it is still being set up, and keeps trying if the provider does not take it at first. A photo never holds up the order. The photo also shows next to the mailbox in Warmbly as soon as the mailbox connects.
|
||||
|
||||
To change it later, open the mailbox and select **Change photo** in its **Subscription** card. To give several purchased mailboxes the same photo, select them on **Mailboxes** and choose **Set profile photo** in the selection bar; it appears only when every selected mailbox was bought here. A photo can be replaced but not removed: the provider keeps the last photo set.
|
||||
|
||||
### Signatures
|
||||
|
||||
Every new mailbox gets a signature, chosen under **Customize** in **Signature**:
|
||||
|
||||
- **Default** signs with the mailbox's full name, `{{.Sender.Name}}`.
|
||||
- **None** buys the mailboxes without a signature.
|
||||
- **Custom** opens the mailbox signature editor. Write the signature once and use **Insert placeholder** for the sender fields: `{{.Sender.FirstName}}`, `{{.Sender.LastName}}`, `{{.Sender.Name}}` and `{{.Sender.Email}}`. They are the same placeholders as a [signature on many mailboxes](/guides/mailboxes/#one-signature-on-many-mailboxes), filled in the same way, and anything else in double braces, such as a contact field, is flagged and sent exactly as written.
|
||||
|
||||
A preview shows the signature filled in for the first mailbox in the order. When you pay, each mailbox gets its own finished signature, with its sender's name and its own address.
|
||||
|
||||
The signature is set when each mailbox connects:
|
||||
|
||||
- **In Warmbly**, as the mailbox's signature, added to the mail Warmbly sends from it, for both providers.
|
||||
- **On the Google account**, as the Gmail signature of the mailbox's address, so mail written in Gmail signs the same way.
|
||||
- **Microsoft 365** has no way for Warmbly to set the signature in Outlook, so those mailboxes sign in Warmbly only.
|
||||
|
||||
If setting it fails, Warmbly keeps trying in the background, and it never holds up the order. It is set once: to change it later, edit the mailbox's signature in its settings, or several at once by selecting them on **Mailboxes** and choosing **Signature** in the selection bar.
|
||||
|
||||
### The admin mailbox
|
||||
|
||||
Each domain's Google Workspace or Microsoft 365 account has one admin, and it is one of the mailboxes you buy on that domain. Choose it with **Admin** next to an address under **Customize**; if you do not, the first mailbox is the admin, and the card marks the admin with a shield. The admin mailbox sends and warms up like the others. Mailboxes you add to the domain later join the same account and keep the admin it already has.
|
||||
|
||||
The admin mailbox carries an **Admin** badge in its **Subscription** card, with an **Admin sign-in** button that shows the address, username, password and sign-in page for the Google or Microsoft admin console of that domain. It asks for a recent sign-in. The details are fetched fresh each time and shown once, so copy what you need before you close the dialog.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Paying
|
||||
|
||||
Every store charge is automatic. The order is paid from money you added to the workspace balance, and when that does not cover it, Warmbly charges your saved card in the same step and adds that to the balance first. The card is charged at least $10 (or your automatic reload amount, when that is larger), so a $3 shortfall adds $10: $3 pays the order and $7 stays on the balance for the next charge. Fewer, larger card charges keep card fees down. Checkout shows this before you pay, for example **Adds $10.00 to your balance · $3.00 used now, $7.00 left**. You never need to top up the balance or turn on automatic reload first. When the balance covers the order, the summary says **Paid from your balance** with what is left, and no card is asked for. When it is short, a chip such as **Add $100 instead** rounds the card charge up to a larger amount, which then stays on the balance.
|
||||
|
||||
Store charges come only from money you added to the balance, or from your card. The monthly AI allowance your plan includes pays for AI usage and never for domains or mailboxes, so a workspace with allowance left and nothing added pays the store by card. Checkout shows the money you added as the balance it pays from. Without a saved card, the summary shows a card field: **Pay** saves the card for the monthly charges (running any 3-D Secure check your bank asks for in the page) and places the order in the same press. If the card field cannot load, for example when a browser extension blocks it, **Pay** takes you to Stripe's page to add the card, and when you come back the order is placed for you at the total you saw. If a price changed meanwhile, the new total is shown and waits for you to pay.
|
||||
|
||||
Paying asks for a recent sign-in, like other changes that move money. See [balance and usage](/guides/ai-credits/) for how the balance and the saved card work.
|
||||
|
||||
Registering a domain needs a registrant: the person or company the domain is registered to, with an address and phone number. Warmbly fills it in from your billing details and your account and saves it with your first order, without asking. Only when the registry needs something those do not have (a phone number or a street address, say) does the summary ask, listing just the missing fields; a field the registry did not accept is marked there too.
|
||||
|
||||
If an order is refused before anything is set up, the charge goes back to the balance. If one part of an order fails later (a domain that could not be registered, a mailbox that could not be created), that part is refunded to the balance and the rest continues.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## How setup works
|
||||
|
||||
After you pay, the order page shows six steps as they happen. It updates live, so you can leave it and come back, or share the link with a teammate.
|
||||
|
||||
| Step | What happens |
|
||||
|------|--------------|
|
||||
| Register | The domain is registered |
|
||||
| DNS | The domain's DNS is set up, with forwarding to your website if you asked for it |
|
||||
| Mail authentication | MX, SPF, DKIM and DMARC records are published |
|
||||
| Mailboxes | The mailboxes are created with their names |
|
||||
| Connect | Warmbly is given access to the mailboxes |
|
||||
| Ready | The mailboxes are connected to your workspace |
|
||||
|
||||
Registering the domain and publishing its records usually takes a few minutes; some domain extensions take longer to register. Creating the mailboxes at Google or Microsoft can take from a few hours to a couple of days, and the **Mailboxes** step stays running until it is done. Nothing is needed from you meanwhile: the steps after it carry on by themselves, and Warmbly sends a notification when the order is ready, or when part of it could not be set up and was refunded. DMARC starts at `p=none`, the setting that reports without rejecting, which you can tighten once the mailboxes send reliably.
|
||||
|
||||
On a [domain you already own](#a-domain-you-already-own) there is nothing to register, so the **Register** step is skipped.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Connected automatically, with warmup on
|
||||
|
||||
Purchased mailboxes connect without a password or a sign-in screen. Warmbly is given access to them during setup, the same way an [admin grant](/guides/mailbox-import/#connect-a-whole-google-workspace-domain) gives it access to a whole domain. On the rare domain where that is not possible, Warmbly connects the mailbox over IMAP and SMTP with credentials it receives once and stores encrypted.
|
||||
|
||||
Warmup is turned on for each new mailbox with your workspace's default warmup settings, where your plan includes warmup, and each mailbox's sender name is set from its first and last name, and its [signature](#signatures) from the order. A new mailbox should warm for a few weeks before it carries cold campaigns; see [warmup](/guides/warmup/).
|
||||
|
||||
New mailboxes start sending gently and ramp up on their own. Starting warmup puts each one under the [warmup graduation](/guides/warmup/#graduating-to-cold-sending) ceiling, so in a campaign whose ramp-up is **As replies come in**, the default, it starts cold sending at five a day and earns more as real recipients reply, up to the mailbox's daily cap of `50`. There is nothing to set up. A campaign set to ramp on a schedule or send at full volume uses that instead; see [ramp-up](/guides/campaigns/#ramp-up). No starting volume guarantees inbox placement.
|
||||
|
||||
Purchased mailboxes show a **Purchased** chip next to their address on **Mailboxes** and in the mailbox drawer, and everything else about them works like any other mailbox. If one cannot be connected after a few attempts, its order shows it as failed; the mailbox itself is still yours and billed, so contact support.
|
||||
|
||||
A domain bought here also gets its open and click [tracking host](/guides/sending-domains/#one-tracking-host-for-a-whole-domain), `link.` followed by the domain (such as `link.getacme.com`), when its first mailbox connects. Warmbly publishes its records itself and points every mailbox on the domain at it, including mailboxes you add to the domain later, so there is nothing to set up. If writing the records fails, Warmbly tries again every hour. The forward you chose is the domain's website redirect. The **Domains** list shows the domain as purchased, and **Finish setting up** never lists it, because its tracking host and redirect are already taken care of.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Your domains and mailboxes
|
||||
|
||||
Purchased domains are listed on the **Purchased** tab of **Domains**: each with its expiry date, an **Auto-renew** switch, **Renew now**, its forwarding URL and its DNS records. Domains you connected are listed there too, marked as renewed at their registrar, with their connection status in place of the renewal controls.
|
||||
|
||||
A purchased mailbox has a **Subscription** card in its drawer, with its monthly price, the date it is paid through, and the button to cancel or resume it. While it is live, its **Danger zone** offers **Cancel subscription** in place of **Disconnect**, and its row menu on **Mailboxes** shows **Cancel subscription** too, which opens the drawer there.
|
||||
|
||||
### DNS records
|
||||
|
||||
A domain's page lists its DNS records. Where Warmbly holds the domain's DNS (a domain bought here, or one connected by changing its nameservers), you can add records and edit or delete any record that is not locked, including the ones copied over when you connected the domain. Use this, for example, to verify the domain with another service. A record's type is fixed once it is created; to change it, delete it and add a new one.
|
||||
|
||||
The records Warmbly keeps for mail and the website forward (MX, SPF, DKIM, DMARC, the provider's verification, the ownership record and the forward) are locked, so they cannot be changed by accident. A new record that would clash with them, such as a second MX, is refused.
|
||||
|
||||
On a domain connected by adding DNS records, your DNS provider holds the records, so add or change them there; the page lists them for reference, and the locked ones are the ones mail needs.
|
||||
|
||||
**Check records** looks the records up in public DNS and marks each one live or not seen yet, along with the nameservers that answered. A record you just changed can take a while to show up everywhere.
|
||||
|
||||
### Owner email and transfer requests
|
||||
|
||||
Domain registries sometimes ask the owner to confirm their email address, typically after a domain is registered or its owner details change. Members with **Manage mailboxes** get a notification naming the address and the deadline, and the domain's page shows it until it is confirmed. Open the message sent to that address and confirm before the deadline, or the domain may stop working.
|
||||
|
||||
If another registrar asks to take a domain you bought here, members with **Manage billing** get a notification, with the date it completes unless it is cancelled at the new registrar. If you did not start the transfer, contact support before that date.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Orders
|
||||
|
||||
Every purchase is kept as an order. Open **Orders** from the header of **Mailboxes**, from the **Add account** menu there, from the store, or from the **Purchased** tab of **Domains** to see them all, newest first, at `/app/emails/buy/orders`. Each order shows its status (being charged, setting up, completed, partly failed or failed), what it contained, what was charged and anything refunded to the balance.
|
||||
|
||||
Open an order to see its lines one by one, the charge and each refund. An order that is still setting up shows the same live setup track you saw after paying, so you can follow it from here or share the link with a teammate. The track updates as each step lands, and keeps moving every couple of seconds even when the live connection to Warmbly is interrupted. Members with **Manage mailboxes** can see orders.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Domain renewals
|
||||
|
||||
Auto-renew is on for every domain you buy. Each domain renews for another year on this schedule:
|
||||
|
||||
| When | What happens |
|
||||
|------|--------------|
|
||||
| 37 days before expiry | An upcoming-renewal notice, such as "getacme.com renews on Oct 17, 2027 for $11.17", with the current renewal price. If the price went up since the last notice, it says so |
|
||||
| 30 days before expiry | The renewal is charged from the workspace balance, and your saved card pays whatever the balance does not cover. Never sooner than 7 days after the notice |
|
||||
|
||||
A domain less than 7 days from expiry with auto-renew on is renewed straight away rather than waiting on a notice, so it is never lost to the wait. A renewal is charged at the domain's renewal price at that time, which can differ from the price shown when you bought it if the registry has changed it since. The **Purchased** tab always shows the current one.
|
||||
|
||||
**Renew now** on a domain renews it straight away, on the same terms.
|
||||
|
||||
When auto-renew is off, or a renewal payment did not go through, Warmbly reminds you 30, 7 and 1 day before the domain expires. A failed renewal is refunded and retried the next day. If the card was declined or your bank asked to confirm the payment, the notice links straight to updating your card, and saving a card retries the renewal at once. Once a domain expires, its mail and the mailboxes on it can stop working, so renew before the date.
|
||||
|
||||
Renewal and payment notices go to members with **Manage billing**, as billing alerts in the app and by email when their notification settings send those.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Mailbox billing
|
||||
|
||||
A mailbox's first month is paid when you buy it. After that, every mailbox in the workspace is billed together once a month, on the workspace's billing day: the day of the month you bought your first mailbox (the 28th for a first purchase on the 29th, 30th or 31st). Each month's charge is made a few days before the billing day (5 by default) and covers every mailbox whose next month starts before the following billing day, so mailboxes bought on different days still mean one charge a month, as one line such as "Mailboxes · 12 × $3.00 · Dec 2026". A mailbox's next month is always paid before it starts. The **Subscription** card shows the date it is paid through and the date of the next charge.
|
||||
|
||||
The charge comes out of the workspace balance; when the balance falls short, your saved card tops it up, by at least $10, with nobody needing to be there.
|
||||
|
||||
If the provider raises a mailbox's price, Warmbly tells you before the month at the new price, and that month is charged at it.
|
||||
|
||||
### Automatic top-ups
|
||||
|
||||
With your first purchase, Warmbly turns on [automatic reload](/guides/ai-credits/#automatic-reload) for the balance, sized to your mailboxes: it adds at least $10 when the balance falls below what your next monthly charge needs, and tops the balance up two days before that charge, so the monthly charge itself comes out of the balance. When a store charge does need the card, the card is also charged what keeps the balance at the reload threshold afterwards (at most one more reload amount), so a purchase never sets off a second card charge minutes later. As you add or cancel mailboxes, Warmbly keeps those amounts in step, within your monthly reload limit.
|
||||
|
||||
It is not turned on if you set automatic reload up yourself, or if you untick it at checkout. Change or turn it off any time under **Settings** > **Billing** > **Balance**; once you change it by hand, Warmbly never changes it again. Without automatic reload, store charges still go through: the card is charged when one is due.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Store charges on your bill
|
||||
|
||||
Store charges come out of the workspace balance, so they are listed with every other charge under **Settings** > **Billing**, one line per item: a domain registration, a month of mailboxes, a renewal, and a refund when part of an order could not be set up. Choose the **Store** filter on that history to see only those lines. The billing page needs **Manage billing**.
|
||||
|
||||
Each time your card pays part of a store charge, you get a receipt with your other invoices, described by what it paid for, such as "Mailboxes · 3 × $3.00 · Dec 2026". Members with **Manage billing** also get a short notice: "You were charged $9.00 for …".
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## When a payment fails
|
||||
|
||||
When neither the balance nor your card can pay the monthly charge (the card was declined, your bank asked to confirm the payment, or there is no card), Warmbly tells you why, with the date the mailboxes stop if it stays unpaid, and tries again every day, telling you each time.
|
||||
|
||||
A day before the first unpaid month would start, the unpaid mailboxes are set to stop at their provider at the end of the month already paid, and you get one more notice: "Your mailboxes stop on Dec 16 unless your card is updated". They keep working until then. Pay before that date and they are resumed and keep running; if the provider can no longer resume one, the month you paid for it goes back to the balance. After that date they are gone, with their mail.
|
||||
|
||||
Each notice links to updating your card. Saving a card pays what is unpaid straight away, without waiting for the next daily attempt. Adding money to the balance works too, and the next daily attempt pays from it.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## When your plan ends
|
||||
|
||||
Buying needs a Warmbly plan, but the mailboxes you already bought do not go away when it ends. Without an active plan:
|
||||
|
||||
- the mailboxes stay connected and keep syncing, and the unified inbox keeps working for the whole workspace: reading, replying and drafts
|
||||
- campaign sending and warmup on the purchased mailboxes pause
|
||||
- each mailbox keeps billing at its monthly price from the workspace balance, and you can still cancel it
|
||||
- buying more domains or mailboxes, or connecting a domain you own, waits for a plan
|
||||
|
||||
Members with **Manage billing** get one notice when this happens, in the app and by email when their notification settings send billing alerts. Each paused mailbox says so in its **Subscription** card, with a link to the plans. Choose a plan and sending and warmup turn back on. See [billing](/guides/billing/).
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Cancelling and resuming
|
||||
|
||||
Cancel a mailbox from its **Subscription** card. It keeps working until the end of the month it is in, and is cancelled then. Nothing more is charged for it, and the unused part of that month is not refunded. If the next month was already paid with the monthly charge, or is being charged as you cancel, that month goes back to the balance, once for each time it was paid. Cancelling a mailbox that was set to stop for an unpaid month makes it your own cancellation: saving a card afterwards no longer charges or resumes it.
|
||||
|
||||
Until that date, **Resume** undoes the cancellation, billing continues as before and the mailbox keeps working. If its next month was not paid yet and falls before your next monthly charge, resuming charges that month first, and the month counts as paid only once the provider confirms the resume. If the provider refuses, that charge goes back to the balance. A resume while that payment is still going through answers `charge_in_progress`.
|
||||
|
||||
On that date the mailbox is deleted at its provider, with its mail and sign-in. Warmbly then switches the mailbox off for you: campaign sending, syncing and warmup stop, and it leaves the warmup pool. Members with **Manage billing** get one notice that it was cancelled and switched off. The same happens when a mailbox is cancelled because its month went unpaid, or by support.
|
||||
|
||||
A cancelled mailbox stays on **Mailboxes** marked **Cancelled** with the date, so its campaign history, conversations and warmup history stay readable. It cannot be switched back on or reconnected, and Warmbly never connects it again. When you no longer need its history, **Disconnect** it from its drawer to delete it.
|
||||
|
||||
### Why a mailbox you still pay for has no Disconnect
|
||||
|
||||
Disconnecting a connected mailbox removes Warmbly's access to it. A purchased mailbox belongs to your subscription, not to a sign-in you gave Warmbly, so disconnecting it would neither delete it nor stop its billing. While it is live, removing or reconnecting it is refused; cancel it instead, or switch it off from its drawer to pause sending, syncing and warmup while you keep it.
|
||||
|
||||
To stop paying for a domain, turn off its **Auto-renew**. It stays yours until it expires.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Taking a domain elsewhere
|
||||
|
||||
A domain is never locked to Warmbly. On its page, choose **Transfer out** in the danger zone to unlock it and get its transfer authorization code, then start the transfer at the registrar you are moving to. This needs **Manage billing** and a recent sign-in.
|
||||
|
||||
Moving the registration does not move the mailboxes. If the new registrar's DNS replaces the records Warmbly published, mailboxes on the domain stop receiving mail and fail authentication, so copy the mail records from the domain's page first, or cancel the mailboxes before you move it.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Who can do what
|
||||
|
||||
| Action | Permission |
|
||||
|--------|------------|
|
||||
| See purchased domains, mailboxes and orders | **Manage mailboxes** |
|
||||
| Rename a purchased mailbox, change its profile photo, change a forwarding URL | **Manage mailboxes** |
|
||||
| Connect, check or remove a domain you already own | **Manage mailboxes** |
|
||||
| Add, edit or delete a domain's DNS records | **Manage mailboxes** |
|
||||
| Show the admin sign-in | **Manage mailboxes** and a recent sign-in |
|
||||
| Pay for an order, renew a domain, turn auto-renew on or off | **Manage billing** and a recent sign-in |
|
||||
| Cancel or resume a mailbox | **Manage billing** and a recent sign-in |
|
||||
| Get a domain's transfer code | **Manage billing** and a recent sign-in |
|
||||
| Change the registrant | **Manage billing** |
|
||||
|
||||
See [team roles](/guides/team-roles/) for how permissions are assigned.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Managing by API and CLI
|
||||
|
||||
Everything on this page can be done from the API as well as the dashboard: search, quotes, orders, domains, DNS records and mailboxes. An API key or OAuth app needs two permissions:
|
||||
|
||||
- **`READ_STORE`** to read the store, its orders, domains and mailboxes.
|
||||
- **`MANAGE_STORE`** to ask for quotes and make changes. Paying, renewing, turning auto-renew on or off, cancelling or resuming a mailbox and getting a transfer code also need the member who made the key to hold **Manage billing**, checked on every request.
|
||||
|
||||
Buying by API spends the workspace balance, like buying in the dashboard. Prices are confirmed the same way: if a domain price changed before the order, nothing is charged and the answer carries the new total to confirm. See the [store endpoints](/api/endpoints/#domains-and-mailboxes) and [permissions](/api/permissions/).
|
||||
|
||||
The [Warmbly CLI](/api/cli/#buying-domains-and-mailboxes) has the same store under `warmbly store`: `search`, `quote`, `buy`, `orders`, `order watch` to follow setup live, `domains`, `mailboxes` and `registrant`. `warmbly store buy` shows the total and asks before it charges.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## For agencies
|
||||
|
||||
An [agency](/guides/agencies/) sees the infrastructure it bought across all its clients in one overview: each client's domains and mailboxes, its monthly spend, renewals coming up in the next 30 days, and anything that needs attention, such as a mailbox that could not be connected, a payment that did not go through, or a domain with auto-renew off. Each client links straight into its **Purchased** domains, its mailboxes and its orders. Only clients where you can manage mailboxes are included.
|
||||
|
||||
Agency staff working in a client workspace buy for that client: the client's plan decides whether it can buy, staff need **Manage billing** in that workspace to pay, and every charge comes out of money added to the client's own balance, then the client's saved card for the rest. The agency's shared AI balance pays for AI usage only, never for the store. A workspace a partner manages keeps the store off; see [workspaces managed by a partner](#workspaces-managed-by-a-partner).
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Moving a workspace
|
||||
|
||||
Purchased domains, domains you connected here, and mailbox subscriptions do not travel in a [workspace archive](/guides/workspace-export-import/), because they are bought and billed through the instance that sold them. The mailboxes they connected are ordinary mailboxes and move with the archive. To take a domain with you, [transfer it out](#taking-a-domain-elsewhere); a domain you connected is still registered where it always was.
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Self-hosted instances
|
||||
|
||||
On a self-hosted instance, buying needs one thing from the operator: a GraphKit API key. Until it is added, **Buy new mailboxes** shows with a lock under **Add account**, and the buy page says a key is needed. An instance admin gets a button to **Setup and health > Integrations** in the admin panel, where the key goes; anyone else can copy a short note asking their operator to add it. The operator can set `GRAPHKIT_API_KEY` in the environment instead, which takes precedence. See [configuration](/development/configuration/#adding-the-key-in-the-admin-panel). The locked state is shown only on an instance whose `DEPLOYMENT_MODE` is self-hosted (or that falls back to it with `BILLING_PROVIDER=none`); a hosted instance without a key shows no store at all.
|
||||
|
||||
On instance that does not bill its users, the self-host default, no plan is needed to buy, so the plan rules on this page do not apply. The operator sets the mailbox price and any markup on domains, and decides whether workspaces pay: on an instance that does not bill its users, workspaces are charged nothing and the operator's own account pays for every domain and mailbox. See [configuration](/development/configuration/#domain-and-mailbox-store).
|
||||
|
||||
</Fold>
|
||||
|
||||
<Fold>
|
||||
|
||||
## Workspaces managed by a partner
|
||||
|
||||
A workspace that a Warmbly partner manages for you buys its domains and mailboxes through that partner. **Buy new mailboxes** is not shown there; ask your partner for new domains or mailboxes.
|
||||
|
||||
</Fold>
|
||||
|
||||
## Related guides
|
||||
|
||||
<Cards>
|
||||
<Card title="Mailboxes" href="/guides/mailboxes/" />
|
||||
<Card title="Sending domains" href="/guides/sending-domains/" />
|
||||
<Card title="Warmup" href="/guides/warmup/" />
|
||||
<Card title="Balance and usage" href="/guides/ai-credits/" />
|
||||
</Cards>
|
||||
@@ -622,6 +622,8 @@ It keeps its worker assignment while off, so switching it back on puts it back o
|
||||
|
||||
**Disconnecting** removes the mailbox for good. It is on the mailbox's own **More** menu in the list, as **Disconnect mailbox**, and at the bottom of its **Settings** tab under Danger zone. To remove several at once, tick their rows and use the selection bar. The machine syncing it is told to drop it before the record is removed, because afterwards there is nothing left to tell. If that instruction cannot be delivered, the disconnect fails with a `503` and nothing is removed, so retry it in a moment rather than assuming it worked.
|
||||
|
||||
A mailbox [bought through Warmbly](/guides/buy-mailboxes/#cancelling-and-resuming) has no **Disconnect** while you still pay for it, because removing it would not stop its billing: cancel it from its **Subscription** card, or switch it off to pause it. Once its subscription ends it is switched off, keeps its history, and can be disconnected like any other mailbox. A mailbox a partner attached is removed through the partner.
|
||||
|
||||
A mailbox belongs to the workspace, not to the member who connected it. Anyone with the **Manage mailboxes** permission can switch any of the workspace's mailboxes off, change its warmup, or disconnect it, including ones a teammate added and ones whose owner has since left. That is the same permission the list itself is behind, so a mailbox you can see is a mailbox you can act on.
|
||||
|
||||
Everything belonging to that mailbox goes with it: its imported mail in the unibox, its warmup history and pool membership, its credentials, its sender links, and any send still scheduled for it. A campaign that was using it keeps running on its remaining senders, and the leads it had been writing to move onto them at their next step. Export the workspace first if you want a copy. Disable the mailbox instead when you only want it to stop.
|
||||
@@ -772,6 +774,16 @@ Health is judged only on what happened while the mailbox was in the pool: signal
|
||||
|
||||
</Fold>
|
||||
|
||||
## In a workspace a reseller manages
|
||||
|
||||
When a reseller (a [partner](/development/partners/)) runs and bills the workspace, it decides what each mailbox may do, and **Mailboxes** shows it on every mailbox, read-only:
|
||||
|
||||
- **Sending & warmup**: campaigns send from it and it warms up.
|
||||
- **Warmup only**: it warms up, and campaigns skip it and use the workspace's other mailboxes.
|
||||
- **Off**: no campaigns and no warmup. It stays connected and keeps its history.
|
||||
|
||||
New mailboxes come through the reseller: the workspace has no store, so there is nothing to buy here. A mailbox you connect here starts **Off**; turn it on in the reseller's product. While the reseller has the workspace paused it is read-only, so connecting is held until it resumes. The reseller may also cap how many campaign emails each mailbox sends per UTC day, below the mailbox's own limit. A mailbox the reseller added is removed or reconnected there, not here: those actions answer that it is managed by the reseller.
|
||||
|
||||
## Related guides
|
||||
|
||||
<Cards>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"---Sending---",
|
||||
"mailboxes",
|
||||
"mailbox-import",
|
||||
"buy-mailboxes",
|
||||
"migrate-from-another-tool",
|
||||
"sending-domains",
|
||||
"sending-behavior",
|
||||
|
||||
@@ -273,6 +273,10 @@ A few things belong to the instance rather than the workspace and are left out o
|
||||
|
||||
[Migrations from another tool](/guides/migrate-from-another-tool/) do not travel, finished or running. A migration is work the source instance is doing, and while it runs it holds the other tool's API key. What it brought over (contacts, draft campaigns, mailboxes and suppressions) is ordinary workspace data and moves with its group. Let a running migration finish before exporting, or what it has not reached yet is not in the archive.
|
||||
|
||||
[Purchased domains and mailbox subscriptions](/guides/buy-mailboxes/) do not travel, and neither do their orders, the saved registrant or the profile photos uploaded for them (each mailbox's photo is already set at its provider, and the connected mailbox carries its own copy). They are bought and billed through the instance that sold them, which keeps paying for them, so an archive cannot hand them to another instance. The mailboxes they connected are ordinary mailboxes and move with the Workspace group, but on the destination they are no longer billed or renewed by the store, and they stop working when the source instance's subscription ends. Cancel them on the source, or keep the source workspace paying for them. To take a domain with you, [transfer it out](/guides/buy-mailboxes/#taking-a-domain-elsewhere) to a registrar of your choice.
|
||||
|
||||
The link to a [partner](/development/partners/) that manages and bills a workspace does not travel, and neither does what the partner set per mailbox (its enablement, the days billed for it, its connect links) or its group's brand. They name a reseller, its keys and its billing on the source instance, so an imported workspace is an ordinary one whose mailboxes arrive unmanaged, and the partner links a workspace again through its own API.
|
||||
|
||||
The list of past exports and imports does not travel either. Each job is a record of work the instance that ran it did, and an export's archive lives in that instance's storage until it expires. The destination lists only the exports and imports run there.
|
||||
|
||||
A [community directory](/guides/integrations/#community-apps) listing does not travel. The OAuth app itself moves with the archive, but its listing is a publication on the source instance, featured or hidden by its team. Publish it again on the destination, where it starts as link only and is featured or not by that instance's team. An app suspended on the source arrives suspended, and so does every app imported into a workspace whose members may not build apps on the destination; the destination's operators decide whether to lift it. An import never clears a suspension the destination already applied. Each app passes the same checks as registering it: a name that breaks the [naming rules](/api/error-codes/#name-refusals) becomes "Imported app", and a website, redirect URI or webhook address the destination would refuse is dropped. Its logo arrives empty, so upload it again.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Saving a card in the checkout is a billing action: the workspace, manage_billing and a fresh session, like every balance route.
|
||||
func TestCardSetupIntentRouteIsABillingRoute(t *testing.T) {
|
||||
file, err := parser.ParseFile(token.NewFileSet(), "routes.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok || len(call.Args) < 2 {
|
||||
return true
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok || sel.Sel.Name != "POST" {
|
||||
return true
|
||||
}
|
||||
group, ok := sel.X.(*ast.Ident)
|
||||
lit, isLit := call.Args[0].(*ast.BasicLit)
|
||||
if !ok || group.Name != "subscriptions" || !isLit {
|
||||
return true
|
||||
}
|
||||
if path, _ := strconv.Unquote(lit.Value); path != "/balance/setup-intent" {
|
||||
return true
|
||||
}
|
||||
found = true
|
||||
var org, billing, fresh bool
|
||||
for _, arg := range call.Args[1:] {
|
||||
c, ok := arg.(*ast.CallExpr)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
s, ok := c.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch s.Sel.Name {
|
||||
case "RequireOrganization":
|
||||
org = true
|
||||
case "RequireFreshAuth":
|
||||
fresh = true
|
||||
case "RequirePermission":
|
||||
if len(c.Args) == 1 {
|
||||
if p, ok := c.Args[0].(*ast.SelectorExpr); ok && p.Sel.Name == "PermManageBilling" {
|
||||
billing = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !org || !billing || !fresh {
|
||||
t.Errorf("POST /subscription/balance/setup-intent gates: organization %v, manage_billing %v, fresh auth %v", org, billing, fresh)
|
||||
}
|
||||
return true
|
||||
})
|
||||
if !found {
|
||||
t.Fatal("POST /subscription/balance/setup-intent is not registered")
|
||||
}
|
||||
}
|
||||
@@ -11,31 +11,36 @@ import (
|
||||
// Each of these changes who can get in or moves money or ownership, so its registration carries RequireFreshAuth.
|
||||
func TestRoutesThatNeedAFreshConfirmation(t *testing.T) {
|
||||
want := map[string]bool{
|
||||
"org DELETE /members/:id": false,
|
||||
"org POST /roles": false,
|
||||
"org PATCH /roles/:id": false,
|
||||
"org DELETE /roles/:id": false,
|
||||
"subscriptions POST /checkout": false,
|
||||
"subscriptions POST /portal": false,
|
||||
"subscriptions POST /cancel": false,
|
||||
"subscriptions POST /change-plan": false,
|
||||
"subscriptions POST /offers/:planId/checkout": false,
|
||||
"subscriptions POST /balance/top-up": false,
|
||||
"subscriptions POST /balance/checkout": false,
|
||||
"subscriptions POST /balance/payment-method": false,
|
||||
"subscriptions PATCH /balance/auto-reload": false,
|
||||
"subscriptions PATCH /credits/settings": false,
|
||||
"poolLink POST /checkout": false,
|
||||
"apiKeys POST ": false,
|
||||
"apiKeys PATCH /:id": false,
|
||||
"webhooks POST ": false,
|
||||
"webhooks PATCH /:id": false,
|
||||
"webhooks POST /:id/rotate-secret": false,
|
||||
"org POST /members/invite": false,
|
||||
"org POST /transfer-ownership": false,
|
||||
"org POST /current/danger-zone/delete": false,
|
||||
"adminRoutes POST /testers/:id/password": false,
|
||||
"protectedAuth POST /passkey/register/finish": false,
|
||||
"org DELETE /members/:id": false,
|
||||
"org POST /roles": false,
|
||||
"org PATCH /roles/:id": false,
|
||||
"org DELETE /roles/:id": false,
|
||||
"subscriptions POST /checkout": false,
|
||||
"subscriptions POST /portal": false,
|
||||
"subscriptions POST /cancel": false,
|
||||
"subscriptions POST /change-plan": false,
|
||||
"subscriptions POST /offers/:planId/checkout": false,
|
||||
"subscriptions POST /balance/top-up": false,
|
||||
"subscriptions POST /balance/checkout": false,
|
||||
"subscriptions POST /balance/payment-method": false,
|
||||
"subscriptions POST /balance/setup-intent": false,
|
||||
"subscriptions POST /balance/setup-intent/default": false,
|
||||
"subscriptions PATCH /balance/auto-reload": false,
|
||||
"subscriptions PATCH /credits/settings": false,
|
||||
"poolLink POST /checkout": false,
|
||||
"apiKeys POST ": false,
|
||||
"apiKeys PATCH /:id": false,
|
||||
"webhooks POST ": false,
|
||||
"webhooks PATCH /:id": false,
|
||||
"webhooks POST /:id/rotate-secret": false,
|
||||
"org POST /members/invite": false,
|
||||
"org POST /transfer-ownership": false,
|
||||
"org POST /current/danger-zone/delete": false,
|
||||
"adminRoutes POST /testers/:id/password": false,
|
||||
"adminRoutes PUT /store/connection": false,
|
||||
"adminRoutes POST /store/connection/test": false,
|
||||
"adminRoutes DELETE /store/connection": false,
|
||||
"protectedAuth POST /passkey/register/finish": false,
|
||||
}
|
||||
file, err := parser.ParseFile(token.NewFileSet(), "routes.go", nil, 0)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
func (h *Handler) partnersAvailable(c *gin.Context) bool {
|
||||
if h.Partners == nil {
|
||||
errx.JSON(c, errx.New(errx.ServiceUnavailable, "partners are not available on this instance"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Handler) adminPartnerParam(c *gin.Context) (uuid.UUID, *uuid.UUID, bool) {
|
||||
adminID := middleware.GetAdminUserID(c)
|
||||
if adminID == nil {
|
||||
errx.JSON(c, errx.ErrUnauthorized)
|
||||
return uuid.Nil, nil, false
|
||||
}
|
||||
if !h.partnersAvailable(c) {
|
||||
return uuid.Nil, nil, false
|
||||
}
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "invalid partner id"))
|
||||
return uuid.Nil, nil, false
|
||||
}
|
||||
return id, adminID, true
|
||||
}
|
||||
|
||||
func (h *Handler) logPartnerAction(c *gin.Context, adminID, partnerID uuid.UUID, action string, details map[string]any) {
|
||||
if h.AdminService != nil {
|
||||
h.AdminService.LogAdminAction(c.Request.Context(), adminID, action, "partner", &partnerID, details, c.ClientIP(), c.Request.UserAgent())
|
||||
}
|
||||
}
|
||||
|
||||
// AdminListPartners is GET /admin/partners.
|
||||
func (h *Handler) AdminListPartners(c *gin.Context) {
|
||||
if !h.partnersAvailable(c) {
|
||||
return
|
||||
}
|
||||
list, err := h.Partners.Repo.ListPartners(c.Request.Context())
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.InternalError())
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": list})
|
||||
}
|
||||
|
||||
type adminPartnerDetail struct {
|
||||
*models.Partner
|
||||
Keys []models.PartnerAPIKey `json:"keys"`
|
||||
}
|
||||
|
||||
// AdminGetPartner is GET /admin/partners/:id: the partner and its keys.
|
||||
func (h *Handler) AdminGetPartner(c *gin.Context) {
|
||||
id, _, ok := h.adminPartnerParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.writePartnerDetail(c, id)
|
||||
}
|
||||
|
||||
func (h *Handler) writePartnerDetail(c *gin.Context, id uuid.UUID) {
|
||||
p, err := h.Partners.Repo.GetPartner(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.InternalError())
|
||||
return
|
||||
}
|
||||
if p == nil {
|
||||
errx.JSON(c, errx.ErrNotFound)
|
||||
return
|
||||
}
|
||||
keys, err := h.Partners.Repo.ListPartnerKeys(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.InternalError())
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, adminPartnerDetail{Partner: p, Keys: keys})
|
||||
}
|
||||
|
||||
// AdminCreatePartner is POST /admin/partners.
|
||||
func (h *Handler) AdminCreatePartner(c *gin.Context) {
|
||||
adminID := middleware.GetAdminUserID(c)
|
||||
if adminID == nil {
|
||||
errx.JSON(c, errx.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
if !h.partnersAvailable(c) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
DisplayName string `json:"display_name"`
|
||||
AllowedHosts []string `json:"allowed_hosts"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
p, xerr := h.Partners.CreatePartner(c.Request.Context(), partner.CreatePartnerInput{
|
||||
Slug: req.Slug, Name: req.Name, DisplayName: req.DisplayName, AllowedHosts: req.AllowedHosts,
|
||||
}, adminID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.logPartnerAction(c, *adminID, p.ID, "create_partner", map[string]any{"slug": p.Slug})
|
||||
h.writePartnerDetail(c, p.ID)
|
||||
}
|
||||
|
||||
// AdminUpdatePartner is PATCH /admin/partners/:id.
|
||||
func (h *Handler) AdminUpdatePartner(c *gin.Context) {
|
||||
id, adminID, ok := h.adminPartnerParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Status *models.PartnerStatus `json:"status"`
|
||||
AllowedHosts *[]string `json:"allowed_hosts"`
|
||||
DelegationDomains *[]string `json:"delegation_domains"`
|
||||
WebhookURL *string `json:"webhook_url"`
|
||||
CallbackBaseURL *string `json:"callback_base_url"`
|
||||
WholesaleSendingWarmupDay *int64 `json:"wholesale_sending_warmup_day_micros"`
|
||||
WholesaleWarmupOnlyDay *int64 `json:"wholesale_warmup_only_day_micros"`
|
||||
RateLimitPerSecond *int `json:"rate_limit_per_second"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
_, xerr := h.Partners.UpdatePartner(c.Request.Context(), id, partner.UpdatePartnerInput{
|
||||
Name: req.Name, DisplayName: req.DisplayName, Status: req.Status, AllowedHosts: req.AllowedHosts, DelegationDomains: req.DelegationDomains,
|
||||
WebhookURL: req.WebhookURL, CallbackBaseURL: req.CallbackBaseURL,
|
||||
WholesaleSendingWarmupDay: req.WholesaleSendingWarmupDay, WholesaleWarmupOnlyDay: req.WholesaleWarmupOnlyDay,
|
||||
RateLimitPerSecond: req.RateLimitPerSecond,
|
||||
})
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
details := map[string]any{}
|
||||
if req.Status != nil {
|
||||
details["status"] = string(*req.Status)
|
||||
}
|
||||
if req.DelegationDomains != nil {
|
||||
details["delegation_domains"] = len(*req.DelegationDomains)
|
||||
}
|
||||
h.logPartnerAction(c, *adminID, id, "update_partner", details)
|
||||
h.writePartnerDetail(c, id)
|
||||
}
|
||||
|
||||
// AdminRotatePartnerWebhookSecret is POST /admin/partners/:id/webhook-secret: the new secret, shown once.
|
||||
func (h *Handler) AdminRotatePartnerWebhookSecret(c *gin.Context) {
|
||||
id, adminID, ok := h.adminPartnerParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
secret, xerr := h.Partners.RotateWebhookSecret(c.Request.Context(), id)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.logPartnerAction(c, *adminID, id, "rotate_partner_webhook_secret", nil)
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.JSON(http.StatusOK, gin.H{"secret": secret})
|
||||
}
|
||||
|
||||
// AdminSetPartnerCallbackKey is PUT /admin/partners/:id/callback-key.
|
||||
func (h *Handler) AdminSetPartnerCallbackKey(c *gin.Context) {
|
||||
id, adminID, ok := h.adminPartnerParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
if xerr := h.Partners.SetCallbackKey(c.Request.Context(), id, req.Key); xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.logPartnerAction(c, *adminID, id, "set_partner_callback_key", map[string]any{"cleared": req.Key == ""})
|
||||
h.writePartnerDetail(c, id)
|
||||
}
|
||||
|
||||
// AdminCreatePartnerKey is POST /admin/partners/:id/keys: the key, shown once.
|
||||
func (h *Handler) AdminCreatePartnerKey(c *gin.Context) {
|
||||
id, adminID, ok := h.adminPartnerParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Mode models.PartnerMode `json:"mode"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
k, xerr := h.Partners.CreateKey(c.Request.Context(), id, req.Mode, req.Name, adminID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.logPartnerAction(c, *adminID, id, "create_partner_key", map[string]any{"key_id": k.ID.String(), "mode": string(k.Mode)})
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.JSON(http.StatusCreated, k)
|
||||
}
|
||||
|
||||
// AdminRevokePartnerKey is DELETE /admin/partners/:id/keys/:keyId.
|
||||
func (h *Handler) AdminRevokePartnerKey(c *gin.Context) {
|
||||
id, adminID, ok := h.adminPartnerParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
keyID, err := uuid.Parse(c.Param("keyId"))
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "invalid key id"))
|
||||
return
|
||||
}
|
||||
if xerr := h.Partners.RevokeKey(c.Request.Context(), id, keyID); xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
h.logPartnerAction(c, *adminID, id, "revoke_partner_key", map[string]any{"key_id": keyID.String()})
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// AdminListPartnerOrganizations is GET /admin/partners/:id/organizations, both modes, newest first.
|
||||
func (h *Handler) AdminListPartnerOrganizations(c *gin.Context) {
|
||||
id, _, ok := h.adminPartnerParam(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, xerr := partner.ParseLimit(c.Query("limit"), 100)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
var after *repository.PartnerOrgCursor
|
||||
if cur := c.Query("cursor"); cur != "" {
|
||||
var okCur bool
|
||||
if after, okCur = partner.DecodeCursor(cur); !okCur {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "invalid cursor"))
|
||||
return
|
||||
}
|
||||
}
|
||||
rows, err := h.Partners.Repo.ListPartnerOrgs(c.Request.Context(), id, nil, after, limit+1)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.InternalError())
|
||||
return
|
||||
}
|
||||
page := partner.Page[models.PartnerOrganization]{Data: rows}
|
||||
if len(rows) > limit {
|
||||
page.Data = rows[:limit]
|
||||
page.Pagination.HasMore = true
|
||||
next := partner.EncodeCursor(rows[limit-1].CreatedAt, rows[limit-1].ID)
|
||||
page.Pagination.NextCursor = &next
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// The admin panel's Store section: instance-wide purchases, health, unit
|
||||
// economics, and the operator's repairs. Every action is audited.
|
||||
|
||||
const adminStoreDefaultLimit = 50
|
||||
|
||||
// adminStoreReady answers 404 store_disabled when the instance sells nothing.
|
||||
func (h *Handler) adminStoreReady(c *gin.Context) bool {
|
||||
if h.StoreService == nil || !h.StoreService.Enabled() {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.NotFound, store.CodeDisabled, store.NotConfiguredMessage))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func adminStoreLimit(c *gin.Context) (int, bool) {
|
||||
raw := c.Query("limit")
|
||||
if raw == "" {
|
||||
return adminStoreDefaultLimit, true
|
||||
}
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_limit", "limit must be between 1 and 100."))
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
// queryOrg reads an optional org_id filter.
|
||||
func queryOrg(c *gin.Context) (*uuid.UUID, bool) {
|
||||
raw := strings.TrimSpace(c.Query("org_id"))
|
||||
if raw == "" {
|
||||
return nil, true
|
||||
}
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "invalid org_id"))
|
||||
return nil, false
|
||||
}
|
||||
return &id, true
|
||||
}
|
||||
|
||||
func queryTrue(c *gin.Context, name string) bool {
|
||||
v, _ := strconv.ParseBool(c.Query(name))
|
||||
return v
|
||||
}
|
||||
|
||||
// auditStore records an operator's store action against the row it touched.
|
||||
func (h *Handler) auditStore(c *gin.Context, action string, entity string, id uuid.UUID, details map[string]any) {
|
||||
adminID := middleware.GetAdminUserID(c)
|
||||
if adminID == nil || h.AdminService == nil {
|
||||
return
|
||||
}
|
||||
h.AdminService.LogAdminAction(c.Request.Context(), *adminID, action, entity, &id, details, c.ClientIP(), c.Request.UserAgent())
|
||||
}
|
||||
|
||||
// AdminStoreHealth is GET /admin/store/health.
|
||||
func (h *Handler) AdminStoreHealth(c *gin.Context) {
|
||||
if h.StoreService == nil {
|
||||
c.JSON(http.StatusOK, &store.Health{Mode: store.ModeOff, Alerts: []store.Alert{}})
|
||||
return
|
||||
}
|
||||
out, err := h.StoreService.AdminHealth(c.Request.Context())
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
if out.Enabled && h.JobRuns != nil {
|
||||
if jobs, err := h.JobRuns.List(c.Request.Context()); err == nil {
|
||||
for _, j := range jobs {
|
||||
st := &store.LoopState{LastStartedAt: j.LastStartedAt, LastFinishedAt: j.LastFinishedAt, LastStatus: j.LastStatus, LastError: j.LastError}
|
||||
if j.LastFinishedAt != nil {
|
||||
st.LagSeconds = int64(time.Since(*j.LastFinishedAt).Seconds())
|
||||
}
|
||||
switch j.Name {
|
||||
case store.LoopReconcile:
|
||||
out.Reconciler = st
|
||||
case store.LoopBilling:
|
||||
out.Billing = st
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// AdminStoreEconomics is GET /admin/store/economics.
|
||||
func (h *Handler) AdminStoreEconomics(c *gin.Context) {
|
||||
if !h.adminStoreReady(c) {
|
||||
return
|
||||
}
|
||||
out, err := h.StoreService.AdminEconomics(c.Request.Context())
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// AdminListStoreOrders is GET /admin/store/orders.
|
||||
func (h *Handler) AdminListStoreOrders(c *gin.Context) {
|
||||
if !h.adminStoreReady(c) {
|
||||
return
|
||||
}
|
||||
limit, ok := adminStoreLimit(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
org, ok := queryOrg(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f := models.StoreAdminOrderFilter{OrgID: org, Status: c.Query("status"), FailureCode: c.Query("failure_code"),
|
||||
Stuck: queryTrue(c, "stuck"), Query: c.Query("q")}
|
||||
page, err := h.StoreService.AdminListOrders(c.Request.Context(), f, c.Query("cursor"), limit)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// AdminGetStoreOrder is GET /admin/store/orders/:id.
|
||||
func (h *Handler) AdminGetStoreOrder(c *gin.Context) {
|
||||
if !h.adminStoreReady(c) {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
o, err := h.StoreService.AdminGetOrder(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, o)
|
||||
}
|
||||
|
||||
// AdminListStoreDomains is GET /admin/store/domains.
|
||||
func (h *Handler) AdminListStoreDomains(c *gin.Context) {
|
||||
if !h.adminStoreReady(c) {
|
||||
return
|
||||
}
|
||||
limit, ok := adminStoreLimit(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
org, ok := queryOrg(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f := models.StoreAdminDomainFilter{OrgID: org, Status: c.Query("status"), RenewalFailed: queryTrue(c, "renewal_failed"), Query: c.Query("q")}
|
||||
if raw := c.Query("auto_renew"); raw != "" {
|
||||
v, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "auto_renew must be true or false"))
|
||||
return
|
||||
}
|
||||
f.AutoRenew = &v
|
||||
}
|
||||
if raw := c.Query("expiring_days"); raw != "" {
|
||||
days, err := strconv.Atoi(raw)
|
||||
if err != nil || days < 0 || days > 3650 {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "expiring_days must be between 0 and 3650"))
|
||||
return
|
||||
}
|
||||
before := time.Now().Add(time.Duration(days) * 24 * time.Hour)
|
||||
f.ExpiresBefore = &before
|
||||
}
|
||||
page, err := h.StoreService.AdminListDomains(c.Request.Context(), f, c.Query("cursor"), limit)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// AdminListStoreMailboxes is GET /admin/store/mailboxes.
|
||||
func (h *Handler) AdminListStoreMailboxes(c *gin.Context) {
|
||||
if !h.adminStoreReady(c) {
|
||||
return
|
||||
}
|
||||
limit, ok := adminStoreLimit(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
org, ok := queryOrg(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f := models.StoreAdminMailboxFilter{OrgID: org, Status: c.Query("status"), ConnectState: c.Query("connect_state"),
|
||||
BillingFailed: queryTrue(c, "billing_failed"), Query: c.Query("q")}
|
||||
page, err := h.StoreService.AdminListMailboxes(c.Request.Context(), f, c.Query("cursor"), limit)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// AdminGetStoreWorkspace is GET /admin/store/workspaces/:orgId.
|
||||
func (h *Handler) AdminGetStoreWorkspace(c *gin.Context) {
|
||||
if !h.adminStoreReady(c) {
|
||||
return
|
||||
}
|
||||
orgID, err := uuid.Parse(c.Param("orgId"))
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.ErrUuid)
|
||||
return
|
||||
}
|
||||
out, err := h.StoreService.AdminWorkspace(c.Request.Context(), orgID)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// adminStoreAction runs one operator action on the row the path names and audits it.
|
||||
func adminStoreAction[T any](h *Handler, c *gin.Context, action, entity string, run func(id uuid.UUID) (T, error), details func(T) map[string]any) {
|
||||
if !h.adminStoreReady(c) {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, err := run(id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
var d map[string]any
|
||||
if details != nil {
|
||||
d = details(out)
|
||||
}
|
||||
h.auditStore(c, action, entity, id, d)
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
func orderDetails(o *store.AdminOrder) map[string]any {
|
||||
return map[string]any{"organization_id": o.OrganizationID.String(), "status": o.Status}
|
||||
}
|
||||
|
||||
func mailboxDetails(m *store.AdminMailbox) map[string]any {
|
||||
return map[string]any{"organization_id": m.OrganizationID.String(), "email": m.Email, "status": m.Status, "connect_state": m.ConnectState}
|
||||
}
|
||||
|
||||
func domainDetails(d *store.AdminDomain) map[string]any {
|
||||
return map[string]any{"organization_id": d.OrganizationID.String(), "domain": d.Name, "status": d.Status, "auto_renew": d.AutoRenew}
|
||||
}
|
||||
|
||||
// AdminRefreshStoreOrder is POST /admin/store/orders/:id/refresh.
|
||||
func (h *Handler) AdminRefreshStoreOrder(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_order_refresh", "store_order", func(id uuid.UUID) (*store.AdminOrder, error) {
|
||||
return h.StoreService.AdminRefreshOrder(c.Request.Context(), id)
|
||||
}, orderDetails)
|
||||
}
|
||||
|
||||
// AdminPlaceStoreOrder is POST /admin/store/orders/:id/place.
|
||||
func (h *Handler) AdminPlaceStoreOrder(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_order_place", "store_order", func(id uuid.UUID) (*store.AdminOrder, error) {
|
||||
return h.StoreService.AdminPlaceOrder(c.Request.Context(), id)
|
||||
}, orderDetails)
|
||||
}
|
||||
|
||||
// AdminRefundStoreOrder is POST /admin/store/orders/:id/refund: a quote line, or an amount under an Idempotency-Key.
|
||||
func (h *Handler) AdminRefundStoreOrder(c *gin.Context) {
|
||||
var in store.RefundRequest
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
in.Key = strings.TrimSpace(c.GetHeader(middleware.IdempotencyKeyHeader))
|
||||
adminStoreAction(h, c, "store_order_refund", "store_order", func(id uuid.UUID) (*store.RefundResult, error) {
|
||||
return h.StoreService.AdminRefund(c.Request.Context(), id, in)
|
||||
}, func(r *store.RefundResult) map[string]any {
|
||||
d := orderDetails(r.Order)
|
||||
d["refunded_micros"] = r.RefundedMicros
|
||||
if in.Line != nil {
|
||||
d["line"] = *in.Line
|
||||
} else {
|
||||
d["amount_micros"] = in.AmountMicros
|
||||
d["reason"] = in.Reason
|
||||
}
|
||||
return d
|
||||
})
|
||||
}
|
||||
|
||||
// AdminRefreshStoreMailbox is POST /admin/store/mailboxes/:id/refresh.
|
||||
func (h *Handler) AdminRefreshStoreMailbox(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_mailbox_refresh", "store_mailbox", func(id uuid.UUID) (*store.AdminMailbox, error) {
|
||||
return h.StoreService.AdminRefreshMailbox(c.Request.Context(), id)
|
||||
}, mailboxDetails)
|
||||
}
|
||||
|
||||
// AdminConnectStoreMailbox is POST /admin/store/mailboxes/:id/connect.
|
||||
func (h *Handler) AdminConnectStoreMailbox(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_mailbox_connect", "store_mailbox", func(id uuid.UUID) (*store.AdminMailbox, error) {
|
||||
return h.StoreService.AdminRetryConnect(c.Request.Context(), id)
|
||||
}, mailboxDetails)
|
||||
}
|
||||
|
||||
// AdminCancelStoreMailbox is POST /admin/store/mailboxes/:id/cancel.
|
||||
func (h *Handler) AdminCancelStoreMailbox(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_mailbox_cancel", "store_mailbox", func(id uuid.UUID) (*store.AdminMailbox, error) {
|
||||
return h.StoreService.AdminCancelMailbox(c.Request.Context(), id)
|
||||
}, mailboxDetails)
|
||||
}
|
||||
|
||||
// AdminResumeStoreMailbox is POST /admin/store/mailboxes/:id/resume.
|
||||
func (h *Handler) AdminResumeStoreMailbox(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_mailbox_resume", "store_mailbox", func(id uuid.UUID) (*store.AdminMailbox, error) {
|
||||
return h.StoreService.AdminResumeMailbox(c.Request.Context(), id)
|
||||
}, mailboxDetails)
|
||||
}
|
||||
|
||||
// AdminRefreshStoreDomain is POST /admin/store/domains/:id/refresh.
|
||||
func (h *Handler) AdminRefreshStoreDomain(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_domain_refresh", "store_domain", func(id uuid.UUID) (*store.AdminDomain, error) {
|
||||
return h.StoreService.AdminRefreshDomain(c.Request.Context(), id)
|
||||
}, domainDetails)
|
||||
}
|
||||
|
||||
// AdminRenewStoreDomain is POST /admin/store/domains/:id/renew.
|
||||
func (h *Handler) AdminRenewStoreDomain(c *gin.Context) {
|
||||
adminStoreAction(h, c, "store_domain_renew", "store_domain", func(id uuid.UUID) (*store.AdminDomain, error) {
|
||||
return h.StoreService.AdminRenewDomain(c.Request.Context(), id)
|
||||
}, domainDetails)
|
||||
}
|
||||
|
||||
// AdminPatchStoreDomain is PATCH /admin/store/domains/:id: auto-renew.
|
||||
func (h *Handler) AdminPatchStoreDomain(c *gin.Context) {
|
||||
var in struct {
|
||||
AutoRenew *bool `json:"auto_renew"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&in); err != nil || in.AutoRenew == nil {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_body", "Send auto_renew as true or false."))
|
||||
return
|
||||
}
|
||||
adminStoreAction(h, c, "store_domain_auto_renew", "store_domain", func(id uuid.UUID) (*store.AdminDomain, error) {
|
||||
return h.StoreService.AdminSetAutoRenew(c.Request.Context(), id, *in.AutoRenew)
|
||||
}, domainDetails)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
)
|
||||
|
||||
// The admin panel's GraphKit connection. Secrets go in and never come out; the environment wins over all of it.
|
||||
|
||||
func (h *Handler) storeConnectionReady(c *gin.Context) bool {
|
||||
if h.StoreService == nil {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.NotFound, store.CodeDisabled, store.NotConfiguredMessage))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// AdminGetStoreConnection is GET /admin/store/connection.
|
||||
func (h *Handler) AdminGetStoreConnection(c *gin.Context) {
|
||||
if !h.storeConnectionReady(c) {
|
||||
return
|
||||
}
|
||||
out, err := h.StoreService.ConnectionView(c.Request.Context())
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
func bindConnection(c *gin.Context) (store.ConnectionInput, bool) {
|
||||
var in store.ConnectionInput
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return in, false
|
||||
}
|
||||
return in, true
|
||||
}
|
||||
|
||||
// AdminPutStoreConnection is PUT /admin/store/connection: tests the key, stores it sealed, and turns the store on.
|
||||
func (h *Handler) AdminPutStoreConnection(c *gin.Context) {
|
||||
adminID := middleware.GetAdminUserID(c)
|
||||
if adminID == nil {
|
||||
errx.JSON(c, errx.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
if !h.storeConnectionReady(c) {
|
||||
return
|
||||
}
|
||||
in, ok := bindConnection(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, err := h.StoreService.SaveConnection(c.Request.Context(), in, *adminID)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditStoreConnection(c, "store_connection_saved", map[string]any{
|
||||
"api_url": out.APIURL, "mode": out.Mode, "api_key_changed": in.APIKey != "", "webhook_secret_changed": in.WebhookSecret != "",
|
||||
})
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// AdminTestStoreConnection is POST /admin/store/connection/test: asks GraphKit with what was typed, saving nothing.
|
||||
func (h *Handler) AdminTestStoreConnection(c *gin.Context) {
|
||||
if !h.storeConnectionReady(c) {
|
||||
return
|
||||
}
|
||||
in, ok := bindConnection(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, err := h.StoreService.TestConnection(c.Request.Context(), in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// AdminDeleteStoreConnection is DELETE /admin/store/connection: deletes the stored key and turns the store off.
|
||||
func (h *Handler) AdminDeleteStoreConnection(c *gin.Context) {
|
||||
if !h.storeConnectionReady(c) {
|
||||
return
|
||||
}
|
||||
out, err := h.StoreService.ClearConnection(c.Request.Context())
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditStoreConnection(c, "store_connection_removed", nil)
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// auditStoreConnection records a connection change; details never carry a secret.
|
||||
func (h *Handler) auditStoreConnection(c *gin.Context, action string, details map[string]any) {
|
||||
adminID := middleware.GetAdminUserID(c)
|
||||
if adminID == nil || h.AdminService == nil {
|
||||
return
|
||||
}
|
||||
h.AdminService.LogAdminAction(c.Request.Context(), *adminID, action, "instance", nil, details, c.ClientIP(), c.Request.UserAgent())
|
||||
}
|
||||
@@ -193,7 +193,8 @@ func buildReplyPrompt(history, contactCtx, instruction string) string {
|
||||
func mapCreditError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case isInsufficientCredits(err):
|
||||
paymentRequiredJSON(c, "The workspace balance is too low. Add funds to keep using AI features.")
|
||||
code, msg := credits.PaymentRefusal(err)
|
||||
paymentRequiredJSON(c, code, msg)
|
||||
case isCapExceeded(err):
|
||||
errx.JSON(c, errx.New(errx.TooManyRequests, "AI usage limit reached, please try again later."))
|
||||
default:
|
||||
|
||||
@@ -217,6 +217,8 @@ func (h *Handler) GetUser(c *gin.Context) {
|
||||
if sess := middleware.GetSession(c); sess != nil {
|
||||
u.SessionMFAVerified = sess.MFAVerified
|
||||
}
|
||||
// The response is read by the person: a partner-bound account shows its contact email, never its sign-in address.
|
||||
u.ForDisplay()
|
||||
|
||||
u.Folders, u.Tags, u.Categories = []models.Group{}, []models.Group{}, []models.Group{}
|
||||
if orgID := middleware.GetOrganizationID(c); orgID != nil {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/credits"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
type burnCredits struct {
|
||||
credits.CreditService
|
||||
burnReads int
|
||||
}
|
||||
|
||||
func (c *burnCredits) Unmetered() bool { return false }
|
||||
func (c *burnCredits) GetLedger(context.Context, uuid.UUID) (*models.CreditLedger, *errx.Error) {
|
||||
return &models.CreditLedger{}, nil
|
||||
}
|
||||
func (c *burnCredits) AgencyAvailable(context.Context, uuid.UUID) models.Micro { return 0 }
|
||||
func (c *burnCredits) AIDailyAverage(context.Context, uuid.UUID, int) (models.Micro, *errx.Error) {
|
||||
c.burnReads++
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// The dashboard reads the balance on every page; only the billing page asks for the daily draw, which sums a month of the ledger.
|
||||
func TestBalanceReadComputesTheDailyDrawOnlyWhenAsked(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
cs := &burnCredits{}
|
||||
h := &Handler{CreditService: cs}
|
||||
read := func(target string) map[string]any {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, target, nil)
|
||||
c.Set(middleware.OrganizationIDKey, uuid.New())
|
||||
h.GetBalance(c)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("%s: status %d %s", target, w.Code, w.Body.String())
|
||||
}
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &out)
|
||||
return out
|
||||
}
|
||||
|
||||
if out := read("/subscription/balance"); out["burn"] != nil || cs.burnReads != 0 {
|
||||
t.Fatalf("plain read: burn %v, %d ledger sums", out["burn"], cs.burnReads)
|
||||
}
|
||||
if out := read("/subscription/balance?include=burn"); out["burn"] == nil || cs.burnReads != 1 {
|
||||
t.Fatalf("include=burn: burn %v, %d ledger sums", out["burn"], cs.burnReads)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/credits"
|
||||
"github.com/warmbly/warmbly/internal/app/stripe"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
)
|
||||
|
||||
type idleCredits struct{ credits.CreditService }
|
||||
|
||||
type cardSetupStripe struct {
|
||||
stripe.StripeService
|
||||
org uuid.UUID
|
||||
adopted string
|
||||
}
|
||||
|
||||
func (s *cardSetupStripe) AdoptCardSetup(_ context.Context, orgID uuid.UUID, setupIntentID string) *errx.Error {
|
||||
s.org, s.adopted = orgID, setupIntentID
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *cardSetupStripe) CreateCardSetupIntent(_ context.Context, _, orgID uuid.UUID) (*stripe.CardSetup, *errx.Error) {
|
||||
s.org = orgID
|
||||
return &stripe.CardSetup{ClientSecret: "seti_secret", PublishableKey: "pk_test"}, nil
|
||||
}
|
||||
|
||||
// The setup is opened for the caller's workspace, and never without one.
|
||||
func TestCardSetupIntentIsScopedToTheWorkspace(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
fake := &cardSetupStripe{}
|
||||
h := &Handler{StripeService: fake, CreditService: idleCredits{}}
|
||||
call := func(org *uuid.UUID) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
c.Set("user_id", uuid.New().String())
|
||||
if org != nil {
|
||||
c.Set(middleware.OrganizationIDKey, *org)
|
||||
}
|
||||
h.CreateCardSetupIntent(c)
|
||||
return w
|
||||
}
|
||||
|
||||
if w := call(nil); w.Code != http.StatusBadRequest || fake.org != uuid.Nil {
|
||||
t.Fatalf("no workspace: status %d, Stripe reached for %s", w.Code, fake.org)
|
||||
}
|
||||
org := uuid.New()
|
||||
w := call(&org)
|
||||
var body stripe.CardSetup
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if w.Code != http.StatusOK || body.ClientSecret != "seti_secret" || body.PublishableKey != "pk_test" || fake.org != org {
|
||||
t.Errorf("status %d body %+v org %s, want 200 for %s", w.Code, body, fake.org, org)
|
||||
}
|
||||
}
|
||||
|
||||
// Making a saved card the default is asked for the caller's workspace, and only with the setup it names.
|
||||
func TestAdoptCardSetupIsScopedToTheWorkspace(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
fake := &cardSetupStripe{}
|
||||
h := &Handler{StripeService: fake, CreditService: idleCredits{}}
|
||||
call := func(org *uuid.UUID, body string) int {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
if org != nil {
|
||||
c.Set(middleware.OrganizationIDKey, *org)
|
||||
}
|
||||
h.AdoptCardSetup(c)
|
||||
return c.Writer.Status()
|
||||
}
|
||||
if code := call(nil, `{"setup_intent_id":"seti_1"}`); code != http.StatusBadRequest || fake.adopted != "" {
|
||||
t.Fatalf("no workspace: status %d, adopted %q", code, fake.adopted)
|
||||
}
|
||||
org := uuid.New()
|
||||
if code := call(&org, `{}`); code != http.StatusBadRequest || fake.adopted != "" {
|
||||
t.Fatalf("no setup id: status %d, adopted %q", code, fake.adopted)
|
||||
}
|
||||
if code := call(&org, `{"setup_intent_id":"seti_1"}`); code != http.StatusNoContent || fake.org != org || fake.adopted != "seti_1" {
|
||||
t.Errorf("status %d org %s adopted %q, want 204 for %s", code, fake.org, fake.adopted, org)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/balance"
|
||||
"github.com/warmbly/warmbly/internal/app/credits"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/utils/paging"
|
||||
@@ -119,7 +121,7 @@ func (h *Handler) GetCreditBalance(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// GetBalance — GET /subscription/balance
|
||||
// GetBalance — GET /subscription/balance[?include=burn]
|
||||
// Everything the balance page shows: what is left, the allowance, the saved
|
||||
// card, automatic reload and its state, and the top-up bounds.
|
||||
func (h *Handler) GetBalance(c *gin.Context) {
|
||||
@@ -190,9 +192,49 @@ func (h *Handler) GetBalance(c *gin.Context) {
|
||||
out["payment_method"] = st.PaymentMethod
|
||||
out["charge_in_progress"] = st.Pending != nil && st.Pending.RetryAt == nil
|
||||
}
|
||||
// The daily draw sums a month of the ledger, so only the billing page asks for it.
|
||||
if c.Query("include") == "burn" {
|
||||
out["burn"] = h.balanceBurn(c, orgID)
|
||||
}
|
||||
// Lets the page save a card with Stripe.js instead of leaving for Checkout.
|
||||
if h.StripeService != nil {
|
||||
if key := h.StripeService.PublishableKey(); key != "" {
|
||||
out["stripe_publishable_key"] = key
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// balanceBurn is what the balance pays for a day, so the page can say how long it lasts. Best effort:
|
||||
// a part that cannot be read counts as nothing rather than failing the balance.
|
||||
func (h *Handler) balanceBurn(c *gin.Context, orgID uuid.UUID) gin.H {
|
||||
ctx := c.Request.Context()
|
||||
var upkeep *store.Upkeep
|
||||
if h.StoreService != nil {
|
||||
if u, err := h.StoreService.Upkeep(ctx, orgID); err == nil {
|
||||
upkeep = u
|
||||
}
|
||||
}
|
||||
ai, _ := h.CreditService.AIDailyAverage(ctx, orgID, 30)
|
||||
b := store.BurnPerDay(upkeep, int64(ai), time.Now())
|
||||
out := gin.H{
|
||||
"per_day_usd": usd(models.Micro(b.PerDayMicros)),
|
||||
"mailboxes_per_day_usd": usd(models.Micro(b.MailboxesPerDayMicros)),
|
||||
"renewals_per_day_usd": usd(models.Micro(b.RenewalsPerDayMicros)),
|
||||
"ai_per_day_usd": usd(models.Micro(b.AIPerDayMicros)),
|
||||
"mailboxes_monthly_usd": 0.0,
|
||||
"renewals_due_usd": usd(models.Micro(b.RenewalsDueMicros)),
|
||||
"billing_day": nil,
|
||||
}
|
||||
if upkeep != nil {
|
||||
out["mailboxes_monthly_usd"] = usd(models.Micro(upkeep.MonthlyMailboxesMicros))
|
||||
if upkeep.BillingDay > 0 {
|
||||
out["billing_day"] = upkeep.BillingDay
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func nilIfEmpty(s string) any {
|
||||
if s == "" {
|
||||
return nil
|
||||
@@ -327,6 +369,56 @@ func (h *Handler) CreatePaymentMethodSetup(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"session_id": sess.ID, "checkout_url": sess.URL})
|
||||
}
|
||||
|
||||
// CreateCardSetupIntent — POST /subscription/balance/setup-intent
|
||||
// A SetupIntent the dashboard confirms in the page with Stripe.js, saving the
|
||||
// card for off-session charges without leaving for Checkout.
|
||||
func (h *Handler) CreateCardSetupIntent(c *gin.Context) {
|
||||
uid, err := uuid.Parse(c.GetString("user_id"))
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.Unauthorized, "invalid user"))
|
||||
return
|
||||
}
|
||||
orgID, ok := h.billingOrg(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if h.StripeService == nil {
|
||||
errx.JSON(c, errx.New(errx.ServiceUnavailable, "card setup is not available"))
|
||||
return
|
||||
}
|
||||
setup, xerr := h.StripeService.CreateCardSetupIntent(c.Request.Context(), uid, orgID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, setup)
|
||||
}
|
||||
|
||||
// AdoptCardSetup — POST /subscription/balance/setup-intent/default {setup_intent_id}
|
||||
// makes a card saved in the page the default before it is charged; a retry sets the same default.
|
||||
func (h *Handler) AdoptCardSetup(c *gin.Context) {
|
||||
orgID, ok := h.billingOrg(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
SetupIntentID string `json:"setup_intent_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil || body.SetupIntentID == "" {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "setup_intent_id is required"))
|
||||
return
|
||||
}
|
||||
if h.StripeService == nil {
|
||||
errx.JSON(c, errx.New(errx.ServiceUnavailable, "card setup is not available"))
|
||||
return
|
||||
}
|
||||
if xerr := h.StripeService.AdoptCardSetup(c.Request.Context(), orgID, body.SetupIntentID); xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// UpdateAutoReload — PATCH /subscription/balance/auto-reload
|
||||
// {enabled, threshold_usd, amount_usd, monthly_limit_usd}. The amount must be
|
||||
// above the threshold and the monthly limit at least the amount.
|
||||
@@ -444,8 +536,17 @@ func (h *Handler) ListCreditTransactions(c *gin.Context) {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
// One extra row tells whether a next page exists.
|
||||
txns, xerr := h.CreditService.ListTransactionsBefore(c.Request.Context(), orgID, limit+1, beforeAt, beforeID)
|
||||
// One extra row tells whether a next page exists; category=store keeps only the store's lines.
|
||||
list := h.CreditService.ListTransactionsBefore
|
||||
switch c.Query("category") {
|
||||
case "":
|
||||
case "store":
|
||||
list = h.CreditService.ListStoreTransactionsBefore
|
||||
default:
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_category", "category must be store or left out."))
|
||||
return
|
||||
}
|
||||
txns, xerr := list(c.Request.Context(), orgID, limit+1, beforeAt, beforeID)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
@@ -503,7 +604,8 @@ func (h *Handler) GetCreditUsage(c *gin.Context) {
|
||||
"spent_today_usd": usd(o.SpentToday), "spent_week_usd": usd(o.SpentWeek), "spent_month_usd": usd(o.SpentMonth),
|
||||
"limit_daily_usd": usdPtr(o.LimitDaily), "limit_weekly_usd": usdPtr(o.LimitWeekly), "limit_monthly_usd": usdPtr(o.LimitMonthly),
|
||||
"spent_today": models.CreditsFromMicro(o.SpentToday), "spent_week": models.CreditsFromMicro(o.SpentWeek), "spent_month": models.CreditsFromMicro(o.SpentMonth),
|
||||
"series": series, "by_reason": buckets(o.ByReason), "by_model": buckets(o.ByModel),
|
||||
"ai_from_balance_month_usd": usd(o.FromBalanceMonth),
|
||||
"series": series, "by_reason": buckets(o.ByReason), "by_model": buckets(o.ByModel),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -517,6 +619,10 @@ func spendSettingsJSON(cfg *models.AISpendSettings) gin.H {
|
||||
"member_limit_monthly_usd": usdPtr(cfg.MemberLimitMonthly),
|
||||
"low_balance_usd": usd(cfg.LowBalanceThreshold),
|
||||
"auto_reload_enabled": cfg.AutoReloadEnabled,
|
||||
// Whether AI may use added money once the plan's included usage is spent, and the most per calendar month.
|
||||
"ai_overage_enabled": cfg.AIOverageEnabled,
|
||||
"ai_overage_monthly_limit_usd": usdPtr(cfg.AIOverageMonthlyLimit),
|
||||
"ai_overage_monthly_limit_micros": cfg.AIOverageMonthlyLimit,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,11 +665,21 @@ func (h *Handler) UpdateCreditSettings(c *gin.Context) {
|
||||
MemberLimitWeekly *int `json:"member_limit_weekly"`
|
||||
MemberLimitMonthly *int `json:"member_limit_monthly"`
|
||||
LowBalanceThreshold *int `json:"low_balance_threshold"`
|
||||
|
||||
// Absent keeps the saved value; a null limit removes it.
|
||||
AIOverageEnabled *bool `json:"ai_overage_enabled"`
|
||||
AIOverageMonthlyLimitUSD json.RawMessage `json:"ai_overage_monthly_limit_usd"`
|
||||
AIOverageMonthlyLimitMicros json.RawMessage `json:"ai_overage_monthly_limit_micros"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
overageLimit, limitSent, lerr := overageLimitFromBody(body.AIOverageMonthlyLimitMicros, body.AIOverageMonthlyLimitUSD)
|
||||
if lerr != nil {
|
||||
errx.JSON(c, lerr)
|
||||
return
|
||||
}
|
||||
low := credits.DefaultLowBalance
|
||||
if v := limitFromBody(body.LowBalanceUSD, body.LowBalanceThreshold); v != nil {
|
||||
low = *v
|
||||
@@ -581,10 +697,52 @@ func (h *Handler) UpdateCreditSettings(c *gin.Context) {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
if body.AIOverageEnabled != nil || limitSent {
|
||||
enabled := cfg.AIOverageEnabled
|
||||
if body.AIOverageEnabled != nil {
|
||||
enabled = *body.AIOverageEnabled
|
||||
}
|
||||
if !limitSent {
|
||||
overageLimit = cfg.AIOverageMonthlyLimit
|
||||
}
|
||||
if cfg, xerr = h.CreditService.UpdateAIOverage(c.Request.Context(), orgID, enabled, overageLimit); xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityCreditGrant, nil, nil, map[string]string{"kind": "spend_settings"})
|
||||
c.JSON(http.StatusOK, spendSettingsJSON(cfg))
|
||||
}
|
||||
|
||||
// overageLimitFromBody reads the AI overage limit, micros first: sent reports
|
||||
// whether either field was present, and a null clears the limit.
|
||||
func overageLimitFromBody(micros, dollars json.RawMessage) (limit *models.Micro, sent bool, xerr *errx.Error) {
|
||||
bad := errx.New(errx.BadRequest, "ai_overage_monthly_limit must be a positive amount or null")
|
||||
switch {
|
||||
case len(micros) > 0:
|
||||
if string(micros) == "null" {
|
||||
return nil, true, nil
|
||||
}
|
||||
var v int64
|
||||
if err := json.Unmarshal(micros, &v); err != nil {
|
||||
return nil, true, bad
|
||||
}
|
||||
m := models.Micro(v)
|
||||
return &m, true, nil
|
||||
case len(dollars) > 0:
|
||||
if string(dollars) == "null" {
|
||||
return nil, true, nil
|
||||
}
|
||||
var v float64
|
||||
if err := json.Unmarshal(dollars, &v); err != nil || math.IsNaN(v) || math.IsInf(v, 0) {
|
||||
return nil, true, bad
|
||||
}
|
||||
m := models.USDToMicro(v)
|
||||
return &m, true, nil
|
||||
}
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
// parseCreditLimit parses an optional ?limit into [1, max], defaulting to def.
|
||||
// A non-numeric or out-of-range value is a 400, never silently clamped.
|
||||
func parseCreditLimit(s string, def, max int) (int, *errx.Error) {
|
||||
|
||||
@@ -357,6 +357,9 @@ func (h *Handler) DeleteEmail(c *gin.Context) {
|
||||
|
||||
emailAccountID := c.Param("id")
|
||||
|
||||
if h.refuseLockedMailbox(c, emailAccountID) {
|
||||
return
|
||||
}
|
||||
if err := h.EmailService.Delete(c.Request.Context(), orgID.String(), emailAccountID); err != nil {
|
||||
errx.Handle(c, err)
|
||||
return
|
||||
|
||||
@@ -139,6 +139,9 @@ func (h *Handler) BulkDeleteEmails(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
res := h.runBulkMailboxes(c, ids, func(ctx context.Context, id uuid.UUID) *errx.Error {
|
||||
if xerr := h.mailboxLock(ctx, *orgID, id); xerr != nil {
|
||||
return xerr
|
||||
}
|
||||
return h.EmailService.Delete(ctx, orgID.String(), id.String())
|
||||
})
|
||||
if res.Succeeded > 0 {
|
||||
|
||||
@@ -138,6 +138,9 @@ func (h *Handler) ReauthEmailOAuth(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if h.refuseLockedMailbox(c, id.String()) {
|
||||
return
|
||||
}
|
||||
resp, xerr := h.EmailService.OAuthReauth(c.Request.Context(), userID, orgID, id, c.GetHeader("Origin"))
|
||||
if xerr != nil {
|
||||
errx.Handle(c, xerr)
|
||||
@@ -169,6 +172,9 @@ func (h *Handler) UpdateEmailSMTPIMAP(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if h.refuseLockedMailbox(c, id.String()) {
|
||||
return
|
||||
}
|
||||
var req OnboardingSMTPIMAPCredentials
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.Handle(c, errx.InvalidBody(err))
|
||||
@@ -312,6 +318,9 @@ func (h *Handler) SwitchEmailToAppPassword(c *gin.Context) {
|
||||
errx.Handle(c, errx.ErrUuid)
|
||||
return
|
||||
}
|
||||
if h.refuseLockedMailbox(c, id.String()) {
|
||||
return
|
||||
}
|
||||
var req appPasswordSwitchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.Handle(c, errx.ErrInvalid)
|
||||
|
||||
@@ -38,11 +38,11 @@ type generationWriteRequest struct {
|
||||
// paymentRequiredJSON emits the standard error envelope with a 402 status.
|
||||
// errx has no PaymentRequired code, so this endpoint writes the 402 directly
|
||||
// while keeping the same {error, message, code, request_id} shape.
|
||||
func paymentRequiredJSON(c *gin.Context, message string) {
|
||||
func paymentRequiredJSON(c *gin.Context, code, message string) {
|
||||
c.JSON(http.StatusPaymentRequired, gin.H{
|
||||
"error": "Payment Required",
|
||||
"message": message,
|
||||
"code": "insufficient_credits",
|
||||
"code": code,
|
||||
"request_id": c.GetString("request_id"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -70,6 +70,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/organization"
|
||||
"github.com/warmbly/warmbly/internal/app/orgrisk"
|
||||
"github.com/warmbly/warmbly/internal/app/orgtransfer"
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/app/passkey"
|
||||
"github.com/warmbly/warmbly/internal/app/pipedrive"
|
||||
"github.com/warmbly/warmbly/internal/app/placement"
|
||||
@@ -85,6 +86,7 @@ import (
|
||||
"github.com/warmbly/warmbly/internal/app/skills"
|
||||
"github.com/warmbly/warmbly/internal/app/slackapp"
|
||||
"github.com/warmbly/warmbly/internal/app/socket"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/app/stripe"
|
||||
"github.com/warmbly/warmbly/internal/app/subscription"
|
||||
"github.com/warmbly/warmbly/internal/app/sysstatus"
|
||||
@@ -282,8 +284,10 @@ type Handler struct {
|
||||
WarmupContentService warmupcontent.Service
|
||||
|
||||
// AI writing assistant + credit ledger.
|
||||
CreditService credits.CreditService
|
||||
BalanceService *balance.Service
|
||||
CreditService credits.CreditService
|
||||
BalanceService *balance.Service
|
||||
// StoreService sells domains and mailboxes; nil or disabled when GraphKit is not configured.
|
||||
StoreService *store.Service
|
||||
WritingGenerator generation.WritingGenerator
|
||||
|
||||
// AI provider layer (RunAgent tool-loop backend) + pluggable web search,
|
||||
@@ -437,6 +441,8 @@ type Handler struct {
|
||||
BrandService *brandkit.Service
|
||||
// PortalHandoff signs clients in to a portal from the main address; nil answers 404.
|
||||
PortalHandoffs *portalhandoff.Service
|
||||
// Partners runs the reseller API and managed workspaces; nil answers the partner API with 401.
|
||||
Partners *partner.Service
|
||||
// CrossOrgCopy copies campaigns and templates into the caller's other workspaces.
|
||||
CrossOrgCopy *crossorgcopy.Service
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ func (h *Handler) GetIdentity(c *gin.Context) {
|
||||
|
||||
resp := models.Identity{
|
||||
UserID: u.ID,
|
||||
Email: u.Email,
|
||||
Email: u.VisibleEmail(),
|
||||
FirstName: u.FirstName,
|
||||
LastName: u.LastName,
|
||||
Name: strings.TrimSpace(u.FirstName + " " + u.LastName),
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
)
|
||||
|
||||
// mailboxLock is why members may not remove or reconnect a mailbox: a partner
|
||||
// attached it, or the workspace bought it and still pays for it. Nil when neither.
|
||||
func (h *Handler) mailboxLock(ctx context.Context, orgID, accountID uuid.UUID) *errx.Error {
|
||||
return MailboxLock(h.Partners, h.StoreService)(ctx, orgID, accountID)
|
||||
}
|
||||
|
||||
// MailboxLock is the one remove-or-reconnect check, shared by the HTTP routes and the AI tools.
|
||||
func MailboxLock(partners *partner.Service, st *store.Service) func(ctx context.Context, orgID, accountID uuid.UUID) *errx.Error {
|
||||
return func(ctx context.Context, orgID, accountID uuid.UUID) *errx.Error {
|
||||
return lockOf(ctx, partners, st, orgID, accountID)
|
||||
}
|
||||
}
|
||||
|
||||
func lockOf(ctx context.Context, partners *partner.Service, st *store.Service, orgID, accountID uuid.UUID) *errx.Error {
|
||||
name, err := partners.MailboxLock(ctx, orgID, accountID)
|
||||
if err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
if name != "" {
|
||||
return partnerMailboxLocked(name)
|
||||
}
|
||||
bought, err := st.MailboxLocked(ctx, orgID, accountID)
|
||||
if err != nil {
|
||||
return errx.InternalError()
|
||||
}
|
||||
if bought && !st.Enabled() {
|
||||
return store.PurchasedMailboxPaused()
|
||||
}
|
||||
if bought {
|
||||
return store.PurchasedMailboxLocked()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// refuseLockedMailbox answers a remove or reconnect of a locked mailbox and reports that it did.
|
||||
func (h *Handler) refuseLockedMailbox(c *gin.Context, accountID string) bool {
|
||||
orgID := middleware.GetOrganizationID(c)
|
||||
id, err := uuid.Parse(accountID)
|
||||
if orgID == nil || err != nil {
|
||||
return false
|
||||
}
|
||||
if xerr := h.mailboxLock(c.Request.Context(), *orgID, id); xerr != nil {
|
||||
errx.Handle(c, xerr)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func partnerMailboxLocked(name string) *errx.Error {
|
||||
return errx.NewWithIdentifier(errx.Forbidden, "partner_managed_mailbox",
|
||||
"This mailbox is managed by "+name+". Remove or reconnect it there.")
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/email"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/graphkit"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
// lockStoreRepo answers which purchase sits behind a mailbox; nothing else is called.
|
||||
type lockStoreRepo struct {
|
||||
repository.StoreRepository
|
||||
org, account uuid.UUID
|
||||
status string
|
||||
}
|
||||
|
||||
func (r *lockStoreRepo) GetMailboxByAccount(_ context.Context, orgID, accountID uuid.UUID) (*models.StoreMailbox, error) {
|
||||
if orgID != r.org || accountID != r.account {
|
||||
return nil, nil
|
||||
}
|
||||
id := r.account
|
||||
return &models.StoreMailbox{ID: uuid.New(), OrganizationID: r.org, Status: r.status, EmailAccountID: &id}, nil
|
||||
}
|
||||
|
||||
// lockEmails records which mailbox operations got past the lock.
|
||||
type lockEmails struct {
|
||||
email.EmailService
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (e *lockEmails) record(op string) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.calls = append(e.calls, op)
|
||||
}
|
||||
|
||||
func (e *lockEmails) Delete(context.Context, string, string) *errx.Error {
|
||||
e.record("delete")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *lockEmails) OAuthReauth(context.Context, string, *uuid.UUID, uuid.UUID, string) (*models.EmailOnboardingStartResponse, *errx.Error) {
|
||||
e.record("reauth")
|
||||
return &models.EmailOnboardingStartResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *lockEmails) UpdateSMTPIMAPCredentials(context.Context, *uuid.UUID, uuid.UUID, *models.SmtpImap) (*models.Email, *errx.Error) {
|
||||
e.record("smtp")
|
||||
return nil, errx.ErrNotFound
|
||||
}
|
||||
|
||||
func (e *lockEmails) SwitchToAppPassword(context.Context, *uuid.UUID, uuid.UUID, string) (*models.Email, *errx.Error) {
|
||||
e.record("app_password")
|
||||
return nil, errx.ErrNotFound
|
||||
}
|
||||
|
||||
func TestPurchasedMailboxIsLockedUntilItsSubscriptionEnds(t *testing.T) {
|
||||
org, account := uuid.New(), uuid.New()
|
||||
routes := []struct {
|
||||
name, method, path, body, op string
|
||||
}{
|
||||
{"delete", http.MethodDelete, "/emails/" + account.String(), "", "delete"},
|
||||
{"oauth reauth", http.MethodPost, "/reauth/" + account.String(), "", "reauth"},
|
||||
{"smtp credentials", http.MethodPut, "/smtp/" + account.String(), `{}`, "smtp"},
|
||||
{"app password", http.MethodPost, "/app-password/" + account.String(), `{"app_password":"abcd efgh ijkl mnop"}`, "app_password"},
|
||||
}
|
||||
for _, status := range []string{"active", "cancelling", "suspended", "cancelled", "failed"} {
|
||||
locked := status != "cancelled" && status != "failed"
|
||||
for _, rt := range routes {
|
||||
t.Run(status+"/"+rt.name, func(t *testing.T) {
|
||||
emails := &lockEmails{}
|
||||
h := &Handler{EmailService: emails, StoreService: store.New(store.Deps{Repo: &lockStoreRepo{org: org, account: account, status: status}})}
|
||||
w := serveLocked(h, org, rt.method, rt.path, rt.body)
|
||||
reached := len(emails.calls) == 1 && emails.calls[0] == rt.op
|
||||
if locked {
|
||||
if w.Code != http.StatusForbidden || responseCode(w) != "purchased_mailbox" || reached {
|
||||
t.Fatalf("status %d code %q calls %v, want 403 purchased_mailbox and nothing done", w.Code, responseCode(w), emails.calls)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !reached || w.Code == http.StatusForbidden {
|
||||
t.Fatalf("status %d calls %v, want the request through", w.Code, emails.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBulkDeleteRefusesALivePurchasedMailboxInItsRow(t *testing.T) {
|
||||
org, bought, other := uuid.New(), uuid.New(), uuid.New()
|
||||
for _, tt := range []struct {
|
||||
status string
|
||||
locked bool
|
||||
}{{"active", true}, {"cancelled", false}} {
|
||||
t.Run(tt.status, func(t *testing.T) {
|
||||
emails := &lockEmails{}
|
||||
h := &Handler{EmailService: emails, StoreService: store.New(store.Deps{API: graphkit.NewFake(), Repo: &lockStoreRepo{org: org, account: bought, status: tt.status}})}
|
||||
w := serveLocked(h, org, http.MethodPost, "/bulk/delete", `{"email_ids":["`+bought.String()+`","`+other.String()+`"]}`)
|
||||
var res bulkMailboxResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil || w.Code != http.StatusOK {
|
||||
t.Fatalf("status %d body %s", w.Code, w.Body.String())
|
||||
}
|
||||
want := 2
|
||||
if tt.locked {
|
||||
want = 1
|
||||
}
|
||||
if res.Succeeded != want || len(emails.calls) != want {
|
||||
t.Fatalf("succeeded %d deletes %d, want %d", res.Succeeded, len(emails.calls), want)
|
||||
}
|
||||
for _, r := range res.Results {
|
||||
refused := r.ID == bought && tt.locked
|
||||
if refused != !r.OK || (refused && (r.Code != "purchased_mailbox" || !strings.Contains(r.Message, "Subscription"))) {
|
||||
t.Fatalf("row %+v", r)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func serveLocked(h *Handler, org uuid.UUID, method, path, body string) *httptest.ResponseRecorder {
|
||||
r := gin.New()
|
||||
r.Use(middleware.RequestIDMiddleware(), func(c *gin.Context) {
|
||||
c.Set(middleware.OrganizationIDKey, org)
|
||||
c.Next()
|
||||
})
|
||||
r.DELETE("/emails/:id", h.DeleteEmail)
|
||||
r.POST("/bulk/delete", h.BulkDeleteEmails)
|
||||
r.POST("/reauth/:id", h.ReauthEmailOAuth)
|
||||
r.PUT("/smtp/:id", h.UpdateEmailSMTPIMAP)
|
||||
r.POST("/app-password/:id", h.SwitchEmailToAppPassword)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequestWithContext(context.Background(), method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func responseCode(w *httptest.ResponseRecorder) string {
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
return body.Code
|
||||
}
|
||||
@@ -93,6 +93,8 @@ type mcpWorld struct {
|
||||
client uuid.UUID
|
||||
agency *mcpAgencyClients
|
||||
seen *aitools.Invocation
|
||||
h *Handler
|
||||
writes int
|
||||
}
|
||||
|
||||
func newMCPWorld(t *testing.T, keyPerms uint64) *mcpWorld {
|
||||
@@ -138,6 +140,7 @@ func newMCPWorld(t *testing.T, keyPerms uint64) *mcpWorld {
|
||||
|
||||
mw := &middleware.Handler{AgencyKeys: keys, OrganizationService: w.members}
|
||||
h := &Handler{AITools: reg, AgencyTools: aitools.BuildAgencyRegistry(aitools.AgencyDeps{Agency: w.agency})}
|
||||
w.h = h
|
||||
w.r = gin.New()
|
||||
w.r.Use(middleware.RequestIDMiddleware())
|
||||
w.r.POST("/v1/mcp", mw.MCPAuthMiddleware(), mw.ResourceScopeGate(), h.MCPEndpoint)
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/aitools"
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/generation"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
// pausedPartnerOrgs reports one workspace as managed by a partner that suspended it.
|
||||
type pausedPartnerOrgs struct {
|
||||
repository.PartnerRepository
|
||||
org uuid.UUID
|
||||
}
|
||||
|
||||
func (pausedPartnerOrgs) HasPartnerOrganizations(context.Context) (bool, error) { return true, nil }
|
||||
|
||||
func (r pausedPartnerOrgs) GetPartnerOrgByOrganization(_ context.Context, orgID uuid.UUID) (*models.PartnerOrganization, string, error) {
|
||||
if orgID != r.org {
|
||||
return nil, "", nil
|
||||
}
|
||||
return &models.PartnerOrganization{OrganizationID: &orgID, State: models.PartnerOrgSuspended, Mode: models.PartnerModeLive}, "GraphKit", nil
|
||||
}
|
||||
|
||||
// Over MCP a workspace its partner paused stays readable, and no tool that changes it runs.
|
||||
func TestMCPRefusesWriteToolsInAPausedWorkspace(t *testing.T) {
|
||||
w := newMCPWorld(t, models.APIPermAgencyRead|models.APIPermReadCampaigns|models.APIPermWriteCampaigns)
|
||||
now := time.Now()
|
||||
w.members.members[w.client] = &models.OrganizationMember{OrganizationID: w.client, UserID: w.owner, Role: string(models.RoleAdmin),
|
||||
Permissions: models.PermViewCampaigns | models.PermManageCampaigns, AcceptedAt: &now}
|
||||
w.h.AITools.Register(aitools.Tool{
|
||||
Name: "rename_campaign", Description: "Renames a campaign.", Risk: generation.RiskWrite,
|
||||
RequiredAPIPerm: models.APIPermWriteCampaigns, RequiredOrgPerm: models.PermManageCampaigns,
|
||||
Handler: func(context.Context, aitools.Invocation, json.RawMessage) (string, error) {
|
||||
w.writes++
|
||||
return "renamed", nil
|
||||
},
|
||||
})
|
||||
call := func(name string, args map[string]any) rpcReply {
|
||||
args["organization_id"] = w.client.String()
|
||||
_, got := w.rpc(t, "", "tools/call", map[string]any{"name": name, "arguments": args})
|
||||
return got
|
||||
}
|
||||
if got := call("rename_campaign", map[string]any{}); got.Error != nil || w.writes != 1 {
|
||||
t.Fatalf("an active workspace refused a write: %+v", got.Error)
|
||||
}
|
||||
|
||||
w.h.Partners = partner.NewService(partner.Deps{Repo: pausedPartnerOrgs{org: w.client}})
|
||||
got := call("rename_campaign", map[string]any{})
|
||||
if got.Error == nil || w.writes != 1 || !strings.Contains(got.Error.Message, "paused") {
|
||||
t.Fatalf("a paused workspace ran a write tool: %+v (writes=%d)", got.Error, w.writes)
|
||||
}
|
||||
got = call(mcpCallTool, map[string]any{"name": "rename_campaign", "arguments": map[string]any{"organization_id": w.client.String()}})
|
||||
if got.Error == nil || w.writes != 1 {
|
||||
t.Fatalf("call_tool reached a write tool in a paused workspace: %+v", got.Error)
|
||||
}
|
||||
if got := call("read_campaigns", map[string]any{"q": "acme"}); got.Error != nil || got.Result.IsError {
|
||||
t.Fatalf("a paused workspace refused a read: %+v %+v", got.Error, got.Result)
|
||||
}
|
||||
}
|
||||
@@ -265,10 +265,18 @@ func (h *Handler) mcpRunTool(c *gin.Context, inv aitools.Invocation, req jsonRPC
|
||||
fallthrough
|
||||
default:
|
||||
// Send-class tools are never exposed or callable over MCP.
|
||||
if t, ok := h.AITools.Get(params.Name); ok && t.Risk == generation.RiskSend {
|
||||
t, ok := h.AITools.Get(params.Name)
|
||||
if ok && t.Risk == generation.RiskSend {
|
||||
c.JSON(http.StatusOK, rpcError(req.ID, -32601, "tool not available"))
|
||||
return
|
||||
}
|
||||
// A workspace its partner paused is read-only here as on every other write route.
|
||||
if ok && t.Risk != generation.RiskRead {
|
||||
if xerr := h.partnerWriteRefusal(c, inv.OrgID); xerr != nil {
|
||||
c.JSON(http.StatusOK, rpcError(req.ID, -32000, xerr.Message))
|
||||
return
|
||||
}
|
||||
}
|
||||
out, err = h.AITools.Call(c.Request.Context(), inv, params.Name, params.Arguments)
|
||||
}
|
||||
mcpToolResult(c, req, params.Name, out, err)
|
||||
|
||||
@@ -190,6 +190,11 @@ func (h *Handler) GetCurrentOrganization(c *gin.Context) {
|
||||
if h.AgencyService != nil {
|
||||
result.Agency = h.AgencyService.AgencyOf(c.Request.Context(), *orgID)
|
||||
}
|
||||
if h.Partners != nil {
|
||||
if ref, err := h.Partners.ManagedRef(c.Request.Context(), *orgID); err == nil {
|
||||
result.Partner = ref
|
||||
}
|
||||
}
|
||||
if restricted {
|
||||
c.JSON(http.StatusOK, scopedOrganizationWithLimits{
|
||||
OrganizationWithLimits: result,
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
)
|
||||
|
||||
// The partner API (/v1/partner) is for resellers that create and run workspaces. Its errors use
|
||||
// {"error": {"code", "message", "request_id"}}, and a request that names no live partner key gets 401.
|
||||
|
||||
const partnerMaxBody = 1 << 20
|
||||
|
||||
// partnerGenericCodes renames the generic class codes to the partner API's vocabulary.
|
||||
var partnerGenericCodes = map[string]string{
|
||||
"bad_request": "invalid_request",
|
||||
"unprocessable": "invalid_request",
|
||||
"rate_limit_exceeded": "rate_limited",
|
||||
"internal_error": "internal",
|
||||
"conflict": "conflict",
|
||||
"service_unavailable": "unavailable",
|
||||
}
|
||||
|
||||
func partnerError(c *gin.Context, xerr *errx.Error) {
|
||||
status := xerr.HTTPStatus()
|
||||
code := xerr.ResponseCode()
|
||||
if alias, ok := partnerGenericCodes[code]; ok {
|
||||
code = alias
|
||||
}
|
||||
if xerr.RetryAfter > 0 {
|
||||
c.Header("Retry-After", strconv.Itoa(xerr.RetryAfter))
|
||||
}
|
||||
c.AbortWithStatusJSON(status, gin.H{"error": gin.H{
|
||||
"code": code,
|
||||
"message": errx.ClientMessage(c, xerr),
|
||||
"request_id": c.GetString(middleware.RequestIDContextKey),
|
||||
}})
|
||||
}
|
||||
|
||||
func partnerCaller(c *gin.Context) *partner.Caller { return partner.CallerFrom(c.Request.Context()) }
|
||||
|
||||
// PartnerAuth resolves the partner key, applies the partner's rate limit, and requires Idempotency-Key on writes.
|
||||
func (h *Handler) PartnerAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if h.Partners == nil {
|
||||
partnerError(c, partner.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
raw, ok := strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
|
||||
if !ok {
|
||||
partnerError(c, partner.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
caller, xerr := h.Partners.Authenticate(c.Request.Context(), strings.TrimSpace(raw))
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
if !h.Partners.Allow(c.Request.Context(), caller) {
|
||||
partnerError(c, &errx.Error{Code: errx.TooManyRequests, Identifier: "rate_limited", Message: "Too many requests for this partner.", RetryAfter: 1})
|
||||
return
|
||||
}
|
||||
c.Request = c.Request.WithContext(partner.WithCaller(c.Request.Context(), caller))
|
||||
c.Header("Cache-Control", "no-store")
|
||||
if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
h.partnerIdempotent(c, caller)
|
||||
}
|
||||
}
|
||||
|
||||
// partnerIdempotent runs a write once per Idempotency-Key, replaying its stored answer to a retry.
|
||||
func (h *Handler) partnerIdempotent(c *gin.Context, caller *partner.Caller) {
|
||||
key := strings.TrimSpace(c.GetHeader(middleware.IdempotencyKeyHeader))
|
||||
if key == "" {
|
||||
partnerError(c, partner.ErrIdempotencyRequired)
|
||||
return
|
||||
}
|
||||
if !partner.ValidIdempotencyKey(key) {
|
||||
partnerError(c, partner.ErrIdempotencyInvalid)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(c.Request.Body, partnerMaxBody+1))
|
||||
if err != nil || len(body) > partnerMaxBody {
|
||||
partnerError(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_request", "The request body is too large or unreadable."))
|
||||
return
|
||||
}
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(body))
|
||||
claim, replay, xerr := h.Partners.BeginIdempotent(c.Request.Context(), caller, key, partner.RequestHash(c.Request.Method, c.Request.URL.Path, body))
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
if replay != nil {
|
||||
c.Header("Idempotent-Replayed", "true")
|
||||
c.Header(middleware.IdempotencyReplayedHeader, "true")
|
||||
ct := replay.ContentType
|
||||
if ct == "" {
|
||||
ct = "application/json; charset=utf-8"
|
||||
}
|
||||
if len(replay.Body) == 0 {
|
||||
c.AbortWithStatus(replay.Status)
|
||||
return
|
||||
}
|
||||
c.Data(replay.Status, ct, replay.Body)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
capture := &partnerCapture{ResponseWriter: c.Writer}
|
||||
c.Writer = capture
|
||||
finished := false
|
||||
defer func() {
|
||||
if !finished {
|
||||
h.Partners.FinishIdempotent(c.Request.Context(), caller, claim, http.StatusInternalServerError, "", nil)
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
finished = true
|
||||
h.Partners.FinishIdempotent(c.Request.Context(), caller, claim, capture.Status(), capture.Header().Get("Content-Type"), capture.body.Bytes())
|
||||
}
|
||||
|
||||
type partnerCapture struct {
|
||||
gin.ResponseWriter
|
||||
body bytes.Buffer
|
||||
}
|
||||
|
||||
func (w *partnerCapture) Write(b []byte) (int, error) {
|
||||
w.body.Write(b)
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (w *partnerCapture) WriteString(s string) (int, error) {
|
||||
w.body.WriteString(s)
|
||||
return w.ResponseWriter.WriteString(s)
|
||||
}
|
||||
|
||||
// bindPartnerJSON decodes a body, ignoring fields it does not know.
|
||||
func bindPartnerJSON(c *gin.Context, dst any) bool {
|
||||
raw, err := io.ReadAll(io.LimitReader(c.Request.Body, partnerMaxBody))
|
||||
if err == nil && len(bytes.TrimSpace(raw)) > 0 {
|
||||
err = json.Unmarshal(raw, dst)
|
||||
}
|
||||
if err != nil {
|
||||
var syntax *json.SyntaxError
|
||||
var typ *json.UnmarshalTypeError
|
||||
msg := "The request body is not valid JSON."
|
||||
if errors.As(err, &typ) {
|
||||
msg = "The field " + typ.Field + " has the wrong type."
|
||||
} else if !errors.As(err, &syntax) {
|
||||
msg = "The request body could not be read."
|
||||
}
|
||||
partnerError(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_request", msg))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// PartnerUpsertOrganization is PUT /v1/partner/organizations/:external_id.
|
||||
func (h *Handler) PartnerUpsertOrganization(c *gin.Context) {
|
||||
var in partner.OrganizationInput
|
||||
if !bindPartnerJSON(c, &in) {
|
||||
return
|
||||
}
|
||||
v, created, xerr := h.Partners.Upsert(c.Request.Context(), partnerCaller(c), c.Param("external_id"), in)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if created {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
c.JSON(status, v)
|
||||
}
|
||||
|
||||
// PartnerGetOrganization is GET /v1/partner/organizations/:external_id.
|
||||
func (h *Handler) PartnerGetOrganization(c *gin.Context) {
|
||||
v, xerr := h.Partners.Get(c.Request.Context(), partnerCaller(c), c.Param("external_id"))
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, v)
|
||||
}
|
||||
|
||||
// PartnerListOrganizations is GET /v1/partner/organizations.
|
||||
func (h *Handler) PartnerListOrganizations(c *gin.Context) {
|
||||
limit, xerr := partner.ParseLimit(c.Query("limit"), 100)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
page, xerr := h.Partners.List(c.Request.Context(), partnerCaller(c), c.Query("cursor"), limit)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// PartnerCancelOrganization is DELETE /v1/partner/organizations/:external_id.
|
||||
func (h *Handler) PartnerCancelOrganization(c *gin.Context) {
|
||||
v, xerr := h.Partners.Cancel(c.Request.Context(), partnerCaller(c), c.Param("external_id"))
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, v)
|
||||
}
|
||||
|
||||
// PartnerCreateLoginLink is POST /v1/partner/organizations/:external_id/login-links.
|
||||
func (h *Handler) PartnerCreateLoginLink(c *gin.Context) {
|
||||
var in partner.LoginInput
|
||||
if !bindPartnerJSON(c, &in) {
|
||||
return
|
||||
}
|
||||
link, xerr := h.Partners.IssueLoginLink(c.Request.Context(), partnerCaller(c), c.Param("external_id"), in)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, link)
|
||||
}
|
||||
|
||||
// PartnerRemovePerson is DELETE /v1/partner/organizations/:external_id/people/:person_external_id.
|
||||
func (h *Handler) PartnerRemovePerson(c *gin.Context) {
|
||||
if xerr := h.Partners.RemovePerson(c.Request.Context(), partnerCaller(c), c.Param("external_id"), c.Param("person_external_id")); xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// PartnerCreateAPIKey is POST /v1/partner/organizations/:external_id/api-keys.
|
||||
func (h *Handler) PartnerCreateAPIKey(c *gin.Context) {
|
||||
var in partner.APIKeyInput
|
||||
if !bindPartnerJSON(c, &in) {
|
||||
return
|
||||
}
|
||||
k, xerr := h.Partners.CreateAPIKey(c.Request.Context(), partnerCaller(c), c.Param("external_id"), in, publicAPIBaseURL(c)+"/v1")
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, k)
|
||||
}
|
||||
|
||||
// PartnerRevokeAPIKey is DELETE /v1/partner/organizations/:external_id/api-keys/:id.
|
||||
func (h *Handler) PartnerRevokeAPIKey(c *gin.Context) {
|
||||
if xerr := h.Partners.RevokeAPIKey(c.Request.Context(), partnerCaller(c), c.Param("external_id"), c.Param("id")); xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// PartnerListEvents is GET /v1/partner/events?after=&limit=.
|
||||
func (h *Handler) PartnerListEvents(c *gin.Context) {
|
||||
limit, xerr := partner.ParseLimit(c.DefaultQuery("limit", "100"), 100)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
page, xerr := h.Partners.Events(c.Request.Context(), partnerCaller(c), c.Query("after"), limit)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// PartnerLoginExchange is POST /v1/auth/partner/exchange: a login link spent once for a session.
|
||||
func (h *Handler) PartnerLoginExchange(c *gin.Context) {
|
||||
if h.Partners == nil {
|
||||
errx.JSON(c, partner.ErrLoginInvalid)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
res, xerr := h.Partners.ExchangeLogin(c.Request.Context(), req.Code, c.ClientIP(), c.Request.UserAgent())
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
// mountPartnerOrganizationRoutes mounts the mailbox half of the partner API; every route on org has a resolved partner caller.
|
||||
func (h *Handler) mountPartnerOrganizationRoutes(org *gin.RouterGroup) {
|
||||
org.GET("/mailboxes", h.PartnerListMailboxes)
|
||||
org.PUT("/mailboxes/:partner_mailbox_id", h.PartnerAttachMailbox)
|
||||
org.DELETE("/mailboxes/:partner_mailbox_id", h.PartnerDetachMailbox)
|
||||
org.PUT("/enablements/:mailbox_id", h.PartnerSetEnablement)
|
||||
org.POST("/connect-links", h.PartnerCreateConnectLink)
|
||||
org.GET("/balance", h.PartnerGetBalance)
|
||||
org.POST("/balance/credits", h.PartnerCreditBalance)
|
||||
}
|
||||
|
||||
// MountPartnerAPI registers /v1/partner on v1. A request with no live partner key gets 401, so the
|
||||
// API does nothing until an operator creates a partner.
|
||||
func (h *Handler) MountPartnerAPI(v1 *gin.RouterGroup) {
|
||||
g := v1.Group("/partner")
|
||||
g.Use(h.PartnerAuth())
|
||||
g.GET("/organizations", h.PartnerListOrganizations)
|
||||
g.PUT("/organizations/:external_id", h.PartnerUpsertOrganization)
|
||||
g.GET("/organizations/:external_id", h.PartnerGetOrganization)
|
||||
g.DELETE("/organizations/:external_id", h.PartnerCancelOrganization)
|
||||
org := g.Group("/organizations/:external_id")
|
||||
org.POST("/login-links", h.PartnerCreateLoginLink)
|
||||
org.DELETE("/people/:person_external_id", h.PartnerRemovePerson)
|
||||
org.POST("/api-keys", h.PartnerCreateAPIKey)
|
||||
org.DELETE("/api-keys/:id", h.PartnerRevokeAPIKey)
|
||||
h.mountPartnerOrganizationRoutes(org)
|
||||
g.GET("/events", h.PartnerListEvents)
|
||||
g.GET("/usage", h.PartnerUsage)
|
||||
g.GET("/usage/mailbox-days", h.PartnerMailboxDays)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/organization"
|
||||
"github.com/warmbly/warmbly/internal/app/user"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
const (
|
||||
partnerLogin = "p-0123456789abcdef01234567@graphkit.partner.invalid"
|
||||
partnerService = "service-0123456789abcdef@graphkit.partner.invalid"
|
||||
partnerContact = "ada@acme.com"
|
||||
)
|
||||
|
||||
// partnerPerson is a person a partner signs in, as the user repository reads it.
|
||||
func partnerPerson(id uuid.UUID) *models.User {
|
||||
return &models.User{ID: id, FirstName: "Ada", LastName: "Lovelace", Email: partnerLogin, ContactEmail: partnerContact}
|
||||
}
|
||||
|
||||
type partnerPersonUsers struct{ user.UserService }
|
||||
|
||||
func (partnerPersonUsers) GetUser(_ context.Context, id uuid.UUID) (*models.User, *errx.Error) {
|
||||
return partnerPerson(id), nil
|
||||
}
|
||||
|
||||
// partnerMembersRepo answers the member list the way the database does: login address plus contact email.
|
||||
type partnerMembersRepo struct {
|
||||
repository.OrganizationRepository
|
||||
person, service uuid.UUID
|
||||
}
|
||||
|
||||
func (r partnerMembersRepo) GetMembers(_ context.Context, orgID uuid.UUID) ([]models.OrganizationMember, error) {
|
||||
person := partnerPerson(r.person)
|
||||
owner := &models.User{ID: r.service, FirstName: "GraphKit", Email: partnerService}
|
||||
return []models.OrganizationMember{
|
||||
{OrganizationID: orgID, UserID: r.service, Role: "owner", User: owner, Email: owner.VisibleEmail(), Name: "GraphKit"},
|
||||
{OrganizationID: orgID, UserID: r.person, Role: "admin", User: person, Email: person.VisibleEmail(), Name: "Ada Lovelace"},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (partnerMembersRepo) HydrateMemberRoles(context.Context, uuid.UUID, []models.OrganizationMember) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (partnerMembersRepo) ListMemberAccess(context.Context, uuid.UUID) (map[uuid.UUID]*models.MemberAccess, error) {
|
||||
return map[uuid.UUID]*models.MemberAccess{}, nil
|
||||
}
|
||||
|
||||
func TestPartnerPersonResponsesShowContactEmailNeverLoginAddress(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
org, person, service := uuid.New(), uuid.New(), uuid.New()
|
||||
h := &Handler{
|
||||
UserService: partnerPersonUsers{},
|
||||
OrganizationService: organization.NewService(partnerMembersRepo{person: person, service: service}, nil, nil, nil, nil),
|
||||
}
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set(middleware.UserIDKey, person.String())
|
||||
if c.Request.URL.Path == "/organization/members" {
|
||||
c.Set(middleware.OrganizationIDKey, org)
|
||||
}
|
||||
})
|
||||
router.GET("/auth/me", h.GetUser)
|
||||
router.GET("/me", h.GetIdentity)
|
||||
router.GET("/organization/members", h.GetMembers)
|
||||
|
||||
for _, path := range []string{"/auth/me", "/me", "/organization/members"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
body := rec.Body.String()
|
||||
if strings.Contains(body, ".invalid") {
|
||||
t.Fatalf("response carries a sign-in address: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, `"email":"`+partnerContact+`"`) {
|
||||
t.Fatalf("response does not show the contact email: %s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleEmail(t *testing.T) {
|
||||
for _, tc := range []struct{ login, contact, want string }{
|
||||
{"ada@acme.com", "", "ada@acme.com"},
|
||||
{"ada@acme.com", "other@acme.com", "ada@acme.com"},
|
||||
{partnerLogin, partnerContact, partnerContact},
|
||||
{partnerLogin, "", ""},
|
||||
{strings.ToUpper(partnerLogin), "x@y.invalid", ""},
|
||||
} {
|
||||
if got := models.VisibleEmail(tc.login, tc.contact); got != tc.want {
|
||||
t.Errorf("VisibleEmail(%q, %q) = %q; want %q", tc.login, tc.contact, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// Writes that are about the signed-in account rather than the selected workspace, allowed while it is read-only.
|
||||
var partnerReadOnlyExempt = map[string]bool{
|
||||
"POST /v1/organization": true,
|
||||
"POST /v1/organization/switch/:id": true,
|
||||
"POST /v1/getaway": true,
|
||||
"POST /v1/invitations/accept": true,
|
||||
}
|
||||
|
||||
func partnerWriteMethod(m string) bool {
|
||||
return m == http.MethodPost || m == http.MethodPut || m == http.MethodPatch || m == http.MethodDelete
|
||||
}
|
||||
|
||||
// PartnerReadOnlyGate keeps a workspace its reseller suspended or cancelled read-only: members and keys may read, not write.
|
||||
func (h *Handler) PartnerReadOnlyGate() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if h.Partners == nil || !partnerWriteMethod(c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
route := c.Request.Method + " " + c.FullPath()
|
||||
if partnerReadOnlyExempt[route] || strings.HasPrefix(c.FullPath(), "/v1/me/") || c.FullPath() == "/v1/me" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
orgID := middleware.GetOrganizationID(c)
|
||||
if orgID == nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if xerr := h.partnerWriteRefusal(c, *orgID); xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// partnerWriteRefusal is the refusal for a change to a workspace its partner paused, nil when the change may go ahead.
|
||||
func (h *Handler) partnerWriteRefusal(c *gin.Context, orgID uuid.UUID) *errx.Error {
|
||||
if h.Partners == nil || orgID == uuid.Nil {
|
||||
return nil
|
||||
}
|
||||
ref, xerr := h.Partners.ReadOnly(c.Request.Context(), orgID)
|
||||
if xerr != nil {
|
||||
return xerr
|
||||
}
|
||||
if ref != nil {
|
||||
return partnerPausedError(ref)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func partnerPausedError(ref *models.PartnerManagedRef) *errx.Error {
|
||||
id := "organization_suspended"
|
||||
if ref.State == models.PartnerOrgCancelled {
|
||||
id = "organization_cancelled"
|
||||
}
|
||||
return errx.NewWithIdentifier(errx.Forbidden, id,
|
||||
"This workspace is paused by "+ref.DisplayName+", which bills it. You can read everything, but changes and sending wait until it is resumed.")
|
||||
}
|
||||
|
||||
// Billing reads and the discount check stay open in a managed workspace; nothing else in billing applies.
|
||||
var partnerBillingOpen = map[string]bool{
|
||||
"/v1/subscription/discount/validate": true,
|
||||
"/v1/subscription/enterprise-inquiry": true,
|
||||
}
|
||||
|
||||
// PartnerBillingGate refuses self-serve billing in a workspace a reseller bills: no checkout, plan change, cancellation or top-up.
|
||||
func (h *Handler) PartnerBillingGate() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if h.Partners == nil || !partnerWriteMethod(c.Request.Method) || partnerBillingOpen[c.FullPath()] {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
orgID := middleware.GetOrganizationID(c)
|
||||
if orgID == nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if managed, name := h.Partners.IsPartnerManaged(c.Request.Context(), *orgID); managed {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.Forbidden, "partner_managed",
|
||||
"This workspace is billed through "+name+". Plan, payment and balance are managed there."))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RefusePartnerBound stops an account a reseller signs in from adding its own way in (a password or a passkey).
|
||||
func (h *Handler) RefusePartnerBound() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if h.Partners == nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
userID, err := uuid.Parse(middleware.GetUserID(c))
|
||||
if err != nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
bound, err := h.Partners.IsPartnerBound(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.InternalError())
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if bound {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.Forbidden, "partner_account",
|
||||
"This account signs in through the service that manages your workspace, so it cannot add a password, passkey or second factor here."))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/partner"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
)
|
||||
|
||||
// PartnerListMailboxes is GET /v1/partner/organizations/:external_id/mailboxes.
|
||||
func (h *Handler) PartnerListMailboxes(c *gin.Context) {
|
||||
limit, xerr := partner.ParseLimit(c.Query("limit"), 100)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
page, xerr := h.Partners.ListMailboxes(c.Request.Context(), partnerCaller(c), c.Param("external_id"), c.Query("cursor"), limit)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// PartnerAttachMailbox is PUT /v1/partner/organizations/:external_id/mailboxes/:partner_mailbox_id.
|
||||
func (h *Handler) PartnerAttachMailbox(c *gin.Context) {
|
||||
var in partner.AttachInput
|
||||
if !bindPartnerJSON(c, &in) {
|
||||
return
|
||||
}
|
||||
m, created, xerr := h.Partners.Attach(c.Request.Context(), partnerCaller(c), c.Param("external_id"), c.Param("partner_mailbox_id"), in)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if created {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
c.JSON(status, m)
|
||||
}
|
||||
|
||||
// PartnerDetachMailbox is DELETE /v1/partner/organizations/:external_id/mailboxes/:partner_mailbox_id.
|
||||
func (h *Handler) PartnerDetachMailbox(c *gin.Context) {
|
||||
if xerr := h.Partners.Detach(c.Request.Context(), partnerCaller(c), c.Param("external_id"), c.Param("partner_mailbox_id")); xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// PartnerSetEnablement is PUT /v1/partner/organizations/:external_id/enablements/:mailbox_id.
|
||||
func (h *Handler) PartnerSetEnablement(c *gin.Context) {
|
||||
var in struct {
|
||||
Enablement string `json:"enablement"`
|
||||
}
|
||||
if !bindPartnerJSON(c, &in) {
|
||||
return
|
||||
}
|
||||
m, xerr := h.Partners.SetEnablement(c.Request.Context(), partnerCaller(c), c.Param("external_id"), c.Param("mailbox_id"), in.Enablement)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, m)
|
||||
}
|
||||
|
||||
// PartnerCreateConnectLink is POST /v1/partner/organizations/:external_id/connect-links.
|
||||
func (h *Handler) PartnerCreateConnectLink(c *gin.Context) {
|
||||
var in partner.ConnectLinkInput
|
||||
if !bindPartnerJSON(c, &in) {
|
||||
return
|
||||
}
|
||||
link, xerr := h.Partners.CreateConnectLink(c.Request.Context(), partnerCaller(c), c.Param("external_id"), in)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, link)
|
||||
}
|
||||
|
||||
// PartnerGetBalance is GET /v1/partner/organizations/:external_id/balance.
|
||||
func (h *Handler) PartnerGetBalance(c *gin.Context) {
|
||||
b, xerr := h.Partners.GetBalance(c.Request.Context(), partnerCaller(c), c.Param("external_id"))
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, b)
|
||||
}
|
||||
|
||||
// PartnerCreditBalance is POST /v1/partner/organizations/:external_id/balance/credits.
|
||||
func (h *Handler) PartnerCreditBalance(c *gin.Context) {
|
||||
var in partner.CreditInput
|
||||
if !bindPartnerJSON(c, &in) {
|
||||
return
|
||||
}
|
||||
b, xerr := h.Partners.CreditBalance(c.Request.Context(), partnerCaller(c), c.Param("external_id"), in)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, b)
|
||||
}
|
||||
|
||||
// PartnerUsage is GET /v1/partner/usage?month=.
|
||||
func (h *Handler) PartnerUsage(c *gin.Context) {
|
||||
out, xerr := h.Partners.Usage(c.Request.Context(), partnerCaller(c), c.Query("month"))
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// PartnerMailboxDays is GET /v1/partner/usage/mailbox-days?month=&cursor=&limit=.
|
||||
func (h *Handler) PartnerMailboxDays(c *gin.Context) {
|
||||
limit, xerr := partner.ParseLimit(c.DefaultQuery("limit", "1000"), partner.MaxMailboxDaysPage)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
out, xerr := h.Partners.MailboxDays(c.Request.Context(), partnerCaller(c), c.Query("month"), c.Query("cursor"), limit)
|
||||
if xerr != nil {
|
||||
partnerError(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
|
||||
// NoRoute answers an unknown path: the partner API's error envelope under /v1/partner, gin's plain 404 elsewhere.
|
||||
func (h *Handler) NoRoute(c *gin.Context) {
|
||||
if p := c.Request.URL.Path; p == "/v1/partner" || strings.HasPrefix(p, "/v1/partner/") {
|
||||
partnerError(c, errx.NewWithIdentifier(errx.NotFound, "not_found", "There is no such partner API route."))
|
||||
return
|
||||
}
|
||||
c.String(http.StatusNotFound, "404 page not found")
|
||||
}
|
||||
|
||||
// WorkspacePartnerMailboxes is GET /v1/emails/partner: each mailbox's enablement in a workspace a partner manages.
|
||||
func (h *Handler) WorkspacePartnerMailboxes(c *gin.Context) {
|
||||
orgID := middleware.GetOrganizationID(c)
|
||||
if orgID == nil {
|
||||
errx.Handle(c, errx.ErrNoOrganization)
|
||||
return
|
||||
}
|
||||
data, xerr := h.Partners.WorkspaceMailboxes(c.Request.Context(), *orgID)
|
||||
if xerr != nil {
|
||||
errx.Handle(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": data})
|
||||
}
|
||||
|
||||
// AdminPartnerStatements is GET /admin/partners/:id/statements: closed months, newest first.
|
||||
func (h *Handler) AdminPartnerStatements(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
errx.Handle(c, errx.ErrUuid)
|
||||
return
|
||||
}
|
||||
list, xerr := h.Partners.AdminStatements(c.Request.Context(), id)
|
||||
if xerr != nil {
|
||||
errx.Handle(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": list})
|
||||
}
|
||||
|
||||
// AdminPartnerStatement is GET /admin/partners/:id/statements/:month: one month, closed or running.
|
||||
func (h *Handler) AdminPartnerStatement(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
errx.Handle(c, errx.ErrUuid)
|
||||
return
|
||||
}
|
||||
st, xerr := h.Partners.AdminStatement(c.Request.Context(), id, c.Param("month"))
|
||||
if xerr != nil {
|
||||
errx.Handle(c, xerr)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, st)
|
||||
}
|
||||
@@ -0,0 +1,790 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/graphkit"
|
||||
)
|
||||
|
||||
// storeCaller is the caller's workspace and user, or false once it has answered.
|
||||
func (h *Handler) storeCaller(c *gin.Context) (uuid.UUID, uuid.UUID, bool) {
|
||||
orgID := middleware.GetOrganizationID(c)
|
||||
if orgID == nil {
|
||||
errx.Handle(c, errx.ErrNoOrganization)
|
||||
return uuid.Nil, uuid.Nil, false
|
||||
}
|
||||
userID, err := middleware.GetUserUUID(c)
|
||||
if err != nil {
|
||||
errx.Handle(c, errx.ErrUser)
|
||||
return uuid.Nil, uuid.Nil, false
|
||||
}
|
||||
return *orgID, userID, true
|
||||
}
|
||||
|
||||
// storeError answers a store failure in Warmbly's error shape.
|
||||
func storeError(c *gin.Context, err error) {
|
||||
rid := c.GetString("request_id")
|
||||
var (
|
||||
price *store.PriceChangedError
|
||||
method *store.PaymentMethodError
|
||||
card *store.CardError
|
||||
bad *store.ContactError
|
||||
)
|
||||
var xerr *errx.Error
|
||||
if errors.As(err, &xerr) && xerr.Identifier == store.ErrIDContactInvalid {
|
||||
err = store.NewContactError(strings.Split(xerr.Reason, ","))
|
||||
}
|
||||
switch {
|
||||
case errors.As(err, &price):
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": "Conflict", "code": store.CodePriceChanged, "request_id": rid,
|
||||
"message": "The price changed since you looked. Review the new total.",
|
||||
"details": gin.H{"quote": price.Quote},
|
||||
})
|
||||
case errors.As(err, &method):
|
||||
c.JSON(http.StatusPaymentRequired, gin.H{
|
||||
"error": "Payment Required", "code": store.CodePaymentMethodRequired, "request_id": rid,
|
||||
"message": "Add a card to pay for this order.",
|
||||
"setup_url": c.GetString("store_setup_url"),
|
||||
})
|
||||
case errors.As(err, &card):
|
||||
c.JSON(http.StatusPaymentRequired, gin.H{
|
||||
"error": "Payment Required", "code": card.Code, "request_id": rid,
|
||||
"message": "The card was not charged. Try another card or add money to your balance.",
|
||||
})
|
||||
case errors.As(err, &bad):
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Bad Request", "code": store.ErrIDContactInvalid, "request_id": rid,
|
||||
"message": bad.Message(),
|
||||
"details": gin.H{"fields": bad.Fields},
|
||||
})
|
||||
default:
|
||||
if !errors.As(err, &xerr) {
|
||||
log.Error().Err(err).Str("request_id", rid).Msg("store: request failed")
|
||||
}
|
||||
errx.Handle(c, err)
|
||||
}
|
||||
}
|
||||
|
||||
func storeLimit(c *gin.Context) (int, bool) {
|
||||
raw := c.Query("limit")
|
||||
if raw == "" {
|
||||
return 0, true
|
||||
}
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_limit", "limit must be between 1 and 100."))
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
func storeID(c *gin.Context) (uuid.UUID, bool) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.ErrUuid)
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
// GetStoreStatus is GET /v1/store/status.
|
||||
func (h *Handler) GetStoreStatus(c *gin.Context) {
|
||||
orgID, userID, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
st, err := h.StoreService.Status(c.Request.Context(), orgID)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
if st.Metered && h.StripeService != nil {
|
||||
st.StripePublishableKey = h.StripeService.PublishableKey()
|
||||
}
|
||||
if st.Enabled {
|
||||
st.DefaultForwardingURL = h.StoreService.DefaultForward(c.Request.Context(), orgID, userID)
|
||||
st.Photos = h.StoreService.PhotosAvailable()
|
||||
}
|
||||
if st.Locked && h.canConfigureStore(c, userID) {
|
||||
st.CanConfigure = true
|
||||
if admin := config.AdminURL(); admin != "" {
|
||||
st.ConfigureURL = admin + storeConfigurePath
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, st)
|
||||
}
|
||||
|
||||
// storeConfigurePath is the admin panel page that takes the GraphKit API key.
|
||||
const storeConfigurePath = "/health?tab=integrations"
|
||||
|
||||
// canConfigureStore reports a signed-in member who is also an instance admin holding manage_settings; never an API key.
|
||||
func (h *Handler) canConfigureStore(c *gin.Context, userID uuid.UUID) bool {
|
||||
if middleware.GetAPIKeyID(c) != nil || h.OrganizationService == nil {
|
||||
return false
|
||||
}
|
||||
perms, err := h.OrganizationService.GetUserAdminPermissions(c.Request.Context(), userID)
|
||||
return err == nil && models.AdminPermission(perms).HasPermission(models.AdminPermManageSettings)
|
||||
}
|
||||
|
||||
// SearchStoreDomains is GET /v1/store/domains/search?q=&tlds=.
|
||||
func (h *Handler) SearchStoreDomains(c *gin.Context) {
|
||||
if _, _, ok := h.storeCaller(c); !ok {
|
||||
return
|
||||
}
|
||||
res, err := h.StoreService.Search(c.Request.Context(), c.Query("q"), c.QueryArray("tlds"))
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
// PutStoreRegistrant is PUT /v1/store/registrant.
|
||||
func (h *Handler) PutStoreRegistrant(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.Registrant
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
r, err := h.StoreService.PutRegistrant(c.Request.Context(), orgID, in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityStoreDomain, nil, nil, map[string]string{"field": "registrant"})
|
||||
c.JSON(http.StatusOK, r)
|
||||
}
|
||||
|
||||
// CreateStoreQuote is POST /v1/store/quotes.
|
||||
func (h *Handler) CreateStoreQuote(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.QuoteRequest
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
q, err := h.StoreService.CreateQuote(c.Request.Context(), orgID, in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, q)
|
||||
}
|
||||
|
||||
// CreateStoreOrder is POST /v1/store/orders: charge the workspace and order.
|
||||
func (h *Handler) CreateStoreOrder(c *gin.Context) {
|
||||
orgID, userID, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.OrderRequest
|
||||
if err := c.ShouldBindJSON(&in); err != nil || in.QuoteID == uuid.Nil {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_body", "Send the quote to order."))
|
||||
return
|
||||
}
|
||||
o, err := h.StoreService.PlaceOrder(c.Request.Context(), orgID, userID, in)
|
||||
if err != nil {
|
||||
var method *store.PaymentMethodError
|
||||
if errors.As(err, &method) && h.StripeService != nil {
|
||||
// The same card setup the billing page uses, returning to the checkout.
|
||||
if sess, xerr := h.StripeService.CreateCardSetupCheckout(c.Request.Context(), userID, orgID,
|
||||
billingReturnURL(c.Request.Context(), "", "/app/emails/buy?payment_method=success"),
|
||||
billingReturnURL(c.Request.Context(), "", "/app/emails/buy?payment_method=canceled")); xerr == nil && sess != nil {
|
||||
c.Set("store_setup_url", sess.URL)
|
||||
}
|
||||
}
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionCreate, models.AuditEntityStoreOrder, &o.ID, nil, map[string]string{
|
||||
"due_now_usd": strconv.FormatFloat(float64(o.DueNowMicros)/1_000_000, 'f', 2, 64),
|
||||
})
|
||||
c.JSON(http.StatusCreated, o)
|
||||
}
|
||||
|
||||
// ListStoreOrders is GET /v1/store/orders.
|
||||
func (h *Handler) ListStoreOrders(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, ok := storeLimit(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := h.StoreService.ListOrders(c.Request.Context(), orgID, c.Query("cursor"), limit)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// GetStoreOrder is GET /v1/store/orders/:id.
|
||||
func (h *Handler) GetStoreOrder(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
o, err := h.StoreService.GetOrder(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, o)
|
||||
}
|
||||
|
||||
// ListStoreDomains is GET /v1/store/domains.
|
||||
func (h *Handler) ListStoreDomains(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, ok := storeLimit(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := h.StoreService.ListDomains(c.Request.Context(), orgID, c.Query("cursor"), limit)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// GetStoreDomain is GET /v1/store/domains/:id, with its DNS records.
|
||||
func (h *Handler) GetStoreDomain(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d, err := h.StoreService.GetDomain(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, d)
|
||||
}
|
||||
|
||||
// credentialCaller is an API key or OAuth token: it presents a scoped credential on every call and has no session to refresh.
|
||||
func credentialCaller(c *gin.Context) bool {
|
||||
t := c.GetString(middleware.AuthTypeKey)
|
||||
return t == middleware.AuthTypeAPIKey || t == middleware.AuthTypeOAuth
|
||||
}
|
||||
|
||||
// PatchStoreDomain is PATCH /v1/store/domains/:id. Turning auto-renew on or
|
||||
// off changes what is charged, so it needs manage_billing and, for a session, a fresh sign-in.
|
||||
func (h *Handler) PatchStoreDomain(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.DomainPatch
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
if in.AutoRenew != nil {
|
||||
perms, _ := middleware.GetMemberPermissions(c)
|
||||
if !perms.HasPermission(models.PermManageBilling) {
|
||||
errx.JSON(c, errx.ErrForbidden)
|
||||
return
|
||||
}
|
||||
if !credentialCaller(c) && !middleware.SessionFresh(c) {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.Forbidden, "reauth_required", "Confirm it is you before making this change."))
|
||||
return
|
||||
}
|
||||
}
|
||||
d, err := h.StoreService.PatchDomain(c.Request.Context(), orgID, id, in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
changes := map[string]string{}
|
||||
if in.AutoRenew != nil {
|
||||
changes["auto_renew"] = strconv.FormatBool(*in.AutoRenew)
|
||||
}
|
||||
if in.ForwardingURL != nil {
|
||||
changes["forwarding_url"] = d.ForwardingURL
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityStoreDomain, &d.ID, changes, map[string]string{"domain": d.Name})
|
||||
c.JSON(http.StatusOK, d)
|
||||
}
|
||||
|
||||
// RenewStoreDomain is POST /v1/store/domains/:id/renew.
|
||||
func (h *Handler) RenewStoreDomain(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d, err := h.StoreService.RenewNow(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityStoreDomain, &d.ID, nil, map[string]string{"domain": d.Name, "action": "renew"})
|
||||
c.JSON(http.StatusOK, d)
|
||||
}
|
||||
|
||||
// TransferOutStoreDomain is POST /v1/store/domains/:id/transfer-out.
|
||||
func (h *Handler) TransferOutStoreDomain(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
code, err := h.StoreService.TransferOut(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionTransfer, models.AuditEntityStoreDomain, &id, nil, nil)
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.JSON(http.StatusOK, gin.H{"auth_code": code})
|
||||
}
|
||||
|
||||
// ListStoreMailboxes is GET /v1/store/mailboxes.
|
||||
func (h *Handler) ListStoreMailboxes(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, ok := storeLimit(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
page, err := h.StoreService.ListMailboxes(c.Request.Context(), orgID, c.Query("cursor"), limit)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, page)
|
||||
}
|
||||
|
||||
// PatchStoreMailbox is PATCH /v1/store/mailboxes/:id: the sender name.
|
||||
func (h *Handler) PatchStoreMailbox(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.MailboxPatch
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
m, err := h.StoreService.RenameMailbox(c.Request.Context(), orgID, id, in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityStoreMailbox, &m.ID, map[string]string{"first_name": m.FirstName, "last_name": m.LastName}, map[string]string{"email": m.Email})
|
||||
c.JSON(http.StatusOK, m)
|
||||
}
|
||||
|
||||
// storePhotoLimits are a mailbox photo's: GraphKit takes PNG or JPG up to 2 MB.
|
||||
var storePhotoLimits = imageLimits{label: "photo", formats: "PNG or JPG", maxBytes: 2 << 20, maxDim: 2048}
|
||||
|
||||
// UploadStorePhoto is POST /v1/store/photos: a multipart "file", or {"from": "profile"}
|
||||
// to copy the caller's own profile photo. Answers the photo's id for an order line or a mailbox.
|
||||
func (h *Handler) UploadStorePhoto(c *gin.Context) {
|
||||
orgID, userID, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var (
|
||||
p *store.Photo
|
||||
err error
|
||||
)
|
||||
if strings.HasPrefix(c.ContentType(), "application/json") {
|
||||
var in struct {
|
||||
From string `json:"from"`
|
||||
}
|
||||
if berr := c.ShouldBindJSON(&in); berr != nil || in.From != "profile" {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_body", `Send a photo as the multipart field "file", or {"from": "profile"}.`))
|
||||
return
|
||||
}
|
||||
p, err = h.StoreService.ProfilePhoto(c.Request.Context(), orgID, userID)
|
||||
} else {
|
||||
body, _, _, xerr := readImageUpload(c, storePhotoLimits)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
p, err = h.StoreService.UploadPhoto(c.Request.Context(), orgID, userID, body)
|
||||
}
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, p)
|
||||
}
|
||||
|
||||
// GetStorePhoto is GET /v1/store/photos/:id: one of the workspace's uploaded photos, as a JPEG.
|
||||
func (h *Handler) GetStorePhoto(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data, err := h.StoreService.PhotoBytes(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "private, max-age=86400")
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
c.Data(http.StatusOK, "image/jpeg", data)
|
||||
}
|
||||
|
||||
// SetStoreMailboxPhoto is PUT /v1/store/mailboxes/:id/photo: the mailbox's profile photo at Google or Microsoft.
|
||||
func (h *Handler) SetStoreMailboxPhoto(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.MailboxPhotoRequest
|
||||
if err := c.ShouldBindJSON(&in); err != nil || in.PhotoID == uuid.Nil {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.BadRequest, "invalid_body", "Send the uploaded photo's photo_id."))
|
||||
return
|
||||
}
|
||||
m, err := h.StoreService.SetMailboxPhoto(c.Request.Context(), orgID, id, in.PhotoID)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityStoreMailbox, &m.ID, nil, map[string]string{"email": m.Email, "field": "photo"})
|
||||
c.JSON(http.StatusOK, m)
|
||||
}
|
||||
|
||||
// CancelStoreMailbox is DELETE /v1/store/mailboxes/:id: cancel at the end of the paid month.
|
||||
func (h *Handler) CancelStoreMailbox(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
m, err := h.StoreService.CancelMailbox(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionDelete, models.AuditEntityStoreMailbox, &m.ID, nil, map[string]string{"email": m.Email})
|
||||
c.JSON(http.StatusOK, m)
|
||||
}
|
||||
|
||||
// ResumeStoreMailbox is POST /v1/store/mailboxes/:id/resume.
|
||||
func (h *Handler) ResumeStoreMailbox(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
m, err := h.StoreService.ResumeMailbox(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionResume, models.AuditEntityStoreMailbox, &m.ID, nil, map[string]string{"email": m.Email})
|
||||
c.JSON(http.StatusOK, m)
|
||||
}
|
||||
|
||||
func storeRecordID(c *gin.Context) (uuid.UUID, bool) {
|
||||
id, err := uuid.Parse(c.Param("record_id"))
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.ErrUuid)
|
||||
return uuid.Nil, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
// storeDomainCall runs a call on one of the workspace's store domains.
|
||||
func (h *Handler) storeDomainCall(c *gin.Context) (uuid.UUID, uuid.UUID, bool) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return uuid.Nil, uuid.Nil, false
|
||||
}
|
||||
id, ok := storeID(c)
|
||||
return orgID, id, ok
|
||||
}
|
||||
|
||||
// ConnectStoreDomain is POST /v1/store/domains/connect: add a domain registered elsewhere.
|
||||
func (h *Handler) ConnectStoreDomain(c *gin.Context) {
|
||||
orgID, _, ok := h.storeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.ConnectRequest
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
d, err := h.StoreService.ConnectDomain(c.Request.Context(), orgID, in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionConnect, models.AuditEntityStoreDomain, &d.ID, nil, map[string]string{"domain": d.Name, "method": in.Method})
|
||||
c.JSON(http.StatusCreated, d)
|
||||
}
|
||||
|
||||
// CheckStoreDomainConnection is POST /v1/store/domains/:id/connection/check.
|
||||
func (h *Handler) CheckStoreDomainConnection(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d, err := h.StoreService.CheckConnection(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, d)
|
||||
}
|
||||
|
||||
// RegenerateStoreDomainConnection is POST /v1/store/domains/:id/connection/regenerate.
|
||||
func (h *Handler) RegenerateStoreDomainConnection(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d, err := h.StoreService.RegenerateConnection(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityStoreDomain, &d.ID, nil, map[string]string{"domain": d.Name, "action": "regenerate"})
|
||||
c.JSON(http.StatusOK, d)
|
||||
}
|
||||
|
||||
// RemoveStoreDomain is DELETE /v1/store/domains/:id: a connected domain with no mailboxes.
|
||||
func (h *Handler) RemoveStoreDomain(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.StoreService.RemoveDomain(c.Request.Context(), orgID, id); err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionRemove, models.AuditEntityStoreDomain, &id, nil, nil)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// AddStoreDNSRecord is POST /v1/store/domains/:id/dns.
|
||||
func (h *Handler) AddStoreDNSRecord(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.DNSRecordInput
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
r, err := h.StoreService.AddDNSRecord(c.Request.Context(), orgID, id, in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionCreate, models.AuditEntityStoreDomain, &id, nil, map[string]string{"dns_record": r.Type + " " + r.Name})
|
||||
c.JSON(http.StatusCreated, r)
|
||||
}
|
||||
|
||||
// UpdateStoreDNSRecord is PATCH /v1/store/domains/:id/dns/:record_id.
|
||||
func (h *Handler) UpdateStoreDNSRecord(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rid, ok := storeRecordID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in store.DNSRecordPatch
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
errx.JSON(c, errx.InvalidBody(err))
|
||||
return
|
||||
}
|
||||
r, err := h.StoreService.UpdateDNSRecord(c.Request.Context(), orgID, id, rid, in)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionUpdate, models.AuditEntityStoreDomain, &id, nil, map[string]string{"dns_record": r.Type + " " + r.Name})
|
||||
c.JSON(http.StatusOK, r)
|
||||
}
|
||||
|
||||
// DeleteStoreDNSRecord is DELETE /v1/store/domains/:id/dns/:record_id.
|
||||
func (h *Handler) DeleteStoreDNSRecord(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rid, ok := storeRecordID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.StoreService.DeleteDNSRecord(c.Request.Context(), orgID, id, rid); err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionDelete, models.AuditEntityStoreDomain, &id, nil, map[string]string{"dns_record_id": rid.String()})
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// CheckStoreDNS is POST /v1/store/domains/:id/dns/check: every record looked up in public DNS now.
|
||||
func (h *Handler) CheckStoreDNS(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
res, err := h.StoreService.CheckDNS(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, res)
|
||||
}
|
||||
|
||||
// StoreMailboxSignIn is POST /v1/store/mailboxes/:id/sign-in: the mailbox's
|
||||
// sign-in, the admin console's for the admin mailbox. Shown once, never cached.
|
||||
func (h *Handler) StoreMailboxSignIn(c *gin.Context) {
|
||||
orgID, id, ok := h.storeDomainCall(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
in, err := h.StoreService.SignIn(c.Request.Context(), orgID, id)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
h.auditOrg(c, models.AuditActionExport, models.AuditEntityStoreMailbox, &id, nil, map[string]string{"email": in.Email, "action": "sign_in"})
|
||||
c.Header("Cache-Control", "no-store")
|
||||
c.JSON(http.StatusOK, in)
|
||||
}
|
||||
|
||||
// GraphKitWebhook is POST /v1/webhooks/graphkit: public, and trusted only
|
||||
// once its signature verifies against the configured secrets.
|
||||
func (h *Handler) GraphKitWebhook(c *gin.Context) {
|
||||
if h.StoreService == nil || !h.StoreService.Enabled() {
|
||||
errx.JSON(c, errx.ErrNotFound)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20))
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.New(errx.BadRequest, "unreadable body"))
|
||||
return
|
||||
}
|
||||
ev, err := h.StoreService.VerifyWebhook(c.GetHeader(graphkit.SignatureHeader), body)
|
||||
if err != nil {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.Unauthorized, "invalid_signature", "The signature is not valid."))
|
||||
return
|
||||
}
|
||||
h.StoreService.NoteWebhook(c.Request.Context())
|
||||
if err := h.StoreService.ApplyEvent(c.Request.Context(), *ev); err != nil {
|
||||
log.Error().Err(err).Str("event_type", ev.Type).Msg("store: applying a webhook failed; GraphKit retries it")
|
||||
errx.JSON(c, errx.InternalError())
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// AdminStorePricing is GET /admin/store/pricing: GraphKit's live price list
|
||||
// and this instance's retail for each TLD.
|
||||
func (h *Handler) AdminStorePricing(c *gin.Context) {
|
||||
if h.StoreService == nil || !h.StoreService.Enabled() {
|
||||
errx.JSON(c, errx.NewWithIdentifier(errx.NotFound, store.CodeDisabled, store.NotConfiguredMessage))
|
||||
return
|
||||
}
|
||||
p, err := h.StoreService.AdminPricing(c.Request.Context())
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, p)
|
||||
}
|
||||
|
||||
// GetAgencyStore is GET /agency/:agencyId/store: the purchased domains and
|
||||
// mailboxes of every client whose mailboxes the caller manages.
|
||||
func (h *Handler) GetAgencyStore(c *gin.Context) {
|
||||
userID, agencyID, ok := h.agencyHomeCaller(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
list, xerr := h.AgencyHomeService.ClientsWith(c.Request.Context(), agencyID, userID, models.PermManageEmails)
|
||||
if xerr != nil {
|
||||
errx.JSON(c, xerr)
|
||||
return
|
||||
}
|
||||
if h.StoreService == nil {
|
||||
c.JSON(http.StatusOK, &store.AgencyOverview{Clients: []store.AgencyClientStore{}, Renewals: []store.AgencyRenewal{}})
|
||||
return
|
||||
}
|
||||
clients := make([]store.AgencyClient, 0, len(list))
|
||||
for _, m := range list {
|
||||
clients = append(clients, store.AgencyClient{ID: m.OrganizationID, Name: m.Name, AvatarURL: m.AvatarURL})
|
||||
}
|
||||
out, err := h.StoreService.AgencyOverview(c.Request.Context(), clients)
|
||||
if err != nil {
|
||||
storeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, out)
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/app/organization"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/config"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/repository"
|
||||
)
|
||||
|
||||
type adminBits struct {
|
||||
organization.OrganizationService
|
||||
perms uint32
|
||||
}
|
||||
|
||||
func (a adminBits) GetUserAdminPermissions(context.Context, uuid.UUID) (uint32, error) {
|
||||
return a.perms, nil
|
||||
}
|
||||
|
||||
// nopStoreRepo is a store repository nothing here reads.
|
||||
type nopStoreRepo struct{ repository.StoreRepository }
|
||||
|
||||
// storeConns keeps a connection in memory and reports nothing live.
|
||||
type storeConns struct{ row *repository.StoreConnection }
|
||||
|
||||
func (s *storeConns) CanSeal() bool { return true }
|
||||
func (s *storeConns) GetConnection(context.Context) (*repository.StoreConnection, error) {
|
||||
return s.row, nil
|
||||
}
|
||||
func (s *storeConns) PutConnection(_ context.Context, c repository.StoreConnection) error {
|
||||
s.row = &c
|
||||
return nil
|
||||
}
|
||||
func (s *storeConns) DeleteConnection(context.Context) error { s.row = nil; return nil }
|
||||
func (s *storeConns) CountLivePurchases(context.Context, *uuid.UUID) (int, int, error) {
|
||||
return 0, 0, nil
|
||||
}
|
||||
|
||||
func storeStatusAs(t *testing.T, h *Handler, apiKey bool) store.Status {
|
||||
t.Helper()
|
||||
r := gin.New()
|
||||
r.Use(middleware.RequestIDMiddleware(), func(c *gin.Context) {
|
||||
c.Set(middleware.OrganizationIDKey, uuid.New())
|
||||
c.Set(middleware.UserIDKey, uuid.NewString())
|
||||
if apiKey {
|
||||
c.Set(middleware.APIKeyIDKey, uuid.NewString())
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
r.GET("/store/status", h.GetStoreStatus)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/store/status", nil))
|
||||
var st store.Status
|
||||
if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &st) != nil {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func TestStoreStatusOffersSetupToAnInstanceAdminOnly(t *testing.T) {
|
||||
t.Setenv("ADMIN_URL", "https://admin.example.com")
|
||||
svc := store.New(store.Deps{SelfHosted: true})
|
||||
settings := uint32(models.AdminPermManageSettings)
|
||||
|
||||
st := storeStatusAs(t, &Handler{StoreService: svc, OrganizationService: adminBits{perms: settings}}, false)
|
||||
if st.Reason != store.ReasonNotConfigured || st.Configured || !st.Locked || !st.CanConfigure || st.ConfigureURL != "https://admin.example.com/health?tab=integrations" {
|
||||
t.Fatalf("instance admin: %+v", st)
|
||||
}
|
||||
for name, h := range map[string]*Handler{
|
||||
"member": {StoreService: svc, OrganizationService: adminBits{}},
|
||||
"other admin bit": {StoreService: svc, OrganizationService: adminBits{perms: uint32(models.AdminPermViewAnalytics)}},
|
||||
"no org service": {StoreService: svc},
|
||||
"api key of admins": {StoreService: svc, OrganizationService: adminBits{perms: settings}},
|
||||
} {
|
||||
if st := storeStatusAs(t, h, name == "api key of admins"); st.CanConfigure || st.ConfigureURL != "" || st.Reason != store.ReasonNotConfigured {
|
||||
t.Fatalf("%s: %+v", name, st)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreStatusKeepsAnUnconfiguredStoreHiddenOnAHostedInstance(t *testing.T) {
|
||||
t.Setenv("ADMIN_URL", "https://admin.example.com")
|
||||
admin := adminBits{perms: uint32(models.AdminPermManageSettings)}
|
||||
for _, selfHosted := range []bool{false, true} {
|
||||
h := &Handler{StoreService: store.New(store.Deps{SelfHosted: selfHosted}), OrganizationService: admin}
|
||||
st := storeStatusAs(t, h, false)
|
||||
// Hosted: not locked, and no setup offer even to an instance admin; the admin panel's card is where they add the key.
|
||||
if st.Enabled || st.Reason != store.ReasonNotConfigured || st.Locked != selfHosted || st.CanConfigure != selfHosted || (st.ConfigureURL != "") != selfHosted {
|
||||
t.Fatalf("self-hosted %v: %+v", selfHosted, st)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// serveAdminConnection registers the connection routes behind the same gates routes.go puts them behind.
|
||||
func serveAdminConnection(h *Handler, perms models.AdminPermission, fresh bool, method, body string) *httptest.ResponseRecorder {
|
||||
r := gin.New()
|
||||
r.Use(middleware.RequestIDMiddleware(), func(c *gin.Context) {
|
||||
admin := uuid.New()
|
||||
session := &models.Session{UserID: admin}
|
||||
if fresh {
|
||||
now := time.Now()
|
||||
session.ReauthAt = &now
|
||||
}
|
||||
c.Set(middleware.SessionKey, session)
|
||||
c.Set(middleware.AdminPermissionsKey, perms)
|
||||
c.Set(middleware.AdminUserIDKey, admin)
|
||||
c.Next()
|
||||
})
|
||||
gate := middleware.RequireAdminPermission(models.AdminPermManageSettings)
|
||||
r.GET("/admin/store/connection", gate, h.AdminGetStoreConnection)
|
||||
r.PUT("/admin/store/connection", gate, middleware.RequireFreshAuth(), h.AdminPutStoreConnection)
|
||||
r.POST("/admin/store/connection", gate, middleware.RequireFreshAuth(), h.AdminTestStoreConnection)
|
||||
r.DELETE("/admin/store/connection", gate, middleware.RequireFreshAuth(), h.AdminDeleteStoreConnection)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequestWithContext(context.Background(), method, "/admin/store/connection", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestAdminStoreConnectionIsGatedAndNeverReturnsASecret(t *testing.T) {
|
||||
t.Setenv("APP_ENV", "development")
|
||||
svc := store.New(store.Deps{Repo: nopStoreRepo{}})
|
||||
conns := &storeConns{}
|
||||
svc.WireConnectionSettings(conns, config.GraphKit{})
|
||||
h := &Handler{StoreService: svc}
|
||||
save := `{"api_url":"fake","webhook_secret":"whsec_hidden_value"}`
|
||||
|
||||
for _, m := range []string{http.MethodGet, http.MethodPut, http.MethodPost, http.MethodDelete} {
|
||||
if w := serveAdminConnection(h, 0, true, m, save); w.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s without admin: %d", m, w.Code)
|
||||
}
|
||||
if w := serveAdminConnection(h, models.AdminPermViewAnalytics, true, m, save); w.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s without manage_settings: %d", m, w.Code)
|
||||
}
|
||||
}
|
||||
for _, m := range []string{http.MethodPut, http.MethodPost, http.MethodDelete} {
|
||||
if w := serveAdminConnection(h, models.AdminPermManageSettings, false, m, save); w.Code != http.StatusForbidden || responseCode(w) != "reauth_required" {
|
||||
t.Fatalf("%s without a fresh confirmation: %d %s", m, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
if conns.row != nil || svc.Enabled() {
|
||||
t.Fatal("a refused request changed the connection")
|
||||
}
|
||||
|
||||
w := serveAdminConnection(h, models.AdminPermManageSettings, true, http.MethodPut, save)
|
||||
if w.Code != http.StatusOK || !svc.Enabled() || conns.row == nil {
|
||||
t.Fatalf("save: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
w = serveAdminConnection(h, models.AdminPermManageSettings, false, http.MethodGet, "")
|
||||
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "whsec_hidden_value") || !strings.Contains(w.Body.String(), `"webhook_secret_set":true`) {
|
||||
t.Fatalf("read: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), store.WebhookPath) {
|
||||
t.Fatalf("the view does not name the webhook URL: %s", w.Body.String())
|
||||
}
|
||||
if w := serveAdminConnection(h, models.AdminPermManageSettings, true, http.MethodDelete, ""); w.Code != http.StatusOK || svc.Enabled() {
|
||||
t.Fatalf("delete: %d, enabled %v", w.Code, svc.Enabled())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// Auto-renew changes what is charged: the member needs manage_billing, and only
|
||||
// a session has a recent confirmation to show; a key or token passes that part.
|
||||
func TestStoreAutoRenewNeedsBillingAndASessionConfirmation(t *testing.T) {
|
||||
org, user := uuid.New(), uuid.New()
|
||||
tests := []struct {
|
||||
name string
|
||||
auth string
|
||||
perm models.OrganizationPermission
|
||||
want string // the refusal's code, or store_disabled once the gates let it through
|
||||
}{
|
||||
{"key without manage_billing", middleware.AuthTypeAPIKey, models.PermManageEmails, "forbidden"},
|
||||
{"key with manage_billing", middleware.AuthTypeAPIKey, models.PermManageEmails | models.PermManageBilling, "store_disabled"},
|
||||
{"oauth with manage_billing", middleware.AuthTypeOAuth, models.PermManageEmails | models.PermManageBilling, "store_disabled"},
|
||||
{"session not confirmed recently", middleware.AuthTypeJWT, models.PermManageEmails | models.PermManageBilling, "reauth_required"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
h := &Handler{}
|
||||
r := gin.New()
|
||||
r.Use(middleware.RequestIDMiddleware(), func(c *gin.Context) {
|
||||
c.Set(middleware.AuthTypeKey, tt.auth)
|
||||
c.Set(middleware.UserIDKey, user.String())
|
||||
c.Set(middleware.OrganizationIDKey, org)
|
||||
c.Set(middleware.SessionMemberKey, &models.OrganizationMember{OrganizationID: org, UserID: user, Role: "member", Permissions: tt.perm})
|
||||
if tt.auth == middleware.AuthTypeJWT {
|
||||
c.Set(middleware.SessionKey, &models.Session{})
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
r.PATCH("/store/domains/:id", h.PatchStoreDomain)
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPatch, "/store/domains/"+uuid.NewString(), strings.NewReader(`{"auto_renew":false}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
got := body.Code
|
||||
if got == "" && w.Code == http.StatusForbidden {
|
||||
got = "forbidden"
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("code = %q (status %d, body %s), want %q", got, w.Code, w.Body.String(), tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/api/middleware"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
func storePhotoRouter(org, user uuid.UUID) *gin.Engine {
|
||||
h := &Handler{}
|
||||
r := gin.New()
|
||||
r.Use(middleware.RequestIDMiddleware(), func(c *gin.Context) {
|
||||
c.Set(middleware.AuthTypeKey, middleware.AuthTypeJWT)
|
||||
c.Set(middleware.UserIDKey, user.String())
|
||||
c.Set(middleware.OrganizationIDKey, org)
|
||||
c.Next()
|
||||
})
|
||||
r.POST("/store/photos", h.UploadStorePhoto)
|
||||
r.PUT("/store/mailboxes/:id/photo", h.SetStoreMailboxPhoto)
|
||||
return r
|
||||
}
|
||||
|
||||
func storeCode(t *testing.T, w *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
return body.Code
|
||||
}
|
||||
|
||||
func TestStoreMailboxPhotoRouteNeedsAnUploadedPhoto(t *testing.T) {
|
||||
r := storePhotoRouter(uuid.New(), uuid.New())
|
||||
for _, tt := range []struct {
|
||||
name, body, want string
|
||||
}{
|
||||
{"no photo", `{}`, "invalid_body"},
|
||||
{"not a photo id", `{"photo_id":"nope"}`, "invalid_body"},
|
||||
// Past validation the route reaches the store, which this instance does not have.
|
||||
{"a photo id", `{"photo_id":"` + uuid.NewString() + `"}`, "store_disabled"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPut, "/store/mailboxes/"+uuid.NewString()+"/photo", strings.NewReader(tt.body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
if got := storeCode(t, w); got != tt.want {
|
||||
t.Fatalf("code = %q (status %d, %s), want %q", got, w.Code, w.Body.String(), tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorePhotoUploadRefusesWhatIsNotAPhoto(t *testing.T) {
|
||||
r := storePhotoRouter(uuid.New(), uuid.New())
|
||||
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
part, _ := mw.CreateFormFile("file", "photo.png")
|
||||
_, _ = part.Write([]byte("<svg xmlns='http://www.w3.org/2000/svg' onload='alert(1)'/>"))
|
||||
_ = mw.Close()
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/store/photos", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest || !strings.HasPrefix(storeCode(t, w), "image_") {
|
||||
t.Fatalf("an SVG upload: status %d, %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
req = httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/store/photos", strings.NewReader(`{"from":"elsewhere"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
r.ServeHTTP(w, req)
|
||||
if got := storeCode(t, w); got != "invalid_body" {
|
||||
t.Fatalf("an unknown source: %q (%s)", got, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Without a workspace the photo routes answer nothing about any photo.
|
||||
func TestStorePhotoRoutesNeedAWorkspace(t *testing.T) {
|
||||
h := &Handler{}
|
||||
r := gin.New()
|
||||
r.Use(middleware.RequestIDMiddleware(), func(c *gin.Context) {
|
||||
c.Set(middleware.UserIDKey, uuid.NewString())
|
||||
c.Set(middleware.SessionMemberKey, &models.OrganizationMember{})
|
||||
c.Next()
|
||||
})
|
||||
r.GET("/store/photos/:id", h.GetStorePhoto)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/store/photos/"+uuid.NewString(), nil))
|
||||
if w.Code == http.StatusOK {
|
||||
t.Fatalf("read a photo with no workspace: %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -171,12 +171,12 @@ const (
|
||||
)
|
||||
|
||||
// classifyOutcome sorts a finished request: refused before it ran frees the key,
|
||||
// a server error is uncertain, anything else is replayed.
|
||||
// a server error or an abandoned request is uncertain, anything else is replayed.
|
||||
func classifyOutcome(status int) idempotentOutcome {
|
||||
switch {
|
||||
case status == http.StatusUnauthorized, status == http.StatusForbidden, status == http.StatusTooManyRequests:
|
||||
return outcomeRefused
|
||||
case status >= http.StatusInternalServerError:
|
||||
case status >= http.StatusInternalServerError, status == errx.StatusClientClosedRequest:
|
||||
return outcomeUncertain
|
||||
default:
|
||||
return outcomeDefinite
|
||||
|
||||
@@ -226,6 +226,24 @@ func TestIdempotencyOutcomeIsRecordedAfterTheClientHangsUp(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyAbandonedInternalErrorLeavesTheOutcomeUncertain(t *testing.T) {
|
||||
svc := &fakeIdempotencyService{state: idempotency.StateStarted}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
r := idempotentRouter(svc, uuid.New(), asUser(uuid.NewString()), func(c *gin.Context) {
|
||||
// The client goes away while the side effect is in flight.
|
||||
cancel()
|
||||
errx.Handle(c, errx.InternalError())
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/contacts", nil)
|
||||
req.Header.Set(IdempotencyKeyHeader, "idem_123")
|
||||
r.ServeHTTP(httptest.NewRecorder(), req)
|
||||
|
||||
if svc.finish != "uncertain" {
|
||||
t.Fatalf("finish = %q status = %d, want uncertain so a retry is not answered with an empty stored reply", svc.finish, svc.status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyOutcomeFollowsTheResponse(t *testing.T) {
|
||||
cases := []struct {
|
||||
status int
|
||||
@@ -241,6 +259,7 @@ func TestIdempotencyOutcomeFollowsTheResponse(t *testing.T) {
|
||||
{http.StatusInternalServerError, "uncertain"},
|
||||
{http.StatusBadGateway, "uncertain"},
|
||||
{http.StatusServiceUnavailable, "uncertain"},
|
||||
{errx.StatusClientClosedRequest, "uncertain"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
svc := &fakeIdempotencyService{state: idempotency.StateStarted}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
)
|
||||
|
||||
// The store's gates as routes.go composes them: reads take READ_STORE, changes
|
||||
// MANAGE_STORE, and a charge also holds the key's member to manage_billing.
|
||||
func TestStoreGatesForAPIKeys(t *testing.T) {
|
||||
h := &Handler{OrganizationService: &membershipOrgs{}}
|
||||
org, other, user := uuid.New(), uuid.New(), uuid.New()
|
||||
emails := models.PermManageEmails
|
||||
both := models.PermManageEmails | models.PermManageBilling
|
||||
|
||||
read := h.RequireAccess(models.PermManageEmails, models.APIPermReadStore)
|
||||
manage := h.RequireAccess(models.PermManageEmails, models.APIPermManageStore)
|
||||
billing := h.RequireAccess(models.PermManageBilling, models.APIPermManageStore)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
auth string
|
||||
scopes uint64
|
||||
member models.OrganizationPermission
|
||||
memOrg uuid.UUID
|
||||
gates []gin.HandlerFunc
|
||||
allowed bool
|
||||
}{
|
||||
{"read without READ_STORE", AuthTypeAPIKey, models.APIPermReadEmails | models.APIPermWriteEmails, emails, org, []gin.HandlerFunc{read}, false},
|
||||
{"read with READ_STORE", AuthTypeAPIKey, models.APIPermReadStore, emails, org, []gin.HandlerFunc{read}, true},
|
||||
{"read with only MANAGE_STORE", AuthTypeAPIKey, models.APIPermManageStore, emails, org, []gin.HandlerFunc{read}, false},
|
||||
{"read by a member without manage_emails", AuthTypeAPIKey, models.APIPermReadStore, models.PermViewCampaigns, org, []gin.HandlerFunc{read}, false},
|
||||
{"change with READ_STORE only", AuthTypeAPIKey, models.APIPermReadStore, both, org, []gin.HandlerFunc{manage}, false},
|
||||
{"change with MANAGE_STORE", AuthTypeAPIKey, models.APIPermManageStore, emails, org, []gin.HandlerFunc{manage}, true},
|
||||
{"charge by a member without manage_billing", AuthTypeAPIKey, models.APIPermManageStore, emails, org, []gin.HandlerFunc{manage, billing}, false},
|
||||
{"charge by a member with manage_billing", AuthTypeAPIKey, models.APIPermManageStore, both, org, []gin.HandlerFunc{manage, billing}, true},
|
||||
{"oauth charge by a member with manage_billing", AuthTypeOAuth, models.APIPermManageStore, both, org, []gin.HandlerFunc{manage, billing}, true},
|
||||
{"oauth charge without manage_billing", AuthTypeOAuth, models.APIPermManageStore, emails, org, []gin.HandlerFunc{manage, billing}, false},
|
||||
// A membership resolved for another workspace grants nothing in this one.
|
||||
{"membership in another workspace", AuthTypeAPIKey, models.APIPermReadStore, both, other, []gin.HandlerFunc{read}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := gin.New()
|
||||
r.Use(RequestIDMiddleware(), func(c *gin.Context) {
|
||||
c.Set(AuthTypeKey, tt.auth)
|
||||
c.Set(APIKeyPermissionsKey, tt.scopes)
|
||||
c.Set(UserIDKey, user.String())
|
||||
c.Set(OrganizationIDKey, org)
|
||||
c.Set(SessionMemberKey, &models.OrganizationMember{OrganizationID: tt.memOrg, UserID: user, Role: "member", Permissions: tt.member})
|
||||
c.Next()
|
||||
})
|
||||
ran := false
|
||||
handlers := append(append([]gin.HandlerFunc{}, tt.gates...), func(c *gin.Context) {
|
||||
ran = true
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
r.GET("/store", handlers...)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/store", nil))
|
||||
if ran != tt.allowed {
|
||||
t.Fatalf("handler ran = %v, want %v (status %d, body %s)", ran, tt.allowed, w.Code, w.Body.String())
|
||||
}
|
||||
if !tt.allowed && w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403", w.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A charge needs a fresh confirmation from a session, never from a key or a token.
|
||||
func TestStoreFreshAuthPassesCredentialsOnly(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
auth string
|
||||
allowed bool
|
||||
}{{AuthTypeAPIKey, true}, {AuthTypeOAuth, true}, {AuthTypeJWT, false}} {
|
||||
r := gin.New()
|
||||
r.Use(RequestIDMiddleware(), func(c *gin.Context) {
|
||||
c.Set(AuthTypeKey, tt.auth)
|
||||
if tt.auth == AuthTypeJWT {
|
||||
c.Set(SessionKey, &models.Session{})
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
ran := false
|
||||
r.POST("/store/orders", RequireFreshAuth(), func(c *gin.Context) { ran = true })
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/store/orders", nil))
|
||||
if ran != tt.allowed {
|
||||
t.Fatalf("%s: handler ran = %v, want %v (status %d)", tt.auth, ran, tt.allowed, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// An account a partner signs in gets in only through the partner, so every route that adds a way in refuses it.
|
||||
func TestRoutesThatAddASignInMethodRefusePartnerAccounts(t *testing.T) {
|
||||
want := map[string]bool{
|
||||
"protectedAuth POST /me/password": false,
|
||||
"protectedAuth POST /me/password/link": false,
|
||||
"protectedAuth POST /passkey/register/begin": false,
|
||||
"protectedAuth POST /passkey/register/finish": false,
|
||||
"protectedAuth POST /2fa/enroll/start": false,
|
||||
"protectedAuth POST /2fa/enroll/confirm": false,
|
||||
}
|
||||
file, err := parser.ParseFile(token.NewFileSet(), "routes.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
call, ok := n.(*ast.CallExpr)
|
||||
if !ok || len(call.Args) < 2 {
|
||||
return true
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
group, ok := sel.X.(*ast.Ident)
|
||||
lit, isLit := call.Args[0].(*ast.BasicLit)
|
||||
if !ok || !isLit || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
path, _ := strconv.Unquote(lit.Value)
|
||||
key := group.Name + " " + sel.Sel.Name + " " + path
|
||||
if _, tracked := want[key]; !tracked {
|
||||
return true
|
||||
}
|
||||
for _, arg := range call.Args[1:] {
|
||||
if c, ok := arg.(*ast.CallExpr); ok {
|
||||
if s, ok := c.Fun.(*ast.SelectorExpr); ok && s.Sel.Name == "RefusePartnerBound" {
|
||||
want[key] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
for key, gated := range want {
|
||||
if !gated {
|
||||
t.Errorf("%s is registered without RefusePartnerBound", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
-9
@@ -375,6 +375,10 @@ func Run(
|
||||
// of this file stays for non-versioned callers.
|
||||
v1.GET("/invitations/lookup", m.PublicIPRateLimitMiddleware(), h.PreviewInvitation)
|
||||
|
||||
// GraphKit's store webhook: no session; every delivery is verified against
|
||||
// the configured webhook secret (or the previous one) before it is read.
|
||||
v1.POST("/webhooks/graphkit", h.GraphKitWebhook)
|
||||
|
||||
// The branded dashboard on a verified agency portal domain: its brand, and the challenge its sign-in embeds.
|
||||
v1.GET("/auth/portal", m.PublicIPRateLimitMiddleware(), h.PortalInfo)
|
||||
v1.GET("/auth/captcha-frame", m.PublicIPRateLimitMiddleware(), h.CaptchaFrame)
|
||||
@@ -491,6 +495,8 @@ func Run(
|
||||
|
||||
// A portal whose agency signs clients in on the main address trades its one-time code here.
|
||||
auth.POST("/portal/exchange", h.PortalExchange)
|
||||
// A reseller's one-time login link is spent here for a session in the workspace it names.
|
||||
auth.POST("/partner/exchange", h.PartnerLoginExchange)
|
||||
}
|
||||
|
||||
protectedAuth := auth.Group("")
|
||||
@@ -515,9 +521,9 @@ func Run(
|
||||
protectedAuth.PUT("/me/product-tour", h.CompleteProductTour)
|
||||
protectedAuth.POST("/me/avatar", h.UploadUserAvatar)
|
||||
protectedAuth.DELETE("/me/avatar", h.DeleteUserAvatar)
|
||||
protectedAuth.POST("/me/password", m.RateLimitMiddleware(models.RateLimitWrite), h.ChangePassword)
|
||||
protectedAuth.POST("/me/password", h.RefusePartnerBound(), m.RateLimitMiddleware(models.RateLimitWrite), h.ChangePassword)
|
||||
// No Idempotency-Key: a repeat mails another single-use link on the capped reset budget.
|
||||
protectedAuth.POST("/me/password/link", m.RateLimitMiddleware(models.RateLimitWrite), h.SendPasswordLink)
|
||||
protectedAuth.POST("/me/password/link", h.RefusePartnerBound(), m.RateLimitMiddleware(models.RateLimitWrite), h.SendPasswordLink)
|
||||
// Removing a sign-in method changes who can get in. A repeat converges, so it takes no Idempotency-Key.
|
||||
protectedAuth.GET("/me/identities", h.LinkedIdentities)
|
||||
protectedAuth.DELETE("/me/identities/:provider", middleware.RequireFreshAuth(), m.RateLimitMiddleware(models.RateLimitWrite), h.UnlinkIdentity)
|
||||
@@ -538,8 +544,8 @@ func Run(
|
||||
// 2FA enrollment + management (user-scoped, behind a live session).
|
||||
protectedAuth.GET("/2fa/status", h.TwoFAStatus)
|
||||
// Enrollment needs a fresh proof of identity; allowEnrollment checks it in the handler.
|
||||
protectedAuth.POST("/2fa/enroll/start", h.TwoFAEnrollStart)
|
||||
protectedAuth.POST("/2fa/enroll/confirm", h.TwoFAEnrollConfirm)
|
||||
protectedAuth.POST("/2fa/enroll/start", h.RefusePartnerBound(), h.TwoFAEnrollStart)
|
||||
protectedAuth.POST("/2fa/enroll/confirm", h.RefusePartnerBound(), h.TwoFAEnrollConfirm)
|
||||
protectedAuth.DELETE("/2fa", h.TwoFADisable)
|
||||
// No Idempotency-Key: the proof code is single-use, so a retry is refused rather than rotating twice.
|
||||
protectedAuth.POST("/2fa/recovery-codes", h.TwoFARegenerateRecoveryCodes)
|
||||
@@ -560,8 +566,8 @@ func Run(
|
||||
// Passkey enrollment + management require an authenticated session.
|
||||
//
|
||||
// Adding or removing a passkey changes who can get in, so it needs a fresh confirmation; listing and renaming do not.
|
||||
protectedAuth.POST("/passkey/register/begin", middleware.RequireFreshAuth(), h.PasskeyRegisterBegin)
|
||||
protectedAuth.POST("/passkey/register/finish", middleware.RequireFreshAuth(), h.PasskeyRegisterFinish)
|
||||
protectedAuth.POST("/passkey/register/begin", h.RefusePartnerBound(), middleware.RequireFreshAuth(), h.PasskeyRegisterBegin)
|
||||
protectedAuth.POST("/passkey/register/finish", h.RefusePartnerBound(), middleware.RequireFreshAuth(), h.PasskeyRegisterFinish)
|
||||
protectedAuth.GET("/passkey/credentials", h.PasskeyListCredentials)
|
||||
protectedAuth.PATCH("/passkey/credentials/:id", h.PasskeyRenameCredential)
|
||||
protectedAuth.DELETE("/passkey/credentials/:id", middleware.RequireFreshAuth(), h.PasskeyDeleteCredential)
|
||||
@@ -588,7 +594,7 @@ func Run(
|
||||
// long-lived API key (billing, org governance, websocket bootstrap, and
|
||||
// the email onboarding flow that writes user-encrypted secrets).
|
||||
jwtOnly := base.Group("")
|
||||
jwtOnly.Use(m.AuthMiddleware(), m.ResourceScopeGate())
|
||||
jwtOnly.Use(m.AuthMiddleware(), m.ResourceScopeGate(), h.PartnerReadOnlyGate())
|
||||
|
||||
// Warmbly MCP server: exposes the shared tool registry over the MCP
|
||||
// streamable-HTTP transport. Accepts an API key (static header) or an OAuth
|
||||
@@ -607,12 +613,14 @@ func Run(
|
||||
protected := base.Group("")
|
||||
// ResourceScopeGate holds a restricted member, and every key or app acting
|
||||
// for one, to the routes that filter to their grants.
|
||||
protected.Use(m.CombinedAuthMiddleware(), m.ResourceScopeGate(), m.APIKeyUsageMiddleware(), m.IdempotencyMiddleware(), h.ForgetUniboxOverviewOnWrite)
|
||||
protected.Use(m.CombinedAuthMiddleware(), m.ResourceScopeGate(), h.PartnerReadOnlyGate(), m.APIKeyUsageMiddleware(), m.IdempotencyMiddleware(), h.ForgetUniboxOverviewOnWrite)
|
||||
{
|
||||
emails := protected.Group("/emails")
|
||||
emails.Use(m.RateLimitMiddleware(models.RateLimitWrite), middleware.UUIDParams("id"))
|
||||
{
|
||||
emails.GET("", m.RequireAccess(models.PermViewCampaigns, models.APIPermReadEmails), h.EmailsSearch)
|
||||
// A managed workspace's per-mailbox enablement, read-only; its partner sets it.
|
||||
emails.GET("/partner", m.RequireAccess(models.PermViewCampaigns, models.APIPermReadEmails), h.WorkspacePartnerMailboxes)
|
||||
emails.GET("/:id", m.RequireAccess(models.PermViewCampaigns, models.APIPermReadEmails), middleware.RequireEmailAccountParam("id"), h.GetEmail)
|
||||
emails.PATCH("/:id", m.RequireAccess(models.PermManageEmails, models.APIPermWriteEmails), middleware.RequireEmailAccountParam("id"), h.UpdateEmail)
|
||||
// Bulk tag add/remove across many mailboxes (set semantics,
|
||||
@@ -747,6 +755,59 @@ func Run(
|
||||
mailboxGrants.POST("/:id/connect", middleware.RequireFreshAuth(), h.RefuseOnPartnership, h.ConnectMailboxGrantUsers)
|
||||
}
|
||||
|
||||
// Domains and mailboxes bought through the instance's GraphKit account, for a
|
||||
// session, an API key or an OAuth app. Reads take READ_STORE; changes take
|
||||
// MANAGE_STORE. Anything that charges or changes what is charged also holds
|
||||
// the member to manage_billing, and a session to a fresh sign-in.
|
||||
// The protected group already applies Idempotency-Key to every write.
|
||||
storeRoutes := protected.Group("/store")
|
||||
storeRoutes.Use(m.RequireOrganization(), m.RateLimitMiddleware(models.RateLimitWrite), middleware.UUIDParams("id"))
|
||||
{
|
||||
read := m.RequireAccess(models.PermManageEmails, models.APIPermReadStore)
|
||||
manage := m.RequireAccess(models.PermManageEmails, models.APIPermManageStore)
|
||||
billing := m.RequireAccess(models.PermManageBilling, models.APIPermManageStore)
|
||||
storeRoutes.GET("/status", read, h.GetStoreStatus)
|
||||
storeRoutes.GET("/domains/search", read, h.SearchStoreDomains)
|
||||
storeRoutes.PUT("/registrant", manage, billing, h.PutStoreRegistrant)
|
||||
storeRoutes.POST("/quotes", manage, h.CreateStoreQuote)
|
||||
storeRoutes.POST("/orders", manage, billing, middleware.RequireFreshAuth(), h.CreateStoreOrder)
|
||||
storeRoutes.GET("/orders", read, h.ListStoreOrders)
|
||||
storeRoutes.GET("/orders/:id", read, h.GetStoreOrder)
|
||||
storeRoutes.GET("/domains", read, h.ListStoreDomains)
|
||||
storeRoutes.GET("/domains/:id", read, h.GetStoreDomain)
|
||||
// auto_renew is checked for manage_billing and, for a session, a fresh sign-in inside the handler.
|
||||
storeRoutes.PATCH("/domains/:id", manage, h.PatchStoreDomain)
|
||||
storeRoutes.POST("/domains/:id/renew", manage, billing, middleware.RequireFreshAuth(), h.RenewStoreDomain)
|
||||
// Domains registered elsewhere, and DNS records on any store domain. Nothing here is charged.
|
||||
storeRoutes.POST("/domains/connect", manage, h.ConnectStoreDomain)
|
||||
storeRoutes.POST("/domains/:id/connection/check", manage, h.CheckStoreDomainConnection)
|
||||
storeRoutes.POST("/domains/:id/connection/regenerate", manage, h.RegenerateStoreDomainConnection)
|
||||
storeRoutes.DELETE("/domains/:id", manage, h.RemoveStoreDomain)
|
||||
storeRoutes.POST("/domains/:id/dns", manage, h.AddStoreDNSRecord)
|
||||
storeRoutes.PATCH("/domains/:id/dns/:record_id", manage, h.UpdateStoreDNSRecord)
|
||||
storeRoutes.DELETE("/domains/:id/dns/:record_id", manage, h.DeleteStoreDNSRecord)
|
||||
storeRoutes.POST("/domains/:id/dns/check", read, h.CheckStoreDNS)
|
||||
storeRoutes.GET("/mailboxes", read, h.ListStoreMailboxes)
|
||||
storeRoutes.PATCH("/mailboxes/:id", manage, h.PatchStoreMailbox)
|
||||
// Profile photos: uploaded once (or copied from the caller's own), then named by an order line or a mailbox.
|
||||
storeRoutes.POST("/photos", manage, h.UploadStorePhoto)
|
||||
storeRoutes.GET("/photos/:id", read, h.GetStorePhoto)
|
||||
storeRoutes.PUT("/mailboxes/:id/photo", manage, h.SetStoreMailboxPhoto)
|
||||
storeRoutes.DELETE("/mailboxes/:id", manage, billing, middleware.RequireFreshAuth(), h.CancelStoreMailbox)
|
||||
storeRoutes.POST("/mailboxes/:id/resume", manage, billing, middleware.RequireFreshAuth(), h.ResumeStoreMailbox)
|
||||
}
|
||||
// Transfer-out and sign-in answer with a secret shown once, so they take no Idempotency-Key and no copy of
|
||||
// the answer is stored; repeating either returns the same secret again and charges nothing.
|
||||
storeSecrets := base.Group("/store")
|
||||
storeSecrets.Use(m.CombinedAuthMiddleware(), m.ResourceScopeGate(), h.PartnerReadOnlyGate(), m.APIKeyUsageMiddleware(),
|
||||
m.RequireOrganization(), m.RateLimitMiddleware(models.RateLimitWrite), middleware.UUIDParams("id"))
|
||||
{
|
||||
manage := m.RequireAccess(models.PermManageEmails, models.APIPermManageStore)
|
||||
storeSecrets.POST("/domains/:id/transfer-out", manage, m.RequireAccess(models.PermManageBilling, models.APIPermManageStore), middleware.RequireFreshAuth(), h.TransferOutStoreDomain)
|
||||
// The admin mailbox's sign-in opens the whole Workspace or tenant, so a session needs a fresh sign-in.
|
||||
storeSecrets.POST("/mailboxes/:id/sign-in", manage, middleware.RequireFreshAuth(), h.StoreMailboxSignIn)
|
||||
}
|
||||
|
||||
// Sending domains: tracking host per domain and the bare-domain redirect.
|
||||
sendingDomains := jwtOnly.Group("/emails/domains")
|
||||
sendingDomains.Use(m.RequireOrganization(), m.RequirePermission(models.PermManageEmails), m.RateLimitMiddleware(models.RateLimitWrite))
|
||||
@@ -1815,6 +1876,8 @@ func Run(
|
||||
// The agency home and the cross-client inbox read each client through the caller's own membership in it.
|
||||
agencyRoutes.GET("/:agencyId/overview", read, h.GetAgencyOverview)
|
||||
agencyRoutes.GET("/:agencyId/mailboxes", read, h.ListAgencyMailboxes)
|
||||
// Purchased domains and mailboxes across the clients whose mailboxes the caller manages.
|
||||
agencyRoutes.GET("/:agencyId/store", middleware.RequireAgencyAccess(models.APIPermAgencyRead|models.APIPermReadStore), h.GetAgencyStore)
|
||||
// Client accounts migrated in from another outreach tool; the service checks staff and each client membership.
|
||||
migrate := middleware.RequireAgencyAccess(models.APIPermAgencyMigrate)
|
||||
agencyRoutes.GET("/:agencyId/migrations/providers", migrate, h.ListToolMigrationProviders)
|
||||
@@ -2038,7 +2101,7 @@ func Run(
|
||||
}
|
||||
|
||||
subscriptions := jwtOnly.Group("/subscription")
|
||||
subscriptions.Use(m.RateLimitMiddleware(models.RateLimitWrite))
|
||||
subscriptions.Use(m.RateLimitMiddleware(models.RateLimitWrite), h.PartnerBillingGate())
|
||||
{
|
||||
subscriptions.GET("", h.GetSubscription)
|
||||
subscriptions.GET("/limits", h.GetSubscriptionLimits)
|
||||
@@ -2073,6 +2136,8 @@ func Run(
|
||||
subscriptions.POST("/balance/top-up", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), m.IdempotencyMiddleware(), h.TopUpBalance)
|
||||
subscriptions.POST("/balance/checkout", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.CreateBalanceCheckout)
|
||||
subscriptions.POST("/balance/payment-method", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.CreatePaymentMethodSetup)
|
||||
subscriptions.POST("/balance/setup-intent", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.CreateCardSetupIntent)
|
||||
subscriptions.POST("/balance/setup-intent/default", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.AdoptCardSetup)
|
||||
subscriptions.PATCH("/balance/auto-reload", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), middleware.RequireFreshAuth(), h.UpdateAutoReload)
|
||||
subscriptions.GET("/balance/invoices", m.RequireOrganization(), m.RequirePermission(models.PermManageBilling), h.ListBalanceInvoices)
|
||||
|
||||
@@ -2083,6 +2148,9 @@ func Run(
|
||||
|
||||
// Single versioned mount. No unversioned alias.
|
||||
mountPublicAPI(v1)
|
||||
// The reseller API: partner keys only, answering 401 until an operator creates a partner.
|
||||
h.MountPartnerAPI(v1)
|
||||
r.NoRoute(h.NoRoute)
|
||||
|
||||
// Admin routes (requires admin permissions)
|
||||
adminRoutes := r.Group("/admin")
|
||||
@@ -2137,6 +2205,18 @@ func Run(
|
||||
|
||||
// Organization (Workspace) Management
|
||||
adminRoutes.GET("/agencies", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminListAgencies)
|
||||
// Resellers that run managed workspaces through /v1/partner.
|
||||
adminRoutes.GET("/partners", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminListPartners)
|
||||
adminRoutes.GET("/partners/:id", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminGetPartner)
|
||||
adminRoutes.GET("/partners/:id/organizations", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminListPartnerOrganizations)
|
||||
adminRoutes.POST("/partners", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), middleware.RequireFreshAuth(), h.AdminCreatePartner)
|
||||
adminRoutes.PATCH("/partners/:id", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), middleware.RequireFreshAuth(), h.AdminUpdatePartner)
|
||||
adminRoutes.POST("/partners/:id/webhook-secret", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), middleware.RequireFreshAuth(), h.AdminRotatePartnerWebhookSecret)
|
||||
adminRoutes.PUT("/partners/:id/callback-key", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), middleware.RequireFreshAuth(), h.AdminSetPartnerCallbackKey)
|
||||
adminRoutes.POST("/partners/:id/keys", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), middleware.RequireFreshAuth(), h.AdminCreatePartnerKey)
|
||||
adminRoutes.DELETE("/partners/:id/keys/:keyId", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), middleware.RequireFreshAuth(), h.AdminRevokePartnerKey)
|
||||
adminRoutes.GET("/partners/:id/statements", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminPartnerStatements)
|
||||
adminRoutes.GET("/partners/:id/statements/:month", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminPartnerStatement)
|
||||
adminRoutes.GET("/agencies/:id", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminGetAgency)
|
||||
// What an operator sets on an agency: a plan held without Stripe, a pool and AI allowance of its own, and credits.
|
||||
adminRoutes.POST("/agencies", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminCreateAgency)
|
||||
@@ -2293,6 +2373,31 @@ func Run(
|
||||
adminRoutes.GET("/instance/limits", middleware.RequireAdminPermission(models.AdminPermViewAnalytics), h.AdminInstanceLimits)
|
||||
adminRoutes.GET("/instance/settings", middleware.RequireAdminPermission(models.AdminPermManageSettings), h.AdminGetInstanceSettings)
|
||||
adminRoutes.PUT("/instance/settings", middleware.RequireAdminPermission(models.AdminPermManageSettings), h.AdminPutInstanceSettings)
|
||||
// GraphKit's live wholesale prices and this instance's retail, for the store settings preview.
|
||||
adminRoutes.GET("/store/pricing", middleware.RequireAdminPermission(models.AdminPermManageSettings), h.AdminStorePricing)
|
||||
// The GraphKit API key the store runs on, when GRAPHKIT_* does not set one. Secrets are write-only.
|
||||
adminRoutes.GET("/store/connection", middleware.RequireAdminPermission(models.AdminPermManageSettings), h.AdminGetStoreConnection)
|
||||
adminRoutes.PUT("/store/connection", middleware.RequireAdminPermission(models.AdminPermManageSettings), middleware.RequireFreshAuth(), h.AdminPutStoreConnection)
|
||||
adminRoutes.POST("/store/connection/test", middleware.RequireAdminPermission(models.AdminPermManageSettings), middleware.RequireFreshAuth(), h.AdminTestStoreConnection)
|
||||
adminRoutes.DELETE("/store/connection", middleware.RequireAdminPermission(models.AdminPermManageSettings), middleware.RequireFreshAuth(), h.AdminDeleteStoreConnection)
|
||||
// The Store section: instance-wide purchases and health to read, repairs to run. Every action is audited.
|
||||
adminRoutes.GET("/store/health", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminStoreHealth)
|
||||
adminRoutes.GET("/store/economics", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminStoreEconomics)
|
||||
adminRoutes.GET("/store/orders", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminListStoreOrders)
|
||||
adminRoutes.GET("/store/orders/:id", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminGetStoreOrder)
|
||||
adminRoutes.GET("/store/domains", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminListStoreDomains)
|
||||
adminRoutes.GET("/store/mailboxes", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminListStoreMailboxes)
|
||||
adminRoutes.GET("/store/workspaces/:orgId", middleware.RequireAdminPermission(models.AdminPermViewOrganizations), h.AdminGetStoreWorkspace)
|
||||
adminRoutes.POST("/store/orders/:id/refresh", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminRefreshStoreOrder)
|
||||
adminRoutes.POST("/store/orders/:id/place", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminPlaceStoreOrder)
|
||||
adminRoutes.POST("/store/orders/:id/refund", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminRefundStoreOrder)
|
||||
adminRoutes.POST("/store/mailboxes/:id/refresh", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminRefreshStoreMailbox)
|
||||
adminRoutes.POST("/store/mailboxes/:id/connect", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminConnectStoreMailbox)
|
||||
adminRoutes.POST("/store/mailboxes/:id/cancel", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminCancelStoreMailbox)
|
||||
adminRoutes.POST("/store/mailboxes/:id/resume", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminResumeStoreMailbox)
|
||||
adminRoutes.POST("/store/domains/:id/refresh", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminRefreshStoreDomain)
|
||||
adminRoutes.POST("/store/domains/:id/renew", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminRenewStoreDomain)
|
||||
adminRoutes.PATCH("/store/domains/:id", middleware.RequireAdminPermission(models.AdminPermManageOrganizations), h.AdminPatchStoreDomain)
|
||||
// Operator notification channels: the channels themselves are part of
|
||||
// the settings document above; these two are the event catalog the
|
||||
// panel renders and the on-demand delivery probe.
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// storeGate is what one store route asks of its caller.
|
||||
type storeGate struct {
|
||||
scope string // READ_STORE or MANAGE_STORE
|
||||
billing bool // the member also needs manage_billing
|
||||
fresh bool // a session also needs a recent confirmation
|
||||
}
|
||||
|
||||
// Every /v1/store route takes an explicit store scope for keys and OAuth apps,
|
||||
// the matching member permission for everyone, and manage_billing plus a fresh
|
||||
// session wherever money moves. A route missing from this table fails too.
|
||||
func TestStoreRoutesCarryTheirScopes(t *testing.T) {
|
||||
r, m, b := storeGate{scope: "READ_STORE"}, storeGate{scope: "MANAGE_STORE"}, storeGate{scope: "MANAGE_STORE", billing: true, fresh: true}
|
||||
want := map[string]storeGate{
|
||||
"GET /status": r,
|
||||
"GET /domains/search": r,
|
||||
"PUT /registrant": {scope: "MANAGE_STORE", billing: true},
|
||||
"POST /quotes": m,
|
||||
"POST /orders": b,
|
||||
"GET /orders": r,
|
||||
"GET /orders/:id": r,
|
||||
"GET /domains": r,
|
||||
"GET /domains/:id": r,
|
||||
"PATCH /domains/:id": m,
|
||||
"POST /domains/:id/renew": b,
|
||||
"POST /domains/:id/transfer-out": b,
|
||||
"POST /domains/connect": m,
|
||||
"POST /domains/:id/connection/check": m,
|
||||
"POST /domains/:id/connection/regenerate": m,
|
||||
"DELETE /domains/:id": m,
|
||||
"POST /domains/:id/dns": m,
|
||||
"PATCH /domains/:id/dns/:record_id": m,
|
||||
"DELETE /domains/:id/dns/:record_id": m,
|
||||
"POST /domains/:id/dns/check": r,
|
||||
"GET /mailboxes": r,
|
||||
"PATCH /mailboxes/:id": m,
|
||||
"PUT /mailboxes/:id/photo": m,
|
||||
"POST /photos": m,
|
||||
"GET /photos/:id": r,
|
||||
"DELETE /mailboxes/:id": b,
|
||||
"POST /mailboxes/:id/resume": b,
|
||||
"POST /mailboxes/:id/sign-in": {scope: "MANAGE_STORE", fresh: true},
|
||||
}
|
||||
file, err := parser.ParseFile(token.NewFileSet(), "routes.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]storeGate{}
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
block, ok := n.(*ast.BlockStmt)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
// The gates a block names, e.g. read := m.RequireAccess(models.PermManageEmails, models.APIPermReadStore).
|
||||
local := map[string]*ast.CallExpr{}
|
||||
for _, stmt := range block.List {
|
||||
if as, ok := stmt.(*ast.AssignStmt); ok && len(as.Lhs) == 1 && len(as.Rhs) == 1 {
|
||||
if id, ok := as.Lhs[0].(*ast.Ident); ok {
|
||||
if call, ok := as.Rhs[0].(*ast.CallExpr); ok {
|
||||
local[id.Name] = call
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, stmt := range block.List {
|
||||
es, ok := stmt.(*ast.ExprStmt)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
call, ok := es.X.(*ast.CallExpr)
|
||||
if !ok || len(call.Args) < 2 {
|
||||
continue
|
||||
}
|
||||
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
group, ok := sel.X.(*ast.Ident)
|
||||
if !ok || (group.Name != "storeRoutes" && group.Name != "storeSecrets") {
|
||||
continue
|
||||
}
|
||||
lit, ok := call.Args[0].(*ast.BasicLit)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
path, _ := strconv.Unquote(lit.Value)
|
||||
var g storeGate
|
||||
for _, arg := range call.Args[1:] {
|
||||
gate, _ := arg.(*ast.CallExpr)
|
||||
if id, ok := arg.(*ast.Ident); ok {
|
||||
gate = local[id.Name]
|
||||
}
|
||||
if gate == nil {
|
||||
continue
|
||||
}
|
||||
name := selName(gate.Fun)
|
||||
switch name {
|
||||
case "RequireFreshAuth":
|
||||
g.fresh = true
|
||||
case "RequireAccess":
|
||||
if len(gate.Args) != 2 {
|
||||
t.Fatalf("%s %s: RequireAccess with %d arguments", sel.Sel.Name, path, len(gate.Args))
|
||||
}
|
||||
org, api := selName(gate.Args[0]), selName(gate.Args[1])
|
||||
switch api {
|
||||
case "APIPermReadStore":
|
||||
g.scope = maxScope(g.scope, "READ_STORE")
|
||||
case "APIPermManageStore":
|
||||
g.scope = maxScope(g.scope, "MANAGE_STORE")
|
||||
default:
|
||||
t.Errorf("%s %s: gated on %s, not a store scope", sel.Sel.Name, path, api)
|
||||
}
|
||||
if org == "PermManageBilling" {
|
||||
g.billing = true
|
||||
} else if org != "PermManageEmails" {
|
||||
t.Errorf("%s %s: member permission %s", sel.Sel.Name, path, org)
|
||||
}
|
||||
}
|
||||
}
|
||||
got[sel.Sel.Name+" "+path] = g
|
||||
}
|
||||
return true
|
||||
})
|
||||
var keys []string
|
||||
for k := range want {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
g, ok := got[k]
|
||||
if !ok {
|
||||
t.Errorf("%s is not registered", k)
|
||||
continue
|
||||
}
|
||||
if g != want[k] {
|
||||
t.Errorf("%s gates = %+v, want %+v", k, g, want[k])
|
||||
}
|
||||
}
|
||||
for k := range got {
|
||||
if _, ok := want[k]; !ok {
|
||||
t.Errorf("%s is registered but not in this table; give it a store scope here", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func selName(e ast.Expr) string {
|
||||
if s, ok := e.(*ast.SelectorExpr); ok {
|
||||
return s.Sel.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func maxScope(a, b string) string {
|
||||
if strings.HasPrefix(a, "MANAGE") {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -107,6 +107,21 @@ func (s *Service) memberships(ctx context.Context, agencyID, userID uuid.UUID) (
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// ClientsWith is the agency's clients where the caller's own membership holds perm, after checking agency staff.
|
||||
func (s *Service) ClientsWith(ctx context.Context, agencyID, userID uuid.UUID, perm models.OrganizationPermission) ([]models.AgencyClientMembership, *errx.Error) {
|
||||
list, xerr := s.memberships(ctx, agencyID, userID)
|
||||
if xerr != nil {
|
||||
return nil, xerr
|
||||
}
|
||||
out := make([]models.AgencyClientMembership, 0, len(list))
|
||||
for _, m := range list {
|
||||
if m.Can(perm) {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// metricOrgs splits the clients by which overview sections the caller may read in each.
|
||||
type metricOrgs struct {
|
||||
campaigns, inbox, advisor []uuid.UUID
|
||||
|
||||
@@ -518,7 +518,9 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod
|
||||
|
||||
var (
|
||||
stopReason string
|
||||
balance *models.Micro // nil on the free path or when unread
|
||||
// creditErr is the refusal behind "out_of_credits", which says why.
|
||||
creditErr error
|
||||
balance *models.Micro // nil on the free path or when unread
|
||||
)
|
||||
creditMeta := models.CreditMeta{ActorID: inv.UserID, Context: models.CreditContext{SessionID: sess.ID.String()}}
|
||||
readBalance := func(ctx context.Context) {
|
||||
@@ -573,7 +575,7 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod
|
||||
if cerr := s.credits.Reserve(mctx, inv.OrgID, credits.EstimateAgentIteration); cerr != nil {
|
||||
switch {
|
||||
case errors.Is(cerr, credits.ErrInsufficientCredits):
|
||||
stopReason = "out_of_credits"
|
||||
stopReason, creditErr = "out_of_credits", cerr
|
||||
return errOutOfCredits
|
||||
case errors.Is(cerr, credits.ErrCapExceeded):
|
||||
stopReason = "usage_cap"
|
||||
@@ -653,7 +655,7 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod
|
||||
_ = s.repo.UpdateSessionContext(ctx, sess.OrgID, sess.UserID, sess.ID, sess.Context)
|
||||
emit(withBalance(StreamEvent{Type: evDone, Message: "awaiting_approval"}))
|
||||
case "stopped":
|
||||
emit(withBalance(stopEvent(stopReason)))
|
||||
emit(withBalance(stopEvent(stopReason, creditErr)))
|
||||
default: // "stop" or "max_iterations"
|
||||
sess.Context.Pending = nil
|
||||
_ = s.repo.UpdateSessionContext(ctx, sess.OrgID, sess.UserID, sess.ID, sess.Context)
|
||||
@@ -662,9 +664,12 @@ func (s *service) runLoop(ctx context.Context, inv aitools.Invocation, sess *mod
|
||||
return nil
|
||||
}
|
||||
|
||||
func stopEvent(reason string) StreamEvent {
|
||||
func stopEvent(reason string, creditErr error) StreamEvent {
|
||||
switch reason {
|
||||
case "out_of_credits":
|
||||
if code, msg := credits.PaymentRefusal(creditErr); code != "insufficient_credits" {
|
||||
return StreamEvent{Type: evError, Code: code, Message: msg}
|
||||
}
|
||||
return StreamEvent{Type: evError, Code: "insufficient_credits", Message: "The workspace balance is too low. Add funds to keep using Remie."}
|
||||
case "usage_cap":
|
||||
return StreamEvent{Type: evError, Code: "usage_cap_exceeded", Message: "AI usage limit reached, please try again later."}
|
||||
|
||||
@@ -39,6 +39,8 @@ import (
|
||||
// handler calls one of these exactly as the matching HTTP handler would, so a
|
||||
// tool never bypasses business rules, validation, or org scoping.
|
||||
type Deps struct {
|
||||
// MailboxLock refuses removing a mailbox a partner attached or the workspace still pays for; read at call time.
|
||||
MailboxLock *func(ctx context.Context, orgID, accountID uuid.UUID) *errx.Error
|
||||
Contacts contact.ContactService
|
||||
CRM crm.CRMService
|
||||
Campaigns campaign.CampaignService
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package aitools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
)
|
||||
|
||||
type countingEmails struct {
|
||||
stubEmails
|
||||
deleted int
|
||||
}
|
||||
|
||||
func (c *countingEmails) Delete(context.Context, string, string) *errx.Error {
|
||||
c.deleted++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestDisconnectToolHonoursTheMailboxLock(t *testing.T) {
|
||||
locked := uuid.New()
|
||||
lock := func(_ context.Context, _, accountID uuid.UUID) *errx.Error {
|
||||
if accountID == locked {
|
||||
return errx.NewWithIdentifier(errx.Forbidden, "purchased_mailbox", "Cancel it under Subscription instead.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
emails := &countingEmails{}
|
||||
d := Deps{Emails: emails, MailboxLock: &lock}
|
||||
inv := Invocation{OrgID: uuid.New(), UserID: uuid.New()}
|
||||
|
||||
args, _ := json.Marshal(map[string]string{"email_account_id": locked.String()})
|
||||
if _, err := d.disconnectMailbox(context.Background(), inv, args); err == nil || emails.deleted != 0 {
|
||||
t.Fatalf("a locked mailbox was removed: err=%v deleted=%d", err, emails.deleted)
|
||||
}
|
||||
|
||||
args, _ = json.Marshal(map[string]string{"email_account_id": uuid.NewString()})
|
||||
if _, err := d.disconnectMailbox(context.Background(), inv, args); err != nil || emails.deleted != 1 {
|
||||
t.Fatalf("an unlocked mailbox was not removed: err=%v deleted=%d", err, emails.deleted)
|
||||
}
|
||||
}
|
||||
@@ -355,6 +355,11 @@ func (d Deps) disconnectMailbox(ctx context.Context, inv Invocation, args json.R
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if d.MailboxLock != nil && *d.MailboxLock != nil {
|
||||
if xerr := (*d.MailboxLock)(ctx, inv.OrgID, aid); xerr != nil {
|
||||
return "", fromErrx(xerr)
|
||||
}
|
||||
}
|
||||
if xerr := d.Emails.Delete(ctx, inv.OrgID.String(), in.EmailAccountID); xerr != nil {
|
||||
return "", fromErrx(xerr)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
package aitools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/audit"
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
"github.com/warmbly/warmbly/internal/errx"
|
||||
"github.com/warmbly/warmbly/internal/models"
|
||||
"github.com/warmbly/warmbly/internal/pkg/generation"
|
||||
)
|
||||
|
||||
// StoreTools is the slice of the store the tools call, exactly as the REST handlers do.
|
||||
type StoreTools interface {
|
||||
Status(ctx context.Context, orgID uuid.UUID) (*store.Status, error)
|
||||
Search(ctx context.Context, query string, tlds []string) (*store.SearchResult, error)
|
||||
ListOrders(ctx context.Context, orgID uuid.UUID, cursor string, limit int) (*store.Page[store.Order], error)
|
||||
GetOrder(ctx context.Context, orgID, id uuid.UUID) (*store.Order, error)
|
||||
ListDomains(ctx context.Context, orgID uuid.UUID, cursor string, limit int) (*store.Page[store.Domain], error)
|
||||
GetDomain(ctx context.Context, orgID, id uuid.UUID) (*store.Domain, error)
|
||||
ListMailboxes(ctx context.Context, orgID uuid.UUID, cursor string, limit int) (*store.Page[store.Mailbox], error)
|
||||
CreateQuote(ctx context.Context, orgID uuid.UUID, in store.QuoteRequest) (*store.Quote, error)
|
||||
PlaceOrder(ctx context.Context, orgID, userID uuid.UUID, in store.OrderRequest) (*store.Order, error)
|
||||
PatchDomain(ctx context.Context, orgID, id uuid.UUID, p store.DomainPatch) (*store.Domain, error)
|
||||
RenewNow(ctx context.Context, orgID, id uuid.UUID) (*store.Domain, error)
|
||||
CancelMailbox(ctx context.Context, orgID, id uuid.UUID) (*store.Mailbox, error)
|
||||
ResumeMailbox(ctx context.Context, orgID, id uuid.UUID) (*store.Mailbox, error)
|
||||
AddDNSRecord(ctx context.Context, orgID, id uuid.UUID, in store.DNSRecordInput) (*store.DNSRecord, error)
|
||||
DeleteDNSRecord(ctx context.Context, orgID, id, rid uuid.UUID) error
|
||||
}
|
||||
|
||||
var _ StoreTools = (*store.Service)(nil)
|
||||
|
||||
// storeCharges is what a tool that charges or changes a charge needs from the member, like the REST route.
|
||||
const storeCharges = models.PermManageEmails | models.PermManageBilling
|
||||
|
||||
// StoreToolNames are the store's tools, read and write.
|
||||
var StoreToolNames = []string{
|
||||
"get_store_status", "search_store_domains", "list_store_orders", "get_store_order", "list_store_domains", "get_store_domain",
|
||||
"list_store_mailboxes", "create_store_quote", "place_store_order", "set_store_domain_auto_renew", "renew_store_domain",
|
||||
"cancel_store_mailbox", "resume_store_mailbox", "add_store_dns_record", "delete_store_dns_record",
|
||||
}
|
||||
|
||||
// RegisterStoreTools adds the domains and mailboxes tools once the store is built.
|
||||
// Reads take READ_STORE; changes take MANAGE_STORE, and a charge also holds the
|
||||
// member to manage_billing and a session to a recent confirmation. Transfer-out
|
||||
// and sign-in answer with a secret, so they are not tools.
|
||||
func RegisterStoreTools(r *Registry, s StoreTools, auditSvc audit.AuditService) {
|
||||
if r == nil || s == nil {
|
||||
return
|
||||
}
|
||||
d := Deps{Audit: auditSvc}
|
||||
read := func(name, desc string, schema map[string]any, h Handler) {
|
||||
r.Register(Tool{Name: name, Description: desc, InputSchema: schema, Risk: generation.RiskRead,
|
||||
RequiredOrgPerm: models.PermManageEmails, RequiredAPIPerm: models.APIPermReadStore, Handler: h})
|
||||
}
|
||||
page := objectSchema(map[string]any{
|
||||
"cursor": strProp("Opaque cursor from the previous page's pagination.next_cursor."),
|
||||
"limit": intProp("How many to return, 1 to 100 (default 25)."),
|
||||
})
|
||||
idArg := func(name, desc string) map[string]any {
|
||||
return objectSchema(map[string]any{name: strProp(desc)}, name)
|
||||
}
|
||||
|
||||
read("get_store_status", "Whether this workspace can buy domains and Google or Microsoft mailboxes, the monthly mailbox price, the workspace balance and saved card, and whether a paid plan is active (buying needs one).",
|
||||
objectSchema(map[string]any{}), func(ctx context.Context, inv Invocation, _ json.RawMessage) (string, error) {
|
||||
return storeResult(s.Status(ctx, inv.OrgID))
|
||||
})
|
||||
read("search_store_domains", "Search domains to buy by keyword or name, with availability, the price for the first term and the yearly renewal price (micro-USD).",
|
||||
objectSchema(map[string]any{
|
||||
"query": strProp("A word or a domain name, e.g. acme or getacme.com."),
|
||||
"tlds": arrProp("Endings to search, e.g. [\"com\", \"io\"]. Optional.", map[string]any{"type": "string"}),
|
||||
}, "query"), func(ctx context.Context, _ Invocation, args json.RawMessage) (string, error) {
|
||||
in, err := decodeArgs[struct {
|
||||
Query string `json:"query"`
|
||||
TLDs []string `json:"tlds"`
|
||||
}](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return storeResult(s.Search(ctx, in.Query, in.TLDs))
|
||||
})
|
||||
read("list_store_orders", "List the workspace's domain and mailbox orders, newest first, with status, totals, refunds and setup steps.",
|
||||
page, func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
p, err := decodeArgs[storePageArgs](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return storeResult(s.ListOrders(ctx, inv.OrgID, p.Cursor, p.Limit))
|
||||
})
|
||||
read("get_store_order", "Read one order: its status, each setup step, what was charged and refunded, and the domains and mailboxes it created.",
|
||||
idArg("order_id", "The order's id."), func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
id, err := idFrom(args, "order_id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return storeResult(s.GetOrder(ctx, inv.OrgID, id))
|
||||
})
|
||||
read("list_store_domains", "List the workspace's purchased and connected domains with expiry, auto-renew, renewal price and mail records.",
|
||||
page, func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
p, err := decodeArgs[storePageArgs](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return storeResult(s.ListDomains(ctx, inv.OrgID, p.Cursor, p.Limit))
|
||||
})
|
||||
read("get_store_domain", "Read one purchased or connected domain with its DNS records.",
|
||||
idArg("domain_id", "The domain's id."), func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
id, err := idFrom(args, "domain_id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return storeResult(s.GetDomain(ctx, inv.OrgID, id))
|
||||
})
|
||||
read("list_store_mailboxes", "List the workspace's purchased mailboxes with status, monthly price, paid-through date, pending cancellation and whether each is connected.",
|
||||
page, func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
p, err := decodeArgs[storePageArgs](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return storeResult(s.ListMailboxes(ctx, inv.OrgID, p.Cursor, p.Limit))
|
||||
})
|
||||
|
||||
write := func(t Tool) {
|
||||
t.Risk = generation.RiskWrite
|
||||
t.RequiredAPIPerm = models.APIPermManageStore
|
||||
if t.RequiredOrgPerm == 0 {
|
||||
t.RequiredOrgPerm = models.PermManageEmails
|
||||
}
|
||||
r.Register(t)
|
||||
}
|
||||
write(Tool{
|
||||
Name: "create_store_quote",
|
||||
Description: "Price a cart of domains and mailboxes; nothing is charged. Each item is {\"type\":\"domain\",\"domain\":\"getacme.com\",\"years\":1} or " +
|
||||
"{\"type\":\"mailboxes\",\"domain\":\"getacme.com\",\"provider\":\"google\"|\"microsoft\",\"mailboxes\":[{\"local_part\":\"ada\",\"first_name\":\"Ada\",\"last_name\":\"Lovelace\"}]}. " +
|
||||
"Returns the quote id, each line, due_now_micros and the monthly total; show the person the total before ordering.",
|
||||
InputSchema: objectSchema(map[string]any{
|
||||
"items": arrProp("Up to 20 items.", map[string]any{"type": "object"}),
|
||||
}, "items"),
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
in, err := decodeArgs[store.QuoteRequest](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return storeResult(s.CreateQuote(ctx, inv.OrgID, in))
|
||||
},
|
||||
})
|
||||
write(Tool{
|
||||
Name: "place_store_order",
|
||||
Description: "Buy what a quote holds, charged to the workspace balance (the saved card tops up any shortfall). " +
|
||||
"expected_due_now_micros must be the total the person agreed to; if the price moved, nothing is charged and the new total comes back to confirm again. Requires user approval.",
|
||||
InputSchema: objectSchema(map[string]any{
|
||||
"quote_id": strProp("The id from create_store_quote."),
|
||||
"expected_due_now_micros": intProp("The quote's due_now_micros the person agreed to."),
|
||||
"forwarding_url": strProp("Optional https:// address the bare domain forwards to."),
|
||||
}, "quote_id", "expected_due_now_micros"),
|
||||
RequiredOrgPerm: storeCharges, FreshAuth: true, AlwaysAsk: true,
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
in, err := decodeArgs[struct {
|
||||
QuoteID string `json:"quote_id"`
|
||||
Expected *int64 `json:"expected_due_now_micros"`
|
||||
ForwardingURL string `json:"forwarding_url"`
|
||||
}](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
qid, err := parseUUIDArg(in.QuoteID)
|
||||
if err != nil || in.Expected == nil {
|
||||
return "", ErrInvalidArgs
|
||||
}
|
||||
o, err := s.PlaceOrder(ctx, inv.OrgID, inv.UserID, store.OrderRequest{QuoteID: qid, ExpectedDueNowMicros: in.Expected, ForwardingURL: in.ForwardingURL})
|
||||
if err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
d.logAudit(ctx, inv, models.AuditActionCreate, models.AuditEntityStoreOrder, &o.ID, map[string]string{"due_now_usd": dollars(o.DueNowMicros)})
|
||||
return jsonResult(o)
|
||||
},
|
||||
})
|
||||
write(Tool{
|
||||
Name: "set_store_domain_auto_renew",
|
||||
Description: "Turn a purchased domain's automatic yearly renewal on or off. Renewals are charged to the workspace balance. Requires user approval.",
|
||||
InputSchema: objectSchema(map[string]any{
|
||||
"domain_id": strProp("The domain's id."),
|
||||
"auto_renew": boolProp("true to renew every year, false to let it expire."),
|
||||
}, "domain_id", "auto_renew"),
|
||||
RequiredOrgPerm: storeCharges, FreshAuth: true, AlwaysAsk: true,
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
in, err := decodeArgs[struct {
|
||||
DomainID string `json:"domain_id"`
|
||||
AutoRenew *bool `json:"auto_renew"`
|
||||
}](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
id, err := parseUUIDArg(in.DomainID)
|
||||
if err != nil || in.AutoRenew == nil {
|
||||
return "", ErrInvalidArgs
|
||||
}
|
||||
dom, err := s.PatchDomain(ctx, inv.OrgID, id, store.DomainPatch{AutoRenew: in.AutoRenew})
|
||||
if err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
d.logAudit(ctx, inv, models.AuditActionUpdate, models.AuditEntityStoreDomain, &dom.ID, map[string]string{"domain": dom.Name, "auto_renew": fmt.Sprint(*in.AutoRenew)})
|
||||
return jsonResult(dom)
|
||||
},
|
||||
})
|
||||
write(Tool{
|
||||
Name: "renew_store_domain",
|
||||
Description: "Renew a purchased domain for one more year now, charged at its current renewal price to the workspace balance. Requires user approval.",
|
||||
InputSchema: idArg("domain_id", "The domain's id."),
|
||||
RequiredOrgPerm: storeCharges, FreshAuth: true, AlwaysAsk: true,
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
id, err := idFrom(args, "domain_id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dom, err := s.RenewNow(ctx, inv.OrgID, id)
|
||||
if err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
d.logAudit(ctx, inv, models.AuditActionUpdate, models.AuditEntityStoreDomain, &dom.ID, map[string]string{"domain": dom.Name, "action": "renew"})
|
||||
return jsonResult(dom)
|
||||
},
|
||||
})
|
||||
write(Tool{
|
||||
Name: "cancel_store_mailbox",
|
||||
Description: "Cancel a purchased mailbox at the end of its paid month; it keeps working until then and nothing more is charged. Requires user approval.",
|
||||
InputSchema: idArg("mailbox_id", "The purchased mailbox's id (from list_store_mailboxes)."),
|
||||
RequiredOrgPerm: storeCharges, FreshAuth: true, AlwaysAsk: true,
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
id, err := idFrom(args, "mailbox_id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m, err := s.CancelMailbox(ctx, inv.OrgID, id)
|
||||
if err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
d.logAudit(ctx, inv, models.AuditActionDelete, models.AuditEntityStoreMailbox, &m.ID, map[string]string{"email": m.Email})
|
||||
return jsonResult(m)
|
||||
},
|
||||
})
|
||||
write(Tool{
|
||||
Name: "resume_store_mailbox",
|
||||
Description: "Undo a purchased mailbox's pending cancellation; it bills monthly again. Requires user approval.",
|
||||
InputSchema: idArg("mailbox_id", "The purchased mailbox's id."),
|
||||
RequiredOrgPerm: storeCharges, FreshAuth: true, AlwaysAsk: true,
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
id, err := idFrom(args, "mailbox_id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m, err := s.ResumeMailbox(ctx, inv.OrgID, id)
|
||||
if err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
d.logAudit(ctx, inv, models.AuditActionResume, models.AuditEntityStoreMailbox, &m.ID, map[string]string{"email": m.Email})
|
||||
return jsonResult(m)
|
||||
},
|
||||
})
|
||||
write(Tool{
|
||||
Name: "add_store_dns_record",
|
||||
Description: "Add a DNS record to a purchased or connected domain whose DNS Warmbly hosts. Records Warmbly keeps for mail cannot be changed.",
|
||||
InputSchema: objectSchema(map[string]any{
|
||||
"domain_id": strProp("The domain's id."),
|
||||
"type": enumProp("Record type.", "A", "AAAA", "CNAME", "TXT", "MX"),
|
||||
"name": strProp("Name relative to the domain, @ for the domain itself."),
|
||||
"content": strProp("The record's value."),
|
||||
"ttl": intProp("Seconds; optional."),
|
||||
"priority": intProp("MX priority; optional."),
|
||||
}, "domain_id", "type", "name", "content"),
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
in, err := decodeArgs[struct {
|
||||
DomainID string `json:"domain_id"`
|
||||
store.DNSRecordInput
|
||||
}](args)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
id, err := parseUUIDArg(in.DomainID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
rec, err := s.AddDNSRecord(ctx, inv.OrgID, id, in.DNSRecordInput)
|
||||
if err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
d.logAudit(ctx, inv, models.AuditActionCreate, models.AuditEntityStoreDomain, &id, map[string]string{"dns_record": rec.Type + " " + rec.Name})
|
||||
return jsonResult(rec)
|
||||
},
|
||||
})
|
||||
write(Tool{
|
||||
Name: "delete_store_dns_record",
|
||||
Description: "Delete one of the workspace's own DNS records on a store domain.",
|
||||
InputSchema: objectSchema(map[string]any{
|
||||
"domain_id": strProp("The domain's id."),
|
||||
"record_id": strProp("The record's id, from get_store_domain."),
|
||||
}, "domain_id", "record_id"),
|
||||
Handler: func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) {
|
||||
id, err := idFrom(args, "domain_id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
rid, err := idFrom(args, "record_id")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := s.DeleteDNSRecord(ctx, inv.OrgID, id, rid); err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
d.logAudit(ctx, inv, models.AuditActionDelete, models.AuditEntityStoreDomain, &id, map[string]string{"dns_record_id": rid.String()})
|
||||
return jsonResult(map[string]any{"deleted": true})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type storePageArgs struct {
|
||||
Cursor string `json:"cursor"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
|
||||
// idFrom reads one required UUID argument by name.
|
||||
func idFrom(args json.RawMessage, name string) (uuid.UUID, error) {
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(args, &m); err != nil {
|
||||
return uuid.Nil, ErrInvalidArgs
|
||||
}
|
||||
s, _ := m[name].(string)
|
||||
return parseUUIDArg(s)
|
||||
}
|
||||
|
||||
func dollars(micros int64) string { return fmt.Sprintf("%.2f", float64(micros)/1_000_000) }
|
||||
|
||||
func storeResult[T any](v *T, err error) (string, error) {
|
||||
if err != nil {
|
||||
return "", storeToolErr(err)
|
||||
}
|
||||
return jsonResult(v)
|
||||
}
|
||||
|
||||
// storeToolErr is the store's refusal in words the assistant can act on; anything unexpected stays in the log.
|
||||
func storeToolErr(err error) error {
|
||||
var (
|
||||
price *store.PriceChangedError
|
||||
method *store.PaymentMethodError
|
||||
card *store.CardError
|
||||
bad *store.ContactError
|
||||
xerr *errx.Error
|
||||
)
|
||||
switch {
|
||||
case errors.As(err, &price) && price.Quote != nil:
|
||||
return fmt.Errorf("price_changed: the total is now $%s (quote %s). Nothing was charged; confirm the new total with the person before ordering again", dollars(price.Quote.DueNowMicros), price.Quote.ID)
|
||||
case errors.As(err, &method):
|
||||
return errors.New("payment_method_required: the balance is short and no card is saved. Add a card or money in Settings > Billing, then try again")
|
||||
case errors.As(err, &card):
|
||||
return errors.New(card.Code + ": the card was not charged. Try another card or add money to the balance")
|
||||
case errors.As(err, &bad):
|
||||
return errors.New("contact_invalid: " + bad.Message())
|
||||
case errors.As(err, &xerr):
|
||||
if code := xerr.ResponseCode(); code != "" {
|
||||
return errors.New(code + ": " + xerr.Message)
|
||||
}
|
||||
return errors.New(xerr.Message)
|
||||
}
|
||||
log.Error().Err(err).Msg("store tool: request failed")
|
||||
return errors.New("the request failed; try again in a moment")
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package aitools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/warmbly/warmbly/internal/app/store"
|
||||
)
|
||||
|
||||
// moneyStore records which store calls move money: a charge, a renewal, or a change to what is billed.
|
||||
type moneyStore struct{ moved []string }
|
||||
|
||||
func (m *moneyStore) Status(context.Context, uuid.UUID) (*store.Status, error) {
|
||||
return &store.Status{}, nil
|
||||
}
|
||||
func (m *moneyStore) Search(context.Context, string, []string) (*store.SearchResult, error) {
|
||||
return &store.SearchResult{}, nil
|
||||
}
|
||||
func (m *moneyStore) ListOrders(context.Context, uuid.UUID, string, int) (*store.Page[store.Order], error) {
|
||||
return &store.Page[store.Order]{}, nil
|
||||
}
|
||||
func (m *moneyStore) GetOrder(context.Context, uuid.UUID, uuid.UUID) (*store.Order, error) {
|
||||
return &store.Order{}, nil
|
||||
}
|
||||
func (m *moneyStore) ListDomains(context.Context, uuid.UUID, string, int) (*store.Page[store.Domain], error) {
|
||||
return &store.Page[store.Domain]{}, nil
|
||||
}
|
||||
func (m *moneyStore) GetDomain(context.Context, uuid.UUID, uuid.UUID) (*store.Domain, error) {
|
||||
return &store.Domain{}, nil
|
||||
}
|
||||
func (m *moneyStore) ListMailboxes(context.Context, uuid.UUID, string, int) (*store.Page[store.Mailbox], error) {
|
||||
return &store.Page[store.Mailbox]{}, nil
|
||||
}
|
||||
func (m *moneyStore) CreateQuote(context.Context, uuid.UUID, store.QuoteRequest) (*store.Quote, error) {
|
||||
return &store.Quote{}, nil
|
||||
}
|
||||
func (m *moneyStore) PlaceOrder(context.Context, uuid.UUID, uuid.UUID, store.OrderRequest) (*store.Order, error) {
|
||||
m.moved = append(m.moved, "PlaceOrder")
|
||||
return &store.Order{}, nil
|
||||
}
|
||||
func (m *moneyStore) PatchDomain(_ context.Context, _, _ uuid.UUID, p store.DomainPatch) (*store.Domain, error) {
|
||||
if p.AutoRenew != nil {
|
||||
m.moved = append(m.moved, "PatchDomain.AutoRenew")
|
||||
}
|
||||
return &store.Domain{}, nil
|
||||
}
|
||||
func (m *moneyStore) RenewNow(context.Context, uuid.UUID, uuid.UUID) (*store.Domain, error) {
|
||||
m.moved = append(m.moved, "RenewNow")
|
||||
return &store.Domain{}, nil
|
||||
}
|
||||
func (m *moneyStore) CancelMailbox(context.Context, uuid.UUID, uuid.UUID) (*store.Mailbox, error) {
|
||||
m.moved = append(m.moved, "CancelMailbox")
|
||||
return &store.Mailbox{}, nil
|
||||
}
|
||||
func (m *moneyStore) ResumeMailbox(context.Context, uuid.UUID, uuid.UUID) (*store.Mailbox, error) {
|
||||
m.moved = append(m.moved, "ResumeMailbox")
|
||||
return &store.Mailbox{}, nil
|
||||
}
|
||||
func (m *moneyStore) AddDNSRecord(context.Context, uuid.UUID, uuid.UUID, store.DNSRecordInput) (*store.DNSRecord, error) {
|
||||
return &store.DNSRecord{}, nil
|
||||
}
|
||||
func (m *moneyStore) DeleteDNSRecord(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Every store tool that reaches a call moving money asks the person each time and needs a fresh confirmation.
|
||||
func TestStoreToolsThatMoveMoneyAlwaysAsk(t *testing.T) {
|
||||
r := NewRegistry()
|
||||
RegisterStoreTools(r, &moneyStore{}, nil)
|
||||
registered := map[string]bool{}
|
||||
for _, name := range r.order {
|
||||
if strings.Contains(name, "store") {
|
||||
registered[name] = true
|
||||
}
|
||||
}
|
||||
for _, name := range StoreToolNames {
|
||||
if !registered[name] {
|
||||
t.Errorf("%s is in StoreToolNames but not registered", name)
|
||||
}
|
||||
delete(registered, name)
|
||||
}
|
||||
for name := range registered {
|
||||
t.Errorf("%s is registered but missing from StoreToolNames", name)
|
||||
}
|
||||
|
||||
id := uuid.NewString()
|
||||
args, _ := json.Marshal(map[string]any{
|
||||
"quote_id": id, "expected_due_now_micros": 1, "domain_id": id, "mailbox_id": id, "order_id": id, "record_id": id,
|
||||
"auto_renew": true, "query": "acme", "items": []any{}, "type": "TXT", "name": "@", "content": "v=x",
|
||||
})
|
||||
reached := map[string]bool{}
|
||||
for _, name := range StoreToolNames {
|
||||
tool, ok := r.Get(name)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
rec := &moneyStore{}
|
||||
local := NewRegistry()
|
||||
RegisterStoreTools(local, rec, nil)
|
||||
lt, _ := local.Get(name)
|
||||
if _, err := lt.Handler(context.Background(), Invocation{OrgID: uuid.New(), UserID: uuid.New()}, args); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if len(rec.moved) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, m := range rec.moved {
|
||||
reached[m] = true
|
||||
}
|
||||
if !tool.AlwaysAsk || !tool.FreshAuth {
|
||||
t.Errorf("%s calls %v but AlwaysAsk=%v FreshAuth=%v", name, rec.moved, tool.AlwaysAsk, tool.FreshAuth)
|
||||
}
|
||||
}
|
||||
// Every money call is reached by some tool, so the recording above cannot go stale.
|
||||
for _, m := range []string{"PlaceOrder", "PatchDomain.AutoRenew", "RenewNow", "CancelMailbox", "ResumeMailbox"} {
|
||||
if !reached[m] {
|
||||
t.Errorf("no store tool reaches %s", m)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user