diff --git a/apps/backend/src/routes/mcp.http.test.ts b/apps/backend/src/routes/mcp.http.test.ts index a3ede9ff7..f96d42c29 100644 --- a/apps/backend/src/routes/mcp.http.test.ts +++ b/apps/backend/src/routes/mcp.http.test.ts @@ -699,7 +699,7 @@ describe("MCP server", () => { const db = customers.storage.db const insertAccount = db.prepare( `INSERT INTO customer_accounts (id, organizationId, name, domains, planName, mrrMinor, currency, - healthStatus, healthScore, lifecycleStage, openRiskHigh) VALUES (?, ?, ?, ?, ?, ?, 'usd', ?, ?, ?, ?)`, + lifecycleStage, openRiskHigh) VALUES (?, ?, ?, ?, ?, ?, 'usd', ?, ?)`, ) insertAccount.run( globex, @@ -708,8 +708,6 @@ describe("MCP server", () => { '["globex.com"]', "Scale", 129_900, - "at_risk", - 41, "active", 1, ) @@ -720,9 +718,7 @@ describe("MCP server", () => { '["initech.io"]', "Team", 19_900, - "healthy", - 88, - "active", + "trialing", 0, ) const evidence = JSON.stringify({ @@ -749,12 +745,6 @@ describe("MCP server", () => { evidence, evidence, ) - // Globex was scored 7 days ago, and never before: earlier days are unknown, not 0. - const daysAgo = (days: number) => - new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10) - db.prepare( - `INSERT INTO customer_health_daily (accountId, day, score, status, breakdown) VALUES (?, ?, 55, 'at_risk', ?)`, - ).run(globex, daysAgo(7), JSON.stringify({ score: 55, status: "at_risk", components: [] })) const all = yield* callTool(world, token, "list_customers", { organization_id: world.orgId }) expect(all.isError).toBeUndefined() @@ -767,8 +757,6 @@ describe("MCP server", () => { domains: ["globex.com"], plan: "Scale", mrr: "$1,299.00", - health: "at_risk", - health_score: 41, lifecycle_stage: "active", open_risks: 1, }) @@ -779,16 +767,16 @@ describe("MCP server", () => { expect(byDomain.structuredContent.customers.map((row: { id: string }) => row.id)).toEqual([ initech, ]) - const atRisk = yield* callTool(world, token, "list_customers", { + const trialing = yield* callTool(world, token, "list_customers", { organization_id: world.orgId, - health: ["at_risk", "critical"], + lifecycle_stage: ["trialing"], }) - expect(atRisk.structuredContent.customers.map((row: { id: string }) => row.id)).toEqual([ - globex, + expect(trialing.structuredContent.customers.map((row: { id: string }) => row.id)).toEqual([ + initech, ]) const badFilter = yield* callTool(world, token, "list_customers", { organization_id: world.orgId, - health: ["sad"], + lifecycle_stage: ["sad"], }) expect(badFilter.isError).toBe(true) @@ -798,9 +786,6 @@ describe("MCP server", () => { }) expect(detail.isError).toBeUndefined() expect(detail.structuredContent.customer).toMatchObject({ name: "Globex", mrr: "$1,299.00" }) - expect(detail.structuredContent.health.score_7d_ago).toBe(55) - expect(detail.structuredContent.health).not.toHaveProperty("score_30d_ago") - expect(detail.structuredContent.health).not.toHaveProperty("score_90d_ago") expect(detail.structuredContent).not.toHaveProperty("more_open_signals") expect(detail.structuredContent.open_signals).toEqual([ expect.objectContaining({ diff --git a/apps/backend/src/routes/mcp.ts b/apps/backend/src/routes/mcp.ts index c79c36d16..d38fc1411 100644 --- a/apps/backend/src/routes/mcp.ts +++ b/apps/backend/src/routes/mcp.ts @@ -26,7 +26,6 @@ import { type ContactRow, CustomersRange, type Event as CustomerEvent, - HealthStatus, type Invoice, type Kpi, LifecycleStage, @@ -515,7 +514,6 @@ interface PageRequestPayload { /** `customers.accounts.list`'s payload, as far as `list_customers` fills it. */ interface AccountsListPayload extends PageRequestPayload { query?: string - healthStatuses?: ReadonlyArray lifecycleStages?: ReadonlyArray } @@ -626,8 +624,6 @@ const customerRow = (account: Account) => plan: account.planName, mrr: money(account.mrrMinor, account.currency), lifecycle_stage: account.lifecycleStage, - health: account.healthStatus, - health_score: account.healthScore, last_active_at: isoOf(account.lastActiveAt), active_users_30d: account.activeUsers30d, open_risks: account.openRiskHigh + account.openRiskMedium + account.openRiskLow, @@ -706,12 +702,6 @@ const pageOut = (key: string, page: PageOf, row: (a: A) => R) => const customerDetail = (detail: AccountDetail, signals: PageOf) => { const { account } = detail - // Only recorded scores: the chart series holds 0 for a day never scored, which is unknown. - const recorded = new Map((detail.healthScores ?? []).map((point) => [point.day, point.score])) - const healthAt = (daysAgo: number) => { - const day = detail.healthSeries[detail.healthSeries.length - 1 - daysAgo]?.day - return day === undefined ? null : (recorded.get(day) ?? null) - } return { customer: compact({ ...customerRow(account), @@ -729,23 +719,6 @@ const customerDetail = (detail: AccountDetail, signals: PageOf) => { champion_inactive_since: isoOf(account.championInactiveSince), left_out_of_needs_attention: account.attentionMutedAt === null ? null : true, }), - health: compact({ - status: account.healthStatus, - score: account.healthScore, - updated_at: isoOf(account.healthUpdatedAt), - score_7d_ago: healthAt(7), - score_30d_ago: healthAt(30), - score_90d_ago: healthAt(89), - components: detail.health?.components.map((component) => - compact({ - key: component.key, - score: component.score, - weight_pct: Math.round(component.effectiveWeight), - excluded: component.excluded || null, - why: component.why, - }), - ), - }), /** Daily active users, oldest first, the last 30 days. */ active_users_30d_daily: detail.activeUsersSeries.map((point) => point.value), open_signals: signals.items.map(signalRow), @@ -843,11 +816,6 @@ const overviewOut = (overview: OverviewResult) => { net: movement("net"), } : null, - health: overview.healthDistribution.map((row) => ({ - status: row.status, - customers: row.count, - mrr: money(row.mrrMinor, currency), - })), usage_gainers: overview.topMovers.gainers.map(mover), usage_decliners: overview.topMovers.decliners.map(mover), recent_churn: overview.recentChurn.map(brief), @@ -867,7 +835,7 @@ const customerTools: ReadonlyArray = [ name: "customers_overview", title: "Customers overview", description: - "An organization's customer KPIs over a range: MRR, paying and active customers, churn, revenue, net retention, MRR movements, health distribution, biggest usage gainers and decliners, recent churn, new customers and trials. Amounts are in the organization's reporting currency; has_billing_data and has_activity_data say which data exists.", + "An organization's customer KPIs over a range: MRR, paying and active customers, churn, revenue, net retention, MRR movements, biggest usage gainers and decliners, recent churn, new customers and trials. Amounts are in the organization's reporting currency; has_billing_data and has_activity_data say which data exists.", scopes: ["customers:read"], readOnly: true, inputSchema: obj( @@ -892,18 +860,13 @@ const customerTools: ReadonlyArray = [ name: "list_customers", title: "List customers", description: - "An organization's customer accounts, highest MRR first: plan, MRR, lifecycle stage, health, last activity and open risk count. Filter by name or domain, health or lifecycle stage.", + "An organization's customer accounts, highest MRR first: plan, MRR, lifecycle stage, last activity and open risk count. Filter by name or domain, or lifecycle stage.", scopes: ["customers:read"], readOnly: true, inputSchema: obj( { organization_id: orgArg, query: str("Name or domain contains this"), - health: { - type: "array", - items: { type: "string", enum: [...HealthStatus.literals] }, - description: "Only these health statuses", - }, lifecycle_stage: { type: "array", items: { type: "string", enum: [...LifecycleStage.literals] }, @@ -916,12 +879,10 @@ const customerTools: ReadonlyArray = [ run: (args, ctx) => Effect.gen(function* () { const organizationId = yield* argOrg(args) - const healthStatuses = yield* optLiterals(args, "health", HealthStatus.literals) const lifecycleStages = yield* optLiterals(args, "lifecycle_stage", LifecycleStage.literals) const query = typeof args.query === "string" ? args.query.trim().slice(0, 200) : "" const payload: AccountsListPayload = pageArgs(args, 25) if (query !== "") payload.query = query - if (healthStatuses !== undefined) payload.healthStatuses = healthStatuses if (lifecycleStages !== undefined) payload.lifecycleStages = lifecycleStages const page = yield* customersRead>( ctx, @@ -936,7 +897,7 @@ const customerTools: ReadonlyArray = [ name: "get_customer", title: "Get customer", description: - "One customer in full: health score and why, usage trend, open risks and opportunities, subscriptions, upcoming and unpaid invoices, company profile, who to reach, recent activity and links to the billing and auth providers.", + "One customer in full: usage trend, open risks and opportunities, subscriptions, upcoming and unpaid invoices, company profile, who to reach, recent activity and links to the billing and auth providers.", scopes: ["customers:read"], readOnly: true, inputSchema: obj({ organization_id: orgArg, customer_id: str("The customer, from list_customers") }, [ diff --git a/apps/backend/src/rpc/handlers/customers.ts b/apps/backend/src/rpc/handlers/customers.ts index 94607274f..8b49f0e3f 100644 --- a/apps/backend/src/rpc/handlers/customers.ts +++ b/apps/backend/src/rpc/handlers/customers.ts @@ -7,7 +7,7 @@ * - Settings, rules, shared views, data sources, unmatched records, the demo seed: admins and owners. * * Mutations answer the `customers:` write position; queue and settings changes ask for a - * compute soon (health and counters follow from them). + * compute soon (signals and at-risk MRR follow from them). */ import { Database, SQLite, schema } from "@hazel/db" import { InternalServerError } from "@hazel/domain" @@ -63,7 +63,7 @@ import { } from "../../worker/objects/customers/channel-suggestions" import { linkChannelNow, publishChannelCustomers } from "../../worker/objects/customers/channels" import { seedDemo } from "../../worker/objects/customers/demo" -import { healthDryRun, ruleDryRun } from "../../worker/objects/customers/dry-run" +import { ruleDryRun } from "../../worker/objects/customers/dry-run" import { accountsWithFlag, sendFeatureFlags, @@ -282,7 +282,7 @@ export const CustomerReadRpcLive = CustomerReadRpcs.toLayer( return yield* overview(range, yield* currentTime) }).pipe(remap), - "customers.accounts.list": ({ query, healthStatuses, lifecycleStages, ...request }) => + "customers.accounts.list": ({ query, lifecycleStages, ...request }) => Effect.gen(function* () { yield* requireMember const page = pageOf(request) @@ -300,9 +300,6 @@ export const CustomerReadRpcLive = CustomerReadRpcs.toLayer( SQLite.sql .cond`EXISTS (SELECT 1 FROM json_each(${$.domains}) WHERE json_each.value LIKE ${pattern} ESCAPE '\\')`, ), - healthStatuses === undefined || healthStatuses.length === 0 - ? undefined - : $.healthStatus.in_(...healthStatuses), lifecycleStages === undefined || lifecycleStages.length === 0 ? undefined : $.lifecycleStage.in_(...lifecycleStages), @@ -468,19 +465,13 @@ export const CustomerReadRpcLive = CustomerReadRpcs.toLayer( return pageResult(rows, page) }).pipe(remap), - // Admins only: a dry run reads every account (the rule editor and health settings are theirs). + // Admins only: a dry run reads every account (the rule editor is theirs). "customers.rule.dryRun": ({ draft, ruleId }) => Effect.gen(function* () { yield* requireAdmin return yield* ruleDryRun(draft, ruleId, yield* currentTime) }).pipe(remap), - "customers.health.dryRun": ({ draft }) => - Effect.gen(function* () { - yield* requireAdmin - return yield* healthDryRun(draft, yield* currentTime) - }).pipe(remap), - "customers.unmatched.list": ({ connectionId, status, ...request }) => Effect.gen(function* () { yield* requireAdmin @@ -598,8 +589,7 @@ const ACTION_EVENT = { reopen: ["signal.reopened", "Reopened"], } satisfies Record -const countsTowardHealth = (status: schema.CustomerSignal["status"]) => - status === "open" || status === "snoozed" +const isUnresolved = (status: schema.CustomerSignal["status"]) => status === "open" || status === "snoozed" /** * A human acted on a signal: check the action applies, write `patch` with the evidence it saw @@ -676,8 +666,9 @@ const actOnSignal = ( const next = typeof changes.status === "string" ? changes.status : signal.status // A linked channel shows the customer's open signals: only a status change moves them. if (next !== signal.status) yield* publishChannelCustomers(signal.organizationId) - // Health counts open and snoozed risk signals: rescore only when that set changed. - if (countsTowardHealth(next) !== countsTowardHealth(signal.status)) yield* requestCompute + // The org's at-risk MRR counts unresolved high risk signals, and only compute writes it: + // recompute when a signal enters or leaves the unresolved set. + if (isUnresolved(next) !== isUnresolved(signal.status)) yield* requestCompute }), ) }).pipe(remap) @@ -1718,7 +1709,7 @@ export const CustomerAdminRpcLive = CustomerAdminRpcs.toLayer( ) }).pipe(remap), - "customers.settings.update": ({ health, attention, reportingCurrency, addOnPlans }) => + "customers.settings.update": ({ attention, reportingCurrency, addOnPlans }) => Effect.gen(function* () { const actor = yield* requireAdmin // The open payload schema no longer refuses an unknown source, and this RPC declares no @@ -1733,7 +1724,6 @@ export const CustomerAdminRpcLive = CustomerAdminRpcs.toLayer( SQLite.update(schema.customerSettingsTable) // `undefined` leaves a column as it is. .set({ - health, attention, reportingCurrency: reportingCurrency?.toLowerCase(), addOnPlans, diff --git a/apps/backend/src/worker/objects/customers/channels.test.ts b/apps/backend/src/worker/objects/customers/channels.test.ts index d971124b5..84471b817 100644 --- a/apps/backend/src/worker/objects/customers/channels.test.ts +++ b/apps/backend/src/worker/objects/customers/channels.test.ts @@ -429,59 +429,20 @@ describe("Customer channel links", () => { const acme = t.accountId("Acme") // The first compute (nothing to compute from): seeded values below stay. yield* t.publish - // No health, no signals yet. + // No signals yet. expect(t.glance(general)).toMatchObject({ - healthStatus: "unknown", - healthScore: null, - healthWhy: null, openSignalCount: 0, topSignals: [], }) t.world.rows( - `UPDATE customer_accounts SET healthStatus = 'at_risk', healthScore = 48, lifecycleStage = 'active', + `UPDATE customer_accounts SET lifecycleStage = 'active', planName = 'Pro', mrrMinor = 240000, currency = 'usd', ownerUserId = ?, seatsUsed = 18, seatsLimit = 25, lastActiveAt = '2026-11-17 09:30:00.000', logoUrl = 'https://acme.test/logo.png' WHERE id = ?`, t.world.owner, acme, ) - const day = new Date().toISOString().slice(0, 10) - t.world.rows( - `INSERT OR REPLACE INTO customer_health_daily (accountId, day, score, status, breakdown) VALUES (?, ?, 48, 'at_risk', ?)`, - acme, - day, - JSON.stringify({ - score: 48, - status: "at_risk", - components: [ - { - key: "usage", - score: 70, - weight: 40, - effectiveWeight: 40, - excluded: false, - why: "usage ok", - }, - { - key: "engagement", - score: 25, - weight: 30, - effectiveWeight: 30, - excluded: false, - why: "No activity for 18 days", - }, - { - key: "billing", - score: null, - weight: 30, - effectiveWeight: 0, - excluded: true, - why: "no billing", - }, - ], - }), - ) const top = t.signal("Acme", "Payment failed", 9) t.signal("Acme", "Usage dropped", 5) t.signal("Acme", "Champion inactive", 3) @@ -496,9 +457,6 @@ describe("Customer channel links", () => { expect(row).toMatchObject({ accountName: "Acme", accountLogoUrl: "https://acme.test/logo.png", - healthStatus: "at_risk", - healthScore: 48, - healthWhy: "No activity for 18 days", lifecycleStage: "active", planName: "Pro", mrrMinor: 240000, @@ -522,17 +480,10 @@ describe("Customer channel links", () => { yield* t.publish expect(t.world.objects.deliveries.length).toBe(before) - // A compute that moves MRR and health resends. - t.world.rows( - `UPDATE customer_accounts SET mrrMinor = 120000, healthStatus = 'critical', healthScore = 30 WHERE id = ?`, - acme, - ) + // A compute that moves MRR resends. + t.world.rows(`UPDATE customer_accounts SET mrrMinor = 120000 WHERE id = ?`, acme) yield* t.publish - expect(t.glance(general)).toMatchObject({ - mrrMinor: 120000, - healthStatus: "critical", - healthScore: 30, - }) + expect(t.glance(general)).toMatchObject({ mrrMinor: 120000 }) // A person closing a signal updates the channel without waiting for a compute. const done = yield* t.world.call( @@ -620,7 +571,6 @@ describe("Customer channel links", () => { expect(t.glance(general)).toMatchObject({ accountName: "Acme", company: null, - healthStatus: "unknown", mrrMinor: null, openSignalCount: 0, topSignals: [], diff --git a/apps/backend/src/worker/objects/customers/channels.ts b/apps/backend/src/worker/objects/customers/channels.ts index 2a51fd344..f89fce4e4 100644 --- a/apps/backend/src/worker/objects/customers/channels.ts +++ b/apps/backend/src/worker/objects/customers/channels.ts @@ -2,12 +2,12 @@ * Channels linked to customer accounts (`docs/customers/channels.md`), on the `CustomersObject` * side: the live links (`customer_channel_links`) and their projection to the `OrgObject` * (`org.setChannelCustomers`, a full snapshot of channel → the account's id, name, logo, company - * profile and glance: health and why, stage, plan, MRR, owner, seats, last active day, open signals, - * provider links). + * profile and glance: stage, plan, MRR, owner, seats, last active day, open signals, provider + * links). * * The snapshot is sent when it changes (its fingerprint covers every field): after a link or * unlink, after a person changes an account's name or owner or a signal's status, and at the end - * of every compute (names and numbers set by sources, health, signals, accounts a source deleted). + * of every compute (names and numbers set by sources, signals, accounts a source deleted). * Only live links of live accounts are projected; the org writes only the rows that changed. * * A link belongs to the customer, not to one environment: it is stored on the group's primary @@ -15,7 +15,7 @@ */ import { Database, SQLite, schema } from "@hazel/db" import { integrations } from "@hazel/customer-integrations" -import { type CustomerProvider, type HealthBreakdown, logoOf } from "@hazel/domain/customers" +import { type CustomerProvider, logoOf } from "@hazel/domain/customers" import { ChannelCustomer } from "@hazel/domain/models" import type { ChannelId, @@ -123,12 +123,9 @@ type Glance = Omit< "channelId" | "accountId" | "accountName" | "accountLogoUrl" | "company" > -/** Days of health history searched for a customer's latest breakdown. */ -const HEALTH_LOOKBACK_DAYS = 7 - /** - * Each customer's glance, over its group (the customer and its environments): health, stage, plan - * and owner are the customer's; MRR (in its currency), seats and last activity are the group's; + * Each customer's glance, over its group (the customer and its environments): stage, plan and + * owner are the customer's; MRR (in its currency), seats and last activity are the group's; * signals and provider links are any of the group's (signals land on the primary). */ const glancesOf = (customers: ReadonlyArray) => @@ -180,17 +177,6 @@ const glancesOf = (customers: ReadonlyArray) => [$.id, "asc"], ]), ) - const today = new Date(yield* Clock.currentTimeMillis) - const since = new Date(today.getTime() - HEALTH_LOOKBACK_DAYS * 86_400_000).toISOString().slice(0, 10) - const health = new Map() - for (const row of yield* db.run( - SQLite.from(schema.customerHealthDailyTable) - .select("accountId", "breakdown") - .where(($) => [inList($.accountId, customerIds), $.day.gte(since)]) - .orderBy(($) => [[$.day, "desc"]]), - )) { - if (!health.has(row.accountId)) health.set(row.accountId, row.breakdown) - } return new Map( customers.map((customer) => { @@ -202,9 +188,6 @@ const glancesOf = (customers: ReadonlyArray) => return [ customer.id, { - healthStatus: customer.healthStatus, - healthScore: customer.healthScore, - healthWhy: customer.healthScore === null ? null : weakestWhy(health.get(customer.id)), // The group's rules, as signals see the customer (`group-facts.ts`). lifecycleStage: groupStage([ customer.lifecycleStage, @@ -241,19 +224,6 @@ type GroupAccount = Pick< "id" | "lifecycleStage" | "planName" | "mrrMinor" | "seatsUsed" | "seatsLimit" | "lastActiveAt" > -/** The scored component pulling the score down most: its plain reason. */ -const weakestWhy = (breakdown: HealthBreakdown | undefined): string | null => { - const scored = (breakdown?.components ?? []).flatMap((component) => - component.excluded || component.score === null - ? [] - : [{ score: component.score, why: component.why }], - ) - const [first, ...rest] = scored - if (first === undefined) return null - return rest.reduce((weakest, component) => (component.score < weakest.score ? component : weakest), first) - .why -} - /** One link per provider, in `PROVIDER_ORDER`: the customer's own record first, else an environment's. */ const sourceLinksOf = ( refs: ReadonlyArray<{ diff --git a/apps/backend/src/worker/objects/customers/compute-loop.test.ts b/apps/backend/src/worker/objects/customers/compute-loop.test.ts index 2f3624f1f..bed1ce3c6 100644 --- a/apps/backend/src/worker/objects/customers/compute-loop.test.ts +++ b/apps/backend/src/worker/objects/customers/compute-loop.test.ts @@ -985,7 +985,12 @@ describe("Customers compute and sync loop", () => { const world = yield* makeCustomersWorld yield* quietOrg(world) const snapshot = () => world.object.run(loadBase(NOW)).pipe(Effect.orDie) - expect((yield* snapshot()).hasActivityData).toBe(true) + expect([...(yield* snapshot()).org.connected].sort()).toEqual([ + "autumn", + "clerk", + "maple", + "stripe", + ]) world.object.storage.db .prepare( `UPDATE customer_connections SET status = 'disconnected' WHERE provider = 'maple'`, @@ -994,9 +999,7 @@ describe("Customers compute and sync loop", () => { world.object.storage.db .prepare(`UPDATE customer_connections SET status = 'error' WHERE provider = 'clerk'`) .run() - const stale = yield* snapshot() - expect(stale.hasActivityData).toBe(false) - expect([...stale.org.connected].sort()).toEqual(["autumn", "stripe"]) + expect([...(yield* snapshot()).org.connected].sort()).toEqual(["autumn", "stripe"]) }), )) @@ -1037,7 +1040,6 @@ describe("Customers compute and sync loop", () => { pulled("clerk", NOW.getTime() - 2 * DAY) pulled("maple", null) const silent = yield* snapshot() - expect(silent.hasActivityData).toBe(false) expect([...silent.org.connected].sort()).toEqual(["autumn", "stripe"]) expect([...silent.org.staleMetrics]).toEqual(["maple.requests"]) yield* world.object.run(runCompute(new Date(NOW.getTime() + DAY))).pipe(Effect.orDie) @@ -1302,20 +1304,17 @@ describe("Customers compute and sync loop", () => { mrrMinor: number lifecycleStage: string customerSince: string | null - healthStatus: string }>( - `SELECT name, mrrMinor, lifecycleStage, customerSince, healthStatus FROM customer_accounts ORDER BY name`, + `SELECT name, mrrMinor, lifecycleStage, customerSince FROM customer_accounts ORDER BY name`, ) const [usageBilled, free] = accounts() expect(usageBilled).toMatchObject({ mrrMinor: 0, lifecycleStage: "active" }) - expect(usageBilled!.healthStatus).not.toBe("unknown") expect(epoch(usageBilled!.customerSince!)).toBe(NOW.getTime() - 30 * DAY) - // A lead (a free plan) is not a customer yet: no health score, so never "at risk". + // A lead (a free plan) is not a customer yet. expect(free).toMatchObject({ mrrMinor: 0, lifecycleStage: "lead", customerSince: null, - healthStatus: "unknown", }) expect(world.rows(`SELECT * FROM customer_mrr_movements`)).toEqual([]) @@ -2173,8 +2172,6 @@ describe("Customers compute and sync loop", () => { Effect.gen(function* () { const world = yield* makeCustomersWorld yield* world.ingest("clerk", manyAccounts(260)) - const scored = () => - world.rows<{ n: number }>(`SELECT count(*) AS n FROM customer_health_daily`)[0]!.n const lastComputed = () => world.rows<{ lastComputedAt: string | null }>( `SELECT lastComputedAt FROM customer_settings`, @@ -2183,9 +2180,11 @@ describe("Customers compute and sync loop", () => { // No time budget: one chunk per turn; the next turn is due right away. const before = Date.now() yield* world.object.run(runCompute(NOW, 0)).pipe(Effect.orDie) - expect(scored()).toBe(250) + const [lastOfChunk] = world.rows<{ id: string }>( + `SELECT id FROM customer_accounts ORDER BY id LIMIT 1 OFFSET 249`, + ) + expect(JSON.parse(meta(world, "computeProgress")!).after).toBe(lastOfChunk!.id) expect(lastComputed()).toBeNull() - expect(meta(world, "computeProgress")).toBeDefined() expect(world.rows(`SELECT day FROM customer_org_daily`)).toEqual([]) const due = Number(meta(world, "computeDueAt")) expect(due).toBeGreaterThanOrEqual(before) @@ -2196,7 +2195,6 @@ describe("Customers compute and sync loop", () => { expect(Number(meta(world, "computeDueAt"))).toBe(due) yield* world.object.run(runCompute(NOW, 0)).pipe(Effect.orDie) - expect(scored()).toBe(260) expect(lastComputed()).not.toBeNull() expect(meta(world, "computeProgress")).toBeUndefined() expect(world.rows(`SELECT day FROM customer_org_daily`)).toEqual([{ day: day(0) }]) @@ -2259,7 +2257,7 @@ describe("Customers compute and sync loop", () => { world.object.storage.db .prepare( - `CREATE TRIGGER fail_health BEFORE INSERT ON customer_health_daily BEGIN SELECT RAISE(ABORT, 'boom'); END`, + `CREATE TRIGGER fail_org_day BEFORE INSERT ON customer_org_daily BEGIN SELECT RAISE(ABORT, 'boom'); END`, ) .run() world.object.storage.db diff --git a/apps/backend/src/worker/objects/customers/compute.ts b/apps/backend/src/worker/objects/customers/compute.ts index 42ce56e54..445a23fe5 100644 --- a/apps/backend/src/worker/objects/customers/compute.ts +++ b/apps/backend/src/worker/objects/customers/compute.ts @@ -3,44 +3,34 @@ * alarm hourly and soon after changes (`./schedule.ts`): * * 1. rollups: each account's denormalized fields, and today's MRR movement; - * 2. health: today's score and breakdown (`customer_health_daily`), band-change events; - * 3. signals: every enabled rule × every account, through the lifecycle (open, refresh, wake, + * 2. signals: every enabled rule × every account, through the lifecycle (open, refresh, wake, * reopen, resolve; baseline mode after a backfill); - * 4. counters: open signals per account, matches per rule; - * 5. the org's day (`customer_org_daily`, and yesterday's user counts again); - * 6. once a day, retention: old daily rows, events, closed signals and sync runs are deleted. + * 3. counters: open signals per account, matches per rule; + * 4. the org's day (`customer_org_daily`, and yesterday's user counts again); + * 5. once a day, retention: old daily rows, events, closed signals and sync runs are deleted. * * After a connection's first backfill, an alarm turn of its own (`runComputeStep`) rebuilds the last * year of history where none is recorded, once no billing backfill is importing (given up after * `MAX_REBUILD_ATTEMPTS` failed attempts). * - * Accounts are processed in chunks (`ACCOUNT_CHUNK`, `./snapshot.ts`): steps 1–4 run per chunk, so + * Accounts are processed in chunks (`ACCOUNT_CHUNK`, `./snapshot.ts`): steps 1–3 run per chunk, so * memory holds one chunk's activity and signals; the org's distinct user counts come from SQL. A * compute past `COMPUTE_TURN_BUDGET_MS` or `MAX_CHUNKS_PER_TURN` stops after a chunk and continues * in the next alarm turn from where it stopped (`computeProgress`; started over when it is stale, or - * the day or the billing sources' readiness changed); step 4's rule counts, 5 and 6 run after the last chunk. + * the day or the billing sources' readiness changed); step 3's rule counts, 4 and 5 run after the last chunk. * * Per-account built-in series are not stored daily: they derive from their sources at read time - * (active users from activity, MRR from movements, health from `customer_health_daily`). + * (active users from activity, MRR from movements). */ import { billingProviders, requiredSourcesOf } from "@hazel/customer-integrations" import { Database, SQLite, schema } from "@hazel/db" -import { - type CustomerProvider, - Day, - type HealthBreakdown, - type HealthSettings, - type SignalTemplate, - TEMPLATES, -} from "@hazel/domain/customers" +import { type CustomerProvider, Day, type SignalTemplate, TEMPLATES } from "@hazel/domain/customers" import { CustomerAccountId, type CustomerSignalId } from "@hazel/schema" import { Clock, Effect, Option, Schema } from "effect" import { readObjectMeta, writeObjectMeta } from "../meta" import { refreshSuggestionsAfterCompute } from "./channel-suggestions" import { publishChannelCustomersAfterCompute } from "./channels" import { evaluate, type Match } from "./evaluate" -import type { AccountFacts } from "./facts" -import { type HealthInputs, scoreHealth } from "./health" import { type LifecycleEvent, limitSignalTarget, transition, valueOf, wakeDue } from "./lifecycle" import { baselineConnections, @@ -245,174 +235,7 @@ const writeRollups = Effect.fn("Customers.writeRollups")(function* ( }) // --------------------------------------------------------------------------- -// 2. Health -// --------------------------------------------------------------------------- - -type RiskCounts = { high: number; medium: number; low: number } - -const openRiskOf = (snapshot: Snapshot, settings: HealthSettings) => { - const excluded = new Set(settings.excludedTemplates) - const counts = new Map() - for (const signal of snapshot.signals) { - if (signal.kind !== "risk" || excluded.has(signal.template)) continue - if (signal.status !== "open" && signal.status !== "snoozed") continue - const current = counts.get(signal.accountId) ?? { high: 0, medium: 0, low: 0 } - current[signal.severity]++ - counts.set(signal.accountId, current) - } - return counts -} - -export const healthInputsOf = ( - snapshot: Snapshot, - account: AccountSnapshot, - openRisk: RiskCounts | undefined, -): HealthInputs => { - const { facts, rollup } = account - const { now, today } = snapshot.org - const live = facts.subscriptions.filter((sub) => sub.status !== "canceled") - /** The due dates of the overdue invoices. */ - const overdue = facts.openInvoices.flatMap((invoice) => - invoice.dueAt !== null && invoice.dueAt < now ? [invoice.dueAt] : [], - ) - const weekAgo = now.getTime() - 7 * 86_400_000 - return { - customer: rollup.lifecycleStage !== "lead" && rollup.lifecycleStage !== "churned", - hasActivityData: snapshot.hasActivityData, - contactCount: rollup.contactCount, - activeUsers30d: rollup.activeUsers30d, - trendPct: rollup.activeUsersTrendPct, - daysSinceActive: facts.lastActiveDay === null ? null : daysBetween(facts.lastActiveDay, today), - billing: - snapshot.hasBillingData && live.length > 0 - ? { - pastDue: live.some((sub) => sub.status === "past_due" || sub.status === "unpaid"), - overdueOverWeek: overdue.some((dueAt) => dueAt.getTime() < weekAgo), - overdue: overdue.length > 0, - cancelScheduled: live.some((sub) => sub.cancelAtPeriodEnd), - } - : null, - openRisk: openRisk ?? { high: 0, medium: 0, low: 0 }, - } -} - -/** Score the snapshot's accounts (pure): what compute writes and the health dry run compares. */ -export const scoreAll = (snapshot: Snapshot, settings = snapshot.health) => { - const openRisk = openRiskOf(snapshot, settings) - return new Map( - snapshot.accounts.map((account) => [ - account.stored.id, - scoreHealth(healthInputsOf(snapshot, account, openRisk.get(account.stored.id)), { ...settings }), - ]), - ) -} - -const STATUS_LABEL = { healthy: "Healthy", at_risk: "At risk", critical: "Critical", unknown: "Unknown" } - -const writeHealth = Effect.fn("Customers.writeHealth")(function* ( - snapshot: Snapshot, - scores: ReadonlyMap, -) { - const db = yield* Database.Database - const { now, today } = snapshot.org - yield* db.transaction( - Effect.forEach( - snapshot.accounts, - ({ stored }) => - Effect.gen(function* () { - const breakdown = scores.get(stored.id) - // `scoreAll` scores every account of the snapshot. - if (breakdown === undefined) return - // Unchanged since the last run today: no write (and no change row to sync). - if (!same(snapshot.todayHealth.get(stored.id) ?? null, breakdown)) - yield* db.run( - SQLite.insertInto(schema.customerHealthDailyTable) - .values({ - accountId: stored.id, - day: today, - score: breakdown.score, - status: breakdown.status, - breakdown, - }) - .onConflictDoUpdate({ - target: ["accountId", "day"], - set: { - score: breakdown.score, - status: breakdown.status, - breakdown, - }, - }), - ) - if (stored.healthScore === breakdown.score && stored.healthStatus === breakdown.status) - return - yield* db.run( - SQLite.update(schema.customerAccountsTable) - .set({ - healthScore: breakdown.score, - healthStatus: breakdown.status, - healthUpdatedAt: now, - updatedAt: now, - }) - .where(($) => [$.id.eq(stored.id)]), - ) - if ( - stored.healthStatus !== "unknown" && - breakdown.status !== "unknown" && - stored.healthStatus !== breakdown.status - ) { - yield* hazelEvent( - stored.id, - "health.status_changed", - `Health ${STATUS_LABEL[stored.healthStatus]} → ${STATUS_LABEL[breakdown.status]}`, - now, - { - from: stored.healthStatus, - to: breakdown.status, - fromScore: stored.healthScore, - toScore: breakdown.score, - }, - ) - } - }), - { discard: true }, - ), - ) -}) - -/** The facts with today's health in place, for `health_drop` (a group's are its primary's). */ -const withTodayHealth = ( - snapshot: Snapshot, - scores: ReadonlyMap, -): Snapshot => ({ - ...snapshot, - accounts: snapshot.accounts.map((account) => { - const breakdown = scores.get(account.stored.id) - // `scoreAll` scores every account of the snapshot. - if (breakdown === undefined) return account - const scored = (facts: AccountFacts): AccountFacts => ({ - ...facts, - account: { ...facts.account, healthScore: breakdown.score, healthStatus: breakdown.status }, - health: [ - ...facts.health.filter((point) => point.day !== snapshot.org.today), - { day: snapshot.org.today, score: breakdown.score, status: breakdown.status }, - ], - }) - const facts = scored(account.facts) - return { - ...account, - facts, - evaluated: - account.evaluated === null - ? null - : account.evaluated === account.facts - ? facts - : scored(account.evaluated), - } - }), -}) - -// --------------------------------------------------------------------------- -// 3–4. Signals and counters +// 2–3. Signals and counters // --------------------------------------------------------------------------- const EVENT_TITLE = { @@ -427,7 +250,7 @@ type Live = Map /** The connections whose finished backfill armed the baseline when the compute started. */ readonly armed: ReadonlyArray @@ -805,7 +628,7 @@ const finishSignals = Effect.fn("Customers.finishSignals")(function* ( }) // --------------------------------------------------------------------------- -// 5. The org's day, and history +// 4. The org's day, and history // --------------------------------------------------------------------------- /** Rows of `activeCounts`' gap queries: `n` keys active on `day`, next active `gap` days later (≤ 30). */ @@ -905,19 +728,11 @@ interface OrgTotals { mrrMinor: number payingAccounts: number trialingAccounts: number - healthy: number - atRisk: number - critical: number /** Σ MRR of the accounts with an open (or snoozed) high risk signal. */ atRiskMrrMinor: number } -const addTotals = ( - totals: OrgTotals, - snapshot: Snapshot, - scores: ReadonlyMap, - live: Live, -) => { +const addTotals = (totals: OrgTotals, snapshot: Snapshot, live: Live) => { const highRisk = new Set( [...live.values()] .filter( @@ -933,10 +748,6 @@ const addTotals = ( if (rollup.mrrMinor > 0) totals.payingAccounts++ if (rollup.lifecycleStage === "trialing") totals.trialingAccounts++ if (highRisk.has(stored.id)) totals.atRiskMrrMinor += rollup.mrrMinor - const status = scores.get(stored.id)?.status - if (status === "healthy") totals.healthy++ - else if (status === "at_risk") totals.atRisk++ - else if (status === "critical") totals.critical++ } } @@ -1055,7 +866,7 @@ export const mrrHistory = ( * MRR movements of the accounts without any in that year before today (today's replaced; their MRR set to where * the movements end, in the same transaction, so a crash before the rollups cannot count them * twice), and the org's daily - * rows (MRR, paying, trialing, active, DAU/WAU/MAU, health counts) for the days without one; a day + * rows (MRR, paying, trialing, active, DAU/WAU/MAU) for the days without one; a day * recorded before billing data existed (no MRR, no paying account) gets its billing columns. */ export const rebuildHistory = Effect.fn("Customers.rebuildHistory")(function* (base: SnapshotBase) { @@ -1129,15 +940,6 @@ export const rebuildHistory = Effect.fn("Customers.rebuildHistory")(function* (b mrrNow.push({ id: account.id, mrrMinor: current }) } const users = yield* activeCounts(first, today) - const health = new Map( - (yield* db.run( - SQLite.from(schema.customerHealthDailyTable) - .select(($) => ({ day: $.day, status: $.status, count: SQLite.count() })) - .where(($) => [$.day.gte(first)]) - .groupBy("day", "status"), - )).map((row) => [`${row.day}:${row.status}`, row.count]), - ) - const healthOf = (day: Day, status: string) => health.get(`${day}:${status}`) ?? 0 // Today's row is written by the compute that follows, with its at-risk MRR. const orgDays = days.flatMap((day, index) => day < today @@ -1148,9 +950,6 @@ export const rebuildHistory = Effect.fn("Customers.rebuildHistory")(function* (b payingAccounts: paying[index], trialingAccounts: trialing[index], ...users(day), - healthy: healthOf(day, "healthy"), - atRisk: healthOf(day, "at_risk"), - critical: healthOf(day, "critical"), atRiskMrrMinor: 0, }, ] @@ -1195,9 +994,6 @@ export const rebuildHistory = Effect.fn("Customers.rebuildHistory")(function* (b dau: SQLite.integer, wau: SQLite.integer, mau: SQLite.integer, - healthy: SQLite.integer, - atRisk: SQLite.integer, - critical: SQLite.integer, atRiskMrrMinor: SQLite.integer, }), ) @@ -1234,7 +1030,7 @@ export const rebuildHistory = Effect.fn("Customers.rebuildHistory")(function* (b }) // --------------------------------------------------------------------------- -// 6. Retention +// 5. Retention // --------------------------------------------------------------------------- /** Once a day: daily rows past 400 days, events past 2 years, closed signals and sync runs. */ @@ -1244,7 +1040,6 @@ const prune = Effect.fn("Customers.prune")(function* (now: Date) { if (Option.getOrUndefined(yield* readObjectMeta(PRUNED_KEY)) === today) return const oldest = addDays(today, -DAILY_RETENTION_DAYS) const ago = (ms: number) => new Date(now.getTime() - ms) - yield* db.run(SQLite.deleteFrom(schema.customerHealthDailyTable).where(($) => [$.day.lt(oldest)])) yield* db.run(SQLite.deleteFrom(schema.customerActivityDailyTable).where(($) => [$.day.lt(oldest)])) yield* db.run(SQLite.deleteFrom(schema.customerMetricDailyTable).where(($) => [$.day.lt(oldest)])) yield* db.run( @@ -1306,9 +1101,6 @@ const ComputeProgress = Schema.Struct({ mrrMinor: Schema.Finite, payingAccounts: Schema.Finite, trialingAccounts: Schema.Finite, - healthy: Schema.Finite, - atRisk: Schema.Finite, - critical: Schema.Finite, atRiskMrrMinor: Schema.Finite, }), matches: Schema.Record(Schema.String, Schema.Finite), @@ -1352,9 +1144,6 @@ export const runCompute = Effect.fn("Customers.compute")(function* ( mrrMinor: 0, payingAccounts: 0, trialingAccounts: 0, - healthy: 0, - atRisk: 0, - critical: 0, atRiskMrrMinor: 0, } : { ...progress.totals } @@ -1366,10 +1155,8 @@ export const runCompute = Effect.fn("Customers.compute")(function* ( for (const groups of chunks) { const snapshot = yield* loadAccounts(base, groups.flat()) switched += yield* writeRollups(snapshot, importing, rebuildPending) - const scores = scoreAll(snapshot) - yield* writeHealth(snapshot, scores) - const live = yield* writeSignals(withTodayHealth(snapshot, scores), signals) - addTotals(totals, snapshot, scores, live) + const live = yield* writeSignals(snapshot, signals) + addTotals(totals, snapshot, live) done++ if ( done < chunks.length && diff --git a/apps/backend/src/worker/objects/customers/customers-authz.test.ts b/apps/backend/src/worker/objects/customers/customers-authz.test.ts index fb34c70e6..d1071e300 100644 --- a/apps/backend/src/worker/objects/customers/customers-authz.test.ts +++ b/apps/backend/src/worker/objects/customers/customers-authz.test.ts @@ -4,12 +4,7 @@ * projects (people, not bots; none for an unknown org); the org's deletion; and the data-source * handlers' edge cases (disconnect, ignore rules, bulk limits, credential rotation). */ -import { - DEFAULT_BUSINESS_HOURS, - DEFAULT_HEALTH_SETTINGS, - DEFAULT_SLA_POLICY, - TEMPLATES, -} from "@hazel/domain/customers" +import { DEFAULT_BUSINESS_HOURS, DEFAULT_SLA_POLICY, TEMPLATES } from "@hazel/domain/customers" import { CustomerRpcs } from "@hazel/domain/rpc" import type { OrganizationId, UserId } from "@hazel/schema" import { ConfigProvider, Effect, Exit, Layer, Option, Redacted, type Scope } from "effect" @@ -64,7 +59,6 @@ const PAYLOADS = { "customers.signals.open": {}, "customers.signals.history": {}, "customers.rule.dryRun": { draft: ruleDraft }, - "customers.health.dryRun": { draft: DEFAULT_HEALTH_SETTINGS }, "customers.unmatched.list": {}, "customers.ignoreRules.list": {}, "customers.plans.list": {}, @@ -130,7 +124,6 @@ const PAYLOADS = { /** Settings, rules and their dry runs, shared views, data sources, unmatched records, the demo seed. */ const ADMIN_ONLY = new Set([ "customers.rule.dryRun", - "customers.health.dryRun", "customers.unmatched.list", "customers.ignoreRules.list", "customers.view.create", // `shared: true` diff --git a/apps/backend/src/worker/objects/customers/customers-rpc.test.ts b/apps/backend/src/worker/objects/customers/customers-rpc.test.ts index 47b8483fc..6b9482413 100644 --- a/apps/backend/src/worker/objects/customers/customers-rpc.test.ts +++ b/apps/backend/src/worker/objects/customers/customers-rpc.test.ts @@ -1,11 +1,10 @@ /** * The Customers RPCs in a `CustomersObject`: authorization (member vs admin), the members * bootstrap from the `OrgObject`, the demo seed through ingest and compute, the queue actions, - * dry runs, and baseline mode after a backfill. + * rule dry run, and baseline mode after a backfill. */ import { DEFAULT_CONNECTION_CONFIG } from "@hazel/customer-integrations" import { - DEFAULT_HEALTH_SETTINGS, type IngestOp, type RuleDraft, SignalTemplate, @@ -18,7 +17,7 @@ import { describe, expect, it } from "vitest" import { customersTarget, orgTarget } from "../kinds" import { makeTestObjects } from "../testing" import { runCompute } from "./compute" -import { healthDryRun, ruleDryRun } from "./dry-run" +import { ruleDryRun } from "./dry-run" import { CustomerIngest } from "./ingest" import { makeCustomersWorld, NOW, ok, tagOf, uuid } from "./test-kit" @@ -36,8 +35,8 @@ describe("Customers RPCs", () => { expect(tagOf(yield* world.call("customers.overview", { range: "30d" }, world.stranger))).toBe( "UnauthorizedError", ) - const health = ok(yield* world.call("customers.overview", { range: "30d" }, world.owner)) - expect(health.hasData).toEqual({ activity: false, billing: false }) + const overview = ok(yield* world.call("customers.overview", { range: "30d" }, world.owner)) + expect(overview.hasData).toEqual({ activity: false, billing: false }) const settings = { reportingCurrency: "eur" } expect(tagOf(yield* world.call("customers.settings.update", settings, world.member))).toBe( @@ -92,13 +91,13 @@ describe("Customers RPCs", () => { expect( tagOf(yield* world.call("customers.view.delete", { viewId: builtIn.id }, world.owner)), ).toBe("CustomersInvalidRequestError") - // Defaults: a rule per template, five built-in views, the built-in metrics. + // Defaults: a rule per template, four built-in views, the built-in metrics. expect(world.rows(`SELECT count(*) AS n FROM customer_signal_rules`)).toEqual([ { n: SignalTemplate.literals.length + 1 }, ]) expect( world.rows(`SELECT count(*) AS n FROM customer_saved_views WHERE builtInKey IS NOT NULL`), - ).toEqual([{ n: 5 }]) + ).toEqual([{ n: 4 }]) // Every provider has an adapter now, so connecting goes to it: this key is not one // Maple issues, which its `validate` says before it calls anything. expect( @@ -319,13 +318,11 @@ describe("Customers RPCs", () => { `SELECT template, count(*) AS n FROM customer_signals WHERE status = 'open' GROUP BY template ORDER BY template`, ) .map((row) => row.template) - // health_drop needs history, and the demo seeds no support issues (the SLA templates); - // every other template fires on day one. + // The demo seeds no support issues (the SLA templates); every other template fires on + // day one. expect(templates).toEqual( expect.arrayContaining( - SignalTemplate.literals.filter( - (template) => template !== "health_drop" && !SLA_TEMPLATES.includes(template), - ), + SignalTemplate.literals.filter((template) => !SLA_TEMPLATES.includes(template)), ), ) const stages = world.rows<{ lifecycleStage: string }>( @@ -338,9 +335,6 @@ describe("Customers RPCs", () => { "past_due", "trialing", ]) - expect(world.rows(`SELECT count(*) AS n FROM customer_health_daily`)).toEqual([ - { n: accounts }, - ]) expect( world.rows<{ n: number }>(`SELECT count(*) AS n FROM customer_org_daily`)[0]!.n, ).toBe(366) @@ -356,12 +350,6 @@ describe("Customers RPCs", () => { expect(overview.kpis.mau.value).toBeGreaterThan(0) expect(overview.bucket).toBe("week") expect(overview.mrrMovements.length).toBeGreaterThanOrEqual(13) - expect( - overview.healthDistribution.reduce( - (sum: number, row: { count: number }) => sum + row.count, - 0, - ), - ).toBe(accounts) expect(overview.hasData).toEqual({ activity: true, billing: true }) const top = world.rows<{ id: string; accountId: string; ruleId: string }>( @@ -374,7 +362,6 @@ describe("Customers RPCs", () => { world.member, ), ) - expect(detail.health.components).toHaveLength(4) expect(detail.activeUsersSeries).toHaveLength(30) expect(detail.subscriptions.length).toBeGreaterThan(0) const series = ok( @@ -459,24 +446,6 @@ describe("Customers RPCs", () => { expect(dry.evaluatedAccounts).toBe(dry.totalAccounts) expect(dry.queueDelta).toEqual({ opens: 0, resolves: 0, stays: open }) expect(dry.topMatches[0].evidence._tag).toBe("amount") - const healthDry = ok( - yield* world.call( - "customers.health.dryRun", - { - draft: { - ...JSON.parse( - world.rows<{ health: string }>( - `SELECT health FROM customer_settings`, - )[0]!.health, - ), - bands: { healthyMin: 95, atRiskMin: 60 }, - }, - }, - world.owner, - ), - ) - expect(healthDry.transitions.length).toBeGreaterThan(0) - expect(healthDry.samples.length).toBeGreaterThan(0) // The queue: snooze, reopen, done, notes. const snoozed = ok( @@ -652,9 +621,9 @@ describe("Customers RPCs", () => { { template: "payment_failed", status: "open", dismissReason: null }, { template: "usage_drop", status: "dismissed", dismissReason: "baseline" }, ]) - expect( - world.rows(`SELECT openRiskHigh, openRiskMedium, healthStatus FROM customer_accounts`), - ).toEqual([{ openRiskHigh: 1, openRiskMedium: 0, healthStatus: "at_risk" }]) + expect(world.rows(`SELECT openRiskHigh, openRiskMedium FROM customer_accounts`)).toEqual([ + { openRiskHigh: 1, openRiskMedium: 0 }, + ]) // Baseline mode is one evaluation: the next compute leaves them, until worse by a step. yield* world.object.run(runCompute(new Date(Date.now() + 3_600_000))).pipe(Effect.orDie) expect( @@ -730,11 +699,6 @@ describe("Customers RPCs", () => { expect(rule.matchCount + rule.nonMatches.reduce((sum, entry) => sum + entry.count, 0)).toBe( 250, ) - const health = yield* world.object - .run(healthDryRun(DEFAULT_HEALTH_SETTINGS, NOW, 0)) - .pipe(Effect.orDie) - expect([health.evaluatedAccounts, health.totalAccounts]).toEqual([250, 260]) - expect(health.current.reduce((sum, row) => sum + row.count, 0)).toBe(250) }), )) }) diff --git a/apps/backend/src/worker/objects/customers/defaults.ts b/apps/backend/src/worker/objects/customers/defaults.ts index 68f8d2c7b..73c301391 100644 --- a/apps/backend/src/worker/objects/customers/defaults.ts +++ b/apps/backend/src/worker/objects/customers/defaults.ts @@ -6,7 +6,6 @@ import { Database, SQLite, schema } from "@hazel/db" import { type BuiltInViewKey, - DEFAULT_HEALTH_SETTINGS, DEFAULT_LIST_COLUMNS, DEFAULT_SLA_POLICY, SignalTemplate, @@ -21,7 +20,6 @@ export const BUILT_IN_METRICS = [ { key: "active_users", name: "Daily active users", unit: "users", aggregation: "max" }, { key: "active_users_30d", name: "Active users (30 days)", unit: "users", aggregation: "last" }, { key: "mrr", name: "MRR", unit: "minor", aggregation: "last" }, - { key: "health_score", name: "Health score", unit: "points", aggregation: "last" }, ] as const export const isBuiltInMetric = (key: string) => BUILT_IN_METRICS.some((metric) => metric.key === key) @@ -34,7 +32,6 @@ export const BUILT_IN_VIEWS: ReadonlyArray<{ { key: "my_customers", name: "My customers", filters: { ownedByMe: true } }, { key: "paying", name: "Paying", filters: { payingOnly: true } }, { key: "trialing", name: "Trialing", filters: { lifecycleStages: ["trialing"] } }, - { key: "at_risk", name: "At risk", filters: { healthStatuses: ["at_risk", "critical"] } }, { key: "churned", name: "Churned", filters: { lifecycleStages: ["churned"] } }, ] @@ -47,7 +44,6 @@ export const installDefaults = Effect.fn("Customers.installDefaults")(function* yield* db.run( SQLite.insertInto(schema.customerSettingsTable).values({ organizationId, - health: DEFAULT_HEALTH_SETTINGS, reportingCurrency: "usd", }), ) diff --git a/apps/backend/src/worker/objects/customers/dry-run.ts b/apps/backend/src/worker/objects/customers/dry-run.ts index b54d1a78c..9fbb75c72 100644 --- a/apps/backend/src/worker/objects/customers/dry-run.ts +++ b/apps/backend/src/worker/objects/customers/dry-run.ts @@ -1,25 +1,20 @@ /** - * Dry runs (`docs/customers/tech-design.md` §4.8): a draft rule or draft health settings evaluated - * over the current data with the same pure functions compute uses, without writing. Admins only - * (they read the accounts); accounts load in chunks, a rule's with only the activity its own - * window needs, and a group of linked accounts evaluates over its combined facts. One RPC - * evaluates at most `MAX_CHUNKS` chunks, and none after `BUDGET_MS`: past that the result is - * partial (`evaluatedAccounts` of `totalAccounts`, groups in their primary's id order). + * The rule dry run (`docs/customers/tech-design.md` §4.7): a draft rule evaluated over the current + * data with the same pure functions compute uses, without writing. Admins only (they read the + * accounts); accounts load in chunks, with only the activity the rule's window needs, and a group + * of linked accounts evaluates over its combined facts. One RPC evaluates at most `MAX_CHUNKS` + * chunks, and none after `BUDGET_MS`: past that the result is partial (`evaluatedAccounts` of + * `totalAccounts`, groups in their primary's id order). */ import { Database, SQLite, schema } from "@hazel/db" import { ENVIRONMENT_TEMPLATES, - type HealthBreakdown, - type HealthDryRunResult, - type HealthSettings, - HealthStatus, type RuleDraft, type RuleDryRunResult, type RuleMatch, } from "@hazel/domain/customers" import type { CustomerAccountId, CustomerSignalRuleId } from "@hazel/schema" import { Clock, Effect } from "effect" -import { scoreAll } from "./compute" import { evaluate, missingSources, type RuleInput } from "./evaluate" import { limitSignalTarget, priorityScore, valueOf } from "./lifecycle" import { evaluatedFor, groupChunks, loadAccounts, loadBase, type SnapshotBase } from "./snapshot" @@ -144,73 +139,3 @@ export const ruleDryRun = Effect.fn("Customers.ruleDryRun")(function* ( totalAccounts: base.accountIds.length, } satisfies RuleDryRunResult }) - -type Account = { readonly id: CustomerAccountId; readonly name: string; readonly mrrMinor: number } - -export const healthDryRun = Effect.fn("Customers.healthDryRun")(function* ( - draft: HealthSettings, - now: Date, - budgetMs = BUDGET_MS, -) { - // Health reads 30 days of activity (the 35-day trend at most): the shortest window. - const base = yield* loadBase(now, { windowRules: [] }) - const distribution = () => - new Map(HealthStatus.literals.map((status) => [status, { status, count: 0, mrrMinor: 0 }])) - const current = distribution() - const proposed = distribution() - const transitions = new Map() - const changed: Array<{ account: Account; current: HealthBreakdown; proposed: HealthBreakdown }> = [] - let evaluatedAccounts = 0 - const { chunks, more } = yield* chunksWithinBudget(base, budgetMs) - for (let done = 0; yield* more(done); done++) { - const snapshot = yield* loadAccounts(base, chunks[done]) - evaluatedAccounts += snapshot.accounts.length - const before = scoreAll(snapshot) - const after = scoreAll(snapshot, draft) - for (const { facts } of snapshot.accounts) { - const account = { - id: facts.account.id, - name: facts.account.name, - mrrMinor: facts.account.mrrMinor, - } - const was = before.get(account.id) - const will = after.get(account.id) - // `scoreAll` scores every account of the snapshot. - if (was === undefined || will === undefined) continue - for (const [into, breakdown] of [ - [current, was], - [proposed, will], - ] as const) { - const bucket = into.get(breakdown.status) - if (bucket === undefined) continue - bucket.count++ - bucket.mrrMinor += account.mrrMinor - } - if (was.status === will.status) continue - const key = `${was.status}:${will.status}` - transitions.set(key, (transitions.get(key) ?? 0) + 1) - // The 5 largest by MRR are shown: keep only those. - changed.push({ account, current: was, proposed: will }) - changed.sort((a, b) => b.account.mrrMinor - a.account.mrrMinor) - changed.splice(5) - } - } - const counts = (buckets: typeof current) => - [...buckets.values()].map(({ status, count, mrrMinor }) => ({ status, count, mrrMinor })) - return { - current: counts(current), - proposed: counts(proposed), - transitions: [...transitions.entries()].map(([key, count]) => { - const [from, to] = key.split(":") as [HealthStatus, HealthStatus] - return { from, to, count } - }), - samples: changed.map((sample) => ({ - accountId: sample.account.id, - name: sample.account.name, - current: sample.current, - proposed: sample.proposed, - })), - evaluatedAccounts, - totalAccounts: base.accountIds.length, - } satisfies HealthDryRunResult -}) diff --git a/apps/backend/src/worker/objects/customers/evaluate.test.ts b/apps/backend/src/worker/objects/customers/evaluate.test.ts index 9b19b9894..ea1488b54 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.test.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.test.ts @@ -305,30 +305,6 @@ describe("signal evaluation", () => { ) }) - it("health_drop: −20 points within 7 days, or entered critical", () => { - const health = ( - before: number, - now: number, - status: "healthy" | "at_risk" | "critical" = "at_risk", - ) => ({ - health: [ - { day: addDays(TODAY, -5), score: before, status: "healthy" as const }, - { day: TODAY, score: now, status }, - ], - }) - const found = match("health_drop", health(80, 55)) - expect(found.evidence).toMatchObject({ _tag: "delta", unit: "points", from: 80, to: 55, step: 0 }) - expect(match("health_drop", health(90, 50)).evidence.step).toBe(1) - expect(run("health_drop", health(70, 60))._tag).toBe("NoMatch") - expect(match("health_drop", health(38, 35, "critical")).reason).toContain("now critical") - // Entered critical: a new account first scored critical has not. - expect(run("health_drop", { health: [{ day: TODAY, score: 35, status: "critical" }] })).toEqual({ - _tag: "NoMatch", - reason: "Below threshold", - }) - expect(run("health_drop", {})).toEqual({ _tag: "NoMatch", reason: "No data" }) - }) - it("champion_inactive: the most active user of the window before went quiet 14+ days", () => { const found = match("champion_inactive", { activity: { ann: range(-40, -16), bob: [-30, -20, -2] }, @@ -857,7 +833,7 @@ describe("signal evaluation", () => { expect(run("response_overdue", lead, narrow)._tag).toBe("Match") expect(run("resolution_overdue", lead, narrow)._tag).toBe("Match") // Other templates stay behind the coverage. - expect(run("health_drop", lead, narrow)).toEqual({ + expect(run("inactive", lead, narrow)).toEqual({ _tag: "NoMatch", reason: "Not covered by Needs attention", }) diff --git a/apps/backend/src/worker/objects/customers/evaluate.ts b/apps/backend/src/worker/objects/customers/evaluate.ts index 781b022d5..230e6f321 100644 --- a/apps/backend/src/worker/objects/customers/evaluate.ts +++ b/apps/backend/src/worker/objects/customers/evaluate.ts @@ -1,5 +1,5 @@ /** - * Signal evaluation (`docs/customers/tech-design.md` §4.4), pure: one rule against one account's + * Signal evaluation (`docs/customers/tech-design.md` §4.3), pure: one rule against one account's * facts. Compute, the rule dry run and the tests share it. * * A match carries its evidence (drawn by the UI per `_tag`) and `step`, how far past the threshold @@ -369,57 +369,6 @@ const onboardingStalled = } } -const healthDrop = - (config: Extract): Check => - (facts, org) => { - const today = facts.health.find((point) => point.day === org.today) - if (today === undefined || today.score === null) return "No data" - const since = addDays(org.today, -config.windowDays) - const before = facts.health.flatMap((point) => - point.day >= since && point.day < org.today && point.score !== null ? [point.score] : [], - ) - const peak = before.reduce((max, score) => Math.max(max, score), today.score) - const drop = peak - today.score - // Entered critical: a scored, non-critical day in the window before (a new account first - // scored critical has not "entered" it). - const critical = - config.onCritical && - today.status === "critical" && - facts.health.some( - (point) => - point.day >= since && - point.day < org.today && - point.status !== "critical" && - point.status !== "unknown", - ) - if (drop < config.dropPoints && !critical) return "Below threshold" - const step = stepOf(drop >= 50, drop >= 35) - const series = facts.health - .filter((point) => point.day >= addDays(org.today, -29)) - .map((point) => ({ day: point.day, value: point.score ?? 0 })) - return { - step, - reason: - drop > 0 - ? `Health fell ${drop} points in ${plural(config.windowDays, "day")} (${peak} → ${today.score})${critical ? ", now critical" : ""}` - : `Health is critical (${today.score})`, - evidence: { - _tag: "delta", - step, - unit: "points", - from: peak, - to: today.score, - changePct: peak === 0 ? null : round1(((today.score - peak) / peak) * 100), - currency: null, - effectiveAt: null, - fromLabel: null, - toLabel: today.status, - reason: null, - series, - }, - } - } - const championInactive = (config: Extract): Check => (facts, org) => { @@ -662,8 +611,6 @@ const checkOf = (config: RuleConfig): Check => { return trialEnding(config) case "onboarding_stalled": return onboardingStalled(config) - case "health_drop": - return healthDrop(config) case "champion_inactive": return championInactive(config) case "near_limit": diff --git a/apps/backend/src/worker/objects/customers/facts.ts b/apps/backend/src/worker/objects/customers/facts.ts index 37eebab5b..f479f3105 100644 --- a/apps/backend/src/worker/objects/customers/facts.ts +++ b/apps/backend/src/worker/objects/customers/facts.ts @@ -1,14 +1,13 @@ /** * What compute knows about the org and each account at one instant: the input of signal - * evaluation (`./evaluate.ts`), the health score and the dry runs, loaded by `./snapshot.ts`. Plain - * data, so the pure parts are tested with hand-built facts. + * evaluation (`./evaluate.ts`) and the rule dry run, loaded by `./snapshot.ts`. Plain data, so the + * pure parts are tested with hand-built facts. */ import type { schema } from "@hazel/db" import type { AttentionSettings, CustomerProvider, Day, - HealthStatus, LifecycleStage, MetricAggregation, SeriesPoint, @@ -34,12 +33,6 @@ export interface MetricPoint { readonly limitValue: number | null } -export interface HealthPoint { - readonly day: Day - readonly score: number | null - readonly status: HealthStatus -} - /** An open support issue's SLA clocks (`customer_issue_slas`), for the overdue templates. */ export interface IssueSlaFacts { readonly issueId: CustomerIssueId @@ -71,8 +64,6 @@ export interface AccountFacts { readonly metrics: ReadonlyMap> /** MRR movements, oldest first. */ readonly movements: ReadonlyArray - /** Daily health over the loaded window, oldest first (today's once scored). */ - readonly health: ReadonlyArray /** Open (not closed, not deleted) support issues with SLA clocks. */ readonly openIssueSlas: ReadonlyArray /** On an environment template's facts: its own subscriptions, whose period the forecast ends at. */ @@ -156,13 +147,8 @@ export const metricSeries = ( }) } -/** Hazel's own series, derived from activity, movements and health (never stored as metrics). */ -export const DERIVED_METRICS: ReadonlySet = new Set([ - "active_users", - "active_users_30d", - "mrr", - "health_score", -]) +/** Hazel's own series, derived from activity and movements (never stored as metrics). */ +export const DERIVED_METRICS: ReadonlySet = new Set(["active_users", "active_users_30d", "mrr"]) /** Any built-in or source metric's series. */ export const seriesOf = ( @@ -179,10 +165,6 @@ export const seriesOf = ( return rollingActiveSeries(facts, last, count) case "mrr": return mrrSeries(facts.movements, facts.account.mrrMinor, last, count) - case "health_score": { - const scores = new Map(facts.health.map((point) => [point.day, point.score ?? 0])) - return dayRange(last, count).map((day) => ({ day, value: scores.get(day) ?? 0 })) - } default: return metricSeries(facts, key, last, count, aggregation) } diff --git a/apps/backend/src/worker/objects/customers/group-facts.test.ts b/apps/backend/src/worker/objects/customers/group-facts.test.ts index 4fcd6b0d3..8a0c6b130 100644 --- a/apps/backend/src/worker/objects/customers/group-facts.test.ts +++ b/apps/backend/src/worker/objects/customers/group-facts.test.ts @@ -76,8 +76,7 @@ describe("groupFacts", () => { expect(group.priorActive.get(30)).toBe(2) }) - it("sums MRR, seats and metrics; takes the earliest and latest dates and the primary's health", () => { - const health = [{ day: TODAY, score: 80, status: "healthy" as const }] + it("sums MRR, seats and metrics; takes the earliest and latest dates", () => { const us = factsOf({ account: { mrrMinor: 10_000, @@ -88,7 +87,6 @@ describe("groupFacts", () => { tags: ["vip"], }, metrics: new Map([["events", [{ day: TODAY, value: 3, limitValue: 10 }]]]), - health, }) const eu = factsOf({ account: { @@ -108,7 +106,6 @@ describe("groupFacts", () => { ], ], ]), - health: [{ day: TODAY, score: 20, status: "critical" as const }], }) const group = groupFacts(us, [eu], FROM) expect(group.account).toMatchObject({ @@ -124,7 +121,6 @@ describe("groupFacts", () => { { day: addDays(TODAY, -1), value: 1, limitValue: null }, { day: TODAY, value: 7, limitValue: 15 }, ]) - expect(group.health).toBe(health) }) it("takes the most advanced stage: churned only when every environment is", () => { diff --git a/apps/backend/src/worker/objects/customers/group-facts.ts b/apps/backend/src/worker/objects/customers/group-facts.ts index 2c7c54d7d..768fd91b7 100644 --- a/apps/backend/src/worker/objects/customers/group-facts.ts +++ b/apps/backend/src/worker/objects/customers/group-facts.ts @@ -1,8 +1,7 @@ /** * A customer with several environments (`./groups.ts`) is alerted on as one: signals evaluate its * primary over the group's combined facts (pure), so "logins stopped" does not fire for one - * environment while another still has logins. Each account's own facts keep feeding its rollups and - * health. + * environment while another still has logins. Each account's own facts keep feeding its rollups. * * - Contacts and activity: unioned, a person in several environments counted once (the same email, * case-insensitive, else the same contact); the last active day, ever-active contacts and the @@ -12,7 +11,6 @@ * on each day one of them moved. * - Metrics: values (and limits) summed per day. `ENVIRONMENT_TEMPLATES` read an environment's own * (`evaluatedFor` in `./snapshot.ts`), and their signals are stored on it. - * - Health: the primary's. * - The account: the primary's row with MRR, trial list price and seats summed, the earliest first * seen, customer since and trial end, the latest activity, the tags of all, and the most advanced * stage (churned only when every environment is). @@ -220,7 +218,6 @@ export const groupFacts = ( ]), ), movements: groupMovements(group), - health: primary.health, openIssueSlas: group.flatMap((facts) => facts.openIssueSlas), } } diff --git a/apps/backend/src/worker/objects/customers/groups.ts b/apps/backend/src/worker/objects/customers/groups.ts index 8e27b4a53..cc4ee4649 100644 --- a/apps/backend/src/worker/objects/customers/groups.ts +++ b/apps/backend/src/worker/objects/customers/groups.ts @@ -2,7 +2,7 @@ * Customers with several environments (`customers.account.link`, `unlink`, `setPrimary`, * `setEnvironment`). Accounts are never merged: each source record stays its own account (an * environment, e.g. a US and an EU region), and accounts link into a group with one primary - * (`primaryAccountId` on the others; no chains). Rollups and health stay per account; signals are + * (`primaryAccountId` on the others; no chains). Rollups stay per account; signals are * evaluated over the group's combined facts (`./group-facts.ts`) and written on the primary, so its * other environments hold no unclosed signal, but for `ENVIRONMENT_TEMPLATES`' (each its own). * diff --git a/apps/backend/src/worker/objects/customers/health.ts b/apps/backend/src/worker/objects/customers/health.ts deleted file mode 100644 index ff6b69a3c..000000000 --- a/apps/backend/src/worker/objects/customers/health.ts +++ /dev/null @@ -1,160 +0,0 @@ -/** - * The health score (`docs/customers/tech-design.md` §4.3), pure: compute, the health dry run and - * the tests share it. - * - * Each component scores 0–100 through its threshold steps or drops out without data; the excluded - * components' weight is shared by the rest (`effectiveWeight = w / Σ w available × 100`); the score - * is the weighted sum, banded. No score (`unknown`) for an account that is not a customer (a lead or - * churned: nothing to retain), or when only `signals` is left. - */ -import type { - HealthBreakdown, - HealthComponentKey, - HealthComponentResult, - HealthSettings, - HealthStatus, - MaxStep, - MinStep, -} from "@hazel/domain/customers" - -export interface BillingHealthInputs { - readonly pastDue: boolean - /** An open invoice more than 7 days past its due date. */ - readonly overdueOverWeek: boolean - readonly overdue: boolean - readonly cancelScheduled: boolean -} - -export interface HealthInputs { - /** Paying, trialing or past due. Leads and churned accounts get no score. */ - readonly customer: boolean - /** The org has usage data (an activity source): without it usage and engagement drop out. */ - readonly hasActivityData: boolean - readonly contactCount: number - readonly activeUsers30d: number - readonly trendPct: number | null - /** Null: never active. */ - readonly daysSinceActive: number | null - /** Null: no billing source, or no live subscription. */ - readonly billing: BillingHealthInputs | null - /** Open (and snoozed) risk signals, without the excluded templates. */ - readonly openRisk: { readonly high: number; readonly medium: number; readonly low: number } -} - -/** The first step (by `min`, descending) whose `min` ≤ `value`; the lowest one otherwise. */ -export const minStep = (steps: ReadonlyArray, value: number): number => { - const sorted = [...steps].sort((a, b) => b.min - a.min) - return (sorted.find((step) => value >= step.min) ?? sorted[sorted.length - 1])?.score ?? 0 -} - -/** The first step (by `max`, ascending) whose `max` ≥ `value`; the highest one otherwise. */ -export const maxStep = (steps: ReadonlyArray, value: number): number => { - const sorted = [...steps].sort((a, b) => a.max - b.max) - return (sorted.find((step) => value <= step.max) ?? sorted[sorted.length - 1])?.score ?? 0 -} - -export const bandOf = (score: number, bands: HealthSettings["bands"]): HealthStatus => - score >= bands.healthyMin ? "healthy" : score >= bands.atRiskMin ? "at_risk" : "critical" - -const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}` - -const signed = (value: number) => `${value > 0 ? "+" : value < 0 ? "−" : ""}${Math.abs(Math.round(value))}%` - -interface Part { - readonly score: number | null - readonly why: string -} - -const usage = (inputs: HealthInputs, settings: HealthSettings): Part => { - if (!inputs.hasActivityData) return { score: null, why: "No usage data source connected" } - const steps = settings.steps.usage - const ratio = inputs.activeUsers30d / Math.max(inputs.contactCount, 1) - const ratioScore = minStep(steps.activeRatio, ratio) - const active = `${inputs.activeUsers30d} of ${plural(inputs.contactCount, "contact")} active in 30 days` - if (inputs.trendPct === null) return { score: ratioScore, why: `${active}; no trend yet` } - const weight = steps.activeRatioWeight / 100 - const score = Math.round(weight * ratioScore + (1 - weight) * minStep(steps.trend, inputs.trendPct)) - return { score, why: `${active}; trend ${signed(inputs.trendPct)}` } -} - -const engagement = (inputs: HealthInputs, settings: HealthSettings): Part => { - if (!inputs.hasActivityData) return { score: null, why: "No usage data source connected" } - const steps = settings.steps.engagement.daysSinceActive - if (inputs.daysSinceActive === null) - return { score: maxStep(steps, Number.MAX_SAFE_INTEGER), why: "Never active" } - const days = inputs.daysSinceActive - return { - score: maxStep(steps, days), - why: days === 0 ? "Active today" : `Last active ${plural(days, "day")} ago`, - } -} - -const billing = (inputs: HealthInputs, settings: HealthSettings): Part => { - if (inputs.billing === null) return { score: null, why: "No subscription" } - const scores = settings.steps.billing - const issues: Array = [] - if (inputs.billing.pastDue) issues.push([scores.pastDue, "Payment past due"]) - if (inputs.billing.overdueOverWeek) - issues.push([scores.overdueOverWeek, "Invoice overdue for over a week"]) - else if (inputs.billing.overdue) issues.push([scores.overdue, "Invoice overdue"]) - if (inputs.billing.cancelScheduled) issues.push([scores.cancelScheduled, "Cancellation scheduled"]) - if (issues.length === 0) return { score: scores.ok, why: "Paid up" } - return { - score: Math.min(...issues.map(([score]) => score)), - why: issues.map(([, why]) => why).join("; "), - } -} - -const signals = (inputs: HealthInputs, settings: HealthSettings): Part => { - const { high, medium, low } = inputs.openRisk - const deduction = - high * settings.steps.signals.high + - medium * settings.steps.signals.medium + - low * settings.steps.signals.low - const total = high + medium + low - if (total === 0) return { score: 100, why: "No open risk signals" } - const parts = [ - high > 0 ? `${high} high` : null, - medium > 0 ? `${medium} medium` : null, - low > 0 ? `${low} low` : null, - ].filter((part) => part !== null) - return { - score: Math.max(0, 100 - deduction), - why: `${plural(total, "open risk signal")} (${parts.join(", ")})`, - } -} - -const COMPONENTS: ReadonlyArray< - readonly [HealthComponentKey, (inputs: HealthInputs, settings: HealthSettings) => Part] -> = [ - ["usage", usage], - ["engagement", engagement], - ["billing", billing], - ["signals", signals], -] - -export const scoreHealth = (inputs: HealthInputs, settings: HealthSettings): HealthBreakdown => { - const parts = COMPONENTS.map(([key, score]) => ({ - key, - ...score(inputs, settings), - weight: settings.weights[key], - })) - const available = parts.filter((part) => part.score !== null) - const totalWeight = available.reduce((sum, part) => sum + part.weight, 0) - const components: Array = parts.map((part) => ({ - key: part.key, - score: part.score, - weight: part.weight, - effectiveWeight: part.score === null || totalWeight === 0 ? 0 : (part.weight / totalWeight) * 100, - excluded: part.score === null, - why: part.why, - })) - const onlySignals = available.every((part) => part.key === "signals") - if (!inputs.customer || onlySignals || totalWeight === 0) { - return { score: null, status: "unknown", components } - } - const score = Math.round( - components.reduce((sum, part) => sum + (part.effectiveWeight / 100) * (part.score ?? 0), 0), - ) - return { score, status: bandOf(score, settings.bands), components } -} diff --git a/apps/backend/src/worker/objects/customers/ingest.ts b/apps/backend/src/worker/objects/customers/ingest.ts index 394c0181b..8b0754cc4 100644 --- a/apps/backend/src/worker/objects/customers/ingest.ts +++ b/apps/backend/src/worker/objects/customers/ingest.ts @@ -82,7 +82,7 @@ export interface CustomerIngestApi { * Close a run (or record a retryable failure on it) and update its connection (`lastSuccessAt`, set * to the run's start as the next pull's watermark, or `lastErrorAt`; `consecutiveFailures`). A * successful `backfill` sets `backfilledAt` and arms the silent baseline evaluation - * (`docs/customers/tech-design.md` §4.7); the connection's first one also rebuilds the daily + * (`docs/customers/tech-design.md` §4.6); the connection's first one also rebuilds the daily * history. */ readonly finishRun: (runId: CustomerSyncRunId, result: RunResult) => Effect.Effect diff --git a/apps/backend/src/worker/objects/customers/integration-tests/clerk.ingest.test.ts b/apps/backend/src/worker/objects/customers/integration-tests/clerk.ingest.test.ts index 3eba0f036..ee6bd6ac2 100644 --- a/apps/backend/src/worker/objects/customers/integration-tests/clerk.ingest.test.ts +++ b/apps/backend/src/worker/objects/customers/integration-tests/clerk.ingest.test.ts @@ -437,7 +437,7 @@ describe("Clerk ops through CustomerIngest", () => { cursor = page.nextCursor } while (cursor !== null) expect(world.rows(`SELECT count(*) AS n FROM customer_unmatched_records`)).toEqual([{ n: 0 }]) - // A paying customer: leads get no health score. + // A paying customer. yield* world.ingest("stripe", [ { _tag: "subscription", @@ -458,11 +458,6 @@ describe("Clerk ops through CustomerIngest", () => { ]) yield* world.object.run(runCompute(now)).pipe(Effect.orDie) - const [account] = world.rows<{ healthStatus: string; healthScore: number | null }>( - `SELECT healthStatus, healthScore FROM customer_accounts`, - ) - expect(account!.healthStatus).not.toBe("critical") - expect(account!.healthScore).not.toBeNull() expect( world.rows( `SELECT template FROM customer_signals diff --git a/apps/backend/src/worker/objects/customers/integration-tests/maple.ingest.test.ts b/apps/backend/src/worker/objects/customers/integration-tests/maple.ingest.test.ts index e029e7e0f..155fee5b0 100644 --- a/apps/backend/src/worker/objects/customers/integration-tests/maple.ingest.test.ts +++ b/apps/backend/src/worker/objects/customers/integration-tests/maple.ingest.test.ts @@ -3,8 +3,8 @@ * on node SQLite: a day of product events has to land on the Clerk contacts of the Clerk account * its `GroupId` names, a group Clerk does not hold has to wait in the unmatched list instead of * becoming a customer, a mapped event has to become a metric only Maple may write — and a world - * where Clerk and Maple are the only sources has to come out with a health score and a - * `usage_drop` signal when the usage falls away. + * where Clerk and Maple are the only sources has to come out with a `usage_drop` signal when the + * usage falls away. */ import type { IngestOp } from "@hazel/domain/customers" import { Effect, type Scope } from "effect" @@ -73,8 +73,8 @@ const DROPPING: ReadonlyArray = [ ] const accounts = (world: CustomersWorld) => - world.rows<{ name: string; activeUsers30d: number; healthStatus: string; healthScore: number | null }>( - `SELECT name, activeUsers30d, healthStatus, healthScore FROM customer_accounts + world.rows<{ name: string; activeUsers30d: number }>( + `SELECT name, activeUsers30d FROM customer_accounts WHERE deletedAt IS NULL ORDER BY name`, ) @@ -252,7 +252,7 @@ describe("Maple ingest", () => { ) }) - it("computes a health score and opens usage_drop in a Clerk-and-Maple world", async () => { + it("opens usage_drop in a Clerk-and-Maple world", async () => { await run( Effect.gen(function* () { const world = yield* makeCustomersWorld @@ -270,7 +270,7 @@ describe("Maple ingest", () => { ).ops, ), ) - // A paying customer: leads get no health score. + // A paying customer. yield* world.ingest("stripe", [ { _tag: "subscription", @@ -292,9 +292,6 @@ describe("Maple ingest", () => { yield* world.object.run(runCompute(NOW)).pipe(Effect.orDie) const [account] = accounts(world) - // Usage data is live, so health is scored rather than unknown. - expect(account?.healthStatus).not.toBe("unknown") - expect(typeof account?.healthScore).toBe("number") expect(account?.activeUsers30d).toBe(4) const drop = signals(world).find((signal) => signal.template === "usage_drop") diff --git a/apps/backend/src/worker/objects/customers/scoring.test.ts b/apps/backend/src/worker/objects/customers/lifecycle.test.ts similarity index 59% rename from apps/backend/src/worker/objects/customers/scoring.test.ts rename to apps/backend/src/worker/objects/customers/lifecycle.test.ts index 622d53cb9..c7f3f4e15 100644 --- a/apps/backend/src/worker/objects/customers/scoring.test.ts +++ b/apps/backend/src/worker/objects/customers/lifecycle.test.ts @@ -1,26 +1,12 @@ /** - * The pure scoring: health components, weight redistribution and bands (`./health.ts`); the signal - * lifecycle and priority (`./lifecycle.ts`). + * The signal lifecycle and priority (`./lifecycle.ts`). */ -import { DEFAULT_HEALTH_SETTINGS, type SignalEvidence } from "@hazel/domain/customers" +import type { SignalEvidence } from "@hazel/domain/customers" import { describe, expect, it } from "vitest" import type { Match } from "./evaluate" -import { type HealthInputs, maxStep, minStep, scoreHealth } from "./health" import { priorityScore, transition, valueOf } from "./lifecycle" import { accountRow, NOW, signalRow } from "./test-kit" -const inputs = (overrides: Partial = {}): HealthInputs => ({ - customer: true, - hasActivityData: true, - contactCount: 10, - activeUsers30d: 7, - trendPct: 12, - daysSinceActive: 0, - billing: { pastDue: false, overdueOverWeek: false, overdue: false, cancelScheduled: false }, - openRisk: { high: 0, medium: 0, low: 0 }, - ...overrides, -}) - const evidence = (step: 0 | 1 | 2): SignalEvidence => ({ _tag: "last_active", step, @@ -44,79 +30,6 @@ const days = (count: number) => count * 86_400_000 const at = (offsetDays: number) => new Date(NOW.getTime() + days(offsetDays)) const input = { now: NOW, baseline: false, valueMinor: 19_900 } -describe("health score", () => { - it("steps pick the first threshold the value passes", () => { - const steps = DEFAULT_HEALTH_SETTINGS.steps - expect(minStep(steps.usage.activeRatio, 0.7)).toBe(100) - expect(minStep(steps.usage.activeRatio, 0.25)).toBe(50) - expect(minStep(steps.usage.activeRatio, 0)).toBe(0) - expect(maxStep(steps.engagement.daysSinceActive, 0)).toBe(100) - expect(maxStep(steps.engagement.daysSinceActive, 10)).toBe(50) - expect(maxStep(steps.engagement.daysSinceActive, 400)).toBe(0) - }) - - it("a healthy account scores 100 and explains each component", () => { - const result = scoreHealth(inputs(), DEFAULT_HEALTH_SETTINGS) - expect(result).toMatchObject({ score: 100, status: "healthy" }) - expect(result.components.find((part) => part.key === "usage")?.why).toBe( - "7 of 10 contacts active in 30 days; trend +12%", - ) - expect(result.components.every((part) => !part.excluded)).toBe(true) - }) - - it("bands the weighted score", () => { - const result = scoreHealth( - inputs({ - activeUsers30d: 2, - trendPct: -40, - daysSinceActive: 10, - billing: { pastDue: true, overdueOverWeek: true, overdue: true, cancelScheduled: false }, - openRisk: { high: 1, medium: 1, low: 0 }, - }), - DEFAULT_HEALTH_SETTINGS, - ) - // usage 0.6×50 + 0.4×10 = 34; engagement 50; billing 20; signals 55. - expect(result.components.map((part) => part.score)).toEqual([34, 50, 20, 55]) - expect(result.score).toBe(Math.round(0.35 * 34 + 0.25 * 50 + 0.25 * 20 + 0.15 * 55)) - expect(result.status).toBe("critical") - expect(result.components.find((part) => part.key === "billing")?.why).toBe( - "Payment past due; Invoice overdue for over a week", - ) - }) - - it("shares an excluded component's weight across the rest", () => { - const result = scoreHealth(inputs({ billing: null, daysSinceActive: 10 }), DEFAULT_HEALTH_SETTINGS) - const billing = result.components.find((part) => part.key === "billing")! - expect(billing).toMatchObject({ - excluded: true, - score: null, - effectiveWeight: 0, - why: "No subscription", - }) - const weights = result.components.map((part) => part.effectiveWeight) - expect(weights.reduce((sum, weight) => sum + weight, 0)).toBeCloseTo(100) - expect(result.components.find((part) => part.key === "usage")?.effectiveWeight).toBeCloseTo( - (35 / 75) * 100, - ) - expect(result.score).toBe(Math.round((35 / 75) * 100 + (25 / 75) * 50 + (15 / 75) * 100)) - }) - - it("has no score for leads and churned accounts, or with only signals to go on", () => { - expect(scoreHealth(inputs({ customer: false }), DEFAULT_HEALTH_SETTINGS)).toMatchObject({ - score: null, - status: "unknown", - }) - expect( - scoreHealth(inputs({ hasActivityData: false, billing: null }), DEFAULT_HEALTH_SETTINGS), - ).toMatchObject({ - score: null, - status: "unknown", - }) - // A billing-only org still gets a score. - expect(scoreHealth(inputs({ hasActivityData: false }), DEFAULT_HEALTH_SETTINGS).score).toBe(100) - }) -}) - describe("signal lifecycle", () => { it("opens a new match, or records it dismissed in baseline mode", () => { expect(transition(null, matchOf(0), input)).toMatchObject({ diff --git a/apps/backend/src/worker/objects/customers/lifecycle.ts b/apps/backend/src/worker/objects/customers/lifecycle.ts index 61d3ee276..708c336fd 100644 --- a/apps/backend/src/worker/objects/customers/lifecycle.ts +++ b/apps/backend/src/worker/objects/customers/lifecycle.ts @@ -1,5 +1,5 @@ /** - * A signal's lifecycle (`docs/customers/tech-design.md` §4.5–§4.7), pure: what one evaluation does + * A signal's lifecycle (`docs/customers/tech-design.md` §4.4–§4.6), pure: what one evaluation does * to the `(rule, account)` episode, and its priority. * * - open: refreshed while true; auto-resolved (closed) once false. diff --git a/apps/backend/src/worker/objects/customers/read.ts b/apps/backend/src/worker/objects/customers/read.ts index bfd902c9a..b9e352132 100644 --- a/apps/backend/src/worker/objects/customers/read.ts +++ b/apps/backend/src/worker/objects/customers/read.ts @@ -11,7 +11,6 @@ import type { ContactRow, CustomersRange, Day, - HealthDistributionRow, Kpi, MetricSeries, Mover, @@ -20,10 +19,10 @@ import type { NewTrial, OverviewResult, } from "@hazel/domain/customers" -import { HealthStatus, logoOf } from "@hazel/domain/customers" +import { logoOf } from "@hazel/domain/customers" import type { CustomerAccountId, CustomerContactId } from "@hazel/schema" import { Effect, Option } from "effect" -import { type AccountFacts, type HealthPoint, type MetricPoint, mrrSeries, seriesOf } from "./facts" +import { type AccountFacts, type MetricPoint, mrrSeries, seriesOf } from "./facts" import { inList, isActive } from "./sql" import { addDays, dayOf, dayRange } from "@hazel/customer-integrations/kit/time" @@ -267,16 +266,11 @@ export const overview = Effect.fn("Customers.overview")(function* (range: Custom }) } - // Health now, from the accounts. const accounts = yield* db.run( SQLite.from(schema.customerAccountsTable) - .select("id", "name", "logoUrl", "companyProfile", "planName", "mrrMinor", "healthStatus") + .select("id", "name", "logoUrl", "companyProfile", "planName", "mrrMinor") .where(($) => [$.deletedAt.isNull()]), ) - const healthDistribution: Array = HealthStatus.literals.map((status) => { - const rows = accounts.filter((account) => account.healthStatus === status) - return { status, count: rows.length, mrrMinor: rows.reduce((sum, row) => sum + row.mrrMinor, 0) } - }) const accountById = new Map(accounts.map((account) => [account.id, account])) // Movers: average daily active users in the range vs the one before. SQL sums each account's @@ -402,7 +396,6 @@ export const overview = Effect.fn("Customers.overview")(function* (range: Custom }, mrrMovements, activeUsers, - healthDistribution, topMovers: { gainers, decliners }, recentChurn, recentNew, @@ -462,12 +455,6 @@ const accountFacts = (account: schema.CustomerAccount, days: number, now: Date) .where(($) => [$.accountId.eq(account.id)]) .orderBy(($) => [[$.day, "asc"]]), ) - const health = yield* db.run( - SQLite.from(schema.customerHealthDailyTable) - .select("day", "score", "status") - .where(($) => [$.accountId.eq(account.id), $.day.gte(from)]) - .orderBy(($) => [[$.day, "asc"]]), - ) return { account, stage: account.lifecycleStage, @@ -481,7 +468,6 @@ const accountFacts = (account: schema.CustomerAccount, days: number, now: Date) openInvoices: [], metrics: metricMap, movements, - health: health as ReadonlyArray, openIssueSlas: [], } satisfies AccountFacts }) @@ -698,13 +684,6 @@ export const accountDetail = Effect.fn("Customers.accountDetail")(function* ( .where(($) => [$.accountId.eq(account.id), $.status.in_("open", "upcoming")]) .orderBy(($) => [[$.dueAt, "asc"]]), ) - const health = yield* db.first( - SQLite.from(schema.customerHealthDailyTable) - .select() - .where(($) => [$.accountId.eq(account.id)]) - .orderBy(($) => [[$.day, "desc"]]) - .limit(1), - ) const facts = yield* accountFacts(account, 90, now) const contacts = yield* db.run( SQLite.from(schema.customerContactsTable) @@ -743,11 +722,6 @@ export const accountDetail = Effect.fn("Customers.accountDetail")(function* ( subscriptions: [...live, ...subscriptions.filter((sub) => sub.status === "canceled")], upcomingInvoice: invoices.find((invoice) => invoice.status === "upcoming") ?? null, openInvoices: invoices.filter((invoice) => invoice.status === "open"), - health: Option.match(health, { onNone: () => null, onSome: (row) => row.breakdown }), - healthSeries: seriesOf(facts, "health_score", today, 90), - healthScores: facts.health - .filter((point) => point.day > addDays(today, -90)) - .map((point) => ({ day: point.day, score: point.score })), activeUsersSeries: seriesOf(facts, "active_users", today, 30), contactsToReach: yield* contactRows(reach, now), recentEvents: events, @@ -838,15 +812,6 @@ export const sparklines = Effect.fn("Customers.sparklines")(function* ( } break } - case "health_score": { - const rows = yield* db.run( - SQLite.from(schema.customerHealthDailyTable) - .select("accountId", "day", "score") - .where(($) => [inList($.accountId, ids), $.day.gte(from)]), - ) - for (const row of rows) set(row.accountId, row.day, row.score ?? 0) - break - } default: { const rows = yield* db.run( SQLite.from(schema.customerMetricDailyTable) diff --git a/apps/backend/src/worker/objects/customers/schedule.ts b/apps/backend/src/worker/objects/customers/schedule.ts index 103f3b4bc..4c2bfeff2 100644 --- a/apps/backend/src/worker/objects/customers/schedule.ts +++ b/apps/backend/src/worker/objects/customers/schedule.ts @@ -118,7 +118,7 @@ export const baselineConnections = Effect.map(readObjectMeta(BASELINE_KEY), (val Option.match(value, { onNone: (): ReadonlyArray => [], onSome: (ids) => ids.split(",") }), ) -/** The next compute evaluates this connection's templates in baseline mode (§4.7): its backfill finished. */ +/** The next compute evaluates this connection's templates in baseline mode (§4.6): its backfill finished. */ export const setBaselineFor = (connectionId: string) => Effect.gen(function* () { const ids = yield* baselineConnections diff --git a/apps/backend/src/worker/objects/customers/seed.test.ts b/apps/backend/src/worker/objects/customers/seed.test.ts index a8ec46070..b3f7ecc83 100644 --- a/apps/backend/src/worker/objects/customers/seed.test.ts +++ b/apps/backend/src/worker/objects/customers/seed.test.ts @@ -90,7 +90,7 @@ describe("generateDemoSeed", { timeout: 30_000 }, () => { } }) expect(new Set(keys).size).toBe(keys.length) - const builtIn = ["active_users", "active_users_30d", "mrr", "health_score"] + const builtIn = ["active_users", "active_users_30d", "mrr"] expect(opsOf("metric").some(({ op }) => builtIn.includes(op.metricKey))).toBe(false) }) diff --git a/apps/backend/src/worker/objects/customers/seed.ts b/apps/backend/src/worker/objects/customers/seed.ts index 6320f7425..b82ab7852 100644 --- a/apps/backend/src/worker/objects/customers/seed.ts +++ b/apps/backend/src/worker/objects/customers/seed.ts @@ -16,9 +16,8 @@ * Each account gets an archetype that shapes its history so every signal template has matches: * `went_quiet` (inactive), `usage_drop`, `payment_failed`, `cancel_scheduled` and `downgraded` * (cancel_scheduled), `trial_ending_low` (trial_ending_low_activation), `onboarding_stalled`, - * `champion_left` (champion_inactive), `near_limit`, `seat_growth`; `healthy_*`, `trial_healthy`, - * `churned` (a recent few: churned) and `lead` fill out the book (and `health_drop` follows from the - * risky ones). + * `champion_left` (champion_inactive), `near_limit`, `seat_growth`; `steady`, `growing`, + * `trial_engaged`, `churned` (a recent few: churned) and `lead` fill out the book. */ import type { CustomerProvider, @@ -51,15 +50,15 @@ export interface DemoSeedOptions { } export type DemoArchetype = - | "healthy_growing" - | "healthy_stable" + | "growing" + | "steady" | "went_quiet" | "usage_drop" | "payment_failed" | "cancel_scheduled" | "downgraded" | "trial_ending_low" - | "trial_healthy" + | "trial_engaged" | "onboarding_stalled" | "champion_left" | "near_limit" @@ -189,10 +188,10 @@ const tierAbove = (plan: Plan) => TIERS[Math.min(3, TIERS.indexOf(plan as (typeo /** Accounts per archetype in a 200-account book. */ const MIX: ReadonlyArray = [ - ["healthy_stable", 50], - ["healthy_growing", 25], + ["steady", 50], + ["growing", 25], ["lead", 15], - ["trial_healthy", 10], + ["trial_engaged", 10], ["trial_ending_low", 6], ["went_quiet", 10], ["usage_drop", 10], @@ -417,7 +416,7 @@ const archetypeCounts = (total: number): Array => { for (const [index, count] of counts.entries()) { if (count === 0) { counts[index] = 1 - counts[0]-- // from healthy_stable + counts[0]-- // from steady } } } @@ -457,14 +456,14 @@ const weighted = (rng: Rng, options: ReadonlyArray): A const pickPlan = (rng: Rng, archetype: DemoArchetype): Plan => { switch (archetype) { - case "healthy_stable": + case "steady": return weighted(rng, [ [STARTER, 30], [TEAM, 40], [BUSINESS, 22], [ENTERPRISE, 8], ]) - case "healthy_growing": + case "growing": return weighted(rng, [ [TEAM, 40], [BUSINESS, 40], @@ -478,7 +477,7 @@ const pickPlan = (rng: Rng, archetype: DemoArchetype): Plan => { ]) case "seat_growth": return BUSINESS - case "trial_healthy": + case "trial_engaged": case "trial_ending_low": return weighted(rng, [ [TEAM, 60], @@ -576,9 +575,9 @@ const planAccounts = ( list.forEach((contact, i) => (contact.weekdayP = silent ? 0 : i === 0 ? 0.55 : 0.15)) } else { switch (archetype) { - case "trial_healthy": + case "trial_engaged": case "trial_ending_low": { - const endsIn = archetype === "trial_healthy" ? rng.int(7, 13) : rng.int(1, 4) + const endsIn = archetype === "trial_engaged" ? rng.int(7, 13) : rng.int(1, 4) const trialEnd = dayAt(clock, -endsIn) + rng.int(8, 18) * 3_600_000 const trialStartAgo = 14 - endsIn createdAgo = trialStartAgo @@ -589,7 +588,7 @@ const planAccounts = ( trialEndsAt: trialEnd, mrrMinor: 0, }) - if (archetype === "trial_healthy") { + if (archetype === "trial_engaged") { contacts = rng.int(3, 6) tweakContacts = (list) => list.forEach((contact, i) => { @@ -665,7 +664,7 @@ const planAccounts = ( break } case "downgraded": - case "healthy_growing": { + case "growing": { // downgraded: from the tier above, 2–12 days ago; growing: up from the tier below. const changeAgo = archetype === "downgraded" ? rng.int(2, 12) : rng.int(20, 200) const startAgo = Math.min(364, changeAgo + rng.int(45, 300)) @@ -686,17 +685,15 @@ const planAccounts = ( start: change, interval: annual ? "year" : "month", }) - if (archetype === "healthy_growing") - intensity = (ago) => 0.7 + 0.3 * Math.max(0, 1 - ago / 120) + if (archetype === "growing") intensity = (ago) => 0.7 + 0.3 * Math.max(0, 1 - ago / 120) break } default: { - // healthy_stable, went_quiet, usage_drop, champion_left, near_limit, seat_growth - const startAgo = rng.int(archetype === "healthy_stable" ? 30 : 75, 364) + // steady, went_quiet, usage_drop, champion_left, near_limit, seat_growth + const startAgo = rng.int(archetype === "steady" ? 30 : 75, 364) createdAgo = startAgo + rng.int(0, 21) const annual = - archetype === "healthy_stable" && - (plan === ENTERPRISE ? rng.chance(0.8) : rng.chance(0.2)) + archetype === "steady" && (plan === ENTERPRISE ? rng.chance(0.8) : rng.chance(0.2)) sub({ plan, mrrMinor: mrrFor(plan), @@ -775,7 +772,7 @@ const planAccounts = ( const contactList = Array.from({ length: contacts }, (_, i) => { if (i === 0) return { ...newContact(createdAgo, 0.9), isAdmin: true, isBillingContact: true } - const spread = archetype === "healthy_growing" ? rng.next() * 0.9 : rng.next() * 0.4 + const spread = archetype === "growing" ? rng.next() * 0.9 : rng.next() * 0.4 const joinAgo = Math.max(0, createdAgo - Math.floor(createdAgo * spread)) const weekdayP = i <= 2 ? rng.between(0.4, 0.55) : rng.chance(0.1) ? 0 : rng.between(0.08, 0.25) const contact = newContact(joinAgo, weekdayP) @@ -801,7 +798,7 @@ const planAccounts = ( /** The few deliberate data-quality cases: removed members, domain-only billing links, a shared domain. */ const addEdgeCases = (rng: Rng, accounts: Array) => { - const stable = accounts.filter((account) => account.archetype === "healthy_stable") + const stable = accounts.filter((account) => account.archetype === "steady") const leavers = stable .flatMap((account) => account.contacts.filter((contact, i) => i > 0 && contact.joinAgo > 90).slice(0, 1), @@ -1315,10 +1312,7 @@ export const generateDemoSeed = (options: DemoSeedOptions): DemoSeed => { const billed = accounts.filter((account) => account.subs.length > 0) const upcomingFor = new Set( billed - .filter( - (account) => - account.archetype === "healthy_stable" || account.archetype === "healthy_growing", - ) + .filter((account) => account.archetype === "steady" || account.archetype === "growing") .flatMap((account) => account.subs.filter((sub) => sub.end === null)) .sort((a, b) => b.mrrMinor - a.mrrMinor || a.externalId.localeCompare(b.externalId)) .slice(0, 2) diff --git a/apps/backend/src/worker/objects/customers/snapshot.ts b/apps/backend/src/worker/objects/customers/snapshot.ts index e6549e55a..b89d45973 100644 --- a/apps/backend/src/worker/objects/customers/snapshot.ts +++ b/apps/backend/src/worker/objects/customers/snapshot.ts @@ -1,10 +1,10 @@ /** - * Loads what compute and the dry runs evaluate (`./facts.ts`): the org-wide part once + * Loads what compute and the rule dry run evaluate (`./facts.ts`): the org-wide part once * (`loadBase`), then the live accounts in chunks (`loadAccounts`), each with its contacts, - * activity over the window the rules need, billing, metrics, MRR movements and a month of health - * history, plus the account fields compute derives from them (`rollupAccount`, §4.2). A chunk holds - * whole groups of linked accounts (`./groups.ts`): a primary's signals evaluate its group's - * combined facts (`./group-facts.ts`). + * activity over the window the rules need, billing, metrics and MRR movements, plus the account + * fields compute derives from them (`rollupAccount`, §4.2). A chunk holds whole groups of linked + * accounts (`./groups.ts`): a primary's signals evaluate its group's combined facts + * (`./group-facts.ts`). */ import { activityProviders, @@ -19,10 +19,7 @@ import { type CustomerProvider, type Day, ENVIRONMENT_TEMPLATES, - type HealthBreakdown, - type HealthSettings, type LifecycleStage, - MAX_WINDOW_DAYS, type SignalTemplate, } from "@hazel/domain/customers" import type { CustomerAccountId, CustomerContactId, CustomerSubscriptionId } from "@hazel/schema" @@ -34,7 +31,6 @@ import { activeUsersIn, billed, type ContactFacts, - type HealthPoint, type IssueSlaFacts, type MetricPoint, type OrgFacts, @@ -106,15 +102,7 @@ export const evaluatedFor = (accounts: ReadonlyArray) => { export interface SnapshotBase { readonly org: OrgFacts readonly settings: schema.CustomerSettings - readonly health: HealthSettings readonly rules: ReadonlyArray - /** - * Usage data is live: an activity source is connected (not in error or disconnected) and - * delivering, or, with no activity connection at all, some contact was ever active. - */ - readonly hasActivityData: boolean - /** Billing data exists (a billing source, or subscriptions). */ - readonly hasBillingData: boolean /** * The billing sources needing a first import that can count for MRR (it is done, and a run * succeeded since they were last connected), in registry order; each account's source is @@ -139,8 +127,6 @@ export interface Snapshot extends SnapshotBase { readonly accounts: ReadonlyArray /** The accounts' unclosed signals. */ readonly signals: ReadonlyArray - /** Today's stored health breakdowns, so an unchanged one is not written again. */ - readonly todayHealth: ReadonlyMap } const sum = (values: ReadonlyArray) => values.reduce((total, value) => total + value, 0) @@ -398,9 +384,6 @@ export const billingByAccount = ( /** Accounts loaded (and their activity held in memory) at a time. */ const ACCOUNT_CHUNK = 250 -/** Days of health history the rules read (`health_drop`'s window, its 30-day series). */ -const HEALTH_DAYS = MAX_WINDOW_DAYS + 1 - export const accountChunks = (items: ReadonlyArray, size = ACCOUNT_CHUNK) => Array.from({ length: Math.ceil(items.length / size) }, (_, index) => items.slice(index * size, (index + 1) * size), @@ -457,12 +440,6 @@ export const loadBase = Effect.fn("Customers.loadBase")(function* ( .map((connection) => connection.provider) .filter((provider) => !(ACTIVITY_PROVIDERS.has(provider) && stale.has(provider))), ) - const anySubscription = yield* db.first( - SQLite.from(schema.customerSubscriptionsTable) - .select("id") - .where(($) => [inList($.provider, billingProviders)]) - .limit(1), - ) const rules = yield* db.run( SQLite.from(schema.customerSignalRulesTable) .select() @@ -485,15 +462,6 @@ export const loadBase = Effect.fn("Customers.loadBase")(function* ( const definitions = yield* db.run( SQLite.from(schema.customerMetricDefinitionsTable).select("key", "name", "aggregation", "provider"), ) - const activityConnections = connections.filter((connection) => - ACTIVITY_PROVIDERS.has(connection.provider), - ) - const anyActivity = yield* db.first( - SQLite.from(schema.customerContactsTable) - .select("id") - .where(($) => [$.lastActiveDay.isNotNull()]) - .limit(1), - ) return { org: { now, @@ -512,15 +480,7 @@ export const loadBase = Effect.fn("Customers.loadBase")(function* ( attention: settings.attention, }, settings, - health: settings.health, rules, - // Stale rows of a disconnected (or silent) source must not keep decaying everyone's usage score. - hasActivityData: - activityConnections.length > 0 - ? activityConnections.some((connection) => connected.has(connection.provider)) - : Option.isSome(anyActivity), - hasBillingData: - billingProviders.some((provider) => connected.has(provider)) || Option.isSome(anySubscription), // A reconnect keeps what it imported before, stale meanwhile: it counts again once the run the // reconnect started succeeds (`lastSuccessAt`, that run's start, not before `connectedAt`). billingReady: firstImportProviders.filter((provider) => @@ -547,7 +507,7 @@ export const loadBase = Effect.fn("Customers.loadBase")(function* ( } satisfies SnapshotBase }) -/** `ids`' accounts (the live ones) with everything compute and the dry runs evaluate. */ +/** `ids`' accounts (the live ones) with everything compute and the rule dry run evaluate. */ export const loadAccounts = Effect.fn("Customers.loadAccounts")(function* ( base: SnapshotBase, ids: ReadonlyArray, @@ -574,7 +534,7 @@ export const loadAccounts = Effect.fn("Customers.loadAccounts")(function* ( const contactsBy = groupBy(contacts, (contact) => contact.accountId) const activityBy = groupBy(activity, (row) => row.accountId) // The last active day over the live contacts and the activity the rollups count (a removed - // contact's recent days included), so engagement and active users agree. + // contact's recent days included), so it agrees with active users. const lastActiveDayBy = new Map() const seen = (accountId: CustomerAccountId, last: Day | null) => { const current = lastActiveDayBy.get(accountId) @@ -655,17 +615,6 @@ export const loadAccounts = Effect.fn("Customers.loadAccounts")(function* ( .where(($) => [inList($.accountId, ids)]) .orderBy(($) => [[$.day, "asc"]]), ) - const health = yield* db.run( - SQLite.from(schema.customerHealthDailyTable) - .select("accountId", "day", "score", "status") - .where(($) => [inList($.accountId, ids), $.day.gte(addDays(today, -HEALTH_DAYS))]) - .orderBy(($) => [[$.day, "asc"]]), - ) - const todayHealth = yield* db.run( - SQLite.from(schema.customerHealthDailyTable) - .select("accountId", "breakdown") - .where(($) => [inList($.accountId, ids), $.day.eq(today)]), - ) const signals = yield* db.run( SQLite.from(schema.customerSignalsTable) .select() @@ -710,7 +659,6 @@ export const loadAccounts = Effect.fn("Customers.loadAccounts")(function* ( const paidInvoicesBy = groupBy(paidInvoices, (invoice) => invoice.accountId) const metricsBy = groupBy(metrics, (row) => row.accountId) const movementsBy = groupBy(movements, (row) => row.accountId) - const healthBy = groupBy(health, (row) => row.accountId) const issueSlasBy = groupBy(issueSlas, (row) => row.accountId) const snapshots = accounts.map((stored): Omit => { @@ -774,11 +722,6 @@ export const loadAccounts = Effect.fn("Customers.loadAccounts")(function* ( openInvoices: invoicesBy.get(stored.id) ?? [], metrics: metricMap, movements: movementsBy.get(stored.id) ?? [], - health: (healthBy.get(stored.id) ?? []).map((row): HealthPoint => ({ - day: row.day, - score: row.score, - status: row.status, - })), openIssueSlas: (issueSlasBy.get(stored.id) ?? []).map( ({ accountId: _accountId, ...issue }): IssueSlaFacts => issue, ), @@ -878,6 +821,5 @@ export const loadAccounts = Effect.fn("Customers.loadAccounts")(function* ( ...base, accounts: withEvaluated, signals, - todayHealth: new Map(todayHealth.map((row) => [row.accountId, row.breakdown])), } satisfies Snapshot }) diff --git a/apps/backend/src/worker/objects/customers/test-kit.ts b/apps/backend/src/worker/objects/customers/test-kit.ts index a1663a009..dfb398984 100644 --- a/apps/backend/src/worker/objects/customers/test-kit.ts +++ b/apps/backend/src/worker/objects/customers/test-kit.ts @@ -1,6 +1,6 @@ /** - * Test helpers for the Customers area: hand-built facts for the pure parts (evaluation, health, - * lifecycle), and a `CustomersObject` with members over node SQLite for the object tests. + * Test helpers for the Customers area: hand-built facts for the pure parts (evaluation, lifecycle), + * and a `CustomersObject` with members over node SQLite for the object tests. */ import { DEFAULT_ATTENTION_SETTINGS, DEFAULT_CONNECTION_CONFIG } from "@hazel/customer-integrations" import type { schema } from "@hazel/db" @@ -49,9 +49,6 @@ export const accountRow = (overrides: Partial = {}): sch mrrSource: null, trialListMrrMinor: null, trialEndsAt: null, - healthScore: null, - healthStatus: "unknown", - healthUpdatedAt: null, seatsUsed: null, seatsLimit: null, contactCount: 0, @@ -95,7 +92,6 @@ export interface FactsInput { readonly openInvoices?: ReadonlyArray> readonly metrics?: AccountFacts["metrics"] readonly movements?: ReadonlyArray> - readonly health?: AccountFacts["health"] readonly priorActive?: ReadonlyArray readonly openIssueSlas?: AccountFacts["openIssueSlas"] /** Default: a Clerk organization with a Stripe customer. */ @@ -217,7 +213,6 @@ export const factsOf = (input: FactsInput = {}): AccountFacts => { createdAt: NOW, ...movement, })), - health: input.health ?? [], openIssueSlas: input.openIssueSlas ?? [], } } diff --git a/apps/backend/src/worker/objects/effects/customers-effects.ts b/apps/backend/src/worker/objects/effects/customers-effects.ts index edc7039d4..ca6adf704 100644 --- a/apps/backend/src/worker/objects/effects/customers-effects.ts +++ b/apps/backend/src/worker/objects/effects/customers-effects.ts @@ -111,7 +111,6 @@ const CUSTOMER_DATA: ReadonlyArray[0]> = [ schema.customerEventsTable, schema.customerMrrMovementsTable, schema.customerSignalsTable, - schema.customerHealthDailyTable, schema.customerNotesTable, schema.customerSyncRunsTable, schema.customerUnmatchedRecordsTable, diff --git a/apps/backend/src/worker/objects/org/channel-customers.ts b/apps/backend/src/worker/objects/org/channel-customers.ts index 3949c65be..0af61f5bd 100644 --- a/apps/backend/src/worker/objects/org/channel-customers.ts +++ b/apps/backend/src/worker/objects/org/channel-customers.ts @@ -6,12 +6,12 @@ * exists here, can be linked (a public or private channel, not a thread or a DM) and is visible * to the person linking it (`channel_access`). * - `org.setChannelCustomers` (effect): the customers object's full, versioned snapshot of its - * links (channel → the account's id, name and its glance: health, MRR, signals…), replacing + * links (channel → the account's id, name and its glance: MRR, signals…), replacing * `channel_customers`. Chat reads it to show a * channel's customer to the org's members who see the channel (never to Connect guests). */ import { Database, SQLite, schema } from "@hazel/db" -import { CompanyProfile, HealthStatus, LifecycleStage } from "@hazel/domain/customers" +import { CompanyProfile, LifecycleStage } from "@hazel/domain/customers" import { ChannelCustomer } from "@hazel/domain/models" import { ChannelId, CustomerAccountId, OrganizationId, UserId } from "@hazel/schema" import { Clock, Effect, Option, Schema } from "effect" @@ -80,9 +80,6 @@ export const customerChannel = Effect.fn("OrgObject.customerChannel")(function* * these fields existed still applies (and the next one, whose fingerprint differs, fills them). */ const glance = { - healthStatus: Schema.optionalKey(HealthStatus), - healthScore: Schema.optionalKey(Schema.NullOr(Schema.Int)), - healthWhy: Schema.optionalKey(Schema.NullOr(Schema.String)), lifecycleStage: Schema.optionalKey(Schema.NullOr(LifecycleStage)), planName: Schema.optionalKey(Schema.NullOr(Schema.String)), mrrMinor: Schema.optionalKey(Schema.NullOr(Schema.Int)), @@ -114,9 +111,6 @@ const rowValuesOf = (link: ChannelCustomerEntry) => ({ accountName: link.accountName, accountLogoUrl: link.accountLogoUrl ?? null, company: link.company ?? null, - healthStatus: link.healthStatus ?? "unknown", - healthScore: link.healthScore ?? null, - healthWhy: link.healthWhy ?? null, lifecycleStage: link.lifecycleStage ?? null, planName: link.planName ?? null, mrrMinor: link.mrrMinor ?? null, diff --git a/apps/ios-hybrid/fixture/snapshot.ts b/apps/ios-hybrid/fixture/snapshot.ts index 8a9ea9f64..987f9b240 100644 --- a/apps/ios-hybrid/fixture/snapshot.ts +++ b/apps/ios-hybrid/fixture/snapshot.ts @@ -250,9 +250,6 @@ const customerRow = ( accountId: uuid(12, n), accountName, accountLogoUrl, - healthStatus: "healthy", - healthScore: null, - healthWhy: null, lifecycleStage: null, planName: null, mrrMinor: null, diff --git a/apps/ios-hybrid/web/look.ts b/apps/ios-hybrid/web/look.ts index eff3d66ee..5d1d0cc0b 100644 --- a/apps/ios-hybrid/web/look.ts +++ b/apps/ios-hybrid/web/look.ts @@ -260,7 +260,9 @@ export const lookOf = ( else if (icon instanceof HTMLImageElement) { // A customer's logo. Loaded or not: the shell loads pictures itself (`ImageLoader.swift`). const src = icon.currentSrc || icon.src - look.icon.avatar = { bg: hex(style.backgroundColor), ...(src === "" ? {} : { src }) } + const avatar: AvatarLook = { bg: hex(style.backgroundColor) } + if (src !== "") avatar.src = src + look.icon.avatar = avatar } else if ( channelIcon !== null && !(icon instanceof SVGElement) && @@ -268,10 +270,9 @@ export const lookOf = ( ) { // A customer without a logo: its initial on its tint (`companyLogo`). const char = icon.textContent?.trim() ?? "" - look.icon.avatar = { - bg: hex(style.backgroundColor), - ...(char === "" ? {} : { initial: { ...textOf(icon), char } }), - } + const avatar: AvatarLook = { bg: hex(style.backgroundColor) } + if (char !== "") avatar.initial = { ...textOf(icon), char } + look.icon.avatar = avatar } else { const key = iconKey(icon) if (key !== undefined) look.icon.image = key diff --git a/apps/raycast/README.md b/apps/raycast/README.md index cae5f2b4d..5af636385 100644 --- a/apps/raycast/README.md +++ b/apps/raycast/README.md @@ -1,7 +1,7 @@ # Hazel for Raycast -Search your organization's customers from Raycast: health, MRR, open risks and billing at a glance, -then jump to the customer's channel, their page in Hazel, or their record in Clerk, Stripe, Autumn or +Search your organization's customers from Raycast: MRR, open risks and billing at a glance, then +jump to the customer's channel, their page in Hazel, or their record in Clerk, Stripe, Autumn or Maple. **Search Customers** opens on the cached list at once, then the chosen organization's list catches up diff --git a/apps/raycast/package.json b/apps/raycast/package.json index 635056d81..ab77f5560 100644 --- a/apps/raycast/package.json +++ b/apps/raycast/package.json @@ -2,7 +2,7 @@ "$schema": "https://www.raycast.com/schemas/extension.json", "name": "hazel", "private": true, - "description": "Search your Hazel customers, see their health and billing, and jump to their channel, Clerk, Stripe or Autumn.", + "description": "Search your Hazel customers, see their billing and open risks, and jump to their channel, Clerk, Stripe or Autumn.", "categories": [ "Communication", "Productivity" diff --git a/apps/raycast/src/customer-detail.tsx b/apps/raycast/src/customer-detail.tsx index 01efa1532..6f15d3a4f 100644 --- a/apps/raycast/src/customer-detail.tsx +++ b/apps/raycast/src/customer-detail.tsx @@ -1,7 +1,7 @@ import { Color, Detail, Icon } from "@raycast/api" import { usePromise } from "@raycast/utils" import { CustomerActions, channelUrl, providerLinks } from "./customer-actions" -import { HEALTH, STAGE, SOURCE, date, httpsUrl, md, money, relative } from "./lib/format" +import { STAGE, SOURCE, date, httpsUrl, md, money, relative } from "./lib/format" import type { Account, AccountDetail, ChannelLink, Organization, Signal } from "./lib/models" import { call } from "./lib/rpc" @@ -10,25 +10,17 @@ export const fetchDetail = (organizationId: string, accountId: string) => call("customers.account.detail", { organizationId, accountId }) const SEVERITY_ICON = { high: "🔴", medium: "🟠", low: "🟡" } as const -const HEALTH_LABEL = { - usage: "Usage", - engagement: "Engagement", - billing: "Billing", - signals: "Signals", -} as const -/** The page: what needs attention first, then health, billing, who to reach and what happened. */ +/** The page: what needs attention first, then billing, who to reach and what happened. */ export const detailMarkdown = ( account: Account, signals: ReadonlyArray, detail: AccountDetail | undefined, ) => { - const health = HEALTH[account.healthStatus] const lines: Array = [ `# ${md(account.name)}`, [ - `**${health.label}${account.healthScore === null ? "" : ` · ${account.healthScore}`}**`, - STAGE[account.lifecycleStage], + `**${STAGE[account.lifecycleStage]}**`, account.planName === null ? null : md(account.planName), account.mrrMinor > 0 ? `${money(account.mrrMinor, account.currency)}/mo` : null, ] @@ -78,21 +70,6 @@ export const detailMarkdown = ( } } - const components = detail.health?.components ?? [] - if (components.length > 0) { - lines.push( - "## Health", - [ - "| | Score | Why |", - "| --- | --- | --- |", - ...components.map( - (component) => - `| ${HEALTH_LABEL[component.key]} | ${component.excluded || component.score === null ? "—" : component.score} | ${md(component.why)} |`, - ), - ].join("\n"), - ) - } - if (detail.contactsToReach.length > 0) { lines.push("## Who to reach") for (const { contact, status } of detail.contactsToReach) { @@ -138,7 +115,6 @@ export function CustomerDetail(props: { failureToastOptions: { title: "Could not load the customer" }, }) const account = detail.data?.account ?? props.account - const health = HEALTH[account.healthStatus] const trend = account.activeUsersTrendPct return ( - - - {account.environment && ( )} diff --git a/apps/raycast/src/customers.tsx b/apps/raycast/src/customers.tsx index 8bded2519..65808c023 100644 --- a/apps/raycast/src/customers.tsx +++ b/apps/raycast/src/customers.tsx @@ -3,7 +3,7 @@ import { useCachedState, usePromise } from "@raycast/utils" import { useEffect, useMemo, useState } from "react" import { CustomerActions, SignOutAction } from "./customer-actions" import { CustomerDetail, accountIcon, fetchDetail } from "./customer-detail" -import { HEALTH, STAGE, money, relative, risk } from "./lib/format" +import { STAGE, money, relative, risk } from "./lib/format" import type { Account, ChannelLink, Signal } from "./lib/models" import { useCustomers } from "./lib/use-customers" @@ -42,7 +42,6 @@ const groupEnvironments = (accounts: ReadonlyArray): ReadonlyArray => { const open = risk(account) - const health = HEALTH[account.healthStatus] return [ ...(account.environment ? [{ tag: account.environment, tooltip: "Environment" }] : []), ...(open.count > 0 @@ -58,13 +57,6 @@ const accessories = (account: Account): Array => { ...(account.mrrMinor > 0 ? [{ text: money(account.mrrMinor, account.currency), tooltip: "MRR" }] : []), - { - tag: { - value: account.healthScore === null ? health.label : `${account.healthScore}`, - color: health.color, - }, - tooltip: `Health: ${health.label}`, - }, ] } diff --git a/apps/raycast/src/lib/format.ts b/apps/raycast/src/lib/format.ts index de08fea91..e7ab236f5 100644 --- a/apps/raycast/src/lib/format.ts +++ b/apps/raycast/src/lib/format.ts @@ -1,5 +1,5 @@ import { Color, Icon } from "@raycast/api" -import type { CustomerSource, HealthStatus, LifecycleStage } from "./models" +import type { CustomerSource, LifecycleStage } from "./models" /** An amount in minor units (cents; whole yen) as currency. */ export const money = (minor: number, currency: string) => { @@ -56,13 +56,6 @@ export const httpsUrl = (url: string | null) => { export const date = (iso: string) => new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" }) -export const HEALTH = { - healthy: { label: "Healthy", color: Color.Green }, - at_risk: { label: "At risk", color: Color.Orange }, - critical: { label: "Critical", color: Color.Red }, - unknown: { label: "No score", color: Color.SecondaryText }, -} satisfies Record - export const STAGE = { lead: "Lead", trialing: "Trialing", diff --git a/apps/raycast/src/lib/models.ts b/apps/raycast/src/lib/models.ts index d63f0911a..6678da24f 100644 --- a/apps/raycast/src/lib/models.ts +++ b/apps/raycast/src/lib/models.ts @@ -4,7 +4,6 @@ * the extension builds on its own. */ -export type HealthStatus = "healthy" | "at_risk" | "critical" | "unknown" export type LifecycleStage = "lead" | "trialing" | "active" | "past_due" | "churned" export type CustomerSource = "clerk" | "stripe" | "autumn" | "maple" | "hazel" @@ -25,8 +24,6 @@ export interface Account { readonly mrrMinor: number readonly currency: string readonly trialEndsAt: string | null - readonly healthScore: number | null - readonly healthStatus: HealthStatus readonly seatsUsed: number | null readonly seatsLimit: number | null readonly contactCount: number @@ -110,13 +107,6 @@ export interface ContactRow { readonly status: "active" | "dormant" | "never_active" } -export interface HealthComponent { - readonly key: "usage" | "engagement" | "billing" | "signals" - readonly score: number | null - readonly excluded: boolean - readonly why: string -} - export interface TimelineEvent { readonly id: string readonly provider: CustomerSource @@ -131,11 +121,6 @@ export interface AccountDetail { readonly subscriptions: ReadonlyArray readonly upcomingInvoice: Invoice | null readonly openInvoices: ReadonlyArray - readonly health: { - readonly score: number | null - readonly status: HealthStatus - readonly components: ReadonlyArray - } | null readonly contactsToReach: ReadonlyArray readonly recentEvents: ReadonlyArray } diff --git a/apps/raycast/src/lib/protocol.test.ts b/apps/raycast/src/lib/protocol.test.ts index 61fe43025..7904155c0 100644 --- a/apps/raycast/src/lib/protocol.test.ts +++ b/apps/raycast/src/lib/protocol.test.ts @@ -6,7 +6,6 @@ const account = (id: string, name: string) => ({ name, domains: [`${name.toLowerCase()}.com`], mrrMinor: 1200, - healthStatus: "healthy", // Columns the extension does not keep. attributes: { plan: "pro" }, fieldSources: { name: "clerk" }, diff --git a/apps/raycast/src/lib/protocol.ts b/apps/raycast/src/lib/protocol.ts index 2d2488168..b1a00d99b 100644 --- a/apps/raycast/src/lib/protocol.ts +++ b/apps/raycast/src/lib/protocol.ts @@ -34,8 +34,6 @@ const ACCOUNT_KEYS = [ "mrrMinor", "currency", "trialEndsAt", - "healthScore", - "healthStatus", "seatsUsed", "seatsLimit", "contactCount", diff --git a/apps/web-foldkit/DESIGN-RULES.md b/apps/web-foldkit/DESIGN-RULES.md index 5430df145..4ddce04ee 100644 --- a/apps/web-foldkit/DESIGN-RULES.md +++ b/apps/web-foldkit/DESIGN-RULES.md @@ -41,7 +41,7 @@ owner in `src/ui`, and a page never redraws it with its own class string or loca | An unread count on a row or tab | `countBadge` (ui/count-badge) | | A hairline between blocks | `separator` (ui/separator) | -Domain views (a customer's health badge, a company logo) live with their feature, built from these. +Domain views (a lifecycle stage badge, a company logo) live with their feature, built from these. If the kit lacks what you need, add the variant or option to the kit component and use it. That is the whole point: the next page gets it for free, and a design change lands in one place. diff --git a/apps/web-foldkit/src/assistant/context.test.ts b/apps/web-foldkit/src/assistant/context.test.ts index 7dc869400..4fac69853 100644 --- a/apps/web-foldkit/src/assistant/context.test.ts +++ b/apps/web-foldkit/src/assistant/context.test.ts @@ -64,7 +64,7 @@ describe("routeContextOf", () => { describe("suggestionsFor", () => { test("adapts the chips to the page", () => { const customer = customerContext("hazel", { id: accountId, name: "Acme" }, "overview") - expect(suggestionsFor(customer)).toContain("Summarize this customer's health") + expect(suggestionsFor(customer)).toContain("Summarize this customer") expect(suggestionsFor(channelContext("hazel", { id: channelId, name: "general" }))).toContain( "Summarize this channel", ) diff --git a/apps/web-foldkit/src/assistant/context.ts b/apps/web-foldkit/src/assistant/context.ts index d17031100..e80ea45cc 100644 --- a/apps/web-foldkit/src/assistant/context.ts +++ b/apps/web-foldkit/src/assistant/context.ts @@ -86,7 +86,7 @@ export const channelContext = ( }) const CUSTOMER_SUGGESTIONS = [ - "Summarize this customer's health", + "Summarize this customer", "What should we follow up on?", "Draft talking points for a call", ] diff --git a/apps/web-foldkit/src/assistant/update.test.ts b/apps/web-foldkit/src/assistant/update.test.ts index 392c95aac..6bfa505b6 100644 --- a/apps/web-foldkit/src/assistant/update.test.ts +++ b/apps/web-foldkit/src/assistant/update.test.ts @@ -51,7 +51,7 @@ const thread = (overrides: Partial = {}): ThreadRow => ({ id: threadId, ownerId: ada, ownerName: "Ada Lovelace", - title: "Acme's health", + title: "Acme summary", visibility: "private", status: "idle", errorMessage: null, @@ -178,9 +178,9 @@ describe("a new chat", () => { test("a suggestion sends at once and keeps what the member typed", () => { const typed = run(opened, Message.ChangedDraft({ value: "half a thought" })).model - const result = run(typed, Message.ClickedSuggestion({ text: "Summarize this customer's health" })) + const result = run(typed, Message.ClickedSuggestion({ text: "Summarize this customer" })) expect(result.model.draft).toBe("half a thought") - expect(pendingOf(result.model)?.text).toBe("Summarize this customer's health") + expect(pendingOf(result.model)?.text).toBe("Summarize this customer") }) test("the context chip turned off sends without context, for that message only", () => { diff --git a/apps/web-foldkit/src/core/styles/theme.css b/apps/web-foldkit/src/core/styles/theme.css index a0ad2f39b..399282c58 100644 --- a/apps/web-foldkit/src/core/styles/theme.css +++ b/apps/web-foldkit/src/core/styles/theme.css @@ -378,10 +378,10 @@ } /* - * Customers: chart, health and severity colors (Wonder "Maple Design System" › Foundations › Color - * Token Reference). Chart hues fill marks only; text never takes a chart color, and every color is - * paired with a label or legend. Health and severity reuse the chart hues for marks (bars, legend - * squares, dots in charts); badges keep the semantic `*-subtle` pairs. + * Customers: chart and severity colors (Wonder "Maple Design System" › Foundations › Color Token + * Reference). Chart hues fill marks only; text never takes a chart color, and every color is paired + * with a label or legend. Severity marks reuse the semantic tokens badges use (`*-subtle-fg`, + * `muted-fg`, `secondary`). */ @theme inline { --color-chart-new: var(--chart-new); @@ -395,11 +395,6 @@ --color-chart-grid: var(--chart-grid); --color-chart-net: var(--chart-net); - --color-health-healthy: var(--health-healthy); - --color-health-at-risk: var(--health-at-risk); - --color-health-critical: var(--health-critical); - --color-health-unknown: var(--health-unknown); - --color-severity-high: var(--severity-high); --color-severity-medium: var(--severity-medium); --color-severity-low: var(--severity-low); @@ -429,11 +424,6 @@ --chart-grid: var(--border); --chart-net: var(--fg); - --health-healthy: var(--chart-new); - --health-at-risk: var(--chart-contraction); - --health-critical: var(--chart-churn); - --health-unknown: var(--chart-neutral); - --severity-high: var(--danger-subtle-fg); --severity-medium: var(--warning-subtle-fg); --severity-low: var(--muted-fg); diff --git a/apps/web-foldkit/src/customers/charts/distribution.ts b/apps/web-foldkit/src/customers/charts/distribution.ts index 1f44211db..39d8a5b53 100644 --- a/apps/web-foldkit/src/customers/charts/distribution.ts +++ b/apps/web-foldkit/src/customers/charts/distribution.ts @@ -1,18 +1,9 @@ -import type { HealthBands, HealthDistributionRow, HealthStatus } from "@hazel/domain/customers" import type { Html, HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" -import { formatCount, formatMoney, formatPct } from "../format" -import { HEALTH_FILL, HEALTH_LABEL } from "../ui/badges" -import { segmented } from "../../ui/segmented-control" -import { chartCard } from "./frame" -/** - * A segmented 100% bar and its legend table (Foundations › Distribution Bar Health), in HTML. - */ +type DistributionSegment = Readonly<{ key: string; label: string; value: number; fillClass: string }> -export type DistributionSegment = Readonly<{ key: string; label: string; value: number; fillClass: string }> - -/** Segments sized by share; zero segments are left out. */ +/** A segmented 100% bar, in HTML: segments sized by share, zero segments left out. */ export const distributionBar = ( h: HtmlBuilder, options: Readonly<{ @@ -50,142 +41,3 @@ export const distributionBar = ( ), ) } - -/** Share of `value` in `total`, as a whole percent (`0%` of nothing). */ -export const shareOf = (value: number, total: number): number => - total === 0 ? 0 : Math.round((value / total) * 100) - -export type HealthMetric = "customers" | "mrr" - -const ORDER: ReadonlyArray = ["healthy", "at_risk", "critical", "unknown"] - -const bandText = (status: HealthStatus, bands: HealthBands): string => - status === "healthy" - ? `≥ ${bands.healthyMin}` - : status === "at_risk" - ? `${bands.atRiskMin}–${bands.healthyMin - 1}` - : status === "critical" - ? `< ${bands.atRiskMin}` - : "No data" - -/** The overview's health card: bar by customers or MRR, then status · band · customers · MRR · share. */ -export const healthDistribution = ( - h: HtmlBuilder, - options: Readonly<{ - rows: ReadonlyArray - bands: HealthBands - currency: string - metric: HealthMetric - onMetric: (metric: HealthMetric) => M - className?: string - }>, -): Html => { - const byStatus = new Map(options.rows.map((row) => [row.status, row])) - const rows = ORDER.map((status) => byStatus.get(status) ?? { status, count: 0, mrrMinor: 0 }) - const valueOf = (row: HealthDistributionRow) => - options.metric === "customers" ? row.count : row.mrrMinor - const total = rows.reduce((sum, row) => sum + valueOf(row), 0) - const customers = rows.reduce((sum, row) => sum + row.count, 0) - const mrr = rows.reduce((sum, row) => sum + row.mrrMinor, 0) - const cell = (text: string, className = "") => - h.td([h.Class(twMerge("py-2 pl-3 text-right tabular-nums whitespace-nowrap", className))], [text]) - return chartCard( - h, - { - title: "Health distribution", - description: `${formatCount(customers)} customers · ${formatMoney(mrr, options.currency)} MRR`, - aside: segmented(h, { - ariaLabel: "Measure health by", - segments: [ - { key: "customers", label: "Customers" }, - { key: "mrr", label: "MRR" }, - ], - selected: options.metric, - onSelect: options.onMetric, - }), - className: options.className, - }, - [ - distributionBar(h, { - ariaLabel: rows - .map((row) => `${HEALTH_LABEL[row.status]} ${shareOf(valueOf(row), total)}%`) - .join(", "), - segments: rows.map((row) => ({ - key: row.status, - label: HEALTH_LABEL[row.status], - value: valueOf(row), - fillClass: HEALTH_FILL[row.status], - })), - }), - h.table( - [h.Class("w-full text-sm")], - [ - h.thead( - [], - [ - h.tr( - [ - h.Class( - "border-border border-b font-medium text-muted-fg text-xs [&>th]:font-medium", - ), - ], - [ - h.th([h.Class("py-2 text-left font-normal")], ["Status"]), - h.th( - [h.Class("py-2 pl-3 text-right font-normal")], - [ - h.span([h.Class("max-sm:hidden")], ["Customers"]), - h.span([h.Class("sm:hidden")], ["Count"]), - ], - ), - h.th([h.Class("py-2 pl-3 text-right font-normal")], ["MRR"]), - h.th([h.Class("py-2 pl-3 text-right font-normal")], ["Share"]), - ], - ), - ], - ), - h.tbody( - [], - rows.map((row) => - h.tr( - [], - [ - h.td( - [h.Class("py-2")], - [ - h.span( - [h.Class("inline-flex items-center gap-2 whitespace-nowrap")], - [ - h.span([ - h.Class( - twMerge( - "size-2.5 rounded-xs", - HEALTH_FILL[row.status], - ), - ), - ]), - h.span([h.Class("text-fg")], [HEALTH_LABEL[row.status]]), - h.span( - // A phone keeps the table in the card; the bands are in Settings › Health. - [h.Class("text-muted-fg text-xs max-sm:hidden")], - [bandText(row.status, options.bands)], - ), - ], - ), - ], - ), - cell(formatCount(row.count), "text-fg"), - cell(formatMoney(row.mrrMinor, options.currency), "text-fg"), - cell( - formatPct(shareOf(valueOf(row), total), { digits: 0 }), - "text-muted-fg", - ), - ], - ), - ), - ), - ], - ), - ], - ) -} diff --git a/apps/web-foldkit/src/customers/customers.gallery.ts b/apps/web-foldkit/src/customers/customers.gallery.ts index 5c3a4e31e..e7f5f70cb 100644 --- a/apps/web-foldkit/src/customers/customers.gallery.ts +++ b/apps/web-foldkit/src/customers/customers.gallery.ts @@ -18,12 +18,10 @@ import { ACTIVITY_ERROR_AT, NOW, OPEN_ENTRIES, - SETTINGS, INVOICES_PROGRESS, memberOf, overviewFixture, } from "../lab/fixtures/customers" -import { healthDistribution } from "./charts/distribution" import { chartCard, chartLegend } from "./charts/frame" import { ACTIVE_USERS_LEGEND, activeUsersChart } from "./charts/line-chart" import { sparkline } from "./charts/sparkline" @@ -36,7 +34,7 @@ import { formatPct, formatRelative, } from "./format" -import { healthBadge, healthDot, kindChip, severityChip, stageBadge } from "./ui/badges" +import { kindChip, severityChip, stageBadge } from "./ui/badges" import { connectCard } from "./ui/connect-card" import { dataTable, primaryCell } from "../ui/data-table" import { allClearState } from "./ui/empty-states" @@ -148,11 +146,6 @@ const badges = (h: HtmlBuilder) => h.div( [h.Class("flex flex-wrap items-center gap-2")], [ - healthBadge(h, { status: "healthy", score: 82 }), - healthBadge(h, { status: "at_risk", score: 54 }), - healthBadge(h, { status: "critical", score: 27 }), - healthBadge(h, { status: "unknown", score: null }), - healthDot(h, { status: "healthy", score: 82 }), severityChip(h, "high"), severityChip(h, "medium"), severityChip(h, "low"), @@ -169,7 +162,7 @@ const badges = (h: HtmlBuilder) => const charts = (h: HtmlBuilder) => h.div( - [h.Class("grid grid-cols-[1fr_1fr_24rem] gap-4")], + [h.Class("grid grid-cols-2 gap-4")], [ chartCard( h, @@ -204,13 +197,6 @@ const charts = (h: HtmlBuilder) => }), ], ), - healthDistribution(h, { - rows: overview.healthDistribution, - bands: SETTINGS.health.bands, - currency: "USD", - metric: "customers", - onMetric: () => ignored, - }), ], ) @@ -250,13 +236,6 @@ const table = (h: HtmlBuilder) => widthClass: "w-28", cell: (account) => formatMoney(account.mrrMinor), }, - { - key: "health", - label: "Health", - widthClass: "w-32", - cell: (account) => - healthBadge(h, { status: account.healthStatus, score: account.healthScore }), - }, { key: "last", label: "Last active", @@ -298,7 +277,6 @@ const queue = (h: HtmlBuilder) => evidence: evidenceViz(h, signal.evidence), age: formatRelative(signal.openedAt, NOW).replace(" ago", ""), assignee: memberOf(signal.assigneeUserId), - health: { status: account.healthStatus, score: account.healthScore }, isFocused: index === 1, actions: [ queueAction(h, { label: "Assign", icon: IconUser(h), onPress: ignored }), diff --git a/apps/web-foldkit/src/customers/format.test.ts b/apps/web-foldkit/src/customers/format.test.ts index 3d9dd621f..1273a8d5e 100644 --- a/apps/web-foldkit/src/customers/format.test.ts +++ b/apps/web-foldkit/src/customers/format.test.ts @@ -92,7 +92,6 @@ describe("numbers", () => { expect(formatDeltaPct(-38)).toBe("−38%") expect(formatDeltaPct(0, { digits: 1 })).toBe("0%") expect(formatDeltaPoints(0.9)).toBe("+0.9 pt") - expect(formatDeltaPoints(-20, "pts")).toBe("−20 pts") }) it("reads a delta's tone from the metric's good direction", () => { diff --git a/apps/web-foldkit/src/customers/format.ts b/apps/web-foldkit/src/customers/format.ts index f2e0336c9..b68e0a733 100644 --- a/apps/web-foldkit/src/customers/format.ts +++ b/apps/web-foldkit/src/customers/format.ts @@ -146,9 +146,9 @@ export const formatPct = (value: number, options: Readonly<{ digits?: number }> export const formatDeltaPct = (value: number, options: Readonly<{ digits?: number }> = {}): string => withSign(value, `${percentNumber(value, options.digits)}%`, true) -/** A change in percentage points (or score points): `+0.9 pt`, `−20 pts`. */ -export const formatDeltaPoints = (value: number, unit: "pt" | "pts" = "pt"): string => - withSign(value, `${percentNumber(value)} ${unit}`, true) +/** A change in percentage points: `+0.9 pt`. */ +export const formatDeltaPoints = (value: number): string => + withSign(value, `${percentNumber(value)} pt`, true) /** Signed count: `+12`, `−3`. */ export const formatDeltaCount = (value: number): string => withSign(value, formatCount(Math.abs(value)), true) diff --git a/apps/web-foldkit/src/customers/queries.ts b/apps/web-foldkit/src/customers/queries.ts index 9cc6ddaff..7ddafa58c 100644 --- a/apps/web-foldkit/src/customers/queries.ts +++ b/apps/web-foldkit/src/customers/queries.ts @@ -54,8 +54,6 @@ export const AccountRow = Schema.Struct({ currency: Schema.String, trialListMrrMinor: Schema.NullOr(Schema.Int), trialEndsAtMs: Schema.NullOr(Schema.Finite), - healthScore: Schema.NullOr(Schema.Int), - healthStatus: Customers.HealthStatus, seatsUsed: Schema.NullOr(Schema.Int), seatsLimit: Schema.NullOr(Schema.Int), contactCount: Schema.Int, @@ -168,8 +166,6 @@ export const toAccountRow = (account: Customers.Account): AccountRow => ({ currency: account.currency, trialListMrrMinor: account.trialListMrrMinor, trialEndsAtMs: msOrNull(account.trialEndsAt), - healthScore: account.healthScore, - healthStatus: account.healthStatus, seatsUsed: account.seatsUsed, seatsLimit: account.seatsLimit, contactCount: account.contactCount, @@ -382,10 +378,9 @@ export const connectedProvidersStream = ( ), ) -/** The org's customer settings the pages show: when compute last ran ("Evaluated 14 min ago"), the bands. */ +/** The org's customer settings the pages show: when compute last ran ("Evaluated 14 min ago"). */ export const SettingsSummary = Schema.Struct({ lastComputedAtMs: Schema.NullOr(Schema.Finite), - bands: Customers.HealthBands, reportingCurrency: Schema.String, }) export type SettingsSummary = typeof SettingsSummary.Type @@ -410,7 +405,6 @@ export const settingsSummaryStream = ( ? null : { lastComputedAtMs: msOrNull(row.lastComputedAt), - bands: row.health.bands, reportingCurrency: row.reportingCurrency, }, ) diff --git a/apps/web-foldkit/src/customers/ui/README.md b/apps/web-foldkit/src/customers/ui/README.md index 561cd9221..b2fe19809 100644 --- a/apps/web-foldkit/src/customers/ui/README.md +++ b/apps/web-foldkit/src/customers/ui/README.md @@ -4,7 +4,7 @@ Stateless Foldkit views for the Customers pages. Every view is `(h, options) → hover and open state live in the page's Model and come in as options, Messages go out through `on*` callbacks. Try them all at `/lab/customers/kit/*`. -**Only domain views live here** (a customer's health badge, a company logo, a severity chip, a queue +**Only domain views live here** (a lifecycle stage badge, a company logo, a severity chip, a queue row, a KPI tile, a connect card…), and each is built from the app kit in `src/ui`. Generic primitives are never redrawn here; take them from the kit (`DESIGN-RULES.md` › Patterns with one owner): @@ -24,8 +24,8 @@ owner): If a domain view needs something the kit lacks, add it to the kit, not here. Colors are theme tokens (`src/core/styles/theme.css` › Customers): `chart-{new,expansion,contraction, -churn,neutral,series-1..3,grid,net}`, `health-{healthy,at-risk,critical,unknown}`, -`severity-{high,medium,low,off}` — use them as `bg-chart-new`, `stroke-chart-series-1`, … +churn,neutral,series-1..3,grid,net}`, `severity-{high,medium,low,off}` — use them as `bg-chart-new`, +`stroke-chart-series-1`, … ## Surface — `ui/surface.ts` @@ -47,7 +47,7 @@ The little text grammar the kit has no component for. Headings are the kit's `he | `formatMoney(minor, currency?, { cents?, signed? })` | `$48,210`, `$1,240.00`, `+$9,400`, `−$1,000` | | `formatMoneyCompact(minor, currency?, { signed? })` | `$48.2K`, `−$4K` | | `formatCount(n)` / `formatCompact(n)` | `1,611` / `461K` | -| `formatPct(pct)` / `formatDeltaPct(pct)` / `formatDeltaPoints(pts, unit?)` / `formatDeltaCount(n)` | `61%` / `+6.2%` / `+0.9 pt` / `+12` | +| `formatPct(pct)` / `formatDeltaPct(pct)` / `formatDeltaPoints(pts)` / `formatDeltaCount(n)` | `61%` / `+6.2%` / `+0.9 pt` / `+12` | | `deltaTone(delta, goodWhen?)` | `"positive" \| "negative" \| "neutral"` | | `formatRelative(at, now)` / `daysBetween(at, now)` | `18d ago`, `in 4d` | | `formatDays(n)` / `formatDaysLeft(n)` | `4 days` / `4 days left` | @@ -58,14 +58,12 @@ The little text grammar the kit has no component for. Headings are the kit's `he ## Badges — `ui/badges.ts` -- `healthBadge(h, { status, score? })` — pill; `score: null` shows `—`, omit to hide the number. -- `healthDot(h, { status, score })` — compact, for dense cells. - `severityChip(h, severity)` / `severityGlyph(h, severity)` — bars; the glyph alone has a title. - `kindChip(h, kind)` — `! Risk` / `↗ Opportunity`. - `stageBadge(h, stage, { trialDaysLeft? })` — square, no dot. - `environmentBadge(h, environment)` — an account's environment (`EU`) beside its name; `environmentsHint(h, count)` — `+2 environments`, muted. - `signalCounts(h, { high, medium, low, opportunities })` — the list's open-signals cell. -- Labels/fills: `HEALTH_LABEL`, `HEALTH_FILL`, `SEVERITY_LABEL`, `KIND_LABEL`, `STAGE_LABEL`. +- Labels: `SEVERITY_LABEL`, `KIND_LABEL`, `STAGE_LABEL`. ## Identity — `ui/identity.ts` @@ -82,7 +80,7 @@ The little text grammar the kit has no component for. Headings are the kit's `he - `deltaPill(h, delta)`, `definedLabel(h, { id, label, definition })` (hover/focus definition card, CSS only). - `evidenceViz(h, evidence)` — the queue's mini-viz per `_tag` (amount, last_active, series, limit, delta, ratio). - `evidenceDetail(h, evidence, { now })` — side panel: facts + chart (series → `evidenceBars`, limit → meter). -- `deltaSummary(deltaEvidence)` — `$1,240 → $0`, `62 → 48 pts`. +- `deltaSummary(deltaEvidence)` — `$1,240 → $0`, `8 → 20 users`. ## Charts — `src/customers/charts/` @@ -91,7 +89,7 @@ The little text grammar the kit has no component for. Headings are the kit's `he `activeUsersChart(h, { points, bucket, hoveredIndex, onHover })` over `OverviewResult.activeUsers`; `ACTIVE_USERS_LEGEND`. - `stacked-bar-chart.ts`: `stackedBarChart(h, { ariaLabel, stacks, bars, netLabel?, formatValue, hoveredIndex, onHover })`; `mrrMovementChart(h, { buckets, bucket, currency, hoveredIndex, onHover })` over `OverviewResult.mrrMovements`; `mrrLegend(buckets)`. -- `distribution.ts`: `distributionBar(h, { segments, ariaLabel })`, `healthDistribution(h, { rows, bands, currency, metric, onMetric })` (the whole card). +- `distribution.ts`: `distributionBar(h, { segments, ariaLabel })`. - `frame.ts`: `chartCard(h, { title, description?, aside? }, children)`, `chartLegend(h, items)`, `chartTooltip`, `CHART_COLOR`. - `scale.ts`: the math (`niceTicks`, `scaleLinear`, `linePath`, `stackSegments`, …). @@ -102,7 +100,7 @@ Charts fill their container's width (no measuring); set the height with `heightC Tables are the kit's `dataTable` and `primaryCell` (`src/ui/data-table.ts`). -- `queueRow(h, { id, rank, account, signal, evidence, age, assignee, health, isFocused?, isSelected?, run?, onPress?, actions? })`, +- `queueRow(h, { id, rank, account, signal, evidence, age, assignee, isFocused?, isSelected?, run?, onPress?, actions? })`, `queueList(h, { ariaLabel }, rows)`, `queueAction(h, { label, icon?, onPress?, iconOnly?, shortcut?, attributes?, overlay? })`, `planLine(account)`, `accountMark(h, account, run?)` (the logo, joined by a line to the same account's rows). Inline actions replace evidence…assignee on hover / focus. A press on an action also reaches the row's `onPress` (selects it). diff --git a/apps/web-foldkit/src/customers/ui/badges.ts b/apps/web-foldkit/src/customers/ui/badges.ts index 35a5c4797..3b5a9d9e6 100644 --- a/apps/web-foldkit/src/customers/ui/badges.ts +++ b/apps/web-foldkit/src/customers/ui/badges.ts @@ -1,119 +1,15 @@ -import type { HealthStatus, LifecycleStage, SignalKind, SignalSeverity } from "@hazel/domain/customers" +import type { LifecycleStage, SignalKind, SignalSeverity } from "@hazel/domain/customers" import type { Html, HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" import { badge } from "../../ui/badge" -import { type StatusTone, statusDot } from "../../ui/status-dot" import { formatDaysLeft } from "../format" import { environmentsHintOf } from "../groups" import { IconOpportunity, IconRisk } from "./icons" /** - * Status badges and chips (Foundations › Health Badge States, Severity And Kind Chips, Lifecycle - * Stage Badges). Health is a pill with a dot; stage is square with no dot, so the two never read as - * the same thing. + * Status badges and chips (Foundations › Severity And Kind Chips, Lifecycle Stage Badges). */ -// HEALTH - -export const HEALTH_LABEL = { - healthy: "Healthy", - at_risk: "At risk", - critical: "Critical", - unknown: "Unknown", -} as const satisfies Record - -const HEALTH_INTENT = { - healthy: "success", - at_risk: "warning", - critical: "danger", - unknown: "secondary", -} as const - -const HEALTH_TONE = { - healthy: "success", - at_risk: "warning", - critical: "danger", - unknown: "neutral", -} as const satisfies Record - -/** The dot's color: the badge's own foreground, so dot and label always agree. */ -const HEALTH_DOT = { - healthy: "bg-success-subtle-fg", - at_risk: "bg-warning-subtle-fg", - critical: "bg-danger-subtle-fg", - unknown: "bg-muted-fg", -} as const satisfies Record - -/** The chart color of a status (distribution bar, legend squares). */ -export const HEALTH_FILL = { - healthy: "bg-health-healthy", - at_risk: "bg-health-at-risk", - critical: "bg-health-critical", - unknown: "bg-health-unknown", -} as const satisfies Record - -const scoreText = (status: HealthStatus, score: number | null): string => - status === "unknown" || score === null ? "—" : String(score) - -/** `● Healthy 82`. Without `score` (undefined) the number is left out; `null` shows `—`. */ -export const healthBadge = ( - h: HtmlBuilder, - options: Readonly<{ status: HealthStatus; score?: number | null; className?: string }>, -): Html => - badge( - h, - { - intent: HEALTH_INTENT[options.status], - className: twMerge( - "shrink-0 whitespace-nowrap rounded-full px-2", - options.status === "unknown" && "[--badge-fg:var(--color-muted-fg)]", - options.className, - ), - }, - [ - statusDot(h, { tone: HEALTH_TONE[options.status], className: HEALTH_DOT[options.status] }), - HEALTH_LABEL[options.status], - ...(options.score === undefined - ? [] - : [ - h.span( - [ - h.Class( - twMerge( - "font-semibold", - options.status === "unknown" ? "text-muted-fg" : "text-fg", - ), - ), - ], - [scoreText(options.status, options.score)], - ), - ]), - ], - ) - -/** `● 82`: dense table cells. The status is in the accessible name, not only the color. */ -export const healthDot = ( - h: HtmlBuilder, - options: Readonly<{ status: HealthStatus; score: number | null; className?: string }>, -): Html => - h.span( - [ - h.Class(twMerge("inline-flex items-center gap-1.5 text-sm tabular-nums", options.className)), - h.Title(HEALTH_LABEL[options.status]), - ], - [ - statusDot(h, { - tone: HEALTH_TONE[options.status], - className: twMerge("size-2", HEALTH_DOT[options.status]), - }), - h.span([h.Class("sr-only")], [`${HEALTH_LABEL[options.status]} `]), - h.span( - [h.Class(options.status === "unknown" ? "text-muted-fg" : "text-fg")], - [scoreText(options.status, options.score)], - ), - ], - ) - // SEVERITY export const SEVERITY_LABEL = { diff --git a/apps/web-foldkit/src/customers/ui/evidence.ts b/apps/web-foldkit/src/customers/ui/evidence.ts index 57f9c5b26..6b718e07a 100644 --- a/apps/web-foldkit/src/customers/ui/evidence.ts +++ b/apps/web-foldkit/src/customers/ui/evidence.ts @@ -24,16 +24,14 @@ import { type Of = Extract -const DELTA_UNIT_TEXT = { points: "pts", users: "users" } as const - const deltaValue = (evidence: Of<"delta">, value: number): string => evidence.unit === "minor" ? formatMoney(value, evidence.currency ?? "USD") : formatCount(value) -/** `$1,240 → $0`, `62 → 48`, `8 → 20 users`, or the labels (`Scale → Growth`) when set. */ +/** `$1,240 → $0`, `8 → 20 users`, or the labels (`Scale → Growth`) when set. */ export const deltaSummary = (evidence: Of<"delta">): string => evidence.fromLabel !== null && evidence.toLabel !== null ? `${evidence.fromLabel} → ${evidence.toLabel}` - : `${deltaValue(evidence, evidence.from)} → ${deltaValue(evidence, evidence.to)}${evidence.unit === "minor" ? "" : ` ${DELTA_UNIT_TEXT[evidence.unit]}`}` + : `${deltaValue(evidence, evidence.from)} → ${deltaValue(evidence, evidence.to)}${evidence.unit === "minor" ? "" : " users"}` const stack = ( h: HtmlBuilder, diff --git a/apps/web-foldkit/src/customers/ui/health-breakdown.ts b/apps/web-foldkit/src/customers/ui/health-breakdown.ts deleted file mode 100644 index 9a2c7b102..000000000 --- a/apps/web-foldkit/src/customers/ui/health-breakdown.ts +++ /dev/null @@ -1,319 +0,0 @@ -import type { - HealthBands, - HealthBreakdown, - HealthComponentKey, - HealthComponentResult, -} from "@hazel/domain/customers" -import type { Html, HtmlBuilder } from "foldkit/html" -import { twMerge } from "tailwind-merge" -import { activityProviders, billingProviders } from "@hazel/customer-integrations" -import { cardClassName } from "../../ui/card" -import { dataTable } from "../../ui/data-table" -import { heading } from "../../ui/heading" -import { sourceLabel, usageSources } from "../providers" -import { healthBadge } from "./badges" - -/** - * "Why health is N" (Customer Page › overview, Health Breakdown Excluded Component): a points bar - * (each component's width is its effective weight, filled by its score), then one row per component - * with why, score, weight and points. An excluded component shows its configured weight struck - * through and 0%; the others show what they gained from it. - */ - -export const COMPONENT_LABEL = { - usage: "Usage", - engagement: "Engagement", - billing: "Billing", - signals: "Signals", -} as const satisfies Record - -/** Where a component's inputs come from. */ -export const COMPONENT_SOURCES = { - usage: usageSources.map(sourceLabel).join(" · "), - engagement: activityProviders.map(sourceLabel).join(" · "), - billing: billingProviders.map(sourceLabel).join(" · "), - signals: sourceLabel("hazel"), -} satisfies Record - -const bandFill = (score: number, bands: HealthBands) => - score >= bands.healthyMin - ? "bg-health-healthy" - : score >= bands.atRiskMin - ? "bg-health-at-risk" - : "bg-health-critical" - -const pointsOf = (component: HealthComponentResult) => - component.score === null ? 0 : (component.score * component.effectiveWeight) / 100 - -const formatWeight = (weight: number) => `${Math.round(weight)}%` - -/** A score on a track, filled in its band's colour. */ -const meter = ( - h: HtmlBuilder, - score: number, - bands: HealthBands, - trackClass: string, - fillClass?: string, -): Html => - h.span( - [h.Class(twMerge("block overflow-hidden rounded-full bg-secondary", trackClass))], - [ - h.span([ - h.Class(twMerge("block h-full", fillClass, bandFill(score, bands))), - h.Style({ width: `${score}%` }), - ]), - ], - ) - -export const healthBreakdown = ( - h: HtmlBuilder, - options: Readonly<{ - breakdown: HealthBreakdown - bands: HealthBands - /** Under the title: `Down 17 points from 71 on Oct 27.` */ - subtitle?: string - /** Top right: `Edit weights` (a link or button). */ - action?: Html - /** Under an excluded component's why: `Link a billing record`. */ - excludedAction?: (key: HealthComponentKey) => Html | null - /** Inside a disclosure that already names the score: no title row, border or radius. */ - isBare?: boolean - className?: string - }>, -): Html => { - const { breakdown, bands } = options - const included = breakdown.components.filter((component) => !component.excluded) - const ordered = [...included, ...breakdown.components.filter((component) => component.excluded)] - const isRedistributed = breakdown.components.some((component) => component.excluded) - const score = breakdown.score - return h.section( - [ - h.Class( - options.isBare === true - ? twMerge("flex min-w-0 flex-col", options.className) - : cardClassName(twMerge("flex min-w-0 flex-col", options.className)), - ), - ], - [ - h.header( - [h.Class("flex flex-col gap-3 p-4 sm:p-5")], - [ - ...(options.isBare === true - ? [] - : [ - h.div( - [h.Class("flex flex-wrap items-start justify-between gap-x-4 gap-y-1")], - [ - h.div( - [h.Class("flex min-w-0 flex-1 basis-48 flex-col gap-1")], - [ - heading( - h, - { - variant: "section", - className: - "flex flex-wrap items-center gap-x-2 gap-y-1", - }, - [ - score === null - ? "No health score yet" - : `Why health is ${score}`, - healthBadge(h, { status: breakdown.status }), - ], - ), - ...(options.subtitle - ? [ - h.p( - [h.Class("text-muted-fg text-sm")], - [options.subtitle], - ), - ] - : []), - ], - ), - ...(options.action ? [options.action] : []), - ], - ), - ]), - h.div( - [ - h.Role("img"), - h.AriaLabel( - included - .map( - (component) => - `${COMPONENT_LABEL[component.key]} ${pointsOf(component).toFixed(1)} of ${formatWeight(component.effectiveWeight)}`, - ) - .join(", "), - ), - h.Class("flex w-full gap-1"), - ], - included.map((component) => - h.div( - [ - h.Class("flex min-w-0 flex-col gap-1.5"), - h.Style({ width: `${component.effectiveWeight}%` }), - ], - [ - meter(h, component.score ?? 0, bands, "h-1.5", "rounded-full"), - h.span( - // A phone has no room for these under the bars; the table below says the same. - [ - h.Class( - "truncate text-muted-fg text-xs tabular-nums max-sm:hidden", - ), - ], - [ - `${COMPONENT_LABEL[component.key]} ${Math.round(pointsOf(component))} of ${Math.round(component.effectiveWeight)}`, - ], - ), - ], - ), - ), - ), - ], - ), - dataTable(h, { - ariaLabel: "Health components", - id: "health-breakdown", - isFramed: false, - className: "border-border border-t", - rows: ordered, - rowKey: (component) => component.key, - columns: [ - { - key: "component", - label: "Component", - widthClass: "w-32 max-sm:w-28", - cell: (component) => - h.div( - [h.Class("py-3")], - [ - h.div( - [ - h.Class( - twMerge( - "font-medium", - component.excluded ? "text-muted-fg" : "text-fg", - ), - ), - ], - [COMPONENT_LABEL[component.key]], - ), - h.div( - [h.Class("text-muted-fg text-xs")], - [component.excluded ? "No data" : COMPONENT_SOURCES[component.key]], - ), - ], - ), - }, - { - key: "why", - label: "Why", - cell: (component) => { - const action = component.excluded - ? (options.excludedAction?.(component.key) ?? null) - : null - return h.div( - [h.Class("py-3")], - [ - h.p( - [h.Class(component.excluded ? "text-muted-fg" : "text-fg-2")], - [component.why], - ), - ...(action === null ? [] : [h.div([h.Class("mt-1")], [action])]), - ], - ) - }, - }, - { - key: "score", - label: "Score", - align: "right", - widthClass: "w-32", - // A phone keeps the points (they sum to the score) and drops the score and weight. - hideClass: "max-sm:hidden", - cell: (component) => - component.score === null - ? h.span( - [ - h.Class( - "rounded-sm border border-border border-dashed px-1.5 py-0.5 text-muted-fg text-xs", - ), - ], - ["Excluded"], - ) - : h.span( - [h.Class("inline-flex items-center justify-end gap-3")], - [ - meter(h, component.score, bands, "h-1 w-10"), - h.span( - [h.Class("w-8 font-medium text-fg tabular-nums")], - [String(component.score)], - ), - ], - ), - }, - { - key: "weight", - label: "Weight", - align: "right", - widthClass: "w-24", - hideClass: "max-sm:hidden", - cell: (component) => - h.span( - [], - [ - ...(isRedistributed && - Math.round(component.effectiveWeight) !== component.weight - ? [ - h.span( - [h.Class("mr-1.5 text-muted-fg text-xs line-through")], - [formatWeight(component.weight)], - ), - ] - : []), - h.span( - [h.Class(component.excluded ? "text-muted-fg" : "text-fg-2")], - [formatWeight(component.effectiveWeight)], - ), - ], - ), - }, - { - key: "points", - label: "Points", - align: "right", - widthClass: "w-20", - cell: (component) => - h.span( - [h.Class(component.excluded ? "font-medium text-muted-fg" : "font-medium")], - [component.excluded ? "—" : pointsOf(component).toFixed(1)], - ), - }, - ], - }), - h.footer( - [ - h.Class( - "flex items-center justify-between gap-4 border-border border-t bg-wash px-4 py-3 sm:px-5", - ), - ], - [ - h.p( - [h.Class("text-muted-fg text-xs")], - [ - isRedistributed - ? `${included.length} of ${breakdown.components.length} components have data. Weights shown after redistribution; struck-through values are your settings.` - : `All ${breakdown.components.length} components have data. A component without data is left out and its weight is shared across the rest.`, - ], - ), - h.span( - [h.Class("shrink-0 font-semibold text-fg tabular-nums")], - [score === null ? "—" : `${score} / 100`], - ), - ], - ), - ], - ) -} diff --git a/apps/web-foldkit/src/customers/ui/queue-row.ts b/apps/web-foldkit/src/customers/ui/queue-row.ts index 3b6897f0d..1800d6c2a 100644 --- a/apps/web-foldkit/src/customers/ui/queue-row.ts +++ b/apps/web-foldkit/src/customers/ui/queue-row.ts @@ -1,18 +1,18 @@ -import type { HealthStatus, SignalKind, SignalSeverity } from "@hazel/domain/customers" +import type { SignalKind, SignalSeverity } from "@hazel/domain/customers" import type { Attribute, ChildAttribute, Html, HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" import { IconChevronDown } from "../../icons" import { ariaButton, button } from "../../ui/button" import { formatMoney } from "../format" import { environmentsHintOf } from "../groups" -import { healthBadge, kindChip, severityChip } from "./badges" +import { kindChip, severityChip } from "./badges" import { companyLogo, personAvatar } from "./identity" import { kbd } from "./shortcuts" /** * A row of the Needs-attention queue (Foundations › Queue Row Signal States): rank, account, - * signal and its plain reason, evidence, severity, age, assignee, health. Hovering or focusing the - * row swaps evidence…assignee for the inline actions. `focused` is the keyboard cursor (j/k). + * signal and its plain reason, evidence, severity, age, assignee. Hovering or focusing the row + * swaps evidence…assignee for the inline actions. `focused` is the keyboard cursor (j/k). */ export type QueueRowOptions = Readonly<{ @@ -32,7 +32,6 @@ export type QueueRowOptions = Readonly<{ /** `2d`, `6h`: since the signal opened. */ age: string assignee: Readonly<{ name: string; avatarUrl?: string | null }> | null - health: Readonly<{ status: HealthStatus; score: number | null }> isFocused?: boolean isSelected?: boolean /** The account's other signals in the rows next to this one (`accountMark`). */ @@ -101,7 +100,7 @@ export const queueRow = (h: HtmlBuilder, options: QueueRowOptions): Htm h.Class( twMerge( "group/queue relative flex min-h-16 items-center gap-4 border-border border-t px-4 py-3 first:border-t-0", - // A phone: account and health on the first line, the signal under them. + // A phone: the account on the first line, the signal under it. "max-md:flex-wrap max-md:gap-x-3 max-md:gap-y-1.5", "transition-colors hover:bg-wash data-focused:bg-wash", "before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-primary before:opacity-0 data-focused:before:opacity-100", @@ -206,10 +205,6 @@ export const queueRow = (h: HtmlBuilder, options: QueueRowOptions): Htm ), ] : []), - h.div( - [h.Role("cell"), h.Class("flex w-28 shrink-0 justify-end max-md:w-auto")], - [healthBadge(h, { status: options.health.status, score: options.health.score })], - ), ], ) diff --git a/apps/web-foldkit/src/customers/ui/view-look.ts b/apps/web-foldkit/src/customers/ui/view-look.ts index 04d9a5517..a50ad7739 100644 --- a/apps/web-foldkit/src/customers/ui/view-look.ts +++ b/apps/web-foldkit/src/customers/ui/view-look.ts @@ -115,7 +115,6 @@ const SHIPPED = { my_customers: { icon: "user", color: null }, paying: { icon: null, color: "green" }, trialing: { icon: null, color: "blue" }, - at_risk: { icon: null, color: "orange" }, churned: { icon: null, color: "gray" }, } as const satisfies Record diff --git a/apps/web-foldkit/src/lab/README.md b/apps/web-foldkit/src/lab/README.md index fc1e1f4ef..d76904a5c 100644 --- a/apps/web-foldkit/src/lab/README.md +++ b/apps/web-foldkit/src/lab/README.md @@ -54,7 +54,7 @@ Helpers: `defineLab` (no flags), `defineLabWithFlags`, `defineStaticLab` (a view ## Fixtures — `fixtures/customers.ts` -Fixed `NOW` (Tue 10 Nov 2026 12:00 UTC). `ACCOUNTS` (214, $48,210 MRR, health split 142/41/18/13), +Fixed `NOW` (Tue 10 Nov 2026 12:00 UTC). `ACCOUNTS` (214, $48,210 MRR), `ACCOUNTS_BY_KEY.` (customers with several environments: Acme is the US primary of `acmeEu`; Halcyon an unnamed primary of `halcyonEu` and `halcyonStaging`), diff --git a/apps/web-foldkit/src/lab/entries/customers/kit/badges.ts b/apps/web-foldkit/src/lab/entries/customers/kit/badges.ts index dc70c573c..674b12e73 100644 --- a/apps/web-foldkit/src/lab/entries/customers/kit/badges.ts +++ b/apps/web-foldkit/src/lab/entries/customers/kit/badges.ts @@ -1,8 +1,6 @@ import { defineStaticLab } from "../../../define" import { labPage, labRow, labSection } from "../../../frame" import { - healthBadge, - healthDot, kindChip, severityChip, severityGlyph, @@ -10,34 +8,10 @@ import { stageBadge, } from "../../../../customers/ui/badges" -// `/lab/customers/kit/badges`: Foundations › Health Badge States, Severity And Kind Chips, Lifecycle Stage Badges. +// `/lab/customers/kit/badges`: Foundations › Severity And Kind Chips, Lifecycle Stage Badges. export const lab = defineStaticLab("Badges", (h) => labPage(h, { title: "Badges and chips" }, [ - labSection(h, "Health badge", [ - labRow(h, [ - healthBadge(h, { status: "healthy" }), - healthBadge(h, { status: "at_risk" }), - healthBadge(h, { status: "critical" }), - healthBadge(h, { status: "unknown" }), - ]), - labRow(h, [ - healthBadge(h, { status: "healthy", score: 82 }), - healthBadge(h, { status: "at_risk", score: 54 }), - healthBadge(h, { status: "critical", score: 27 }), - healthBadge(h, { status: "unknown", score: null }), - ]), - labRow( - h, - [ - healthDot(h, { status: "healthy", score: 82 }), - healthDot(h, { status: "at_risk", score: 54 }), - healthDot(h, { status: "critical", score: 27 }), - healthDot(h, { status: "unknown", score: null }), - ], - "Compact, for dense table cells", - ), - ]), labSection(h, "Severity chip", [ labRow(h, [severityChip(h, "high"), severityChip(h, "medium"), severityChip(h, "low")]), labRow( @@ -61,7 +35,7 @@ export const lab = defineStaticLab("Badges", (h) => stageBadge(h, "trialing", { trialDaysLeft: 4 }), stageBadge(h, "trialing", { trialDaysLeft: 0 }), ], - "Square corners, no dot: stage, not health", + "Square corners, no dot", ), ]), labSection(h, "Open signals (list cell)", [ diff --git a/apps/web-foldkit/src/lab/entries/customers/kit/charts.ts b/apps/web-foldkit/src/lab/entries/customers/kit/charts.ts index 6fda5dbc8..82c56758f 100644 --- a/apps/web-foldkit/src/lab/entries/customers/kit/charts.ts +++ b/apps/web-foldkit/src/lab/entries/customers/kit/charts.ts @@ -2,7 +2,6 @@ import { CustomersRange } from "@hazel/domain/customers" import { Effect, Schema } from "effect" import { defineMessageUnion } from "foldkit/message" import type { Html, HtmlBuilder } from "foldkit/html" -import { healthDistribution } from "../../../../customers/charts/distribution" import { chartCard, chartLegend } from "../../../../customers/charts/frame" import { ACTIVE_USERS_LEGEND, activeUsersChart } from "../../../../customers/charts/line-chart" import { mrrLegend, mrrMovementChart } from "../../../../customers/charts/stacked-bar-chart" @@ -10,11 +9,11 @@ import { noSourcesState } from "../../../../customers/ui/empty-states" import { rangePicker } from "../../../../customers/ui/filter-bar" import { defineLabWithFlags, queryParam } from "../../../define" import { labPage, labSection } from "../../../frame" -import { SETTINGS, overviewFixture } from "../../../fixtures/customers" +import { overviewFixture } from "../../../fixtures/customers" import { INVOICES, PLANS } from "../../../fixtures/customers-demo-sources" -// `/lab/customers/kit/charts`: Foundations › Line Chart Active Users, Stacked Bar Chart MRR Movement, -// Distribution Bar Health. Hover for tooltips; `?state=default|partial|empty`. +// `/lab/customers/kit/charts`: Foundations › Line Chart Active Users, Stacked Bar Chart MRR Movement. +// Hover for tooltips; `?state=default|partial|empty`. const STATES = ["default", "partial", "empty"] as const const State = Schema.Literals(STATES) @@ -24,7 +23,6 @@ const Model = Schema.Struct({ range: CustomersRange, usersHover: Schema.NullOr(Schema.Finite), mrrHover: Schema.NullOr(Schema.Finite), - healthMetric: Schema.Literals(["customers", "mrr"]), }) type Model = typeof Model.Type @@ -32,7 +30,6 @@ const Message = defineMessageUnion({ HoveredUsers: { index: Schema.NullOr(Schema.Finite) }, HoveredMrr: { index: Schema.NullOr(Schema.Finite) }, ChoseRange: { range: CustomersRange }, - ChoseHealthMetric: { metric: Schema.Literals(["customers", "mrr"]) }, }) type Message = typeof Message.Type @@ -43,7 +40,6 @@ const update = (model: Model, message: Message): { model: Model } => ({ HoveredUsers: ({ index }) => ({ ...model, usersHover: index }), HoveredMrr: ({ index }) => ({ ...model, mrrHover: index }), ChoseRange: ({ range }) => ({ ...model, range, usersHover: null, mrrHover: null }), - ChoseHealthMetric: ({ metric }) => ({ ...model, healthMetric: metric }), }), }) @@ -104,14 +100,6 @@ const view = (model: Model, h: HtmlBuilder): Html => { ), ], ), - healthDistribution(h, { - rows: overview.healthDistribution, - bands: SETTINGS.health.bands, - currency: overview.currency, - metric: model.healthMetric, - onMetric: (metric) => Message.ChoseHealthMetric({ metric }), - className: "max-w-lg", - }), ] return labPage( h, @@ -128,7 +116,7 @@ export const lab = defineLabWithFlags("Charts", { range: queryParam("range", CustomersRange.literals, "30d"), }), init: (flags) => ({ - model: { ...flags, usersHover: null, mrrHover: null, healthMetric: "customers" as const }, + model: { ...flags, usersHover: null, mrrHover: null }, }), update, view, diff --git a/apps/web-foldkit/src/lab/entries/customers/kit/controls.ts b/apps/web-foldkit/src/lab/entries/customers/kit/controls.ts index e09698958..c48bc8750 100644 --- a/apps/web-foldkit/src/lab/entries/customers/kit/controls.ts +++ b/apps/web-foldkit/src/lab/entries/customers/kit/controls.ts @@ -21,7 +21,7 @@ import { labPage, labSection } from "../../../frame" // `/lab/customers/kit/controls`: Foundations › Filter Bar And Tabs, live. const QueueTab = Schema.Literals(["open", "snoozed", "done"]) -const SavedView = Schema.Literals(["current", "mine", "paying", "trialing", "at_risk", "churned", "all"]) +const SavedView = Schema.Literals(["current", "mine", "paying", "trialing", "churned", "all"]) const Grouping = Schema.Literals(["signals", "accounts"]) const CHIPS = [ { key: "kind", field: "Kind", operator: "is", value: "Risk" }, @@ -132,7 +132,6 @@ const view = (model: Model, h: HtmlBuilder): Html => { key: "mine", label: "My customers" }, { key: "paying", label: "Paying" }, { key: "trialing", label: "Trialing" }, - { key: "at_risk", label: "At risk" }, { key: "churned", label: "Churned" }, { key: "all", label: "All customers" }, ], diff --git a/apps/web-foldkit/src/lab/entries/customers/kit/queue.ts b/apps/web-foldkit/src/lab/entries/customers/kit/queue.ts index 44db9931b..ebbf014c8 100644 --- a/apps/web-foldkit/src/lab/entries/customers/kit/queue.ts +++ b/apps/web-foldkit/src/lab/entries/customers/kit/queue.ts @@ -83,7 +83,6 @@ const view = (model: Model, h: HtmlBuilder): Html => evidence: evidenceViz(h, signal.evidence), age: age(signal.openedAt), assignee: memberOf(signal.assigneeUserId), - health: { status: account.healthStatus, score: account.healthScore }, isFocused: index === model.focused, isSelected: signal.id === model.selected, onPress: Message.PressedRow({ id: signal.id }), diff --git a/apps/web-foldkit/src/lab/entries/customers/kit/table.ts b/apps/web-foldkit/src/lab/entries/customers/kit/table.ts index 3f2d69350..826525fd7 100644 --- a/apps/web-foldkit/src/lab/entries/customers/kit/table.ts +++ b/apps/web-foldkit/src/lab/entries/customers/kit/table.ts @@ -6,7 +6,7 @@ import { toEpochMs } from "~/lib/utils" import { IconDots } from "../../../../icons" import { sparkline } from "../../../../customers/charts/sparkline" import { formatCount, formatMoney, formatRelative } from "../../../../customers/format" -import { healthBadge, stageBadge } from "../../../../customers/ui/badges" +import { stageBadge } from "../../../../customers/ui/badges" import { type Column, dataTable, primaryCell } from "../../../../ui/data-table" import { noResultsState } from "../../../../customers/ui/empty-states" import { companyLogo, personLabel } from "../../../../customers/ui/identity" @@ -87,7 +87,7 @@ const update = (model: Model, message: Message): { model: Model } => ({ }) const view = (model: Model, h: HtmlBuilder): Html => { - const tableColumns: ReadonlyArray> = [ + const tableColumns: ReadonlyArray> = [ { key: "name", label: "Customer", @@ -143,12 +143,6 @@ const view = (model: Model, h: HtmlBuilder): Html => { ], ), }, - { - key: "health", - label: "Health", - widthClass: "w-32", - cell: (account) => healthBadge(h, { status: account.healthStatus, score: account.healthScore }), - }, { key: "last_active", label: "Last active", diff --git a/apps/web-foldkit/src/lab/entries/customers/kit/tokens.ts b/apps/web-foldkit/src/lab/entries/customers/kit/tokens.ts index 406c10ab5..d667ee9e0 100644 --- a/apps/web-foldkit/src/lab/entries/customers/kit/tokens.ts +++ b/apps/web-foldkit/src/lab/entries/customers/kit/tokens.ts @@ -21,11 +21,11 @@ export const lab = defineStaticLab("Customers tokens", (h) => h.div( [h.Class("flex flex-wrap gap-3")], [ - swatch(h, "bg-chart-new", "chart-new", "new / healthy"), + swatch(h, "bg-chart-new", "chart-new"), swatch(h, "bg-chart-expansion", "chart-expansion"), - swatch(h, "bg-chart-contraction", "chart-contraction", "contraction / at risk"), - swatch(h, "bg-chart-churn", "chart-churn", "churn / critical"), - swatch(h, "bg-chart-neutral", "chart-neutral", "neutral / unknown"), + swatch(h, "bg-chart-contraction", "chart-contraction"), + swatch(h, "bg-chart-churn", "chart-churn"), + swatch(h, "bg-chart-neutral", "chart-neutral"), swatch(h, "bg-chart-series-1", "chart-series-1", "DAU"), swatch(h, "bg-chart-series-2", "chart-series-2", "WAU"), swatch(h, "bg-chart-series-3", "chart-series-3", "MAU"), @@ -34,17 +34,6 @@ export const lab = defineStaticLab("Customers tokens", (h) => ], ), ]), - labSection(h, "Health", [ - h.div( - [h.Class("flex flex-wrap gap-3")], - [ - swatch(h, "bg-health-healthy", "health-healthy"), - swatch(h, "bg-health-at-risk", "health-at-risk"), - swatch(h, "bg-health-critical", "health-critical"), - swatch(h, "bg-health-unknown", "health-unknown"), - ], - ), - ]), labSection(h, "Severity", [ h.div( [h.Class("flex flex-wrap gap-3")], diff --git a/apps/web-foldkit/src/lab/entries/customers/pages/customer.ts b/apps/web-foldkit/src/lab/entries/customers/pages/customer.ts index 6f748d0a0..c793cacb2 100644 --- a/apps/web-foldkit/src/lab/entries/customers/pages/customer.ts +++ b/apps/web-foldkit/src/lab/entries/customers/pages/customer.ts @@ -42,7 +42,7 @@ import { ACTIVITY, DIRECTORY, INVOICES, PLANS } from "../../../fixtures/customer // (feature flags, the grouping actions), `?account=eu` shows Acme's EU environment instead of its US // primary, `?dialog=` opens the link or environment dialog. -const STATES = ["default", "payment-failed", "excluded-health", "loading", "not-found"] as const +const STATES = ["default", "payment-failed", "no-billing", "loading", "not-found"] as const const State = Schema.Literals(STATES) const ROLES = ["member", "admin"] as const const VIEWED = ["us", "eu"] as const @@ -254,7 +254,6 @@ const EVENTS: ReadonlyArray = [ ), event(2, 2, "hazel", "signal.opened", "Signal opened: Champion inactive", { severity: "medium" }), event(3, 4, "hazel", "signal.opened", "Signal opened: Usage dropped", { severity: "high" }), - event(4, 4, "hazel", "health.status_changed", "Health changed: Healthy → At risk", { from: 71, to: 66 }), event(5, 9, INVOICES.id, "invoice.paid", "Invoice paid", { number: "INV-2039", amount: "$1,240.00" }), event(6, 11, DIRECTORY.id, "contact.joined", "2 contacts joined", { invitedBy: "Lucas Ferreira" }), event(7, 16, ACTIVITY.id, "activity.last", "Last activity from Priya Shah", { events: 46 }), @@ -342,7 +341,7 @@ const withCompany = (account: Customers.Account): Customers.Account => { } const detailFor = (state: typeof State.Type): Customers.AccountDetail => { - const healthy: Customers.AccountDetail = { + const base: Customers.AccountDetail = { ...ACME_DETAIL, account: withCompany(ACCOUNT), subscriptions: [{ ...SUBSCRIPTION, status: "active", planName: "Pro", mrrMinor: 124_000 }], @@ -353,57 +352,13 @@ const detailFor = (state: typeof State.Type): Customers.AccountDetail => { } if (state === "payment-failed") return { - ...healthy, - account: { ...ACCOUNT, lifecycleStage: "past_due", healthStatus: "critical", healthScore: 34 }, + ...base, + account: { ...ACCOUNT, lifecycleStage: "past_due" }, subscriptions: ACME_DETAIL.subscriptions, openInvoices: ACME_DETAIL.openInvoices, } - if (state === "excluded-health") - return { - ...healthy, - subscriptions: [], - upcomingInvoice: null, - account: { ...ACCOUNT, healthStatus: "healthy", healthScore: 82 }, - health: { - score: 82, - status: "healthy", - components: [ - { - key: "usage", - score: 68, - weight: 40, - effectiveWeight: 50, - excluded: false, - why: "11 of 16 contacts active in the last 30 days (69%). Daily actives flat vs the prior 28 days.", - }, - { - key: "engagement", - score: 92, - weight: 25, - effectiveWeight: 31.25, - excluded: false, - why: "Last activity 20 minutes ago. Active every weekday this month.", - }, - { - key: "signals", - score: 100, - weight: 15, - effectiveWeight: 18.75, - excluded: false, - why: "No open risk signals.", - }, - { - key: "billing", - score: null, - weight: 20, - effectiveWeight: 0, - excluded: true, - why: `Left out: no ${INVOICES.name} or ${PLANS.name} record is linked to this account, so its 20% is shared across the other three in proportion.`, - }, - ], - }, - } - return healthy + if (state === "no-billing") return { ...base, subscriptions: [], upcomingInvoice: null } + return base } // PROGRAM @@ -472,7 +427,7 @@ const answer = (command: AnyCommand, current: typeof State.Type): Message | null case "FetchCustomerMrrHistory": return Message.SucceededFetchMrrHistory({ accountId: accountId(), - series: current === "excluded-health" ? [] : [MRR_HISTORY], + series: current === "no-billing" ? [] : [MRR_HISTORY], }) case "FetchCustomerContacts": return Message.SucceededFetchContacts({ diff --git a/apps/web-foldkit/src/lab/entries/customers/pages/health.ts b/apps/web-foldkit/src/lab/entries/customers/pages/health.ts deleted file mode 100644 index bdc5ed77a..000000000 --- a/apps/web-foldkit/src/lab/entries/customers/pages/health.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { OrganizationMemberId } from "@hazel/schema" -import { Effect, Option, Schema } from "effect" -import { Subscription } from "foldkit" -import * as AsyncData from "foldkit/asyncData" -import type { Html, HtmlBuilder } from "foldkit/html" -import { toAccountRow } from "../../../../customers/queries" -import type { Shared } from "../../../../page/contract" -import { labShared } from "../../../../page/customers/lab-shared" -import { Message } from "../../../../page/customers/settings/health/message" -import { Model, validDraftOf } from "../../../../page/customers/settings/health/model" -import { sliderSubscriptions } from "../../../../page/customers/settings/health/subscription" -import { init, update } from "../../../../page/customers/settings/health/update" -import { view } from "../../../../page/customers/settings/health/view" -import * as Select from "../../../../ui/select" -import { defineLabWithFlags, queryParam } from "../../../define" -import { labPage } from "../../../frame" -import { ACCOUNTS, SETTINGS } from "../../../fixtures/customers" -import { - HEALTH_DRAFT, - HEALTH_DRY_RUN, - HEALTH_INVALID_DRAFT, - savedBreakdownOf, -} from "../../../fixtures/customers-health" - -// `/lab/customers/pages/health`: the real health settings page over the fixtures (`?state=`). Its -// update runs; its Commands do not: the dry run answers `HEALTH_DRY_RUN`, a picked customer its -// fixture breakdown, and a save lands as if the settings row synced. - -const STATES = ["default", "unsaved", "invalid", "check-customer", "read-only", "loading"] as const -const State = Schema.Literals(STATES) -const Flags = Schema.Struct({ state: State }) - -const currentState = () => new URLSearchParams(window.location.search).get("state") ?? "default" - -const adminShared: Shared = { - ...labShared, - member: { - id: Schema.decodeSync(OrganizationMemberId)("00000000-0000-4000-8000-000000000901"), - role: "admin", - }, -} -const sharedOf = (): Shared => (currentState() === "read-only" ? labShared : adminShared) - -/** What the Commands would have brought back: the dry run at once (no delay), the picked breakdown. */ -const answered = (model: Model): Model => { - const dryRun = AsyncData.isPending(model.preview.result) - ? update( - model, - Message.SucceededFetchHealthDryRun({ - version: model.preview.version, - result: HEALTH_DRY_RUN, - }), - sharedOf(), - ).model - : model - return dryRun.check !== null && AsyncData.isLoading(dryRun.check.saved) - ? { - ...dryRun, - check: { - ...dryRun.check, - saved: AsyncData.Success({ data: savedBreakdownOf(dryRun.check.accountId) }), - }, - } - : dryRun -} - -const step = (model: Model, message: Message): Model => { - const next = answered(update(model, message, sharedOf()).model) - // A save only starts for a valid draft: that is what lands. - const saved = validDraftOf(next) - if (!next.isSaving || next.settings === null || saved === null) return next - const synced = { ...next, settings: { ...next.settings, health: saved } } - return answered(update(synced, Message.SucceededSaveHealthSettings(), sharedOf()).model) -} - -const stateModel = (state: typeof State.Type): Model => { - const base = init().model - if (state === "loading") return base - const loaded = [ - Message.UpdatedSettings({ - settings: { - id: SETTINGS.id, - health: SETTINGS.health, - reportingCurrency: SETTINGS.reportingCurrency, - }, - }), - Message.UpdatedAccounts({ accounts: ACCOUNTS.map(toAccountRow) }), - ].reduce(step, base) - if (state === "unsaved" || state === "check-customer") { - const unsaved = [ - Message.ChangedWeight({ key: "usage", value: HEALTH_DRAFT.weights.usage }), - Message.ChangedWeight({ key: "engagement", value: HEALTH_DRAFT.weights.engagement }), - ].reduce(step, loaded) - if (state === "unsaved") return unsaved - // The second sample, picked as opening the picker and clicking its option would. - const items = ACCOUNTS.map((account) => Select.item(account.id, account.name)) - const key = HEALTH_DRY_RUN.samples[1]?.accountId ?? "" - return [ - Select.Message.PressedTrigger({ pointerType: "mouse" }), - Select.Message.ClickedOption({ key, items }), - ] - .map((message) => Message.GotCheckAccountMessage({ message })) - .reduce(step, unsaved) - } - if (state === "invalid") - return step( - loaded, - Message.ChangedWeight({ key: "usage", value: HEALTH_INVALID_DRAFT.weights.usage }), - ) - return loaded -} - -const sliders = Subscription.lift(sliderSubscriptions)({ - read: (model) => Option.some({ model, shared: sharedOf() }), - toParentMessage: (message) => message, -}) - -const toMessage = (message: Message) => message - -export const lab = defineLabWithFlags("Health score settings", { - Model, - Flags, - flags: Effect.all({ state: queryParam("state", STATES, "default") }), - init: ({ state }) => ({ model: stateModel(state) }), - update: (model: Model, message: Message) => ({ model: step(model, message) }), - view: (model: Model, h: HtmlBuilder): Html => - labPage( - h, - { - title: "Health score settings", - switches: [{ name: "state", values: STATES, current: currentState() }], - }, - [ - h.div( - [h.Class("h-[calc(100dvh-57px)] border-border border-t")], - [ - h.submodel({ - slotId: "health", - model, - view, - viewInputs: { shared: sharedOf() }, - toParentMessage: toMessage, - }), - ], - ), - ], - ), - subscriptions: sliders, -}) diff --git a/apps/web-foldkit/src/lab/entries/customers/pages/list.ts b/apps/web-foldkit/src/lab/entries/customers/pages/list.ts index b7d07fd42..924a51708 100644 --- a/apps/web-foldkit/src/lab/entries/customers/pages/list.ts +++ b/apps/web-foldkit/src/lab/entries/customers/pages/list.ts @@ -31,7 +31,6 @@ import { const STATES = [ "all", - "at-risk", "filter", "columns", "company", @@ -71,7 +70,6 @@ export const LIST_VIEWS: ReadonlyArray = [ builtIn(0, "my_customers", "My customers", { ownedByMe: true }), builtIn(1, "paying", "Paying", { payingOnly: true }), builtIn(2, "trialing", "Trialing", { lifecycleStages: ["trialing"] }), - builtIn(3, "at_risk", "At risk", { healthStatuses: ["at_risk", "critical"] }), builtIn(4, "churned", "Churned", { lifecycleStages: ["churned"] }), { id: VIEW_IDS[5], @@ -81,7 +79,7 @@ export const LIST_VIEWS: ReadonlyArray = [ position: 5, filters: { planNames: ["Scale"] }, sort: { column: "customer_since", direction: "asc" }, - columns: ["name", "owner", "mrr", "health", "last_active", "customer_since", "tags"], + columns: ["name", "owner", "mrr", "last_active", "customer_since", "tags"], icon: "rocket", color: "teal", }, @@ -189,8 +187,6 @@ const stateOf = (state: typeof State.Type) => { return run(init(routeOf(null)).model, []) case "first-run": return loadedList(null, true) - case "at-risk": - return loadedList("at_risk") case "filter": { const base = loadedList(null) return run(base.model, [ diff --git a/apps/web-foldkit/src/lab/entries/customers/pages/overview.ts b/apps/web-foldkit/src/lab/entries/customers/pages/overview.ts index efd812889..711407aca 100644 --- a/apps/web-foldkit/src/lab/entries/customers/pages/overview.ts +++ b/apps/web-foldkit/src/lab/entries/customers/pages/overview.ts @@ -47,7 +47,6 @@ const stateModel = (flags: typeof Flags.Type): Model => { ), settings: { lastComputedAtMs: SETTINGS.lastComputedAt === null ? null : msOf(SETTINGS.lastComputedAt), - bands: SETTINGS.health.bands, reportingCurrency: SETTINGS.reportingCurrency, }, } diff --git a/apps/web-foldkit/src/lab/entries/customers/pages/saved-views.ts b/apps/web-foldkit/src/lab/entries/customers/pages/saved-views.ts index 333e7a999..b03c7a96f 100644 --- a/apps/web-foldkit/src/lab/entries/customers/pages/saved-views.ts +++ b/apps/web-foldkit/src/lab/entries/customers/pages/saved-views.ts @@ -193,7 +193,7 @@ const init = (state: typeof State.Type): Result => { // Renewals first, Churned out of the sidebar, All customers in it. const layout = { id: LAYOUT_ID, - order: [RENEWALS_ID, CURRENT_KEY, "my_customers", "at_risk", "paying", "trialing", "churned", "all"], + order: [RENEWALS_ID, CURRENT_KEY, "my_customers", "paying", "trialing", "churned", "all"], sidebarHidden: ["churned"], } return { diff --git a/apps/web-foldkit/src/lab/entries/customers/pages/signals.ts b/apps/web-foldkit/src/lab/entries/customers/pages/signals.ts index 5eaf88699..f0404d052 100644 --- a/apps/web-foldkit/src/lab/entries/customers/pages/signals.ts +++ b/apps/web-foldkit/src/lab/entries/customers/pages/signals.ts @@ -79,7 +79,6 @@ const live = (model: Model, shared: Shared): Model => settings: { lastComputedAtMs: SETTINGS.lastComputedAt === null ? null : msOf(SETTINGS.lastComputedAt) - 13 * 60_000, - bands: SETTINGS.health.bands, reportingCurrency: SETTINGS.reportingCurrency, }, }), diff --git a/apps/web-foldkit/src/lab/fixtures/customers-health.ts b/apps/web-foldkit/src/lab/fixtures/customers-health.ts deleted file mode 100644 index 40624b012..000000000 --- a/apps/web-foldkit/src/lab/fixtures/customers-health.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { - type Account, - DEFAULT_HEALTH_SETTINGS, - type HealthBreakdown, - type HealthComponentKey, - type HealthDistributionRow, - type HealthDryRunResult, - type HealthSettings, - HealthStatus, -} from "@hazel/domain/customers" -import type { CustomerAccountId } from "@hazel/schema" -import { ACCOUNTS, ACCOUNTS_BY_KEY } from "./customers" - -/** The health settings page's fixtures: drafts, a dry run of them, and saved breakdowns. */ - -/** Wonder `mao`: usage up, engagement down, still 100%. */ -export const HEALTH_DRAFT: HealthSettings = { - ...DEFAULT_HEALTH_SETTINGS, - weights: { usage: 40, engagement: 20, billing: 25, signals: 15 }, -} - -/** Wonder `aal`: usage pushed to 45%, the weights add up to 110%. */ -export const HEALTH_INVALID_DRAFT: HealthSettings = { - ...DEFAULT_HEALTH_SETTINGS, - weights: { usage: 45, engagement: 25, billing: 25, signals: 15 }, -} - -type Part = readonly [key: HealthComponentKey, score: number | null, why: string] - -/** A breakdown as the backend builds it: excluded parts share their weight, the score is banded. */ -export const breakdownOf = (settings: HealthSettings, parts: ReadonlyArray): HealthBreakdown => { - const available = parts.reduce( - (sum, [key, score]) => sum + (score === null ? 0 : settings.weights[key]), - 0, - ) - const components = parts.map(([key, score, why]) => ({ - key, - score, - weight: settings.weights[key], - effectiveWeight: score === null ? 0 : (settings.weights[key] / available) * 100, - excluded: score === null, - why, - })) - const score = Math.round( - components.reduce((sum, part) => sum + (part.effectiveWeight / 100) * (part.score ?? 0), 0), - ) - const { healthyMin, atRiskMin } = settings.bands - return { - score, - status: score >= healthyMin ? "healthy" : score >= atRiskMin ? "at_risk" : "critical", - components, - } -} - -const NORTHWIND: ReadonlyArray = [ - ["usage", 20, "9 of 51 contacts active in 30 days; trend −41%"], - ["engagement", 100, "Active today"], - ["billing", 100, "Paid up"], - ["signals", 100, "No open risk signals"], -] -const SABLE: ReadonlyArray = [ - ["usage", 85, "7 of 9 contacts active in 30 days; trend +6%"], - ["engagement", 100, "Active today"], - ["billing", 40, "Cancellation scheduled"], - ["signals", 85, "1 open risk signal (1 medium)"], -] -const ACME: ReadonlyArray = [ - ["usage", 10, "4 of 24 contacts active in 30 days; trend −48%"], - ["engagement", 90, "Last active 3 days ago"], - ["billing", 20, "Payment past due"], - ["signals", 70, "1 open risk signal (1 high)"], -] -const KESTREL: ReadonlyArray = [ - ["usage", 31, "9 of 14 contacts active in 30 days; trend −64%"], - ["engagement", 25, "Last active 18 days ago"], - ["billing", 30, "Invoice overdue for over a week"], - ["signals", 55, "2 open risk signals (1 high, 1 medium)"], -] - -const PARTS_BY_ACCOUNT = new Map>([ - [ACCOUNTS_BY_KEY.northwind.id, NORTHWIND], - [ACCOUNTS_BY_KEY.sable.id, SABLE], - [ACCOUNTS_BY_KEY.acme.id, ACME], - [ACCOUNTS_BY_KEY.kestrel.id, KESTREL], -]) - -/** `customers.account.detail`'s `health` for any account: the named ones by hand, the rest generic. */ -export const savedBreakdownOf = (accountId: CustomerAccountId): HealthBreakdown | null => { - const account = ACCOUNTS.find((candidate) => candidate.id === accountId) - if (account === undefined || account.healthStatus === "unknown") return null - return breakdownOf( - DEFAULT_HEALTH_SETTINGS, - PARTS_BY_ACCOUNT.get(accountId) ?? [ - [ - "usage", - account.healthScore, - `${account.activeUsers30d} of ${account.contactCount} contacts active in 30 days`, - ], - ["engagement", account.healthScore, "Lab fixture: matches its synced score"], - ["billing", null, "No subscription"], - ["signals", account.healthScore, "Lab fixture: matches its synced score"], - ], - ) -} - -const distribution = (accounts: ReadonlyArray): ReadonlyArray => - HealthStatus.literals.map((status) => { - const rows = accounts.filter((account) => account.healthStatus === status) - return { status, count: rows.length, mrrMinor: rows.reduce((sum, row) => sum + row.mrrMinor, 0) } - }) - -/** The book as saved, and after `HEALTH_DRAFT`: 6 healthy slip to at risk, 2 at risk to critical. */ -const moved = (rows: ReadonlyArray): ReadonlyArray => { - const shift = (status: HealthStatus, count: number, mrrMinor: number) => { - const row = rows.find((candidate) => candidate.status === status) - return { status, count: (row?.count ?? 0) + count, mrrMinor: (row?.mrrMinor ?? 0) + mrrMinor } - } - return [ - shift("healthy", -6, -1_186_000), - shift("at_risk", 4, 1_186_000 - 345_000), - shift("critical", 2, 345_000), - shift("unknown", 0, 0), - ] -} - -const CURRENT = distribution(ACCOUNTS) - -export const HEALTH_DRY_RUN: HealthDryRunResult = { - current: CURRENT, - proposed: moved(CURRENT), - transitions: [ - { from: "healthy", to: "at_risk", count: 6 }, - { from: "at_risk", to: "critical", count: 2 }, - ], - samples: [ - { - accountId: ACCOUNTS_BY_KEY.northwind.id, - name: ACCOUNTS_BY_KEY.northwind.name, - current: breakdownOf(DEFAULT_HEALTH_SETTINGS, NORTHWIND), - proposed: breakdownOf(HEALTH_DRAFT, NORTHWIND), - }, - { - accountId: ACCOUNTS_BY_KEY.acme.id, - name: ACCOUNTS_BY_KEY.acme.name, - current: breakdownOf(DEFAULT_HEALTH_SETTINGS, ACME), - proposed: breakdownOf(HEALTH_DRAFT, ACME), - }, - ], - evaluatedAccounts: ACCOUNTS.length, - totalAccounts: ACCOUNTS.length, -} diff --git a/apps/web-foldkit/src/lab/fixtures/customers.test.ts b/apps/web-foldkit/src/lab/fixtures/customers.test.ts index 791366118..305eb2840 100644 --- a/apps/web-foldkit/src/lab/fixtures/customers.test.ts +++ b/apps/web-foldkit/src/lab/fixtures/customers.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest" -import { ACCOUNTS, ACCOUNTS_BY_KEY, HEALTH_TOTALS, OPEN_SIGNALS, SIGNALS, overviewFixture } from "./customers" +import { ACCOUNTS, ACCOUNTS_BY_KEY, OPEN_SIGNALS, SIGNALS, overviewFixture } from "./customers" describe("customers fixtures", () => { it("add up to the designs' book: 214 accounts, $48,210 MRR", () => { @@ -8,15 +8,6 @@ describe("customers fixtures", () => { expect(new Set(ACCOUNTS.map((account) => account.id)).size).toBe(214) }) - it("match the health distribution per status", () => { - for (const [status, [count, mrr]] of Object.entries(HEALTH_TOTALS)) { - const accounts = ACCOUNTS.filter((account) => account.healthStatus === status) - expect(accounts).toHaveLength(count) - expect(accounts.reduce((sum, account) => sum + account.mrrMinor, 0)).toBe(mrr * 100) - expect(accounts.every((account) => account.mrrMinor >= 0)).toBe(true) - } - }) - it("cover every evidence viz and every signal status", () => { expect(new Set(SIGNALS.map((signal) => signal.evidence._tag))).toEqual( new Set(["amount", "last_active", "series", "limit", "delta", "ratio"]), diff --git a/apps/web-foldkit/src/lab/fixtures/customers.ts b/apps/web-foldkit/src/lab/fixtures/customers.ts index 8163bbc03..e6593546f 100644 --- a/apps/web-foldkit/src/lab/fixtures/customers.ts +++ b/apps/web-foldkit/src/lab/fixtures/customers.ts @@ -9,10 +9,7 @@ import { type ContactRow, type CustomersRange, DEFAULT_BUSINESS_HOURS, - DEFAULT_HEALTH_SETTINGS, EMPTY_SYNC_STATS, - type HealthDistributionRow, - type HealthStatus, type LifecycleStage, type MrrMovementBucket, type OverviewResult, @@ -50,9 +47,8 @@ import { ACTIVITY, DIRECTORY, INVOICES } from "./customers-demo-sources" * Customers lab fixtures: one fictional org, internally consistent with the Wonder designs. * * - `NOW` is fixed (Tue 10 Nov 2026, 12:00 UTC); every age and date is relative to it. - * - 214 accounts, $48,210 MRR: healthy 142 ($35,980) · at risk 41 ($8,140) · critical 18 ($3,310) - * · unknown 13 ($780). The ~20 named accounts carry the edge cases (huge MRR, trial with no MRR, - * churned, past due, long name, no logo); the rest are generated (seeded) to hit those totals. + * - 214 accounts, $48,210 MRR. The ~20 named accounts carry the edge cases (huge MRR, trial with no + * MRR, churned, past due, long name, no logo); the rest are generated (seeded) to hit those totals. * - Signals cover every evidence viz and every status. * - Typed against `@hazel/domain/customers`, so a contract change breaks here first. */ @@ -117,8 +113,6 @@ type AccountSeed = Readonly<{ domain: string | null plan: string | null mrr: number - health: HealthStatus - score: number | null stage?: LifecycleStage owner?: TeamMember | null contacts?: number @@ -317,9 +311,6 @@ const makeAccount = (seed: AccountSeed, n: number): Account => { trialListMrrMinor: seed.trialListMrr === undefined ? null : seed.trialListMrr * 100, trialEndsAt: seed.trialEndsInDays === undefined ? null : new Date(NOW.getTime() + seed.trialEndsInDays * DAY), - healthScore: seed.score, - healthStatus: seed.health, - healthUpdatedAt: ago(HOUR), seatsUsed: seed.seats?.[0] ?? null, seatsLimit: seed.seats?.[1] ?? null, contactCount: seed.contacts ?? 8, @@ -368,8 +359,6 @@ const NAMED_SEEDS = { domain: "northwind.dev", plan: "Scale", mrr: 4_800, - health: "healthy", - score: 82, owner: MAYA, contacts: 51, active30d: 42, @@ -385,8 +374,6 @@ const NAMED_SEEDS = { domain: "acmerobotics.io", plan: "Growth", mrr: 2_150, - health: "at_risk", - score: 54, stage: "past_due", owner: JONAS, contacts: 24, @@ -403,8 +390,6 @@ const NAMED_SEEDS = { domain: "kestrel.so", plan: "Scale", mrr: 1_320, - health: "critical", - score: 27, owner: MAYA, contacts: 14, active30d: 9, @@ -420,8 +405,6 @@ const NAMED_SEEDS = { domain: "brightfield.co", plan: "Trial", mrr: 0, - health: "unknown", - score: null, stage: "trialing", owner: null, contacts: 7, @@ -439,8 +422,6 @@ const NAMED_SEEDS = { domain: "halcyonhealth.com", plan: "Enterprise", mrr: 8_900, - health: "healthy", - score: 91, owner: DANA, contacts: 212, active30d: 168, @@ -455,8 +436,6 @@ const NAMED_SEEDS = { domain: "oakridge-logistics.com", plan: null, mrr: 0, - health: "unknown", - score: null, stage: "churned", owner: JONAS, contacts: 9, @@ -471,8 +450,6 @@ const NAMED_SEEDS = { domain: "ciwmh.de", plan: "Growth", mrr: 640, - health: "at_risk", - score: 48, owner: PRIYA, contacts: 33, active30d: 11, @@ -485,8 +462,6 @@ const NAMED_SEEDS = { domain: null, plan: null, mrr: 0, - health: "unknown", - score: null, stage: "lead", owner: null, contacts: 2, @@ -500,8 +475,6 @@ const NAMED_SEEDS = { domain: "lumen.health", plan: "Growth", mrr: 890, - health: "at_risk", - score: 61, owner: DANA, contacts: 19, active30d: 12, @@ -514,8 +487,6 @@ const NAMED_SEEDS = { domain: "fernway.app", plan: "Starter", mrr: 380, - health: "critical", - score: 36, owner: PRIYA, contacts: 6, active30d: 2, @@ -528,8 +499,6 @@ const NAMED_SEEDS = { domain: "quarrylabs.io", plan: "Growth", mrr: 1_150, - health: "healthy", - score: 88, owner: MAYA, contacts: 26, active30d: 20, @@ -543,8 +512,6 @@ const NAMED_SEEDS = { domain: "tidewater.co", plan: "Starter", mrr: 290, - health: "critical", - score: 31, owner: JONAS, contacts: 5, active30d: 1, @@ -559,8 +526,6 @@ const NAMED_SEEDS = { domain: "marlowfinch.com", plan: "Growth", mrr: 760, - health: "at_risk", - score: 57, owner: MAYA, contacts: 17, active30d: 10, @@ -573,8 +538,6 @@ const NAMED_SEEDS = { domain: "vantablack.studio", plan: "Scale", mrr: 990, - health: "critical", - score: 22, stage: "past_due", owner: DANA, contacts: 11, @@ -588,8 +551,6 @@ const NAMED_SEEDS = { domain: "cobaltfreight.com", plan: "Growth", mrr: 520, - health: "at_risk", - score: 49, owner: MAYA, contacts: 15, active30d: 6, @@ -601,8 +562,6 @@ const NAMED_SEEDS = { domain: "juniper.ai", plan: "Growth", mrr: 690, - health: "healthy", - score: 76, owner: MAYA, contacts: 12, active30d: 10, @@ -614,8 +573,6 @@ const NAMED_SEEDS = { domain: "ridgeview.partners", plan: "Starter", mrr: 310, - health: "at_risk", - score: 52, owner: PRIYA, contacts: 4, active30d: 2, @@ -627,8 +584,6 @@ const NAMED_SEEDS = { domain: "sable.dev", plan: "Starter", mrr: 480, - health: "healthy", - score: 79, owner: JONAS, contacts: 9, active30d: 7, @@ -641,8 +596,6 @@ const NAMED_SEEDS = { domain: "acmerobotics.io", plan: "Growth", mrr: 640, - health: "healthy", - score: 78, owner: JONAS, contacts: 9, active30d: 8, @@ -656,8 +609,6 @@ const NAMED_SEEDS = { domain: "halcyonhealth.com", plan: "Enterprise", mrr: 3_200, - health: "healthy", - score: 86, owner: DANA, contacts: 64, active30d: 51, @@ -672,8 +623,6 @@ const NAMED_SEEDS = { domain: "halcyonhealth.com", plan: null, mrr: 0, - health: "unknown", - score: null, stage: "lead", owner: DANA, contacts: 6, @@ -766,17 +715,55 @@ const SUFFIXES = [ const PLANS_BY_MRR = (mrr: number): string | null => mrr === 0 ? null : mrr < 150 ? "Starter" : mrr < 700 ? "Growth" : mrr < 3_000 ? "Scale" : "Enterprise" -/** Status → [count, MRR] the whole book must reach (the overview's health distribution). */ -export const HEALTH_TOTALS = { - healthy: [142, 35_980], - at_risk: [41, 8_140], - critical: [18, 3_310], - unknown: [13, 780], -} as const satisfies Record +/** + * The generated book by engagement: accounts, their MRR ($), the share of contacts active (null: + * never active), how far the trend leans down, the longest idle time, and the open risk they carry. + */ +const COHORTS: ReadonlyArray< + Readonly<{ + count: number + mrr: number + activeShare: number | null + trendDown: number + idleHours: number + risk: readonly [high: number, medium: number, low: number] + hasFreeAccounts?: boolean + hasPastDue?: boolean + }> +> = [ + { count: 135, mrr: 16_120, activeShare: 0.7, trendDown: 15, idleHours: 48, risk: [0, 0, 0] }, + { + count: 35, + mrr: 2_870, + activeShare: 0.4, + trendDown: 40, + idleHours: 240, + risk: [0, 1, 0], + hasFreeAccounts: true, + }, + { + count: 14, + mrr: 330, + activeShare: 0.15, + trendDown: 40, + idleHours: 600, + risk: [1, 0, 0], + hasFreeAccounts: true, + hasPastDue: true, + }, + { + count: 9, + mrr: 780, + activeShare: null, + trendDown: 0, + idleHours: 0, + risk: [0, 0, 0], + hasFreeAccounts: true, + }, +] const generated = (() => { const random = prng(214) - const named = Object.values(NAMED_SEEDS) as ReadonlyArray const seeds: Array = [] let nameIndex = 0 const nextName = () => { @@ -784,43 +771,25 @@ const generated = (() => { nameIndex += 1 return name } - for (const status of ["healthy", "at_risk", "critical", "unknown"] as const) { - const [count, mrr] = HEALTH_TOTALS[status] - const own = named.filter((seed) => seed.health === status) - const remainingCount = count - own.length - const remainingMrr = mrr - own.reduce((sum, seed) => sum + seed.mrr, 0) - // Weights skewed small (most accounts are small), some at $0 for critical/unknown leads. - const weights = Array.from({ length: remainingCount }, () => { + for (const cohort of COHORTS) { + const { activeShare } = cohort + // Weights skewed small (most accounts are small), some at $0 for leads. + const weights = Array.from({ length: cohort.count }, () => { const roll = random() - return status !== "healthy" && roll < 0.3 ? 0 : roll ** 2.2 + 0.05 + return cohort.hasFreeAccounts === true && roll < 0.3 ? 0 : roll ** 2.2 + 0.05 }) const total = weights.reduce((sum, weight) => sum + weight, 0) // Whole $10 steps rounded down; the biggest account takes the remainder, so the total is exact. - const mrrs = weights.map((weight) => Math.floor(((weight / total) * remainingMrr) / 10) * 10) + const mrrs = weights.map((weight) => Math.floor(((weight / total) * cohort.mrr) / 10) * 10) const biggest = weights.indexOf(Math.max(...weights)) - const remainder = remainingMrr - mrrs.reduce((sum, value) => sum + value, 0) + const remainder = cohort.mrr - mrrs.reduce((sum, value) => sum + value, 0) const exact = mrrs.map((value, index) => (index === biggest ? value + remainder : value)) exact.forEach((accountMrr, index) => { const name = nextName() - const scoreBase = status === "healthy" ? 70 : status === "at_risk" ? 40 : 5 - const score = - status === "unknown" - ? null - : scoreBase + - Math.floor(random() * (status === "healthy" ? 30 : status === "at_risk" ? 30 : 35)) const contacts = 2 + Math.floor(random() * (accountMrr / 40 + 6)) - const active = - status === "unknown" - ? 0 - : Math.max( - 1, - Math.round( - contacts * (status === "healthy" ? 0.7 : status === "at_risk" ? 0.4 : 0.15), - ), - ) const stage: LifecycleStage = accountMrr > 0 - ? status === "critical" && index % 5 === 0 + ? cohort.hasPastDue === true && index % 5 === 0 ? "past_due" : "active" : index % 3 === 0 @@ -831,22 +800,13 @@ const generated = (() => { domain: `${name.toLowerCase().replace(/[^a-z0-9]+/g, "")}.com`, plan: stage === "trialing" ? "Trial" : PLANS_BY_MRR(accountMrr), mrr: accountMrr, - health: status, - score, stage, contacts, - active30d: active, + active30d: activeShare === null ? 0 : Math.max(1, Math.round(contacts * activeShare)), trendPct: - status === "unknown" - ? null - : Math.round((random() * 60 - (status === "healthy" ? 15 : 40)) * 10) / 10, - lastActiveHours: - status === "unknown" - ? null - : Math.round( - random() * (status === "healthy" ? 48 : status === "at_risk" ? 240 : 600), - ), - risk: status === "critical" ? [1, 0, 0] : status === "at_risk" ? [0, 1, 0] : [0, 0, 0], + activeShare === null ? null : Math.round((random() * 60 - cohort.trendDown) * 10) / 10, + lastActiveHours: activeShare === null ? null : Math.round(random() * cohort.idleHours), + risk: cohort.risk, trialEndsInDays: stage === "trialing" ? 1 + Math.floor(random() * 13) : undefined, trialListMrr: stage === "trialing" ? 290 : undefined, }) @@ -1106,25 +1066,21 @@ const SIGNAL_SEEDS: ReadonlyArray = [ }, { account: "fernway", - template: "health_drop", + template: "usage_drop", severity: "medium", - title: "Health dropped", - reason: "Health fell 36 points in 7 days, from 72 to 36", + reason: "Daily active users down 55% (7-day avg 2 vs 4.4 before)", priority: 5.8, openedDaysAgo: 2, evidence: { - _tag: "delta", + _tag: "series", step: 1, - unit: "points", - from: 72, - to: 36, - changePct: -50, - currency: null, - effectiveAt: null, - fromLabel: null, - toLabel: null, - reason: null, - series: series([72, 70, 66, 58, 51, 44, 40, 36]), + metricKey: "active_users", + recentAvg: 2, + baselineAvg: 4.4, + changePct: -54.5, + recentDays: 7, + baselineDays: 28, + series: dropSeries(4.4, 2, 17), }, }, { @@ -1252,27 +1208,23 @@ const SIGNAL_SEEDS: ReadonlyArray = [ }, { account: "ridgeview", - template: "health_drop", + template: "usage_drop", severity: "low", status: "dismissed", - title: "Health dropped", - reason: "Health fell 21 points in 7 days, from 73 to 52", + reason: "Daily active users down 29% (7-day avg 1.7 vs 2.4 before)", priority: 2.2, openedDaysAgo: 9, resolvedDaysAgo: 6, evidence: { - _tag: "delta", + _tag: "series", step: 0, - unit: "points", - from: 73, - to: 52, - changePct: -28.8, - currency: null, - effectiveAt: null, - fromLabel: null, - toLabel: null, - reason: null, - series: [], + metricKey: "active_users", + recentAvg: 1.7, + baselineAvg: 2.4, + changePct: -29.2, + recentDays: 7, + baselineDays: 28, + series: dropSeries(2.4, 1.7, 19), }, }, { @@ -1347,7 +1299,7 @@ export const RULES: ReadonlyArray = (Object.keys(TEMPLATES) as Reado config: meta.defaultConfig, scope: {}, // One rule off, so the rules list shows a disabled row. - enabled: template !== "health_drop", + enabled: template !== "churned", createdBy: null, updatedBy: null, lastTriggeredAt: matching > 0 ? daysAgo(1) : null, @@ -1362,7 +1314,6 @@ export const RULES: ReadonlyArray = (Object.keys(TEMPLATES) as Reado export const SETTINGS: Settings = { id: Schema.decodeSync(CustomerSettingsId)(uuid(22, 1)), organizationId: ORGANIZATION_ID, - health: DEFAULT_HEALTH_SETTINGS, attention: DEFAULT_ATTENTION_SETTINGS, reportingCurrency: CURRENCY, addOnPlans: [], @@ -1524,10 +1475,6 @@ const activeUsersDaily = (days: number): ReadonlyArray => { const bucketed = (points: ReadonlyArray, every: number): ReadonlyArray => points.filter((_, index) => (points.length - 1 - index) % every === 0) -export const HEALTH_DISTRIBUTION: ReadonlyArray = ( - ["healthy", "at_risk", "critical", "unknown"] as const -).map((status) => ({ status, count: HEALTH_TOTALS[status][0], mrrMinor: HEALTH_TOTALS[status][1] * 100 })) - const brief = (key: NamedAccount, at: Date) => { const account = ACCOUNTS_BY_KEY[key] return { @@ -1611,7 +1558,6 @@ export const overviewFixture = ( }, mrrMovements: billing ? mrrMovements : [], activeUsers, - healthDistribution: HEALTH_DISTRIBUTION, topMovers: { gainers: [ mover("quarry", 5.6, 14, [8, 9, 9, 11, 12, 14, 15, 17, 18, 20]), @@ -1765,49 +1711,6 @@ export const ACME_DETAIL: AccountDetail = { updatedAt: daysAgo(1), }, ], - health: { - score: 54, - status: "at_risk", - components: [ - { - key: "usage", - score: 55, - weight: 35, - effectiveWeight: 35, - excluded: false, - why: "18 of 24 contacts active in 30 days; trend −22%", - }, - { - key: "engagement", - score: 90, - weight: 25, - effectiveWeight: 25, - excluded: false, - why: "Last active 3 days ago", - }, - { - key: "billing", - score: 20, - weight: 25, - effectiveWeight: 25, - excluded: false, - why: "Subscription past due; INV-2041 9 days overdue", - }, - { - key: "signals", - score: 70, - weight: 15, - effectiveWeight: 15, - excluded: false, - why: "1 open high-severity risk signal", - }, - ], - }, - healthSeries: series( - Array.from({ length: 90 }, (_, index) => - index < 75 ? 72 + ((index * 5) % 7) : 72 - (index - 74) * 1.2, - ).map(Math.round), - ), activeUsersSeries: series( Array.from({ length: 30 }, (_, index) => Math.max(3, Math.round(14 - index * 0.25 + ((index * 7) % 5))), diff --git a/apps/web-foldkit/src/lab/registry.ts b/apps/web-foldkit/src/lab/registry.ts index ca923a28f..13c9b9b56 100644 --- a/apps/web-foldkit/src/lab/registry.ts +++ b/apps/web-foldkit/src/lab/registry.ts @@ -31,11 +31,8 @@ export const LAB_DESCRIPTIONS: ReadonlyMap = new Map([ "/lab/kit", "Every src/ui component, live: tokens, buttons, fields, selection, navigation, feedback, overlays.", ], - ["/lab/customers/kit/tokens", "Chart, health and severity color tokens in light and dark."], - [ - "/lab/customers/kit/badges", - "Health badges and dots, severity and kind chips, lifecycle stages, open-signal counts.", - ], + ["/lab/customers/kit/tokens", "Chart and severity color tokens in light and dark."], + ["/lab/customers/kit/badges", "Severity and kind chips, lifecycle stages, open-signal counts."], ["/lab/customers/kit/identity", "Company logos and tints, owner avatars, source marks and chips."], [ "/lab/customers/kit/kpi-tiles", @@ -45,7 +42,7 @@ export const LAB_DESCRIPTIONS: ReadonlyMap = new Map([ ["/lab/customers/kit/evidence", "Every evidence viz, compact (queue) and detailed (side panel)."], [ "/lab/customers/kit/charts", - "Active users lines, MRR movement bars, health distribution, with hover tooltips (`?range=`).", + "Active users lines and MRR movement bars, with hover tooltips (`?range=`).", ], [ "/lab/customers/kit/table", diff --git a/apps/web-foldkit/src/page/chat/channel/issue.story.test.ts b/apps/web-foldkit/src/page/chat/channel/issue.story.test.ts index aea5d420d..e7ac77a09 100644 --- a/apps/web-foldkit/src/page/chat/channel/issue.story.test.ts +++ b/apps/web-foldkit/src/page/chat/channel/issue.story.test.ts @@ -46,9 +46,6 @@ const linkedModel = (): Model => ({ accountId, accountName: "Acme", accountLogoUrl: null, - healthStatus: "unknown", - healthScore: null, - healthWhy: null, lifecycleStage: null, planName: null, mrrMinor: null, diff --git a/apps/web-foldkit/src/page/chat/customer-card.gallery.ts b/apps/web-foldkit/src/page/chat/customer-card.gallery.ts index a6d648459..f0d56e892 100644 --- a/apps/web-foldkit/src/page/chat/customer-card.gallery.ts +++ b/apps/web-foldkit/src/page/chat/customer-card.gallery.ts @@ -19,7 +19,7 @@ import { ACTIVITY, DIRECTORY, INVOICES } from "../../lab/fixtures/customers-demo /** * The linked channel's customer at a glance (`customer-card.ts`): the header chip and the card in - * each state the PR shows (populated, many signals, unknown health, a new customer, no customer), + * each state the PR shows (populated, many signals, a new customer, no customer), * desktop and phone width, light and dark (`bun run gallery`). Writes `customer-card-.png`. */ @@ -102,9 +102,6 @@ const base: ChannelCustomer.Type = { colors: ["#6938ef"], logoUrl: null, }, - healthStatus: "at_risk", - healthScore: 48, - healthWhy: "No sign-ins for 18 days; 12 weekly active users before", lifecycleStage: "active", planName: "Pro", mrrMinor: 240_000, @@ -129,9 +126,6 @@ const base: ChannelCustomer.Type = { const manySignals: ChannelCustomer.Type = { ...base, accountName: "Globex International Holdings", - healthStatus: "critical", - healthScore: 22, - healthWhy: "Subscription past due; 3 high-severity risk signals open", lifecycleStage: "past_due", openSignalCount: 9, topSignals: [ @@ -141,14 +135,11 @@ const manySignals: ChannelCustomer.Type = { ], } -const unknownHealth: ChannelCustomer.Type = { +const newCustomer: ChannelCustomer.Type = { ...base, accountName: "Initech", // No enriched company: no company block. company: null, - healthStatus: "unknown", - healthScore: null, - healthWhy: null, lifecycleStage: "trialing", planName: "Team trial", mrrMinor: 0, @@ -275,9 +266,9 @@ const screen = (h: HtmlBuilder) => h.Class("flex w-[1720px] flex-wrap items-start gap-6 bg-bg p-8 font-sans text-fg antialiased"), ], [ - frame(h, "Desktop · at risk", base, { width: 520 }), + frame(h, "Desktop · open signals", base, { width: 520 }), frame(h, "Desktop · many signals", manySignals, { width: 520 }), - frame(h, "Desktop · unknown health, new customer", unknownHealth, { width: 520 }), + frame(h, "Desktop · new customer", newCustomer, { width: 520 }), frame(h, "Desktop · no customer", null, { width: 520 }), frame(h, "Phone · sheet", base, { width: 400, isMobile: true }), frame(h, "Phone · many signals", manySignals, { width: 400, isMobile: true }), diff --git a/apps/web-foldkit/src/page/chat/customer-card.ts b/apps/web-foldkit/src/page/chat/customer-card.ts index 22ba5bf46..b3b2278bf 100644 --- a/apps/web-foldkit/src/page/chat/customer-card.ts +++ b/apps/web-foldkit/src/page/chat/customer-card.ts @@ -1,6 +1,6 @@ /** * A linked channel's customer at a glance (`docs/customers/channels.md`, "In the channel"): the - * header chip, and the card it opens: health and why, stage, plan, MRR, owner, seats, last active, + * header chip, and the card it opens: stage, plan, MRR, owner, seats, last active, * the enriched company (description, facts, links), open signals and the ways out (the customer page, the queue, the providers). From the org source * (`channel_customers`), so nothing opens the Customers source. * @@ -9,7 +9,7 @@ * same card in a bottom sheet. */ import type { ChannelCustomer } from "@hazel/domain/models" -import type { CompanyProfile, HealthStatus } from "@hazel/domain/customers" +import type { CompanyProfile } from "@hazel/domain/customers" import { Duration, Effect, Option, Schema } from "effect" import { Command, Mount } from "foldkit" import type { Html, HtmlBuilder } from "foldkit/html" @@ -17,7 +17,7 @@ import { defineMessageUnion } from "foldkit/message" import { modifyFields } from "foldkit/struct" import { twMerge } from "tailwind-merge" import { dayToMs, formatMoney, formatRelative } from "../../customers/format" -import { HEALTH_FILL, healthBadge, severityGlyph, stageBadge } from "../../customers/ui/badges" +import { severityGlyph, stageBadge } from "../../customers/ui/badges" import { companyFacts, companyLinks } from "../../customers/ui/company" import { safeSourceUrl, sourceLabel } from "../../customers/providers" import { companyLogo, sourceLogo } from "../../customers/ui/identity" @@ -26,7 +26,6 @@ import { IconOffice } from "../../icons" import { ariaButton } from "../../ui/button" import * as Modal from "../../ui/modal" import * as Sheet from "../../ui/sheet" -import { statusDot } from "../../ui/status-dot" // MODEL @@ -237,13 +236,6 @@ export type CardContext = Readonly<{ support?: ReadonlyArray }> -const HEALTH_CHIP_LABEL = { - healthy: "healthy", - at_risk: "at risk", - critical: "critical", - unknown: "health unknown", -} as const satisfies Record - /** Whether the chip's card (or a phone's sheet) is showing: all the header needs of the Model. */ export const isOpenOf = (model: Model, isMobile: boolean): boolean => isMobile ? model.sheet.isOpen : model.phase === "hover" || model.phase === "pinned" @@ -258,7 +250,7 @@ const escapeKey = (h: HtmlBuilder, toMessage: (message: Message) => M) => ) /** - * The header chip: the health dot and the customer's name; it opens the card. Above a pinned card's + * The header chip: an office mark and the customer's name; it opens the card. Above a pinned card's * backdrop (`z-50`), so a second press on it closes the card instead of landing on the backdrop. * Its hit area reaches 12px past its edges, a ~46px touch target in a 56px header. */ @@ -282,7 +274,7 @@ export const chip = ( onPress: toMessage(Message.PressedChip({ isMobile: options.isMobile })), attributes: [ h.Id(CHIP_ID), - h.AriaLabel(`Customer: ${customer.accountName}, ${HEALTH_CHIP_LABEL[customer.healthStatus]}`), + h.AriaLabel(`Customer: ${customer.accountName}`), h.AriaExpanded(isOpen), h.AriaHasPopup("dialog"), ...(isOpen @@ -298,9 +290,7 @@ export const chip = ( ], }, [ - customer.healthStatus === "unknown" - ? IconOffice(h, { className: "size-3 shrink-0" }) - : statusDot(h, { tone: "neutral", className: HEALTH_FILL[customer.healthStatus] }), + IconOffice(h, { className: "size-3 shrink-0" }), h.span([h.Class("truncate")], [customer.accountName]), ], ) @@ -461,7 +451,7 @@ const pendingBody = (h: HtmlBuilder, context: CardContext): Html => ), h.p( [h.Class(twMerge(descriptionClass, "px-4 pb-3 text-xs"))], - ["Health, revenue and signals show here after the next customer sync."], + ["Revenue and signals show here after the next customer sync."], ), h.div( [h.Class("border-border border-t bg-secondary/40 px-4 py-2.5")], @@ -479,7 +469,7 @@ export const cardBody = (h: HtmlBuilder, context: CardContext): Html => { return h.div( [h.Class("flex flex-col")], [ - // Who, and how they are doing. + // Who, and where they are in their lifecycle. h.div( [h.Class("flex items-start gap-3 px-4 pt-4 pb-3")], [ @@ -498,35 +488,14 @@ export const cardBody = (h: HtmlBuilder, context: CardContext): Html => { ], [customer.accountName], ), - h.div( - [h.Class("flex flex-wrap items-center gap-1.5")], - [ - customer.healthStatus === "unknown" - ? healthBadge(h, { status: customer.healthStatus }) - : healthBadge(h, { - status: customer.healthStatus, - score: customer.healthScore, - }), - ...(customer.lifecycleStage === null - ? [] - : [stageBadge(h, customer.lifecycleStage)]), - ], - ), + ...(customer.lifecycleStage === null + ? [] + : [stageBadge(h, customer.lifecycleStage, { className: "w-fit" })]), ], ), ], ), - ...(customer.healthStatus === "unknown" - ? [ - h.p( - [h.Class(twMerge(descriptionClass, "px-4 pb-3 text-xs"))], - ["No health score yet: it needs a connected source with usage or billing."], - ), - ] - : customer.healthWhy === null - ? [] - : [h.p([h.Class(twMerge(descriptionClass, "px-4 pb-3 text-xs"))], [customer.healthWhy])]), - // What the company is (enriched), under the health it explains. + // What the company is (enriched). ...(customer.company === undefined || customer.company === null ? [] : companyBlock(h, customer.company)), diff --git a/apps/web-foldkit/src/page/customers/README.md b/apps/web-foldkit/src/page/customers/README.md index d75b45319..87efbf9d4 100644 --- a/apps/web-foldkit/src/page/customers/README.md +++ b/apps/web-foldkit/src/page/customers/README.md @@ -15,7 +15,6 @@ here is an ordinary page (`definePage`), registered in `pages.ts`, the Customers | `CustomersSettingsSignals` | `/settings/signals` | | `settings/signals/` | | `CustomersSettingsSignalNew` | `/settings/signals/new?template=` | `template: Option` | `settings/signals/` | | `CustomersSettingsSignalRule` | `/settings/signals/$ruleId` | `ruleId` | `settings/signals/` | -| `CustomersSettingsHealth` | `/settings/health` | | `settings/health/` | | `CustomersSettingsPlans` | `/settings/plans` | | `settings/plans/` | | `CustomersSettingsSla` | `/settings/sla` | | `settings/sla/` | | `CustomersSettingsFeatureFlags` | `/settings/feature-flags` | | `settings/feature-flags/` | @@ -23,8 +22,8 @@ here is an ordinary page (`definePage`), registered in `pages.ts`, the Customers | `CustomersSourceDetail` | `/settings/sources/$provider` | `provider: CustomerProvider` | `settings/sources/` | | `CustomersUnmatched` | `/settings/sources/unmatched` | | `settings/unmatched/` | -- `view` is a built-in view's key (`BuiltInViewKey`: `my_customers`, `paying`, `trialing`, `at_risk`, - `churned`) or a saved view's id; the sidebar links built-ins by key, so they work before views sync. +- `view` is a built-in view's key (`BuiltInViewKey`: `my_customers`, `paying`, `trialing`, `churned`) + or a saved view's id; the sidebar links built-ins by key, so they work before views sync. - `CustomerTab` = `overview | users | billing | activity | notes` (none = overview). - Helpers: `customersListRoute(orgSlug, view?)`, `customerRoute(orgSlug, accountId, tab?)`; `isCustomersRoute`. Links are `h.Href(hrefOf(route))`; navigation from `update` is `requestedOrgNavigation(shared.orgSlug, (orgSlug) => customerRoute(orgSlug, id))`. @@ -54,7 +53,7 @@ Synced rows become plain page rows (dates as epoch ms), the same shape the lab f - `myOpenSignalCountStream(orgId, userId, toMessage)`: the sidebar badge. - `savedViewsStream(orgId, userId, toMessage)`: shared + mine, by position. - `connectedProvidersStream(orgId, toMessage)`: providers not disconnected. - - `settingsSummaryStream(orgId, toMessage)`: `{ lastComputedAtMs, bands, reportingCurrency }` or null. + - `settingsSummaryStream(orgId, toMessage)`: `{ lastComputedAtMs, reportingCurrency }` or null. - `orgMembersStream(orgId, toMessage)`: `MemberRow`s (owners, assignees); from the org source. - `impersonatorsStream(orgId, toMessage)`: `ImpersonatorRow`s, the members who may impersonate. - "Mine" everywhere (queue filter, sidebar badge, overview) = signals on accounts I own. diff --git a/apps/web-foldkit/src/page/customers/attention/model.ts b/apps/web-foldkit/src/page/customers/attention/model.ts index 126c5dde1..9b5b50806 100644 --- a/apps/web-foldkit/src/page/customers/attention/model.ts +++ b/apps/web-foldkit/src/page/customers/attention/model.ts @@ -33,16 +33,15 @@ import * as Modal from "../../../ui/modal" export const Tab = Schema.Literals(["open", "snoozed", "done"]) export const Grouping = Schema.Literals(["signals", "accounts"]) export type Grouping = typeof Grouping.Type -export const Sort = Schema.Literals(["priority", "account", "signal", "severity", "age", "health", "mrr"]) +export const Sort = Schema.Literals(["priority", "account", "signal", "severity", "age", "mrr"]) export type Sort = typeof Sort.Type -/** Each sort's own direction (the header's `aria-sort`): # runs 1 down, Age oldest first, Health worst first. */ +/** Each sort's own direction (the header's `aria-sort`): # runs 1 down, Age oldest first. */ export const SORT_ASCENDING = { priority: true, account: true, signal: true, severity: false, age: false, - health: true, mrr: false, } as const satisfies Record /** Whose accounts: the default, "Mine or unowned", is accounts I own plus ones nobody owns yet. */ @@ -218,11 +217,6 @@ const sortedForTab = ( signal: Order.mapInput(Order.String, (signal: SignalRowType) => signal.title.toLowerCase()), severity: bySeverity, age: byOpened, - // No score yet sorts last. - health: Order.mapInput( - Order.Number, - (signal: SignalRowType) => accountOf(signal)?.healthScore ?? Infinity, - ), mrr: Order.mapInput( Order.flip(Order.Number), (signal: SignalRowType) => accountOf(signal)?.mrrMinor ?? 0, diff --git a/apps/web-foldkit/src/page/customers/attention/preview.ts b/apps/web-foldkit/src/page/customers/attention/preview.ts index c239a69b4..31e5c5711 100644 --- a/apps/web-foldkit/src/page/customers/attention/preview.ts +++ b/apps/web-foldkit/src/page/customers/attention/preview.ts @@ -6,7 +6,7 @@ import { customerAccountOf, queueNameOf } from "../../../customers/groups" import type { AccountRow, SignalRow } from "../../../customers/queries" import { formatCount, formatDate, formatMoney, formatRelative } from "../../../customers/format" import { environmentCounts, environmentsHintOf } from "../../../customers/groups" -import { healthBadge, kindChip, severityChip, STAGE_LABEL } from "../../../customers/ui/badges" +import { kindChip, severityChip, STAGE_LABEL } from "../../../customers/ui/badges" import { evidenceDetail } from "../../../customers/ui/evidence" import { companyLogo, personLabel, sourceMark } from "../../../customers/ui/identity" import { kbd } from "../../../customers/ui/shortcuts" @@ -50,22 +50,13 @@ const section = (h: HtmlBuilder, title: string, children: ReadonlyArray const summary = (h: HtmlBuilder, account: AccountRow, owner: string | null): Html => h.div( - [h.Class("grid grid-cols-2 gap-3 px-5 py-4 md:grid-cols-4")], + [h.Class("grid grid-cols-3 gap-3 px-5 py-4")], [ stat(h, { label: "MRR", value: formatMoney(account.mrrMinor, account.currency), detail: account.planName, }), - stat(h, { - label: "Health", - value: healthBadge(h, { - status: account.healthStatus, - score: account.healthScore, - className: "w-fit", - }), - detail: null, - }), stat(h, { label: "Active 30d", value: `${formatCount(account.activeUsers30d)} of ${formatCount(account.contactCount)}`, diff --git a/apps/web-foldkit/src/page/customers/attention/rows.ts b/apps/web-foldkit/src/page/customers/attention/rows.ts index 03252d71c..d991e3dde 100644 --- a/apps/web-foldkit/src/page/customers/attention/rows.ts +++ b/apps/web-foldkit/src/page/customers/attention/rows.ts @@ -4,13 +4,7 @@ import { queueNameOf } from "../../../customers/groups" import type { AccountRow, MemberRow, SignalRow } from "../../../customers/queries" import { resolvedAtMsOf } from "../../../customers/queries" import { formatDate, formatMoney, formatWeekdayTime } from "../../../customers/format" -import { - environmentsHint, - healthBadge, - healthDot, - kindChip, - severityGlyph, -} from "../../../customers/ui/badges" +import { environmentsHint, kindChip, severityGlyph } from "../../../customers/ui/badges" import { evidenceViz } from "../../../customers/ui/evidence" import { companyLogo, personAvatar, personLabel } from "../../../customers/ui/identity" import { @@ -152,7 +146,6 @@ export const signalRow = ( evidence: evidenceViz(h, signal.evidence), age: ageText(signal.openedAtMs, context.nowMs), assignee: personOf(context, signal.assigneeUserId), - health: { status: account.healthStatus, score: account.healthScore }, environmentCount: context.environmentCounts.get(account.id) ?? 0, isFocused: isSelected, isSelected, @@ -161,7 +154,7 @@ export const signalRow = ( }) } -/** Open tab beside the preview (Wonder: Queue Selected With Preview): account, signal, age, health. */ +/** Open tab beside the preview (Wonder: Queue Selected With Preview): account, signal, age. */ export const compactRow = ( h: HtmlBuilder, signal: SignalRow, @@ -216,10 +209,6 @@ export const compactRow = ( [h.Role("cell"), h.Class("w-8 text-right text-muted-fg text-sm tabular-nums")], [ageText(signal.openedAtMs, context.nowMs)], ), - h.span( - [h.Role("cell"), h.Class("w-12 shrink-0 text-right")], - [healthDot(h, { status: account.healthStatus, score: account.healthScore })], - ), ]) } @@ -311,10 +300,6 @@ export const accountGroupRow = ( [h.Role("cell"), h.Class("flex w-10 justify-center -space-x-1.5 max-md:hidden")], assignees.map((userId) => personAvatar(h, personOf(context, userId), { ring: true })), ), - h.div( - [h.Role("cell"), h.Class("flex w-28 shrink-0 justify-end max-md:w-auto")], - [healthBadge(h, { status: account.healthStatus, score: account.healthScore })], - ), ]) } @@ -403,10 +388,6 @@ export const snoozedRow = ( ], ), ...(signal.id === context.selectedId ? context.actions : []), - h.div( - [h.Role("cell"), h.Class("flex w-28 shrink-0 justify-end max-md:w-auto")], - [healthBadge(h, { status: account.healthStatus, score: account.healthScore })], - ), ]) } diff --git a/apps/web-foldkit/src/page/customers/attention/story.test.ts b/apps/web-foldkit/src/page/customers/attention/story.test.ts index e1de02736..d9bbe7139 100644 --- a/apps/web-foldkit/src/page/customers/attention/story.test.ts +++ b/apps/web-foldkit/src/page/customers/attention/story.test.ts @@ -96,8 +96,6 @@ const account = ( currency: "USD", trialListMrrMinor: null, trialEndsAtMs: null, - healthScore: 54, - healthStatus: "at_risk", seatsUsed: null, seatsLimit: null, contactCount: 10, @@ -198,7 +196,7 @@ const snoozed = signal(5, acme, { priorityScore: 4, }) const done = signal(6, kestrel, { - title: "Health dropped", + title: "Usage dropped", status: "done", outcome: "fixed", resolvedAtMs: NOW - DAY, @@ -348,7 +346,7 @@ describe("needs attention: what shows", () => { // Oldest first, then newest first; each account's signals stay together. expect(ids(visibleSignals(byAge, viewer))).toEqual(ids([usageDown, paymentFailed, stoppedLogging])) expect(ids(visibleSignals(reversed, viewer))).toEqual(ids([paymentFailed, usageDown, stoppedLogging])) - expect(pageUpdate(reversed, Message.ClickedColumnSort({ sort: "health" })).model.isSortReversed).toBe( + expect(pageUpdate(reversed, Message.ClickedColumnSort({ sort: "mrr" })).model.isSortReversed).toBe( false, ) }) diff --git a/apps/web-foldkit/src/page/customers/attention/view.ts b/apps/web-foldkit/src/page/customers/attention/view.ts index f0c14e65c..1bc0b1dcb 100644 --- a/apps/web-foldkit/src/page/customers/attention/view.ts +++ b/apps/web-foldkit/src/page/customers/attention/view.ts @@ -78,7 +78,6 @@ const SORT_LABEL = { signal: "Signal", severity: "Severity", age: "Age", - health: "Health", mrr: "MRR", } as const satisfies Record const OWNER_LABEL = { @@ -584,7 +583,6 @@ const list = (h: HtmlBuilder, model: Model, viewer: Viewer): Html => { ["Signal and snooze note", "flex-1"], ["Wakes up", "w-44"], ["Snoozed by", "w-36 max-lg:hidden"], - ["Health", "w-28 text-right"], ]), ...signals.map((signal, index) => snoozedRow(h, signal, context, accountRunOf(signals, index))), h.div( @@ -627,7 +625,6 @@ const list = (h: HtmlBuilder, model: Model, viewer: Viewer): Html => { ["Open signals", "flex-1"], ["Oldest", "w-8 text-right", "age"], ["", "w-10"], - ["Health", "w-28 text-right", "health"], ]), ...accountGroups(signals).map((group, index) => accountGroupRow(h, group, index + 1, context), @@ -642,7 +639,6 @@ const list = (h: HtmlBuilder, model: Model, viewer: Viewer): Html => { ["Severity", "w-24", "severity"], ["Age", "w-8 text-right", "age"], ["", "w-6"], - ["Health", "w-28 text-right", "health"], ]), ...signals.map((signal, index) => signalRow(h, signal, index + 1, context, accountRunOf(signals, index)), diff --git a/apps/web-foldkit/src/page/customers/detail/activity-tab.ts b/apps/web-foldkit/src/page/customers/detail/activity-tab.ts index e389d09a8..5451e411f 100644 --- a/apps/web-foldkit/src/page/customers/detail/activity-tab.ts +++ b/apps/web-foldkit/src/page/customers/detail/activity-tab.ts @@ -32,7 +32,6 @@ const TYPE_LABEL = { billing: "Billing", signals: "Signals", contacts: "Contacts", - health: "Health", notes: "Notes", } as const satisfies Record diff --git a/apps/web-foldkit/src/page/customers/detail/event-detail.ts b/apps/web-foldkit/src/page/customers/detail/event-detail.ts index b66fad2b6..eaa63e696 100644 --- a/apps/web-foldkit/src/page/customers/detail/event-detail.ts +++ b/apps/web-foldkit/src/page/customers/detail/event-detail.ts @@ -96,11 +96,6 @@ const summaryOf = (event: Customers.Event, context: DetailContext): string | nul ? null : `${formatMoney(from, context.currency)}/mo → ${formatMoney(to, context.currency)}/mo` } - case "health.status_changed": { - const from = count(data.fromScore) - const to = count(data.toScore) - return from === null || to === null ? null : `Score ${from} → ${to}` - } default: return null } diff --git a/apps/web-foldkit/src/page/customers/detail/message.ts b/apps/web-foldkit/src/page/customers/detail/message.ts index 4b442abb8..130a1898c 100644 --- a/apps/web-foldkit/src/page/customers/detail/message.ts +++ b/apps/web-foldkit/src/page/customers/detail/message.ts @@ -59,7 +59,6 @@ export const Message = defineMessageUnion({ UpdatedMembers: { members: Schema.Array(MemberRow) }, UpdatedMetrics: { metrics: Schema.Array(MetricRow) }, UpdatedConnectedProviders: { providers: Schema.Array(Customers.CustomerProvider) }, - UpdatedBands: { bands: Customers.HealthBands }, ClickedTab: { tab: CustomerTab }, PressedNeighbour: { step: Schema.Literals([-1, 1]) }, diff --git a/apps/web-foldkit/src/page/customers/detail/model.ts b/apps/web-foldkit/src/page/customers/detail/model.ts index afc04ff63..64f9f3afa 100644 --- a/apps/web-foldkit/src/page/customers/detail/model.ts +++ b/apps/web-foldkit/src/page/customers/detail/model.ts @@ -72,7 +72,7 @@ export const EMPTY_PAGE = { items: [], nextCursor: null, status: "Idle" } as con export const ContactFilter = Schema.Literals(["all", "active", "dormant", "never_active"]) export type ContactFilter = typeof ContactFilter.Type -export const EventType = Schema.Literals(["all", "billing", "signals", "contacts", "health", "notes"]) +export const EventType = Schema.Literals(["all", "billing", "signals", "contacts", "notes"]) export type EventType = typeof EventType.Type /** `customers.events.list` type prefixes per filter. */ @@ -81,7 +81,6 @@ export const EVENT_TYPE_PREFIXES = { billing: ["invoice.", "subscription."], signals: ["signal."], contacts: ["contact."], - health: ["health."], notes: ["note."], } as const satisfies Record> @@ -131,8 +130,6 @@ export const Model = Schema.Struct({ members: Schema.Array(MemberRow), metrics: Schema.Array(MetricRow), connectedProviders: Schema.Array(Customers.CustomerProvider), - /** The org's health bands (the breakdown's colors and "At risk is 40–69"). */ - bands: Customers.HealthBands, detail: Detail.schema, usageMetric: Schema.String, usageRange: Customers.CustomersRange, diff --git a/apps/web-foldkit/src/page/customers/detail/overview-tab.ts b/apps/web-foldkit/src/page/customers/detail/overview-tab.ts index f6e1fc734..643de7721 100644 --- a/apps/web-foldkit/src/page/customers/detail/overview-tab.ts +++ b/apps/web-foldkit/src/page/customers/detail/overview-tab.ts @@ -20,9 +20,8 @@ import { accountLabelOf } from "../../../customers/groups" import { msOf, type SignalRow } from "../../../customers/queries" import { overdueByMs } from "../../../customers/sla" import { formatResponse, formatWithin } from "../../../customers/support-report" -import { HEALTH_LABEL, severityGlyph } from "../../../customers/ui/badges" +import { severityGlyph } from "../../../customers/ui/badges" import { rangePicker } from "../../../customers/ui/filter-bar" -import { healthBreakdown } from "../../../customers/ui/health-breakdown" import { personLabel, sourceMark } from "../../../customers/ui/identity" import { snoozeMenuContent } from "../../../customers/ui/menus" import { queueAction } from "../../../customers/ui/queue-row" @@ -40,7 +39,6 @@ import { AppRoute, customerRoute, hrefOf } from "../../../route" import { button } from "../../../ui/button" import { heading } from "../../../ui/heading" import { menuLabel } from "../../../ui/menu-view" -import { disclosure } from "../../../customers/ui/disclosure" import { Message } from "./message" import { ASSIGN_ME, @@ -64,9 +62,9 @@ import { skeleton } from "../../../ui/skeleton" /** * The overview tab, read top to bottom as "what needs me, how are they doing, what happened": the - * open signals with their actions, one strip of numbers, usage, the health score's reasons (folded), - * support in a line, then pinned notes and recent activity. Billing facts live in the Billing tab and - * the side panel, so nothing here repeats them. + * open signals with their actions, one strip of numbers, support in a line, usage, then pinned notes + * and recent activity. Billing facts live in the Billing tab and the side panel, so nothing here + * repeats them. */ const DAY_MS = 86_400_000 @@ -79,13 +77,6 @@ const sectionTitle = (h: HtmlBuilder, title: string, aside?: Html): Htm // PULSE -const HEALTH_TEXT = { - healthy: "text-success-subtle-fg", - at_risk: "text-warning-subtle-fg", - critical: "text-danger-subtle-fg", - unknown: "text-muted-fg", -} as const satisfies Record - /** One cell of the pulse strip: a label, a number, and what it is measured against. */ const pulseStat = ( h: HtmlBuilder, @@ -97,15 +88,14 @@ const pulseStat = ( suffix?: string | undefined detail?: string | undefined valueClass?: string | undefined - detailClass?: string | undefined }>, ): Html => h.div( [ h.Id(`customer-kpi-${options.id}`), h.Class( - // Two by two on a phone: the second row gets a top rule, the second column a left one. - "flex min-w-0 flex-col gap-0.5 border-border px-4 py-3 md:border-l md:first:border-l-0 max-md:even:border-l max-md:[&:nth-child(n+3)]:border-t", + // Two columns on a phone, the third cell across both under a top rule. + "flex min-w-0 flex-col gap-0.5 border-border px-4 py-3 md:border-l md:first:border-l-0 max-md:even:border-l max-md:last:col-span-2 max-md:last:border-t", ), ], [ @@ -138,19 +128,13 @@ const pulseStat = ( ? [] : [ h.span( - [ - h.Class(twMerge("truncate text-muted-fg text-xs", options.detailClass)), - h.Title(options.detail), - ], + [h.Class("truncate text-muted-fg text-xs"), h.Title(options.detail)], [options.detail], ), ]), ], ) -/** The health score a week ago, from the daily series. */ -const healthWeekAgo = (context: Context): number | undefined => context.detail?.healthSeries.at(-8)?.value - const pulse = (h: HtmlBuilder, context: Context): Html => { const { account } = context const now = new Date(context.nowMs) @@ -159,9 +143,6 @@ const pulse = (h: HtmlBuilder, context: Context): Html => { context.detail?.contactsToReach.find( (row) => row.contact.id === context.detail?.account.lastActiveContactId, )?.contact.name ?? null - const weekAgo = healthWeekAgo(context) - const healthChange = - weekAgo === undefined || account.healthScore === null ? null : account.healthScore - weekAgo const trendTone = trend === null || Math.abs(trend) < 5 ? undefined @@ -172,7 +153,7 @@ const pulse = (h: HtmlBuilder, context: Context): Html => { [ h.AriaLabel("At a glance"), h.Role("group"), - h.Class(cardClassName("grid grid-cols-2 md:grid-cols-4")), + h.Class(cardClassName("grid grid-cols-2 md:grid-cols-3")), ], [ pulseStat(h, { @@ -189,22 +170,6 @@ const pulse = (h: HtmlBuilder, context: Context): Html => { valueClass: trendTone, detail: "7d vs prior 28d", }), - pulseStat(h, { - id: "health", - label: "Health", - value: account.healthScore === null ? "—" : String(account.healthScore), - valueClass: HEALTH_TEXT[account.healthStatus], - detail: - healthChange === null || healthChange === 0 - ? HEALTH_LABEL[account.healthStatus] - : `${healthChange < 0 ? "−" : "+"}${Math.abs(healthChange)} in 7 days`, - detailClass: - healthChange === null || healthChange === 0 - ? undefined - : healthChange < 0 - ? "text-danger-subtle-fg" - : "text-success-subtle-fg", - }), pulseStat(h, { id: "last-active", label: "Last active", @@ -320,98 +285,6 @@ const usageSection = (h: HtmlBuilder, model: Model, context: Context): ) } -// HEALTH - -/** - * Why the score is what it is, folded: the pulse strip already shows the number, so the per-component - * table opens on request. - */ -const healthSection = ( - h: HtmlBuilder, - context: Context, - bands: Customers.HealthBands, -): ReadonlyArray => { - const breakdown = context.detail?.health ?? null - if (breakdown === null || breakdown.score === null) return [] - const weekAgo = healthWeekAgo(context) - const computedAt = context.detail?.account.healthUpdatedAt ?? null - const note = [ - weekAgo === undefined || weekAgo === breakdown.score - ? null - : `${breakdown.score < weekAgo ? "Down" : "Up"} ${Math.abs(breakdown.score - weekAgo)} points in 7 days`, - `at risk is ${bands.atRiskMin}–${bands.healthyMin - 1}`, - computedAt === null ? null : `computed ${formatRelative(computedAt, new Date(context.nowMs))}`, - ] - .filter((part) => part !== null) - .join(" · ") - return [ - h.div( - [h.Class(cardClassName())], - [ - disclosure( - h, - { - summaryClassName: "px-4 py-3 text-sm", - summary: [ - h.span( - [h.Class("shrink-0 font-medium text-fg")], - [`Why health is ${breakdown.score}`], - ), - h.span([h.Class("min-w-0 truncate text-muted-fg text-xs max-sm:hidden")], [note]), - ], - }, - [ - h.div( - [h.Class("border-border border-t")], - [ - healthBreakdown(h, { - breakdown, - bands, - isBare: true, - excludedAction: (key) => - key === "billing" - ? h.a( - [ - h.Href( - hrefOf( - AppRoute.CustomersSettingsSources({ - orgSlug: context.orgSlug, - }), - ), - ), - h.Class(linkClass), - ], - ["Connect a billing source"], - ) - : null, - }), - h.div( - [h.Class("flex justify-end border-border border-t px-4 py-2.5 sm:px-5")], - [ - h.a( - [ - h.Href( - hrefOf( - AppRoute.CustomersSettingsHealth({ - orgSlug: context.orgSlug, - }), - ), - ), - h.Class(twMerge(linkClass, "text-xs")), - ], - ["Edit weights"], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ] -} - // SIGNALS const OUTCOME_LABEL = { @@ -769,19 +642,14 @@ const activitySection = (h: HtmlBuilder, model: Model, context: Context ) } -export const overviewTab = ( - h: HtmlBuilder, - model: Model, - context: Context, - bands: Customers.HealthBands, -): ReadonlyArray => [ +export const overviewTab = (h: HtmlBuilder, model: Model, context: Context): ReadonlyArray => [ h.div( [h.Class("flex min-w-0 flex-col gap-6")], [ ...attentionSection(h, model, context), h.div( [h.Class("flex min-w-0 flex-col gap-3")], - [pulse(h, context), ...healthSection(h, context, bands), supportCard(h, model, context)], + [pulse(h, context), supportCard(h, model, context)], ), usageSection(h, model, context), activitySection(h, model, context), diff --git a/apps/web-foldkit/src/page/customers/detail/story.test.ts b/apps/web-foldkit/src/page/customers/detail/story.test.ts index 029876557..cef4d620a 100644 --- a/apps/web-foldkit/src/page/customers/detail/story.test.ts +++ b/apps/web-foldkit/src/page/customers/detail/story.test.ts @@ -96,8 +96,6 @@ const account = (n: number, name: string): AccountRow => ({ currency: "USD", trialListMrrMinor: null, trialEndsAtMs: null, - healthScore: 80, - healthStatus: "healthy", seatsUsed: null, seatsLimit: null, contactCount: 10, diff --git a/apps/web-foldkit/src/page/customers/detail/subscription.ts b/apps/web-foldkit/src/page/customers/detail/subscription.ts index e93ff793c..d711f3b76 100644 --- a/apps/web-foldkit/src/page/customers/detail/subscription.ts +++ b/apps/web-foldkit/src/page/customers/detail/subscription.ts @@ -1,4 +1,3 @@ -import { DEFAULT_HEALTH_SETTINGS } from "@hazel/domain/customers" import { CustomerAccountId, OrganizationId, UserId } from "@hazel/schema" import { Schema, Stream } from "effect" import { Subscription } from "foldkit" @@ -8,7 +7,6 @@ import { createdFeatureFlagsStream, impersonatorsStream, orgMembersStream, - settingsSummaryStream, signalsStream, } from "../../../customers/queries" import { channelLinksStream, channelOptionsStream } from "../../../customers/channels" @@ -128,15 +126,6 @@ export const subscriptions = Subscription.make()((entry) => ({ ? Stream.empty : metricsStream(organizationId, (metrics) => Message.UpdatedMetrics({ metrics })), }), - bands: entry(organization, { - modelToDependencies: organizationOf, - dependenciesToStream: ({ organizationId }) => - organizationId === null - ? Stream.empty - : settingsSummaryStream(organizationId, (settings) => - Message.UpdatedBands({ bands: settings?.bands ?? DEFAULT_HEALTH_SETTINGS.bands }), - ), - }), channelLinks: entry(organization, { modelToDependencies: organizationOf, dependenciesToStream: ({ organizationId }) => diff --git a/apps/web-foldkit/src/page/customers/detail/update.ts b/apps/web-foldkit/src/page/customers/detail/update.ts index 251fa58ca..61d8b3506 100644 --- a/apps/web-foldkit/src/page/customers/detail/update.ts +++ b/apps/web-foldkit/src/page/customers/detail/update.ts @@ -257,7 +257,6 @@ const initialModel = (route: Route): Model => ({ members: [], metrics: [], connectedProviders: [], - bands: Customers.DEFAULT_HEALTH_SETTINGS.bands, detail: AsyncData.Idle(), usageMetric: "active_users", usageRange: "30d", @@ -759,8 +758,6 @@ const updateOwn = (model: Model, message: Message, shared: Shared): Return => model: modifyFields(model, { connectedProviders: () => providers }), }), - UpdatedBands: ({ bands }) => ({ model: modifyFields(model, { bands: () => bands }) }), - ClickedTab: ({ tab }) => (tab === model.tab ? { model } : navigateToTab(model, shared, tab)), PressedNeighbour: ({ step }) => { const position = positionOf(model) diff --git a/apps/web-foldkit/src/page/customers/detail/users-tab.ts b/apps/web-foldkit/src/page/customers/detail/users-tab.ts index 332133a19..afef1372a 100644 --- a/apps/web-foldkit/src/page/customers/detail/users-tab.ts +++ b/apps/web-foldkit/src/page/customers/detail/users-tab.ts @@ -28,9 +28,9 @@ const DAY_MS = 86_400_000 const nonNull = (html: Html | null): ReadonlyArray => (html === null ? [] : [html]) const STATUS = { - active: ["Active", "success", "seen in the last 30 days", "bg-health-healthy"], - dormant: ["Dormant", "warning", "not seen for 30+ days", "bg-health-at-risk"], - never_active: ["Never active", "secondary", "joined, no product activity", "bg-health-unknown"], + active: ["Active", "success", "seen in the last 30 days", "bg-chart-new"], + dormant: ["Dormant", "warning", "not seen for 30+ days", "bg-chart-contraction"], + never_active: ["Never active", "secondary", "joined, no product activity", "bg-chart-neutral"], } as const satisfies Record /** 30 days of activity as cells: brighter is more events that day. */ diff --git a/apps/web-foldkit/src/page/customers/detail/view.ts b/apps/web-foldkit/src/page/customers/detail/view.ts index 1938ef6ff..e228e5bb1 100644 --- a/apps/web-foldkit/src/page/customers/detail/view.ts +++ b/apps/web-foldkit/src/page/customers/detail/view.ts @@ -8,7 +8,7 @@ import { twMerge } from "tailwind-merge" import { commonMessage } from "~/lib/error-messages" import { formatCount, formatDate, formatMoney, formatRelative } from "../../../customers/format" import { accountLabelOf, environmentCounts, environmentsHintOf } from "../../../customers/groups" -import { environmentBadge, healthBadge, stageBadge } from "../../../customers/ui/badges" +import { environmentBadge, stageBadge } from "../../../customers/ui/badges" import { viewTabs } from "../../../customers/ui/filter-bar" import { linkClass } from "../../../customers/ui/surface" import { companyLogo, menuAvatar, personLabel, sourceLogo } from "../../../customers/ui/identity" @@ -95,7 +95,7 @@ const ACTION_LABEL = { change_owner: "Change owner…", mute_attention: "Mute in Needs attention", unmute_attention: "Unmute in Needs attention", - recompute: "Recompute health and signals", + recompute: "Recompute signals", link_source: "Link a source record…", link_customer: "Link to another customer…", make_primary: "Make primary", @@ -403,10 +403,6 @@ const header = (h: HtmlBuilder, model: Model, context: Context): Html = [account.name], ), ...environmentSwitch(h, model, context), - healthBadge(h, { - status: account.healthStatus, - score: account.healthScore, - }), ...attentionMutedBadge(h, account), ], ), @@ -1468,7 +1464,7 @@ export const view = Submodel.defineView((model, ? activityTab(h, model, context) : model.tab === "notes" ? notesTab(h, model, context, shared.organization?.name ?? "your workspace") - : overviewTab(h, model, context, model.bands) + : overviewTab(h, model, context) const hasSidebar = model.isSidebarOpen && model.tab !== "users" && !shared.isMobile return h.div( [h.Class("flex h-full min-h-0 flex-col")], diff --git a/apps/web-foldkit/src/page/customers/inbox/story.test.ts b/apps/web-foldkit/src/page/customers/inbox/story.test.ts index 9b5520610..c4d022a27 100644 --- a/apps/web-foldkit/src/page/customers/inbox/story.test.ts +++ b/apps/web-foldkit/src/page/customers/inbox/story.test.ts @@ -83,8 +83,6 @@ const acme: AccountRow = { currency: "USD", trialListMrrMinor: null, trialEndsAtMs: null, - healthScore: 54, - healthStatus: "at_risk", seatsUsed: null, seatsLimit: null, contactCount: 10, diff --git a/apps/web-foldkit/src/page/customers/list/controls.ts b/apps/web-foldkit/src/page/customers/list/controls.ts index 204e1d90d..5a97513b1 100644 --- a/apps/web-foldkit/src/page/customers/list/controls.ts +++ b/apps/web-foldkit/src/page/customers/list/controls.ts @@ -1,12 +1,11 @@ import * as Customers from "@hazel/domain/customers" import type { ChildAttribute, Html, HtmlBuilder } from "foldkit/html" import { twMerge } from "tailwind-merge" -import { distributionBar } from "../../../customers/charts/distribution" import { currencySymbol, formatCount, formatMoney, toMajor, toMinor } from "../../../customers/format" import { namesLabel, providerOf, usageSources } from "../../../customers/providers" import type { AccountRow, MemberRow } from "../../../customers/queries" import { countryFlag, countryNameOf, fundingStageLabel } from "../../../customers/company" -import { HEALTH_FILL, HEALTH_LABEL, STAGE_LABEL } from "../../../customers/ui/badges" +import { STAGE_LABEL } from "../../../customers/ui/badges" import { IconChevronDown, IconChevronRight } from "../../../icons" import { ariaButton, button, iconButton } from "../../../ui/button" import { checkbox } from "../../../ui/checkbox" @@ -30,7 +29,6 @@ import { withFilter, } from "./model" import { label as fieldLabel } from "../../../ui/field" -import { statusDot } from "../../../ui/status-dot" /** The filter builder's panes, the chips' wording and the column picker. */ @@ -39,7 +37,6 @@ const FIELD_LABEL = { plan: "Plan", owner: "Owner", tag: "Tag", - health: "Health", mrr: "MRR", last_active: "Last active", signals: "Open risk signals", @@ -54,7 +51,6 @@ const FIELD_KIND = { plan: "Select", owner: "Person", tag: "Select", - health: "Status", mrr: "Amount", last_active: "Date", signals: "Yes / no", @@ -66,7 +62,7 @@ const FIELD_KIND = { const FIELD_GROUPS: ReadonlyArray]> = [ ["Account", ["stage", "plan", "owner", "tag"]], - ["Health and usage", ["health", "last_active"]], + ["Usage", ["last_active"]], ["Revenue", ["mrr"]], ["Signals", ["signals"]], ["Company", ["industry", "company_size", "country", "funding"]], @@ -77,7 +73,6 @@ const FIELD_DESCRIPTION = { plan: "The plan of its largest subscription.", owner: "Who in your team looks after the account.", tag: "Tags your team added.", - health: "The account's health band from its latest score.", mrr: "Monthly recurring revenue, in your reporting currency.", last_active: `Most recent activity from any contact, from ${namesLabel(usageSources.map((source) => [providerOf(source).name, providerOf(source).activityLabel?.noun].filter(Boolean).join(" ")))}.`, signals: "Whether the account has an open risk signal now.", @@ -109,8 +104,6 @@ export const chipOf = ( switch (field) { case "stage": return anyOf(filters.lifecycleStages?.map((stage) => STAGE_LABEL[stage])) - case "health": - return anyOf(filters.healthStatuses?.map((status) => HEALTH_LABEL[status])) case "plan": return anyOf(filters.planNames) case "tag": @@ -280,25 +273,6 @@ const editor = ( withFilter(pending, "lifecycleStages", toggleIn(pending.lifecycleStages, stage)), ), ) - case "health": - return Customers.HealthStatus.literals.map((status) => - option( - h, - optionId(status), - h.span( - [h.Class("inline-flex items-center gap-2")], - [ - statusDot(h, { - tone: "neutral", - className: twMerge("size-2", HEALTH_FILL[status]), - }), - HEALTH_LABEL[status], - ], - ), - pending.healthStatuses?.includes(status) ?? false, - withFilter(pending, "healthStatuses", toggleIn(pending.healthStatuses, status)), - ), - ) case "plan": return plansOf(accounts).map((plan) => option( @@ -528,7 +502,7 @@ const editor = ( } } -/** The preview under the editor: how many accounts the pending filters keep, their MRR and health. */ +/** The preview under the editor: how many accounts the pending filters keep, and their MRR. */ const matchPreview = ( h: HtmlBuilder, builder: Builder, @@ -543,39 +517,13 @@ const matchPreview = ( const filters = search.trim() === "" ? builder.pending : { ...builder.pending, search } const matches = accounts.filter((account) => matchesFilters(filters, account, viewer)) const mrr = matches.reduce((sum, account) => sum + account.mrrMinor, 0) - const counts = Customers.HealthStatus.literals.map((status) => ({ - status, - count: matches.filter((account) => account.healthStatus === status).length, - })) - return h.div( - [h.Class("flex flex-col gap-2 rounded-lg border border-border p-3")], + return h.p( + [h.Class("rounded-lg border border-border p-3 text-sm"), h.AriaLive("polite")], [ - h.p( - [h.Class("text-sm"), h.AriaLive("polite")], - [ - h.span([h.Class("font-semibold text-fg")], [`${formatCount(matches.length)} customers`]), - h.span( - [h.Class("text-muted-fg")], - [` of ${formatCount(accounts.length)} · ${formatMoney(mrr, options.currency)} MRR`], - ), - ], - ), - distributionBar(h, { - ariaLabel: "Health of the matching customers", - segments: counts.map(({ status, count }) => ({ - key: status, - label: HEALTH_LABEL[status], - value: count, - fillClass: HEALTH_FILL[status], - })), - }), - h.p( - [h.Class("text-muted-fg text-xs")], - [ - counts - .map(({ status, count }) => `${count} ${HEALTH_LABEL[status].toLowerCase()}`) - .join(" · "), - ], + h.span([h.Class("font-semibold text-fg")], [`${formatCount(matches.length)} customers`]), + h.span( + [h.Class("text-muted-fg")], + [` of ${formatCount(accounts.length)} · ${formatMoney(mrr, options.currency)} MRR`], ), ], ) diff --git a/apps/web-foldkit/src/page/customers/list/model.ts b/apps/web-foldkit/src/page/customers/list/model.ts index 0dadc5c51..5da0a9d50 100644 --- a/apps/web-foldkit/src/page/customers/list/model.ts +++ b/apps/web-foldkit/src/page/customers/list/model.ts @@ -55,7 +55,6 @@ export const FilterField = Schema.Literals([ "plan", "owner", "tag", - "health", "mrr", "last_active", "signals", @@ -161,7 +160,6 @@ const BUILT_IN_FALLBACK: ReadonlyArray<{ { key: "my_customers", name: "My customers", filters: { ownedByMe: true } }, { key: "paying", name: "Paying", filters: { payingOnly: true } }, { key: "trialing", name: "Trialing", filters: { lifecycleStages: ["trialing"] } }, - { key: "at_risk", name: "At risk", filters: { healthStatuses: ["at_risk", "critical"] } }, { key: "churned", name: "Churned", filters: { lifecycleStages: ["churned"] } }, ] @@ -171,7 +169,7 @@ export const ALL_DRAFT: Draft = { columns: Customers.DEFAULT_LIST_COLUMNS, } -/** The default tab: paying and trialing accounts (the backend's "customer", `compute.ts` health inputs). */ +/** The default tab: paying and trialing accounts (the backend's "customer"). */ export const CURRENT_DRAFT: Draft = { filters: { lifecycleStages: ["trialing", "active", "past_due"] }, sort: { column: "mrr", direction: "desc" }, @@ -330,7 +328,6 @@ export const matchesFilters = ( inKnownList(filters.countryCodes, countryOf(account)) && inKnownList(filters.fundingStages, fundingOf(account)) && inList(filters.lifecycleStages, account.lifecycleStage) && - inList(filters.healthStatuses, account.healthStatus) && inList(filters.planNames, account.planName ?? "") && (filters.tagsAny === undefined || filters.tagsAny.length === 0 || @@ -389,8 +386,6 @@ const sortKeyOf = ( return (account.planName ?? "￿").toLowerCase() case "mrr": return account.mrrMinor - case "health": - return nullsLast(account.healthStatus === "unknown" ? null : account.healthScore, direction) case "active_users_30d": return account.activeUsers30d case "usage_trend": @@ -553,7 +548,6 @@ export const COLUMN_LABEL = { stage: "Stage", plan: "Plan", mrr: "MRR", - health: "Health", active_users_30d: "Active 30d", usage_trend: "Trend", last_active: "Last active", @@ -620,7 +614,6 @@ const FIELD_KEYS = { stage: ["lifecycleStages"], plan: ["planNames"], tag: ["tagsAny"], - health: ["healthStatuses"], mrr: ["minMrrMinor", "maxMrrMinor", "payingOnly"], last_active: ["lastActiveWithinDays", "inactiveForDays"], signals: ["hasOpenRiskSignals"], @@ -732,7 +725,6 @@ export const missingSparklines = (model: Model, viewer: Viewer): ReadonlyArray = [ "name", "mrr", - "health", "active_users_30d", "usage_trend", "last_active", diff --git a/apps/web-foldkit/src/page/customers/list/story.test.ts b/apps/web-foldkit/src/page/customers/list/story.test.ts index 9482e3d65..05bbb4f6c 100644 --- a/apps/web-foldkit/src/page/customers/list/story.test.ts +++ b/apps/web-foldkit/src/page/customers/list/story.test.ts @@ -81,8 +81,6 @@ const account = (n: number, name: string, fields: Partial = {}): Acc currency: "USD", trialListMrrMinor: null, trialEndsAtMs: null, - healthScore: 80, - healthStatus: "healthy", seatsUsed: null, seatsLimit: null, contactCount: 10, @@ -108,8 +106,6 @@ const account = (n: number, name: string, fields: Partial = {}): Acc const acme = account(1, "Acme Robotics", { mrrMinor: 215_000, - healthStatus: "at_risk", - healthScore: 54, openRiskHigh: 1, planName: "Scale", }) @@ -121,28 +117,26 @@ const brightfield = account(2, "Brightfield", { }) const kestrel = account(3, "Kestrel Systems", { mrrMinor: 132_000, - healthStatus: "critical", - healthScore: 27, lastActiveAtMs: NOW - 20 * DAY, tags: ["enterprise"], }) const northwind = account(4, "Northwind Labs", { ownerUserId: null, mrrMinor: 480_000, planName: "Scale" }) const accounts = [acme, brightfield, kestrel, northwind] -const atRisk: ViewRow = { +const myCustomers: ViewRow = { id: Schema.decodeSync(CustomerSavedViewId)(uuid(40)), - name: "At risk", - builtInKey: "at_risk", + name: "My customers", + builtInKey: "my_customers", ownerUserId: null, position: 3, - filters: { healthStatuses: ["at_risk", "critical"] }, + filters: { ownedByMe: true }, sort: { column: "mrr", direction: "desc" }, - columns: ["name", "owner", "mrr", "health"], + columns: ["name", "owner", "mrr"], icon: null, color: null, } const mine: ViewRow = { - ...atRisk, + ...myCustomers, id: Schema.decodeSync(CustomerSavedViewId)(uuid(41)), name: "Scale accounts", builtInKey: null, @@ -158,7 +152,7 @@ const run = (model: Model, messages: ReadonlyArray) => messages.reduce((current, message) => update(current, message, shared).model, model) const loaded = (view: string | null = ALL_VIEW_KEY): Model => run(init(route(view)).model, [ - Message.UpdatedViews({ views: [atRisk, mine] }), + Message.UpdatedViews({ views: [myCustomers, mine] }), Message.UpdatedAccounts({ accounts }), ]) const names = (model: Model) => visibleAccounts(model, viewer).map((row) => row.name) @@ -186,24 +180,23 @@ describe("customers list: filters and views", () => { const churned = account(5, "Zephyr", { lifecycleStage: "churned", mrrMinor: 0 }) const lead = account(6, "Yonder", { lifecycleStage: "lead", mrrMinor: 0 }) const model = run(init(route(null)).model, [ - Message.UpdatedViews({ views: [atRisk, mine] }), + Message.UpdatedViews({ views: [myCustomers, mine] }), Message.UpdatedAccounts({ accounts: [...accounts, churned, lead] }), ]) expect(names(model)).toEqual(["Northwind Labs", "Acme Robotics", "Kestrel Systems", "Brightfield"]) expect(viewTabsOf(model.views).map((tab) => tab.name)).toEqual([ "Current customers", - "At risk", + "My customers", "Scale accounts", "All customers", ]) }) test("a built-in view applies its filters and sort, before and after the views sync", () => { - expect(names(run(init(route("at_risk")).model, [Message.UpdatedAccounts({ accounts })]))).toEqual([ - "Acme Robotics", - "Kestrel Systems", - ]) - expect(names(loaded("at_risk"))).toEqual(["Acme Robotics", "Kestrel Systems"]) + expect( + names(run(init(route("my_customers")).model, [Message.UpdatedAccounts({ accounts })])), + ).toEqual(["Acme Robotics", "Kestrel Systems"]) + expect(names(loaded("my_customers"))).toEqual(["Acme Robotics", "Kestrel Systems"]) }) test("each filter narrows", () => { @@ -264,11 +257,11 @@ describe("customers list: filters and views", () => { test("an unedited draft follows its view when it changes; an edited one stays", () => { const changed = { ...mine, filters: { planNames: ["Growth"] } } - const following = run(loaded(mine.id), [Message.UpdatedViews({ views: [atRisk, changed] })]) + const following = run(loaded(mine.id), [Message.UpdatedViews({ views: [myCustomers, changed] })]) expect(following.draft.filters).toEqual({ planNames: ["Growth"] }) const edited = run(loaded(mine.id), [ Message.ClickedSortHeader({ column: "mrr" }), - Message.UpdatedViews({ views: [atRisk, changed] }), + Message.UpdatedViews({ views: [myCustomers, changed] }), ]) expect(edited.draft.filters).toEqual({ planNames: ["Scale"] }) }) @@ -291,7 +284,6 @@ describe("customers list: sort and columns", () => { primaryAccountId: acme.id, environment: "EU", mrrMinor: 5_000, - healthStatus: "healthy", }) const model = run(loaded(), [Message.UpdatedAccounts({ accounts: [...accounts, acmeEu] })]) const ids = (current: Model) => visibleAccounts(current, viewer).map((row) => row.id) @@ -310,21 +302,23 @@ describe("customers list: sort and columns", () => { expect(ids(ascending).slice(0, 3)).toEqual([brightfield.id, acme.id, acmeEu.id]) // A search that drops the primary keeps the environment, on its own. expect(ids(run(model, [Message.ChangedSearch({ value: "eu" })]))).toEqual([acmeEu.id]) - const atRiskOnly = run(init(route("at_risk")).model, [ - Message.UpdatedAccounts({ accounts: [...accounts, acmeEu] }), - ]) - expect(ids(atRiskOnly)).toEqual([acme.id, kestrel.id]) + // A filter the environment fails drops it and keeps its primary. + const largeOnly = { + ...model, + draft: { ...model.draft, filters: { ownedByMe: true, minMrrMinor: 100_000 } }, + } + expect(ids(largeOnly)).toEqual([acme.id, kestrel.id]) }) - test("health sorts unscored accounts last either way", () => { - const unknown = account(5, "Zeta", { healthStatus: "unknown", healthScore: null }) + test("usage trend sorts accounts without one last either way", () => { + const unknown = account(5, "Zeta", { activeUsersTrendPct: null }) const model = run(loaded(), [Message.UpdatedAccounts({ accounts: [...accounts, unknown] })]) const ascending = run(model, [ - Message.ClickedSortHeader({ column: "health" }), - Message.ClickedSortHeader({ column: "health" }), + Message.ClickedSortHeader({ column: "usage_trend" }), + Message.ClickedSortHeader({ column: "usage_trend" }), ]) expect(names(ascending).at(-1)).toBe("Zeta") - expect(names(run(model, [Message.ClickedSortHeader({ column: "health" })])).at(-1)).toBe("Zeta") + expect(names(run(model, [Message.ClickedSortHeader({ column: "usage_trend" })])).at(-1)).toBe("Zeta") }) test("columns toggle and reorder; the name column stays first", () => { @@ -382,7 +376,7 @@ describe("customers list: saving views", () => { test("a built-in view offers no delete", () => { const asked = pick( - loaded("at_risk"), + loaded("my_customers"), (message) => Message.GotViewMenuMessage({ message }), "delete", [Menu.item("delete")], @@ -421,13 +415,13 @@ describe("customers list: arranging the views", () => { expect(tabNames(dropped.model)).toEqual([ "All customers", "Current customers", - "At risk", + "My customers", "Scale accounts", ]) expect(commandNames(dropped)).toContain("SaveListLayout") expect(dropped.commands?.[0]?.args).toMatchObject({ layoutId: null, - layout: { order: ["all", "current", "at_risk", mine.id], sidebarHidden: ["all"] }, + layout: { order: ["all", "current", "my_customers", mine.id], sidebarHidden: ["all"] }, }) const stepped = update(dropped.model, Message.SteppedViewTab({ key: mine.id, step: -1 }), shared) @@ -435,7 +429,7 @@ describe("customers list: arranging the views", () => { "All customers", "Current customers", "Scale accounts", - "At risk", + "My customers", ]) expect(commandNames(stepped)).toContain("SaveListLayout") }) @@ -450,12 +444,12 @@ describe("customers list: arranging the views", () => { ) expect(shown.model.layout?.sidebarHidden).toEqual([]) const hidden = pick( - loaded("at_risk"), + loaded("my_customers"), (message) => Message.GotViewMenuMessage({ message }), "sidebar", - viewMenuEntries(loaded("at_risk"), viewer), + viewMenuEntries(loaded("my_customers"), viewer), ) - expect(hidden.model.layout?.sidebarHidden).toEqual(["all", "at_risk"]) + expect(hidden.model.layout?.sidebarHidden).toEqual(["all", "my_customers"]) }) test("editing a view sends its name and its new icon and colour", () => { @@ -487,7 +481,7 @@ describe("customers list: arranging the views", () => { describe("customers list: built-in view defaults", () => { test("an admin resets an edited built-in view to its shipped name and draft", () => { - const model = loaded("at_risk") + const model = loaded("my_customers") const admin = { ...viewer, isAdmin: true } const items = (entries: ReadonlyArray) => entries.flatMap((entry) => (entry._tag === "Item" ? [entry.item] : [])) @@ -505,15 +499,15 @@ describe("customers list: built-in view defaults", () => { ) expect(commandNames(restored)).toContain("UpdateSavedView") expect(restored.commands?.find((command) => command.name === "UpdateSavedView")?.args).toMatchObject({ - viewId: atRisk.id, - view: { name: "At risk", filters: { healthStatuses: ["at_risk", "critical"] } }, + viewId: myCustomers.id, + view: { name: "My customers", filters: { ownedByMe: true } }, }) }) }) describe("customers list: selection and bulk actions", () => { test("select all takes the visible rows only", () => { - const selected = run(loaded("at_risk"), [Message.ToggledAllRows({ isSelected: true })]) + const selected = run(loaded("my_customers"), [Message.ToggledAllRows({ isSelected: true })]) expect(selected.selected).toEqual([acme.id, kestrel.id]) expect(run(selected, [Message.ClearedSelection()]).selected).toEqual([]) }) diff --git a/apps/web-foldkit/src/page/customers/list/table.ts b/apps/web-foldkit/src/page/customers/list/table.ts index 85cccb7af..001f83ad5 100644 --- a/apps/web-foldkit/src/page/customers/list/table.ts +++ b/apps/web-foldkit/src/page/customers/list/table.ts @@ -13,15 +13,7 @@ import { } from "../../../customers/format" import { accountLabelOf } from "../../../customers/groups" import type { AccountRow, MemberRow } from "../../../customers/queries" -import { - environmentBadge, - HEALTH_LABEL, - healthBadge, - healthDot, - STAGE_LABEL, - signalCounts, - stageBadge, -} from "../../../customers/ui/badges" +import { environmentBadge, STAGE_LABEL, signalCounts, stageBadge } from "../../../customers/ui/badges" import type { Column } from "../../../ui/data-table" import { primaryCell } from "../../../ui/data-table" import { companyLogo, personAvatar } from "../../../customers/ui/identity" @@ -84,10 +76,6 @@ export const csvValue = ( return account.planName ?? "" case "mrr": return formatMajor(account.mrrMinor, account.currency) - case "health": - return account.healthStatus === "unknown" - ? HEALTH_LABEL.unknown - : `${HEALTH_LABEL[account.healthStatus]} ${account.healthScore ?? ""}`.trim() case "active_users_30d": return String(account.activeUsers30d) case "usage_trend": @@ -187,25 +175,6 @@ const footerOf = ( accounts.reduce((sum, account) => sum + account.mrrMinor, 0), currency, ) - case "health": { - const scored = accounts.filter( - (account) => account.healthStatus !== "unknown" && account.healthScore !== null, - ) - return scored.length === 0 - ? undefined - : h.span( - [], - [ - muted(h, "Avg "), - String( - Math.round( - scored.reduce((sum, account) => sum + (account.healthScore ?? 0), 0) / - scored.length, - ), - ), - ], - ) - } case "active_users_30d": return formatCount(accounts.reduce((sum, account) => sum + account.activeUsers30d, 0)) default: @@ -264,25 +233,6 @@ const cellOf = ( [h.Class(account.mrrMinor === 0 ? "text-muted-fg" : "font-medium")], [formatMoney(account.mrrMinor, account.currency)], ) - case "health": - return account.lifecycleStage === "churned" - ? muted(h, "—") - : // A phone's table: the dot and score, so the name keeps the width. - h.span( - [], - [ - healthBadge(h, { - status: account.healthStatus, - score: account.healthScore, - className: "@max-xl:hidden", - }), - healthDot(h, { - status: account.healthStatus, - score: account.healthScore, - className: "@xl:hidden", - }), - ], - ) case "active_users_30d": { const values = context.sparklines[account.id] return h.span( @@ -355,8 +305,8 @@ const cellOf = ( * Columns drop by the table's own width (a container query on the table's frame), not the * viewport's: the app's sidebars take a different share at every window size. Each one shows once * the columns before it fit, so a table never runs off its frame until every picked column is in; - * a phone keeps name, MRR and health. The name takes whatever width is left and truncates (a - * `max-w-0` cell is the one that gives), rather than widening the table to its longest domain. + * a phone keeps name and MRR. The name takes whatever width is left and truncates (a `max-w-0` + * cell is the one that gives), rather than widening the table to its longest domain. */ const COLUMN_LAYOUT = { name: { widthClass: "w-full max-w-0 min-w-44 @max-xl:min-w-0" }, @@ -364,7 +314,6 @@ const COLUMN_LAYOUT = { stage: { widthClass: "w-24", hideClass: "@max-2xl:hidden" }, plan: { widthClass: "w-18", hideClass: "@max-3xl:hidden" }, mrr: { align: "right", widthClass: "w-20" }, - health: { widthClass: "w-28 @max-xl:w-14" }, active_users_30d: { align: "right", widthClass: "w-28", hideClass: "@max-7xl:hidden" }, usage_trend: { align: "right", widthClass: "w-16", hideClass: "@max-5xl:hidden" }, last_active: { align: "right", widthClass: "w-22", hideClass: "@max-4xl:hidden" }, diff --git a/apps/web-foldkit/src/page/customers/list/view.ts b/apps/web-foldkit/src/page/customers/list/view.ts index 216300842..47eba0034 100644 --- a/apps/web-foldkit/src/page/customers/list/view.ts +++ b/apps/web-foldkit/src/page/customers/list/view.ts @@ -7,7 +7,7 @@ import { twMerge } from "tailwind-merge" import { formatCount, formatDeltaPct, formatMoney, formatRelative } from "../../../customers/format" import { accountLabelOf, nestedIdsOf } from "../../../customers/groups" import type { AccountRow, SignalRow } from "../../../customers/queries" -import { environmentBadge, healthBadge, severityGlyph } from "../../../customers/ui/badges" +import { environmentBadge, severityGlyph } from "../../../customers/ui/badges" import { connectCard } from "../../../customers/ui/connect-card" import { dataTable } from "../../../ui/data-table" import { @@ -83,7 +83,7 @@ import { menu } from "../shared-view" import { separator } from "../../../ui/separator" import { badge } from "../../../ui/badge" -/** The customers list (Wonder: List — all, at risk, filter builder, columns, bulk, hover, no results, first run). */ +/** The customers list (Wonder: List — all, filter builder, columns, bulk, hover, no results, first run). */ const TABLE_ID = "customers-list-table" const icon = { attributes: { "data-slot": "icon" } } @@ -413,7 +413,6 @@ const hoverCard = (h: HtmlBuilder, model: Model, account: AccountRow, v ), ], ), - healthBadge(h, { status: account.healthStatus, score: account.healthScore }), ], ), ...companyBlock(h, account), diff --git a/apps/web-foldkit/src/page/customers/overview/index.ts b/apps/web-foldkit/src/page/customers/overview/index.ts index 5f1eb61a6..05d0c7987 100644 --- a/apps/web-foldkit/src/page/customers/overview/index.ts +++ b/apps/web-foldkit/src/page/customers/overview/index.ts @@ -5,7 +5,7 @@ import { subscriptions } from "./subscription" import { init, sharedChanged, update } from "./update" import { view } from "./view" -/** `/$orgSlug/customers`: revenue, usage and health across the org's customers. */ +/** `/$orgSlug/customers`: revenue and usage across the org's customers. */ export const page = definePage( "CustomersOverview", { Model, Message }, diff --git a/apps/web-foldkit/src/page/customers/overview/message.ts b/apps/web-foldkit/src/page/customers/overview/message.ts index 846f32d0c..ba9592a69 100644 --- a/apps/web-foldkit/src/page/customers/overview/message.ts +++ b/apps/web-foldkit/src/page/customers/overview/message.ts @@ -6,12 +6,11 @@ import { CommonReason } from "~/lib/error-messages" import { ChannelOption } from "../../../customers/channels" import { AccountRow, SettingsSummary, SignalRow } from "../../../customers/queries" import { SuggestionMessage, SuggestionRow } from "../../../customers/suggestions" -import { Chart, HealthMetric } from "./model" +import { Chart } from "./model" export const Message = defineMessageUnion({ ClickedRange: { range: Customers.CustomersRange }, ToggledCompare: { isComparing: Schema.Boolean }, - ClickedHealthMetric: { metric: HealthMetric }, HoveredChart: { chart: Chart, index: Schema.NullOr(Schema.Int) }, PressedRetry: {}, /** A setup card's Connect: the data source's page, where connecting happens. */ diff --git a/apps/web-foldkit/src/page/customers/overview/model.ts b/apps/web-foldkit/src/page/customers/overview/model.ts index b1f9971e0..34b9bfe97 100644 --- a/apps/web-foldkit/src/page/customers/overview/model.ts +++ b/apps/web-foldkit/src/page/customers/overview/model.ts @@ -15,7 +15,6 @@ export type Overview = typeof Overview.schema.Type /** `customers.support.report` for the same range: the four support tiles. */ export const Support = AsyncData.Schema(Customers.SupportReport, CommonReason) -export const HealthMetric = Schema.Literals(["customers", "mrr"]) export const Chart = Schema.Literals(["mrr", "activeUsers"]) export type Chart = typeof Chart.Type @@ -26,7 +25,6 @@ export const Model = Schema.Struct({ /** `customers.overview` for `range`; kept while another range loads. */ overview: Overview.schema, support: Support.schema, - healthMetric: HealthMetric, hoveredMrr: Schema.NullOr(Schema.Int), hoveredActiveUsers: Schema.NullOr(Schema.Int), /** Live rows; null until each query answers. */ diff --git a/apps/web-foldkit/src/page/customers/overview/scene.test.ts b/apps/web-foldkit/src/page/customers/overview/scene.test.ts index d2afc94fa..9b7d99354 100644 --- a/apps/web-foldkit/src/page/customers/overview/scene.test.ts +++ b/apps/web-foldkit/src/page/customers/overview/scene.test.ts @@ -31,7 +31,6 @@ const answered = (options: Readonly<{ billing: boolean; signals: boolean }>): Mo ), settings: { lastComputedAtMs: SETTINGS.lastComputedAt === null ? null : msOf(SETTINGS.lastComputedAt), - bands: SETTINGS.health.bands, reportingCurrency: SETTINGS.reportingCurrency, }, overview: AsyncData.Success({ data: overviewFixture("30d", { partial: !options.billing }) }), @@ -50,11 +49,6 @@ describe("Customers overview", () => { Scene.expect(Scene.within(keyNumbers, Scene.role("button", { name: "MRR at risk" }))).toExist(), Scene.expect(Scene.within(keyNumbers, Scene.text("$48,210"))).toExist(), Scene.expect(Scene.role("button", { name: "Logo churn" })).toExist(), - Scene.expect( - Scene.role("img", { - name: "MRR by health: Healthy $35,980, At risk $8,140, Critical $3,310, Unknown $780", - }), - ).toExist(), ) }) diff --git a/apps/web-foldkit/src/page/customers/overview/update.ts b/apps/web-foldkit/src/page/customers/overview/update.ts index fe5da8c60..938821d93 100644 --- a/apps/web-foldkit/src/page/customers/overview/update.ts +++ b/apps/web-foldkit/src/page/customers/overview/update.ts @@ -82,7 +82,6 @@ export const init = (_route: unknown, shared: Shared): Return => isComparing: true, overview: AsyncData.Idle(), support: AsyncData.Idle(), - healthMetric: "customers", hoveredMrr: null, hoveredActiveUsers: null, signals: null, @@ -115,7 +114,6 @@ export const update = (model: Model, message: Message, shared: Shared): Return = ToggledCompare: ({ isComparing }) => ({ model: modifyFields(model, { isComparing: () => isComparing }), }), - ClickedHealthMetric: ({ metric }) => ({ model: modifyFields(model, { healthMetric: () => metric }) }), HoveredChart: ({ chart, index }) => ({ model: chart === "mrr" diff --git a/apps/web-foldkit/src/page/customers/overview/view.ts b/apps/web-foldkit/src/page/customers/overview/view.ts index 30eb0d2f6..21baeec9f 100644 --- a/apps/web-foldkit/src/page/customers/overview/view.ts +++ b/apps/web-foldkit/src/page/customers/overview/view.ts @@ -13,7 +13,6 @@ import { twMerge } from "tailwind-merge" import { commonMessage } from "~/lib/error-messages" import { activeUsersChart } from "../../../customers/charts/line-chart" import { chartLegend } from "../../../customers/charts/frame" -import { distributionBar, healthDistribution } from "../../../customers/charts/distribution" import { sparkline } from "../../../customers/charts/sparkline" import { mrrLegend, mrrMovementChart } from "../../../customers/charts/stacked-bar-chart" import { @@ -28,13 +27,7 @@ import { } from "../../../customers/format" import { type AccountRow, msOf, type SignalRow } from "../../../customers/queries" import { shownSuggestions, suggestionRow } from "../../../customers/suggestions" -import { - environmentsHint, - HEALTH_FILL, - HEALTH_LABEL, - healthDot, - severityGlyph, -} from "../../../customers/ui/badges" +import { environmentsHint, severityGlyph } from "../../../customers/ui/badges" import { customerAccountOf, environmentCounts, queueNameOf } from "../../../customers/groups" import { connectCard } from "../../../customers/ui/connect-card" import { companyLogo } from "../../../customers/ui/identity" @@ -73,7 +66,6 @@ type Result = Customers.OverviewResult const toHoverMrr = (index: number | null) => Message.HoveredChart({ chart: "mrr", index }) const toHoverActiveUsers = (index: number | null) => Message.HoveredChart({ chart: "activeUsers", index }) const toRange = (range: Customers.CustomersRange) => Message.ClickedRange({ range }) -const toHealthMetric = (metric: "customers" | "mrr") => Message.ClickedHealthMetric({ metric }) const toCompare = (isComparing: boolean) => Message.ToggledCompare({ isComparing }) interface Context { @@ -97,7 +89,7 @@ const header = (h: HtmlBuilder, model: Model, result: Result | undefine const subtitle = isUnconnected(model) ? "No data sources connected yet" : [ - `${result?.hasData.billing === false ? "Usage and health" : "Revenue, usage and health"} across ${formatCount(customers)} customers`, + `${result?.hasData.billing === false ? "Usage" : "Revenue and usage"} across ${formatCount(customers)} customers`, ...(synced === null ? [] : [synced]), ].join(" · ") const previous = previousPeriodOf(model.range, nowMs) @@ -153,7 +145,6 @@ const headlineCell = ( suffix?: string delta?: Delta | null detail?: string - footer?: Html }>, ): Html => h.div( @@ -193,7 +184,6 @@ const headlineCell = ( : [h.span([h.Class("truncate")], [options.detail])]), ], ), - ...(options.footer === undefined ? [] : [options.footer]), ], ) @@ -263,15 +253,6 @@ const headline = ( active, ]) const atRiskPct = kpis.mrrMinor.value === 0 ? 0 : (kpis.atRiskMrrMinor.value / kpis.mrrMinor.value) * 100 - const mrrByHealth = HEALTH_ORDER.map((status) => ({ - key: status, - label: HEALTH_LABEL[status], - value: result.healthDistribution.find((row) => row.status === status)?.mrrMinor ?? 0, - fillClass: HEALTH_FILL[status], - })) - const risky = result.healthDistribution - .filter((row) => row.status === "at_risk" || row.status === "critical") - .reduce((sum, row) => sum + row.count, 0) return strip([ headlineCell(h, { id: "kpi-mrr", @@ -288,20 +269,12 @@ const headline = ( definition: "MRR of customers with an open high-severity risk signal.", value: formatMoney(kpis.atRiskMrrMinor.value, currency), valueClass: kpis.atRiskMrrMinor.value > 0 ? "text-warning-subtle-fg" : undefined, - detail: `${formatPct(atRiskPct, { digits: 0 })} of MRR · ${formatCount(risky)} ${risky === 1 ? "customer" : "customers"} at risk or critical`, - footer: distributionBar(h, { - // The bar is an image: its name says what each segment holds. - ariaLabel: `MRR by health: ${mrrByHealth.map((segment) => `${segment.label} ${formatMoney(segment.value, currency)}`).join(", ")}`, - className: "mt-1.5 h-1.5", - segments: mrrByHealth, - }), + detail: `${formatPct(atRiskPct, { digits: 0 })} of MRR`, }), active, ]) } -const HEALTH_ORDER: ReadonlyArray = ["healthy", "at_risk", "critical", "unknown"] - /** Revenue, paying customers and logo churn: worth a glance, not a tile each. */ const secondaryLine = ( h: HtmlBuilder, @@ -824,23 +797,6 @@ const moversCard = (h: HtmlBuilder, result: Result, context: Context): }, "w-16 shrink-0 justify-end text-sm", ), - ...(account === undefined - ? [] - : [ - h.span( - [ - h.Class( - "w-12 shrink-0 text-right max-sm:w-9", - ), - ], - [ - healthDot(h, { - status: account.healthStatus, - score: account.healthScore, - }), - ], - ), - ]), ], ), ], @@ -1071,9 +1027,8 @@ const lifecycleSection = (h: HtmlBuilder, model: Model, result: Result, // TRENDS /** The charts, folded: worth opening on a review, not on every visit. */ -const trendsSection = (h: HtmlBuilder, model: Model, result: Result, context: Context): Html => { - const bands = model.settings?.bands ?? Customers.DEFAULT_HEALTH_SETTINGS.bands - return h.section( +const trendsSection = (h: HtmlBuilder, model: Model, result: Result, context: Context): Html => + h.section( [h.AriaLabel("Charts and trends")], [ disclosure( @@ -1084,7 +1039,7 @@ const trendsSection = (h: HtmlBuilder, model: Model, result: Result, co h.span([h.Class("font-medium text-fg")], ["Charts and trends"]), h.span( [h.Class("text-muted-fg text-xs max-sm:hidden")], - ["MRR movement, active users, health distribution, top movers"], + ["MRR movement, active users, top movers"], ), ], }, @@ -1093,19 +1048,7 @@ const trendsSection = (h: HtmlBuilder, model: Model, result: Result, co [h.Class("flex flex-col gap-4 pt-3")], [ mrrCard(h, model, result), - h.div( - [h.Class("grid gap-4 lg:grid-cols-2")], - [ - activeUsersCard(h, model, result), - healthDistribution(h, { - rows: result.healthDistribution, - bands, - currency: result.currency, - metric: model.healthMetric, - onMetric: toHealthMetric, - }), - ], - ), + activeUsersCard(h, model, result), moversCard(h, result, context), ], ), @@ -1113,7 +1056,6 @@ const trendsSection = (h: HtmlBuilder, model: Model, result: Result, co ), ], ) -} // STATES diff --git a/apps/web-foldkit/src/page/customers/pages.ts b/apps/web-foldkit/src/page/customers/pages.ts index f53fc47bb..9b6a05533 100644 --- a/apps/web-foldkit/src/page/customers/pages.ts +++ b/apps/web-foldkit/src/page/customers/pages.ts @@ -3,7 +3,6 @@ import * as CustomerDetail from "./detail" import * as CustomersInbox from "./inbox" import * as CustomersList from "./list" import * as CustomersOverview from "./overview" -import * as CustomersSettingsHealth from "./settings/health" import * as CustomersSettingsFeatureFlags from "./settings/feature-flags" import * as CustomersSettingsPlans from "./settings/plans" import * as CustomersSettingsSignals from "./settings/signals" @@ -21,7 +20,6 @@ export const pages = [ CustomersList.page, CustomerDetail.page, CustomersSettingsSignals.page, - CustomersSettingsHealth.page, CustomersSettingsPlans.page, CustomersSettingsSla.page, CustomersSettingsFeatureFlags.page, diff --git a/apps/web-foldkit/src/page/customers/settings/feature-flags/story.test.ts b/apps/web-foldkit/src/page/customers/settings/feature-flags/story.test.ts index f4c68add1..5b6abe1cf 100644 --- a/apps/web-foldkit/src/page/customers/settings/feature-flags/story.test.ts +++ b/apps/web-foldkit/src/page/customers/settings/feature-flags/story.test.ts @@ -54,8 +54,6 @@ const account = (n: number, featureFlags: Record): AccountRow = currency: "usd", trialListMrrMinor: null, trialEndsAtMs: null, - healthScore: null, - healthStatus: "unknown", seatsUsed: null, seatsLimit: null, contactCount: 0, diff --git a/apps/web-foldkit/src/page/customers/settings/health/commands.ts b/apps/web-foldkit/src/page/customers/settings/health/commands.ts deleted file mode 100644 index aeb1a35a1..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/commands.ts +++ /dev/null @@ -1,103 +0,0 @@ -import * as Customers from "@hazel/domain/customers" -import { CustomerAccountId, CustomerSettingsId, OrganizationId } from "@hazel/schema" -import { optimisticAction } from "@hazel/effect-db-collection" -import { Duration, Effect, Schema } from "effect" -import { Command } from "foldkit" -import { customerSettingsCollection } from "~/db/collections" -import { catchCommon } from "../../../../data/actions" -import { HazelRpc } from "../../../../rpc" -import { Message } from "./message" - -/** The health settings page's Commands: the debounced dry run, one account's breakdown, saving. */ - -/** How long the draft must stay still before it is scored. */ -export const PREVIEW_DELAY = Duration.millis(400) - -export const DelayHealthPreview = Command.define("DelayHealthPreview", { - args: { version: Schema.Int }, - messages: [Message.ElapsedHealthPreviewDelay], - execute: ({ version }) => - Effect.sleep(PREVIEW_DELAY).pipe(Effect.as(Message.ElapsedHealthPreviewDelay({ version }))), -}) - -export const FetchHealthDryRun = Command.define("FetchHealthDryRun", { - args: { organizationId: OrganizationId, draft: Customers.HealthSettings, version: Schema.Int }, - messages: [Message.SucceededFetchHealthDryRun, Message.FailedFetchHealthDryRun], - execute: ({ organizationId, draft, version }) => - HazelRpc.use((rpc) => rpc("customers.health.dryRun", { organizationId, draft })).pipe( - Effect.map((result) => Message.SucceededFetchHealthDryRun({ version, result })), - catchCommon((reason) => Message.FailedFetchHealthDryRun({ version, reason })), - ), -}) - -/** The account's saved breakdown, from its detail. */ -export const FetchHealthCheckDetail = Command.define("FetchHealthCheckDetail", { - args: { organizationId: OrganizationId, accountId: CustomerAccountId }, - messages: [Message.SucceededFetchHealthCheckDetail, Message.FailedFetchHealthCheckDetail], - execute: ({ organizationId, accountId }) => - HazelRpc.use((rpc) => rpc("customers.account.detail", { organizationId, accountId })).pipe( - Effect.map((detail) => - Message.SucceededFetchHealthCheckDetail({ accountId, health: detail.health }), - ), - // Deleted since it synced: reads like any other failure, the panel offers nothing more. - Effect.catchTag("CustomersNotFoundError", () => - Effect.succeed(Message.FailedFetchHealthCheckDetail({ accountId, reason: "Unexpected" })), - ), - catchCommon((reason) => Message.FailedFetchHealthCheckDetail({ accountId, reason })), - ), -}) - -interface SaveProps { - readonly organizationId: OrganizationId - readonly settingsId: CustomerSettingsId - readonly health: Customers.HealthSettings -} - -/** The collection row's mutable copy (its arrays are not readonly). */ -const writable = (health: Customers.HealthSettings) => ({ - ...health, - steps: { - ...health.steps, - usage: { - ...health.steps.usage, - activeRatio: [...health.steps.usage.activeRatio], - trend: [...health.steps.usage.trend], - }, - engagement: { daysSinceActive: [...health.steps.engagement.daysSinceActive] }, - }, - excludedTemplates: [...health.excludedTemplates], -}) - -/** The settings row takes the draft at once; the server rescores on its next compute. */ -const saveHealthSettingsAction = optimisticAction({ - collections: [customerSettingsCollection], - onMutate: (props: SaveProps) => { - customerSettingsCollection.update(props.settingsId, (row) => { - row.health = writable(props.health) - }) - return { settingsId: props.settingsId } - }, - mutate: (props) => - Effect.gen(function* () { - const client = yield* HazelRpc - const result = yield* client("customers.settings.update", { - organizationId: props.organizationId, - health: props.health, - }) - return { data: result, transactionId: result.transactionId } - }), -}) - -export const SaveHealthSettings = Command.define("SaveHealthSettings", { - args: { - organizationId: OrganizationId, - settingsId: CustomerSettingsId, - health: Customers.HealthSettings, - }, - messages: [Message.SucceededSaveHealthSettings, Message.FailedSaveHealthSettings], - execute: (args) => - saveHealthSettingsAction(args).pipe( - Effect.as(Message.SucceededSaveHealthSettings()), - catchCommon((reason) => Message.FailedSaveHealthSettings({ reason })), - ), -}) diff --git a/apps/web-foldkit/src/page/customers/settings/health/components-view.ts b/apps/web-foldkit/src/page/customers/settings/health/components-view.ts deleted file mode 100644 index c0c9b8126..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/components-view.ts +++ /dev/null @@ -1,548 +0,0 @@ -import { activityProviders, billingProviders } from "@hazel/customer-integrations" -import * as Customers from "@hazel/domain/customers" -import type { Html } from "foldkit/html" -import { twMerge } from "tailwind-merge" -import { severityGlyph } from "../../../../customers/ui/badges" -import { sourceMark } from "../../../../customers/ui/identity" -import { IconCheck, IconWarning } from "../../../../icons" -import { badge } from "../../../../ui/badge" -import { ariaButton, button } from "../../../../ui/button" -import { panel } from "../../../../ui/card" -import * as Slider from "../../../../ui/slider" -import { type Context, type H, numberInput, parseNumber, ruleHeading, ruleRow, textOf } from "./fields" -import { Message } from "./message" -import { - COMPONENT_LABEL, - COMPONENTS, - type Model, - PENALTY_FIELDS, - type ScoreField, - type StepList, -} from "./model" -import { SLIDER_MESSAGE } from "./update" -import { heading } from "../../../../ui/heading" - -/** The score card (weights and their total) and the four component cards (weight, scoring rules). */ - -type ComponentKey = Customers.HealthComponentKey - -export const COMPONENT_FILL = { - usage: "bg-chart-series-1", - engagement: "bg-chart-series-2", - billing: "bg-chart-series-3", - signals: "bg-chart-neutral", -} as const satisfies Record - -const COMPONENT_BORDER = { - usage: "border-chart-series-1", - engagement: "border-chart-series-2", - billing: "border-chart-series-3", - signals: "border-chart-neutral", -} as const satisfies Record - -const DESCRIPTION = { - usage: "How much of the account uses the product", - engagement: "How recently anyone at the account was active", - billing: "Whether the account pays on time", - signals: "Open risk items in Needs attention", -} as const satisfies Record - -const SOURCES = { - usage: activityProviders, - engagement: activityProviders, - billing: billingProviders, - signals: ["hazel"], -} satisfies Record> - -const off = (total: number) => Math.abs(total - 100) - -/** "Weights add up to 110%. Lower one or more parts by 10 points in total, …" */ -export const totalProblem = (total: number): string => - `Weights add up to ${total}%. ${total > 100 ? "Lower" : "Raise"} one or more parts by ${off(total)} points in total, or scale them back to 100%.` - -export const scaleButton = (h: H, className?: string): Html => - button(h, { intent: "outline", size: "xs", onPress: Message.PressedScaleWeights(), className }, [ - "Scale to 100%", - ]) - -const totalPill = (h: H, total: number): Html => - total === 100 - ? badge(h, { intent: "success", isPill: true }, [ - IconCheck(h, { attributes: { "data-slot": "icon" } }), - "100%", - h.span([h.Class("font-normal")], ["total"]), - ]) - : badge(h, { intent: "danger", isPill: true }, [ - IconWarning(h, { attributes: { "data-slot": "icon" } }), - `${total}%`, - h.span([h.Class("font-normal")], [`${off(total)} ${total > 100 ? "over" : "under"}`]), - ]) - -/** "Score = weighted average of four parts": the stacked weights, their legend and total. */ -export const weightsCard = (h: H, context: Context): Html => { - const { draft, saved, total } = context - const isOff = total !== 100 - const scale = Math.max(total, 100) - return panel(h, { className: isOff ? "border-danger" : undefined }, [ - h.div( - [h.Class("flex flex-wrap items-start justify-between gap-3")], - [ - h.div( - [h.Class("flex min-w-0 flex-col gap-0.5")], - [ - heading(h, { variant: "subsection", level: 2 }, [ - "Score = weighted average of four parts", - ]), - isOff - ? h.p( - [h.Role("alert"), h.Class("text-danger-subtle-fg text-xs")], - [totalProblem(total)], - ) - : h.p( - [h.Class("text-muted-fg text-xs")], - [ - "Each part scores 0–100 from the rules below. A part with no data drops out and its weight is shared by the others.", - ], - ), - ], - ), - h.div( - [h.Class("flex items-center gap-2")], - [...(isOff && context.canEdit ? [scaleButton(h)] : []), totalPill(h, total)], - ), - ], - ), - h.div( - [h.Class("relative")], - [ - h.div( - [ - h.Role("img"), - h.AriaLabel( - COMPONENTS.map((key) => `${COMPONENT_LABEL[key]} ${draft.weights[key]}%`).join( - ", ", - ), - ), - h.Class("flex h-2.5 w-full gap-0.5 overflow-hidden rounded-full bg-secondary"), - ], - COMPONENTS.filter((key) => draft.weights[key] > 0).map((key) => - h.span([ - h.Class( - twMerge( - "block h-full first:rounded-l-full last:rounded-r-full", - COMPONENT_FILL[key], - ), - ), - h.Style({ width: `${(draft.weights[key] / scale) * 100}%` }), - ]), - ), - ), - ...(total > 100 - ? [ - h.span([ - h.AriaHidden(true), - h.Class( - "absolute -top-1 -bottom-1 w-0.5 -translate-x-1/2 rounded-full bg-danger", - ), - h.Style({ left: `${(100 / total) * 100}%` }), - ]), - ] - : []), - ], - ), - h.div( - [h.Class("flex flex-wrap items-center gap-x-4 gap-y-1 text-xs")], - [ - ...COMPONENTS.map((key) => - h.span( - [h.Class("inline-flex items-center gap-1.5")], - [ - h.span([h.Class(twMerge("size-2.5 rounded-xs", COMPONENT_FILL[key]))]), - h.span([h.Class("text-muted-fg")], [COMPONENT_LABEL[key]]), - h.span([h.Class("font-medium text-fg tabular-nums")], [`${draft.weights[key]}%`]), - ...(draft.weights[key] === saved.weights[key] - ? [] - : [ - h.span( - [h.Class("text-warning-subtle-fg")], - [`was ${saved.weights[key]}%`], - ), - ]), - ], - ), - ), - ...(total > 100 ? [h.span([h.Class("ml-auto text-muted-fg")], ["Red line = 100%"])] : []), - ], - ), - ]) -} - -// COMPONENT CARDS - -/** − 40% +: steps by 5 to the next multiple of 5. */ -const stepper = (h: H, key: ComponentKey, context: Context): Html => { - const value = context.draft.weights[key] - const isChanged = value !== context.saved.weights[key] - const stepButton = (label: string, ariaLabel: string, next: number) => - ariaButton( - h, - { - isDisabled: !context.canEdit || next === value, - onPress: Message.ChangedWeight({ key, value: next }), - attributes: [h.AriaLabel(ariaLabel)], - className: - "flex h-7 w-7 cursor-pointer items-center justify-center text-muted-fg outline-hidden hover:text-fg focus-visible:text-fg disabled:cursor-default disabled:opacity-50", - }, - [label], - ) - return h.div( - [ - h.Class( - twMerge( - "flex shrink-0 items-center rounded-lg border border-border bg-bg", - isChanged && "border-warning", - ), - ), - ], - [ - stepButton( - "−", - `Lower the ${COMPONENT_LABEL[key]} weight`, - Math.max(0, Math.ceil(value / 5) * 5 - 5), - ), - h.span( - [ - h.AriaLive("polite"), - h.Class("w-11 text-center font-semibold text-fg text-sm tabular-nums"), - ], - [`${value}%`], - ), - stepButton( - "+", - `Raise the ${COMPONENT_LABEL[key]} weight`, - Math.min(100, Math.floor(value / 5) * 5 + 5), - ), - ], - ) -} - -const weightSlider = (h: H, model: Model, key: ComponentKey, context: Context): Html => { - const saved = context.saved.weights[key] - const value = context.draft.weights[key] - return h.submodel({ - slotId: `health-weight-${key}`, - model: model.sliders[key], - view: Slider.view, - viewInputs: { - value, - ariaLabel: `${COMPONENT_LABEL[key]} weight`, - formatValue: (weight: number) => `${weight}%`, - isDisabled: !context.canEdit, - toView: (attributes) => - h.div( - [ - ...attributes.root, - h.Class( - "relative flex h-4 w-full touch-none select-none items-center data-disabled:opacity-60", - ), - ], - [ - h.div( - [...attributes.track, h.Class("h-1.5 w-full rounded-full bg-secondary")], - [ - h.div([ - ...attributes.filledTrack, - h.Class(twMerge("rounded-full", COMPONENT_FILL[key])), - ]), - ...(saved === value - ? [] - : [ - h.span([ - h.Title(`Saved: ${saved}%`), - h.Class( - "pointer-events-none absolute top-1/2 h-4 w-0.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-muted-fg", - ), - h.Style({ left: `${saved}%` }), - ]), - ]), - ], - ), - h.div([ - ...attributes.thumb, - h.Class( - twMerge( - "top-1/2 size-4 -translate-y-1/2 cursor-grab rounded-full border-2 bg-fg outline-hidden focus-visible:ring-3 focus-visible:ring-ring/30 data-dragging:cursor-grabbing data-disabled:cursor-default", - COMPONENT_BORDER[key], - ), - ), - ]), - ], - ), - }, - toParentMessage: SLIDER_MESSAGE[key], - }) -} - -const scoreInput = ( - h: H, - field: ScoreField, - value: number | null, - ariaLabel: string, - context: Context, -): Html => - numberInput(h, context, { - field, - value, - ariaLabel, - onInput: (text) => Message.ChangedScore({ field, value: parseNumber(text), text }), - }) - -/** One threshold list: every step but the last has a threshold; the last catches the rest. */ -const stepRows = ( - h: H, - context: Context, - options: Readonly<{ - list: StepList - steps: ReadonlyArray<{ readonly threshold: number | null; readonly score: number | null }> - /** The threshold as the input shows it, and back (an emptied one stays emptied). */ - show: (threshold: number) => number - read: (shown: number) => number - condition: (input: Html) => ReadonlyArray - otherwise: string - unit: string - }>, -): ReadonlyArray => - options.steps.map((step, index) => { - const isLast = index === options.steps.length - 1 - const threshold = numberInput(h, context, { - field: `${options.list}.${index}.threshold`, - value: step.threshold === null ? null : options.show(step.threshold), - ariaLabel: `Step ${index + 1} threshold, ${options.unit}`, - onInput: (text) => { - const shown = parseNumber(text) - return Message.ChangedStep({ - list: options.list, - index, - field: "threshold", - value: shown === null ? null : options.read(shown), - text, - }) - }, - }) - return ruleRow(h, isLast ? [options.otherwise] : options.condition(threshold), [ - "→", - numberInput(h, context, { - field: `${options.list}.${index}.score`, - value: step.score, - ariaLabel: `Step ${index + 1} score`, - onInput: (text) => - Message.ChangedStep({ - list: options.list, - index, - field: "score", - value: parseNumber(text), - text, - }), - }), - ]) - }) - -const rules = (h: H, key: ComponentKey, context: Context): ReadonlyArray => { - const { steps } = context.draft - const { activeRatioWeight } = steps.usage - const trendShare = activeRatioWeight === null ? null : 100 - activeRatioWeight - const identity = (value: number) => value - const section = (children: ReadonlyArray) => - h.div([h.Class("flex flex-col gap-1.5")], [...children]) - switch (key) { - case "usage": - return [ - section([ - ruleHeading(h, "Active ratio", "active users 30d ÷ contacts"), - ...stepRows(h, context, { - list: "activeRatio", - steps: steps.usage.activeRatio.map((step) => ({ - threshold: step.min, - score: step.score, - })), - show: (ratio) => Math.round(ratio * 10_000) / 100, - read: (percent) => percent / 100, - condition: (input) => ["At least", input, "%"], - otherwise: "Anything lower", - unit: "percent of contacts", - }), - ]), - section([ - ruleHeading(h, "Usage trend", "active users, last 7 days vs the 28 before"), - ...stepRows(h, context, { - list: "trend", - steps: steps.usage.trend.map((step) => ({ threshold: step.min, score: step.score })), - show: identity, - read: identity, - condition: (input) => ["Change of at least", input, "%"], - otherwise: "Anything lower", - unit: "percent change", - }), - ]), - h.p( - [h.Class("flex flex-wrap items-center gap-1.5 text-muted-fg text-xs")], - // Each phrase wraps whole, so the `%` never lands apart from its input. - [ - h.span([h.Class("whitespace-nowrap")], ["Part score ="]), - h.span( - [h.Class("inline-flex items-center gap-1.5 whitespace-nowrap")], - [ - scoreInput( - h, - "activeRatioWeight", - steps.usage.activeRatioWeight, - "Active ratio share", - context, - ), - "% active ratio", - ], - ), - h.span([h.Class("whitespace-nowrap")], [`+ ${textOf(trendShare)}% trend.`]), - h.span([], ["No trend yet: the ratio alone."]), - ], - ), - ] - case "engagement": - return [ - section([ - ruleHeading(h, "Days since last activity", "any contact, any source"), - ...stepRows(h, context, { - list: "daysSinceActive", - steps: steps.engagement.daysSinceActive.map((step) => ({ - threshold: step.max, - score: step.score, - })), - show: identity, - read: identity, - condition: (input) => ["Active in the last", input, "days"], - otherwise: "Anything older, or never active", - unit: "days", - }), - ]), - ] - case "billing": { - const row = (field: (typeof BILLING_ROWS)[number][0], label: string) => - ruleRow( - h, - [label], - ["→", scoreInput(h, field, steps.billing[field], `${label} score`, context)], - ) - return [ - section([ - ruleHeading(h, "Payment status", "worst state wins"), - ...BILLING_ROWS.map(([field, label]) => row(field, label)), - ]), - ] - } - case "signals": - return [ - section([ - ruleHeading(h, "Start at 100, subtract per open item", "floor at 0"), - ...PENALTY_FIELDS.map((severity) => - ruleRow( - h, - [severityGlyph(h, severity), `Each open ${severity}-severity risk`], - [ - "−", - scoreInput( - h, - severity, - steps.signals[severity], - `${severity} severity penalty`, - context, - ), - ], - ), - ), - ]), - h.p( - [h.Class("text-muted-fg text-xs")], - [ - `Snoozed items count; dismissed ones and opportunities don't. Never counted, so the score can't feed itself: ${context.draft.excludedTemplates - .map((template) => Customers.TEMPLATES[template].name) - .join(", ")}.`, - ], - ), - ] - } -} - -const BILLING_ROWS = [ - ["ok", "Paid up, no open invoices"], - ["overdue", "Invoice overdue up to 7 days"], - ["cancelScheduled", "Cancellation scheduled"], - ["overdueOverWeek", "Invoice overdue more than 7 days"], - ["pastDue", "Payment past due or unpaid"], -] as const satisfies ReadonlyArray - -export interface DataGaps { - readonly neverActive: number - readonly noSubscription: number -} - -const footnote = (key: ComponentKey, gaps: DataGaps | null): string | null => { - if (key === "signals") return "Always has data" - if (gaps === null) return null - if (key === "billing") - return gaps.noSubscription === 0 - ? "Every account has a subscription" - : `No subscription: ${gaps.noSubscription} accounts, weight shared` - return gaps.neverActive === 0 - ? "Every account has been active" - : `Never active: ${gaps.neverActive} accounts, lowest step` -} - -export const componentCard = ( - h: H, - model: Model, - key: ComponentKey, - context: Context, - gaps: DataGaps | null, -): Html => { - const { weights } = context.draft - const others = context.total - weights[key] - const note = footnote(key, gaps) - return panel(h, {}, [ - h.div( - [h.Class("flex items-start justify-between gap-3")], - [ - h.div( - [h.Class("flex min-w-0 flex-col gap-0.5")], - [ - h.div( - [h.Class("flex items-center gap-2")], - [ - h.span([h.Class(twMerge("size-2.5 rounded-xs", COMPONENT_FILL[key]))]), - heading(h, { variant: "subsection" }, [COMPONENT_LABEL[key]]), - ], - ), - h.p([h.Class("text-muted-fg text-xs")], [DESCRIPTION[key]]), - ], - ), - stepper(h, key, context), - ], - ), - weightSlider(h, model, key, context), - ...(model.lastWeight === key && context.total > 100 - ? [ - h.p( - [h.Class("-mt-2 text-danger-subtle-fg text-xs")], - [`Max ${Math.max(0, 100 - others)}% here while the other parts stay at ${others}%`], - ), - ] - : []), - h.div([h.Class("flex flex-col gap-3")], [...rules(h, key, context)]), - h.div( - [h.Class("mt-auto flex items-center gap-1.5 border-border border-t pt-3")], - [ - ...SOURCES[key].map((source) => sourceMark(h, source, { size: "sm" })), - ...(note === null ? [] : [h.span([h.Class("ml-auto text-muted-fg text-xs")], [note])]), - ], - ), - ]) -} diff --git a/apps/web-foldkit/src/page/customers/settings/health/fields.ts b/apps/web-foldkit/src/page/customers/settings/health/fields.ts deleted file mode 100644 index fce4da86f..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/fields.ts +++ /dev/null @@ -1,98 +0,0 @@ -import type * as Customers from "@hazel/domain/customers" -import type { Html, HtmlBuilder } from "foldkit/html" -import { twMerge } from "tailwind-merge" -import type { Message } from "./message" -import type { HealthDraft } from "./model" -import { inputElement } from "../../../../ui/input" - -/** What every part of the health settings view reads: the saved and draft settings and who may edit. */ -export interface Context { - readonly saved: Customers.HealthSettings - readonly draft: HealthDraft - /** `invalidFieldsOf(draft)`. */ - readonly invalid: ReadonlySet - readonly total: number - readonly isDirty: boolean - readonly canEdit: boolean - /** `Model.typing`. */ - readonly typing: Readonly<{ field: string; text: string }> | null -} - -export type H = HtmlBuilder - -/** An input's text: an emptied field holds `null`. */ -export const textOf = (value: number | null): string => (value === null ? "" : String(value)) -/** - * Plain decimals only (`12`, `-0.5`, `1.`): `1e2`, `0x10` or `Infinity` read as invalid (`null`), not - * as a number, and so do digits too many to be a finite one. - */ -const DECIMAL = /^\s*-?(\d+\.?\d*|\.\d+)\s*$/ -export const parseNumber = (text: string): number | null => { - if (!DECIMAL.test(text)) return null - const value = Number(text) - return Number.isFinite(value) ? value : null -} - -/** The field's text: what was typed in it while that still reads as `value` (`-`, `1.`), else the value. */ -export const numberText = (typing: Context["typing"], field: string, value: number | null): string => - typing !== null && typing.field === field && Object.is(parseNumber(typing.text), value) - ? typing.text - : textOf(value) - -/** A compact number field for a step's threshold or score; `field` is its `invalidFieldsOf` key. */ -export const numberInput = ( - h: H, - context: Context, - options: Readonly<{ - field: string - value: number | null - ariaLabel: string - onInput: (text: string) => Message - className?: string - }>, -): Html => { - const isInvalid = context.invalid.has(options.field) - return inputElement(h, { - isInvalid, - isDisabled: !context.canEdit, - className: twMerge( - "inline-block h-7 w-12 rounded-md px-1.5 py-0 text-right text-xs tabular-nums sm:px-1.5 sm:py-0 sm:text-xs", - options.className, - ), - attributes: [ - h.Type("text"), - h.InputMode("decimal"), - h.Value(numberText(context.typing, options.field, options.value)), - h.AriaLabel(options.ariaLabel), - h.OnInput(options.onInput), - ], - }) -} - -/** A scoring rule's row: the condition (text and inputs) left, the points right. */ -export const ruleRow = ( - h: H, - condition: ReadonlyArray, - points: ReadonlyArray, -) => - h.div( - [ - h.Class( - "flex min-h-9 items-center justify-between gap-3 rounded-md bg-secondary/50 px-2 py-1 text-secondary-fg text-xs", - ), - ], - [ - h.span([h.Class("flex min-w-0 items-center gap-1.5")], [...condition]), - h.span([h.Class("flex shrink-0 items-center gap-1 text-muted-fg")], [...points]), - ], - ) - -/** A rules section's heading: its input on the left, how it is measured on the right. */ -export const ruleHeading = (h: H, name: string, formula: string): Html => - h.div( - [h.Class("flex items-baseline justify-between gap-3")], - [ - h.span([h.Class("font-medium text-secondary-fg text-xs")], [name]), - h.span([h.Class("text-right text-2xs text-muted-fg")], [formula]), - ], - ) diff --git a/apps/web-foldkit/src/page/customers/settings/health/index.ts b/apps/web-foldkit/src/page/customers/settings/health/index.ts deleted file mode 100644 index 4b1dc2423..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { definePage } from "../../../contract" -import { Message } from "./message" -import { Model } from "./model" -import { subscriptions } from "./subscription" -import { init, update } from "./update" -import { view } from "./view" - -/** `/$orgSlug/customers/settings/health`: how the health score is built, with a dry run of the edits. */ -export const page = definePage( - "CustomersSettingsHealth", - { Model, Message }, - { routes: ["CustomersSettingsHealth"], init, update, view, subscriptions }, -) diff --git a/apps/web-foldkit/src/page/customers/settings/health/message.ts b/apps/web-foldkit/src/page/customers/settings/health/message.ts deleted file mode 100644 index 101ce4c96..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/message.ts +++ /dev/null @@ -1,50 +0,0 @@ -import * as Customers from "@hazel/domain/customers" -import { CustomerAccountId } from "@hazel/schema" -import { Schema } from "effect" -import { defineMessageUnion } from "foldkit/message" -import { CommonReason } from "~/lib/error-messages" -import { AccountRow } from "../../../../customers/queries" -import * as Select from "../../../../ui/select" -import * as Slider from "../../../../ui/slider" -import { BandKey, PreviewMetric, SavedSettings, ScoreField, SliderId, StepField, StepList } from "./model" - -export const Message = defineMessageUnion({ - UpdatedSettings: { settings: Schema.NullOr(SavedSettings) }, - UpdatedAccounts: { accounts: Schema.Array(AccountRow) }, - - /** A weight's stepper; its slider reports through `GotSliderMessage`. */ - ChangedWeight: { key: Customers.HealthComponentKey, value: Schema.Finite }, - /** - * A band's number input (the handles report through `GotSliderMessage`). `null`: emptied or not a - * number yet; `text` is what was typed (`-`, `1.`), kept while it still reads as `value`. - */ - ChangedBand: { band: BandKey, value: Schema.NullOr(Schema.Finite), text: Schema.String }, - ChangedStep: { - list: StepList, - index: Schema.Int, - field: StepField, - value: Schema.NullOr(Schema.Finite), - text: Schema.String, - }, - ChangedScore: { field: ScoreField, value: Schema.NullOr(Schema.Finite), text: Schema.String }, - GotSliderMessage: { id: SliderId, message: Slider.Message }, - PressedScaleWeights: {}, - PressedResetDefaults: {}, - PressedDiscard: {}, - PressedSave: {}, - PressedRetryPreview: {}, - ClickedPreviewMetric: { metric: PreviewMetric }, - GotCheckAccountMessage: { message: Select.Message }, - - ElapsedHealthPreviewDelay: { version: Schema.Int }, - SucceededFetchHealthDryRun: { version: Schema.Int, result: Customers.HealthDryRunResult }, - FailedFetchHealthDryRun: { version: Schema.Int, reason: CommonReason }, - SucceededFetchHealthCheckDetail: { - accountId: CustomerAccountId, - health: Schema.NullOr(Customers.HealthBreakdown), - }, - FailedFetchHealthCheckDetail: { accountId: CustomerAccountId, reason: CommonReason }, - SucceededSaveHealthSettings: {}, - FailedSaveHealthSettings: { reason: CommonReason }, -}) -export type Message = typeof Message.Type diff --git a/apps/web-foldkit/src/page/customers/settings/health/model.ts b/apps/web-foldkit/src/page/customers/settings/health/model.ts deleted file mode 100644 index c61baa662..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/model.ts +++ /dev/null @@ -1,360 +0,0 @@ -import * as Customers from "@hazel/domain/customers" -import { CustomerAccountId, CustomerSettingsId } from "@hazel/schema" -import { Equal, Schema } from "effect" -import * as AsyncData from "foldkit/asyncData" -import { CommonReason } from "~/lib/error-messages" -import { AccountRow } from "../../../../customers/queries" -import * as Select from "../../../../ui/select" -import * as Slider from "../../../../ui/slider" - -/** - * Health score settings (`docs/customers/spec.md` › Settings, Wonder `mao` / `aal`): the org's saved - * `HealthSettings`, a draft the admin edits, its dry run, and one customer's breakdown. - */ - -type HealthSettings = Customers.HealthSettings -type ComponentKey = Customers.HealthComponentKey - -// DRAFT - -const Steps = (fields: F) => Schema.Array(Schema.Struct(fields)) - -/** A number input's value: null while it is emptied or does not read as a number. */ -const Entry = Schema.NullOr(Schema.Finite) - -/** - * `HealthSettings` without its checks: the draft holds whatever the inputs hold (an emptied field - * is `null`) until it decodes as `HealthSettings` again. The weights only move by stepper and slider. - */ -export const HealthDraft = Schema.Struct({ - weights: Schema.Struct({ - usage: Schema.Finite, - engagement: Schema.Finite, - billing: Schema.Finite, - signals: Schema.Finite, - }), - bands: Schema.Struct({ healthyMin: Entry, atRiskMin: Entry }), - steps: Schema.Struct({ - usage: Schema.Struct({ - activeRatioWeight: Entry, - activeRatio: Steps({ min: Entry, score: Entry }), - trend: Steps({ min: Entry, score: Entry }), - }), - engagement: Schema.Struct({ daysSinceActive: Steps({ max: Entry, score: Entry }) }), - billing: Schema.Struct({ - pastDue: Entry, - overdueOverWeek: Entry, - overdue: Entry, - cancelScheduled: Entry, - ok: Entry, - }), - signals: Schema.Struct({ high: Entry, medium: Entry, low: Entry }), - }), - excludedTemplates: Schema.Array(Customers.SignalTemplate), -}) -export type HealthDraft = typeof HealthDraft.Type - -export const COMPONENTS: ReadonlyArray = Customers.HealthComponentKey.literals - -export const BandKey = Schema.Literals(["healthyMin", "atRiskMin"]) -export type BandKey = typeof BandKey.Type - -/** The threshold lists: `activeRatio` and `trend` are `MinStep`s, `daysSinceActive` `MaxStep`s. */ -export const StepList = Schema.Literals(["activeRatio", "trend", "daysSinceActive"]) -export type StepList = typeof StepList.Type - -export const StepField = Schema.Literals(["threshold", "score"]) -export type StepField = typeof StepField.Type - -export const BILLING_FIELDS = ["ok", "overdue", "cancelScheduled", "overdueOverWeek", "pastDue"] as const -export const PENALTY_FIELDS = ["high", "medium", "low"] as const - -/** A single 0–100 number of the steps: the usage mix, a billing state's score, a severity's penalty. */ -export const ScoreField = Schema.Literals(["activeRatioWeight", ...BILLING_FIELDS, ...PENALTY_FIELDS]) -export type ScoreField = typeof ScoreField.Type - -// MODEL - -export const SliderId = Schema.Literals([...Customers.HealthComponentKey.literals, ...BandKey.literals]) -export type SliderId = typeof SliderId.Type - -export const SavedSettings = Schema.Struct({ - id: CustomerSettingsId, - health: Customers.HealthSettings, - reportingCurrency: Schema.String, -}) -export type SavedSettings = typeof SavedSettings.Type - -export const DryRun = AsyncData.Schema(Customers.HealthDryRunResult, CommonReason) -export type DryRun = typeof DryRun.schema.Type - -/** The dry run of the latest draft; `version` counts drafts, so a slower answer for an older one is dropped. */ -export const Preview = Schema.Struct({ version: Schema.Int, result: DryRun.schema }) - -export const SavedBreakdown = AsyncData.Schema(Schema.NullOr(Customers.HealthBreakdown), CommonReason) - -/** "Check one customer": the picked account's saved breakdown (`customers.account.detail`). */ -export const Check = Schema.Struct({ accountId: CustomerAccountId, saved: SavedBreakdown.schema }) - -export const PreviewMetric = Schema.Literals(["customers", "mrr"]) -export type PreviewMetric = typeof PreviewMetric.Type - -export const Model = Schema.Struct({ - /** The synced settings row; null until it syncs. */ - settings: Schema.NullOr(SavedSettings), - /** Null: no edits (the saved settings show). Never equal to the saved ones while not saving. */ - draft: Schema.NullOr(HealthDraft), - /** The weight last moved: its card explains how far it may go while the total is over. */ - lastWeight: Schema.NullOr(Customers.HealthComponentKey), - accounts: Schema.NullOr(Schema.Array(AccountRow)), - sliders: Schema.Struct({ - usage: Slider.Model, - engagement: Slider.Model, - billing: Slider.Model, - signals: Slider.Model, - healthyMin: Slider.Model, - atRiskMin: Slider.Model, - }), - preview: Preview, - previewMetric: PreviewMetric, - checkAccount: Select.Model, - check: Schema.NullOr(Check), - isSaving: Schema.Boolean, - /** The number field last typed in (its `invalidFieldsOf` key) and its text, shown while it reads as the value. */ - typing: Schema.NullOr(Schema.Struct({ field: Schema.String, text: Schema.String })), -}) -export type Model = typeof Model.Type - -export const CHECK_ACCOUNT_ID = "health-check-account" - -/** What the page edits and previews: the draft, or the saved settings when there is none. */ -export const draftOf = (model: Model): HealthDraft | null => model.draft ?? model.settings?.health ?? null - -export const isDirty = (model: Model): boolean => - model.draft !== null && model.settings !== null && !Equal.equals(model.draft, model.settings.health) - -// VALIDATION - -export const weightTotal = (draft: HealthDraft): number => - COMPONENTS.reduce((sum, key) => sum + draft.weights[key], 0) - -const isScore = (value: number | null) => - value !== null && Number.isInteger(value) && value >= 0 && value <= 100 - -/** Keys of the fields that do not hold: `healthyMin`, `trend.2.threshold`, `pastDue`, … An emptied one never does. */ -export const invalidFieldsOf = (draft: HealthDraft): ReadonlySet => { - const invalid = new Set() - const { bands, steps } = draft - for (const band of BandKey.literals) if (!isScore(bands[band])) invalid.add(band) - if (bands.atRiskMin === null || bands.healthyMin === null || !(bands.atRiskMin < bands.healthyMin)) { - invalid.add("healthyMin") - invalid.add("atRiskMin") - } - const checkList = ( - list: StepList, - rows: ReadonlyArray<{ readonly threshold: number | null; readonly score: number | null }>, - isThreshold: (value: number) => boolean, - isOrdered: (previous: number, next: number) => boolean, - ) => - rows.forEach((row, index) => { - if (!isScore(row.score)) invalid.add(`${list}.${index}.score`) - const previous = rows[index - 1] - // A step after an emptied one cannot be ordered against it either. - if ( - row.threshold === null || - !isThreshold(row.threshold) || - (previous !== undefined && - (previous.threshold === null || !isOrdered(previous.threshold, row.threshold))) - ) - invalid.add(`${list}.${index}.threshold`) - }) - const descending = (previous: number, next: number) => next < previous - checkList( - "activeRatio", - steps.usage.activeRatio.map((step) => ({ threshold: step.min, score: step.score })), - (value) => value >= 0 && value <= 1, - descending, - ) - checkList( - "trend", - steps.usage.trend.map((step) => ({ threshold: step.min, score: step.score })), - Number.isFinite, - descending, - ) - checkList( - "daysSinceActive", - steps.engagement.daysSinceActive.map((step) => ({ threshold: step.max, score: step.score })), - (value) => Number.isInteger(value) && value >= 0, - (previous, next) => next > previous, - ) - if (!isScore(steps.usage.activeRatioWeight)) invalid.add("activeRatioWeight") - for (const field of BILLING_FIELDS) if (!isScore(steps.billing[field])) invalid.add(field) - for (const field of PENALTY_FIELDS) if (!isScore(steps.signals[field])) invalid.add(field) - return invalid -} - -const isHealthSettings = Schema.is(Customers.HealthSettings) - -/** The draft, when it is one the server takes: fields in range and ordered, weights summing to 100. */ -export const validDraftOf = (model: Model): HealthSettings | null => { - const { draft } = model - return draft !== null && - invalidFieldsOf(draft).size === 0 && - weightTotal(draft) === 100 && - isHealthSettings(draft) - ? draft - : null -} - -// EDITS - -const replaceAt = (items: ReadonlyArray, index: number, f: (item: A) => A): ReadonlyArray => - items.map((item, at) => (at === index ? f(item) : item)) - -export const withWeight = (draft: HealthDraft, key: ComponentKey, value: number): HealthDraft => ({ - ...draft, - weights: { ...draft.weights, [key]: Math.min(100, Math.max(0, Math.round(value))) }, -}) - -export const withBand = (draft: HealthDraft, band: BandKey, value: number | null): HealthDraft => ({ - ...draft, - bands: { ...draft.bands, [band]: value }, -}) - -/** - * A handle moves within its side of the other one, so the bands stay ordered. While the other one is - * emptied there is no side to stay on, and the band stays unset too. - */ -export const withBandHandle = (draft: HealthDraft, band: BandKey, value: number): HealthDraft => { - const { atRiskMin, healthyMin } = draft.bands - return withBand( - draft, - band, - band === "healthyMin" - ? atRiskMin === null - ? null - : Math.max(value, atRiskMin + 1) - : healthyMin === null - ? null - : Math.min(value, healthyMin - 1), - ) -} - -export const withStep = ( - draft: HealthDraft, - list: StepList, - index: number, - field: StepField, - value: number | null, -): HealthDraft => { - if (list === "daysSinceActive") - return { - ...draft, - steps: { - ...draft.steps, - engagement: { - daysSinceActive: replaceAt(draft.steps.engagement.daysSinceActive, index, (step) => - field === "score" ? { ...step, score: value } : { ...step, max: value }, - ), - }, - }, - } - return { - ...draft, - steps: { - ...draft.steps, - usage: { - ...draft.steps.usage, - [list]: replaceAt(draft.steps.usage[list], index, (step) => - field === "score" ? { ...step, score: value } : { ...step, min: value }, - ), - }, - }, - } -} - -export const withScore = (draft: HealthDraft, field: ScoreField, value: number | null): HealthDraft => { - const { steps } = draft - if (field === "activeRatioWeight") - return { ...draft, steps: { ...steps, usage: { ...steps.usage, activeRatioWeight: value } } } - if (field === "high" || field === "medium" || field === "low") - return { ...draft, steps: { ...steps, signals: { ...steps.signals, [field]: value } } } - return { ...draft, steps: { ...steps, billing: { ...steps.billing, [field]: value } } } -} - -/** - * Weights rescaled to sum to exactly 100, keeping their proportions: each gets the floor of its share, - * and the points left go to the largest remainders (ties to the first part). All zero: equal shares. - */ -export const scaledWeights = (weights: Customers.HealthWeights): Customers.HealthWeights => { - const total = COMPONENTS.reduce((sum, key) => sum + weights[key], 0) - const exact = COMPONENTS.map((key) => ({ - key, - share: total === 0 ? 100 / COMPONENTS.length : (weights[key] / total) * 100, - })) - const floors = new Map(exact.map(({ key, share }) => [key, Math.floor(share)])) - const left = 100 - [...floors.values()].reduce((sum, value) => sum + value, 0) - const byRemainder = [...exact].sort( - (a, b) => b.share - Math.floor(b.share) - (a.share - Math.floor(a.share)), - ) - for (const { key } of byRemainder.slice(0, left)) floors.set(key, (floors.get(key) ?? 0) + 1) - return { - usage: floors.get("usage") ?? 0, - engagement: floors.get("engagement") ?? 0, - billing: floors.get("billing") ?? 0, - signals: floors.get("signals") ?? 0, - } -} - -// DERIVED - -export const COMPONENT_LABEL = { - usage: "Usage", - engagement: "Engagement", - billing: "Billing", - signals: "Signals", -} as const satisfies Record - -const BAND_LABEL = { healthyMin: "Healthy", atRiskMin: "At risk" } as const satisfies Record - -/** The unsaved-changes bar: "Usage 35% → 40%", "Healthy from 70 → 75", "Scoring rules". */ -export const changesOf = (saved: HealthSettings, draft: HealthSettings): ReadonlyArray => [ - ...COMPONENTS.filter((key) => draft.weights[key] !== saved.weights[key]).map( - (key) => `${COMPONENT_LABEL[key]} ${saved.weights[key]}% → ${draft.weights[key]}%`, - ), - ...BandKey.literals - .filter((band) => draft.bands[band] !== saved.bands[band]) - .map((band) => `${BAND_LABEL[band]} from ${saved.bands[band]} → ${draft.bands[band]}`), - ...(Equal.equals(draft.steps, saved.steps) ? [] : ["Scoring rules changed"]), -] - -/** Customers whose band the draft changes, from the dry run. */ -export const movedCount = (result: Customers.HealthDryRunResult): number => - result.transitions.reduce((sum, transition) => sum + transition.count, 0) - -/** The saved distribution as the synced accounts carry it (no dry run needed). */ -export const distributionOf = ( - accounts: ReadonlyArray, -): ReadonlyArray => - Customers.HealthStatus.literals.map((status) => { - const rows = accounts.filter((account) => account.healthStatus === status) - return { status, count: rows.length, mrrMinor: rows.reduce((sum, row) => sum + row.mrrMinor, 0) } - }) - -/** - * The cards' footnotes, over accounts that get a score (not churned): never active (usage and - * engagement score them by their last step) and without a subscription (billing drops out, its - * weight shared). A trial counts as subscribed. - */ -export const dataGapsOf = ( - accounts: ReadonlyArray, -): Readonly<{ neverActive: number; noSubscription: number }> => { - const scored = accounts.filter((account) => account.lifecycleStage !== "churned") - return { - neverActive: scored.filter((account) => account.lastActiveAtMs === null).length, - noSubscription: scored.filter( - (account) => - account.planName === null && account.mrrMinor === 0 && account.lifecycleStage !== "trialing", - ).length, - } -} diff --git a/apps/web-foldkit/src/page/customers/settings/health/preview-view.ts b/apps/web-foldkit/src/page/customers/settings/health/preview-view.ts deleted file mode 100644 index bbbbb1cd6..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/preview-view.ts +++ /dev/null @@ -1,650 +0,0 @@ -import * as Customers from "@hazel/domain/customers" -import { Option } from "effect" -import * as AsyncData from "foldkit/asyncData" -import type { Html } from "foldkit/html" -import { twMerge } from "tailwind-merge" -import { commonMessage } from "~/lib/error-messages" -import { distributionBar } from "../../../../customers/charts/distribution" -import { formatCount, formatDeltaCount, formatMoney } from "../../../../customers/format" -import type { AccountRow } from "../../../../customers/queries" -import { HEALTH_FILL, HEALTH_LABEL, healthBadge } from "../../../../customers/ui/badges" -import { segmented } from "../../../../ui/segmented-control" -import { IconChevronRight } from "../../../../icons" -import { button } from "../../../../ui/button" -import { callout } from "../../../../ui/callout" -import { panel, panelHeader } from "../../../../ui/card" -import { type Column, dataTable } from "../../../../ui/data-table" -import { emptyState } from "../../../../ui/empty-state" -import { loadingState } from "../../../../ui/loader" -import { statusDot } from "../../../../ui/status-dot" - -import * as Select from "../../../../ui/select" -import { view as selectView } from "../../../../ui/select-view" -import * as Slider from "../../../../ui/slider" -import { scaleButton } from "./components-view" -import { type Context, type H, numberInput, parseNumber, textOf } from "./fields" -import { Message } from "./message" -import { - type BandKey, - COMPONENT_LABEL, - changesOf, - distributionOf, - type Model, - movedCount, - type PreviewMetric, -} from "./model" -import { SLIDER_MESSAGE, toCheckAccountMessage } from "./update" -import { heading } from "../../../../ui/heading" - -/** The bands editor, the distribution preview, "Check one customer" and the unsaved-changes bar. */ - -type Status = Customers.HealthStatus -type Row = Customers.HealthDistributionRow - -const STATUSES: ReadonlyArray = ["healthy", "at_risk", "critical", "unknown"] - -/** The last score below a band's start; none while the band is emptied. */ -const below = (min: number | null) => (min === null ? null : min - 1) - -/** A position on the 0–100 scale; an emptied field sits at 0. */ -const onScale = (value: number | null) => (value === null ? 0 : Math.min(100, Math.max(0, value))) - -// BANDS - -const bandHandle = (h: H, model: Model, band: BandKey, context: Context): Html => { - const value = onScale(context.draft.bands[band]) - return h.submodel({ - slotId: `health-band-${band}`, - model: model.sliders[band], - view: Slider.view, - viewInputs: { - value, - ariaLabel: band === "healthyMin" ? "Healthy from" : "At risk from", - isDisabled: !context.canEdit, - toView: (attributes) => - h.div( - [...attributes.root, h.Class("pointer-events-none absolute inset-0 flex items-center")], - [ - h.div([...attributes.track, h.Class("h-1.5 w-full")]), - h.div( - [ - ...attributes.thumb, - h.Class( - "pointer-events-auto top-1/2 size-4 -translate-y-1/2 cursor-grab rounded-full border-2 border-bg bg-fg shadow-sm outline-hidden focus-visible:ring-3 focus-visible:ring-ring/40 data-dragging:cursor-grabbing data-disabled:cursor-default", - ), - ], - [ - h.span( - [ - h.AriaHidden(true), - h.Class( - "absolute -top-5 left-1/2 -translate-x-1/2 font-medium text-fg text-xs tabular-nums", - ), - ], - [String(value)], - ), - ], - ), - ], - ), - }, - toParentMessage: SLIDER_MESSAGE[band], - }) -} - -const bandInput = (h: H, band: BandKey, context: Context): Html => - numberInput(h, context, { - field: band, - value: context.draft.bands[band], - ariaLabel: band === "healthyMin" ? "Healthy from score" : "At risk from score", - onInput: (text) => Message.ChangedBand({ band, value: parseNumber(text), text }), - }) - -/** "Score of at least", shortened to "At least" where a phone has no room for it on one line. */ -const atLeast = (h: H): Html => - h.span( - [h.Class("whitespace-nowrap")], - [ - h.span([h.Class("max-sm:hidden")], ["Score of at least"]), - h.span([h.Class("sm:hidden")], ["At least"]), - ], - ) - -const statusLabel = (h: H, status: Status): Html => - h.span( - [h.Class("inline-flex w-20 shrink-0 items-center gap-2 text-fg")], - [ - statusDot(h, { tone: "neutral", className: twMerge("size-2", HEALTH_FILL[status]) }), - HEALTH_LABEL[status], - ], - ) - -export const bandsCard = (h: H, model: Model, context: Context): Html => { - const { healthyMin, atRiskMin } = context.draft.bands - const healthy = onScale(healthyMin) - const atRisk = Math.min(onScale(atRiskMin), healthy) - const bandRow = (status: Status, rule: ReadonlyArray, range: string) => - h.div( - [h.Class("flex min-h-10 items-center gap-3 border-border border-b px-1 text-xs last:border-b-0")], - [ - statusLabel(h, status), - h.span([h.Class("flex min-w-0 flex-1 items-center gap-2 text-muted-fg")], [...rule]), - h.span([h.Class("w-14 shrink-0 text-right text-muted-fg tabular-nums")], [range]), - ], - ) - return panel(h, {}, [ - panelHeader(h, { title: "Bands", description: "Where a score turns into a status" }), - h.div( - [h.Class("flex flex-col gap-1 pt-5")], - [ - h.div( - [h.Class("relative h-4")], - [ - h.div( - [ - h.AriaHidden(true), - h.Class( - "absolute inset-x-0 top-1/2 flex h-1.5 -translate-y-1/2 overflow-hidden rounded-full", - ), - ], - [ - h.span([ - h.Class("h-full bg-health-critical"), - h.Style({ width: `${atRisk}%` }), - ]), - h.span([ - h.Class("h-full bg-health-at-risk"), - h.Style({ width: `${healthy - atRisk}%` }), - ]), - h.span([h.Class("h-full flex-1 bg-health-healthy")]), - ], - ), - bandHandle(h, model, "atRiskMin", context), - bandHandle(h, model, "healthyMin", context), - ], - ), - h.div( - [h.Class("flex justify-between text-muted-fg text-xs tabular-nums")], - [h.span([], ["0"]), h.span([], ["100"])], - ), - ], - ), - h.div( - [h.Class("flex flex-col rounded-lg border border-border px-2")], - [ - bandRow( - "healthy", - [atLeast(h), bandInput(h, "healthyMin", context)], - `${textOf(healthyMin)}–100`, - ), - bandRow( - "at_risk", - [atLeast(h), bandInput(h, "atRiskMin", context)], - `${textOf(atRiskMin)}–${textOf(below(healthyMin))}`, - ), - bandRow( - "critical", - [`Everything below ${textOf(atRiskMin)}`], - `0–${textOf(below(atRiskMin))}`, - ), - bandRow("unknown", ["Leads, churned, or no part has data yet"], ""), - ], - ), - ...(context.invalid.has("healthyMin") || context.invalid.has("atRiskMin") - ? [ - h.p( - [h.Role("alert"), h.Class("text-danger-subtle-fg text-xs")], - ["Bands are whole scores from 0 to 100, and at risk starts below healthy."], - ), - ] - : []), - ]) -} - -// DISTRIBUTION - -const byStatus = (rows: ReadonlyArray, status: Status): Row => - rows.find((row) => row.status === status) ?? { status, count: 0, mrrMinor: 0 } - -const bar = (h: H, label: string, rows: ReadonlyArray, metric: PreviewMetric): Html => - h.div( - [h.Class("grid grid-cols-[6.5rem_1fr] items-center gap-3 text-xs")], - [ - h.span([h.Class("text-muted-fg")], [label]), - distributionBar(h, { - ariaLabel: `${label}: ${STATUSES.map((status) => `${HEALTH_LABEL[status]} ${byStatus(rows, status).count}`).join(", ")}`, - segments: STATUSES.map((status) => { - const row = byStatus(rows, status) - return { - key: status, - label: HEALTH_LABEL[status], - value: metric === "customers" ? row.count : row.mrrMinor, - fillClass: HEALTH_FILL[status], - } - }), - }), - ], - ) - -const bandText = (status: Status, bands: Customers.HealthBands): string => - status === "healthy" - ? `≥ ${bands.healthyMin}` - : status === "at_risk" - ? `${bands.atRiskMin}–${bands.healthyMin - 1}` - : status === "critical" - ? `< ${bands.atRiskMin}` - : "No data" - -/** "8 customers change band: 6 Healthy → At risk, 2 At risk → Critical." */ -export const transitionsText = (result: Customers.HealthDryRunResult): string => { - const moved = movedCount(result) - if (moved === 0) return "No customer changes band." - const parts = [...result.transitions] - .sort((a, b) => b.count - a.count) - .map( - (transition) => - `${transition.count} ${HEALTH_LABEL[transition.from]} → ${HEALTH_LABEL[transition.to]}`, - ) - return `${formatCount(moved)} ${moved === 1 ? "customer changes" : "customers change"} band: ${parts.join(", ")}.` -} - -/** A number cell, quieted or tinted by `className`. */ -const numberCell = (h: H, text: string, className?: string): Html | string => - className === undefined ? text : h.span([h.Class(className)], [text]) - -const distributionTable = ( - h: H, - saved: ReadonlyArray, - proposed: ReadonlyArray | null, - bands: Customers.HealthBands, - currency: string, -): Html => { - const name: Column = { - key: "status", - label: "Status", - cell: (status) => - h.span( - [h.Class("inline-flex items-center gap-2 whitespace-nowrap")], - [ - h.span([h.Class(twMerge("size-2.5 shrink-0 rounded-xs", HEALTH_FILL[status]))]), - h.span([h.Class("text-fg")], [HEALTH_LABEL[status]]), - h.span([h.Class("text-muted-fg text-xs")], [bandText(status, bands)]), - ], - ), - } - const number = (key: string, label: string, cell: (status: Status) => Html | string): Column => ({ - key, - label, - align: "right", - widthClass: "w-28", - cell, - }) - const columns: ReadonlyArray> = - proposed === null - ? [ - name, - number("customers", "Customers", (status) => formatCount(byStatus(saved, status).count)), - number("mrr", "MRR", (status) => formatMoney(byStatus(saved, status).mrrMinor, currency)), - ] - : [ - name, - number("saved", "Saved", (status) => - numberCell(h, formatCount(byStatus(saved, status).count), "text-muted-fg"), - ), - number("proposed", "With changes", (status) => - formatCount(byStatus(proposed, status).count), - ), - number("change", "Change", (status) => { - const change = byStatus(proposed, status).count - byStatus(saved, status).count - return numberCell( - h, - change === 0 ? "—" : formatDeltaCount(change), - change === 0 - ? "text-muted-fg" - : (status === "healthy") === change > 0 - ? "text-success-subtle-fg" - : "text-danger-subtle-fg", - ) - }), - number("mrr", "MRR", (status) => - formatMoney(byStatus(proposed, status).mrrMinor, currency), - ), - ] - return dataTable(h, { - ariaLabel: "Customers by status", - id: "health-distribution", - columns, - rows: STATUSES, - rowKey: (status) => status, - isFramed: false, - }) -} - -const metricToggle = (h: H, metric: PreviewMetric): Html => - segmented(h, { - ariaLabel: "Measure the distribution by", - segments: [ - { key: "customers", label: "Customers" }, - { key: "mrr", label: "MRR" }, - ], - selected: metric, - onSelect: (next) => Message.ClickedPreviewMetric({ metric: next }), - }) - -const pausedPanel = (h: H, title: string, body: string): Html => - emptyState(h, { title, description: body, className: "flex-1 py-10" }) - -export const distributionCard = ( - h: H, - model: Model, - context: Context, - valid: Customers.HealthSettings | null, - currency: string, -): Html => { - const accounts = model.accounts - const totals = (rows: ReadonlyArray) => - `${formatCount(rows.reduce((sum, row) => sum + row.count, 0))} customers · ${formatMoney( - rows.reduce((sum, row) => sum + row.mrrMinor, 0), - currency, - )} MRR` - const frame = (subtitle: string, children: ReadonlyArray) => - panel(h, {}, [ - panelHeader(h, { - title: "Distribution preview", - description: subtitle, - aside: metricToggle(h, model.previewMetric), - }), - ...children, - ]) - - if (!context.isDirty) { - if (accounts === null) return frame("Loading customers…", []) - const saved = distributionOf(accounts) - return frame(`${totals(saved)} · as saved`, [ - bar(h, "Saved", saved, model.previewMetric), - distributionTable(h, saved, null, context.saved.bands, currency), - ]) - } - if (valid === null) { - const customers = accounts === null ? "customers" : `${formatCount(accounts.length)} customers` - const first = context.total === 100 ? "Fix the highlighted fields" : "Weights must add up to 100%" - return panel(h, {}, [ - pausedPanel( - h, - "Preview paused", - `${first} before we can rescore your ${customers}. Saved scores stay live in the meantime.`, - ), - ]) - } - return AsyncData.match(model.preview.result, { - onIdle: () => frame("Scoring your changes…", []), - onLoading: () => - frame("Scoring your changes…", [ - pausedPanel(h, "Scoring your customers…", "Saved scores stay live in the meantime."), - ]), - onFailure: (reason) => - frame(commonMessage(reason).title, [ - h.div( - [h.Class("flex items-center gap-3")], - [ - h.p([h.Class("text-muted-fg text-sm")], ["The preview couldn't be computed."]), - button(h, { intent: "outline", size: "xs", onPress: Message.PressedRetryPreview() }, [ - "Try again", - ]), - ], - ), - ]), - onSuccess: (result) => previewResult(h, model, valid, result, currency, frame, totals, false), - onRefreshing: (result) => previewResult(h, model, valid, result, currency, frame, totals, true), - onStale: ({ data: result }) => previewResult(h, model, valid, result, currency, frame, totals, false), - }) -} - -const previewResult = ( - h: H, - model: Model, - valid: Customers.HealthSettings, - result: Customers.HealthDryRunResult, - currency: string, - frame: (subtitle: string, children: ReadonlyArray) => Html, - totals: (rows: ReadonlyArray) => string, - isRefreshing: boolean, -): Html => - frame( - result.evaluatedAccounts < result.totalAccounts - ? `Preview based on ${formatCount(result.evaluatedAccounts)} of ${formatCount(result.totalAccounts)} customers · scored with your unsaved changes` - : `${totals(result.proposed)} · scored with your unsaved changes`, - [ - h.div( - [ - h.Class(twMerge("flex flex-col gap-4 transition-opacity", isRefreshing && "opacity-60")), - h.AriaBusy(isRefreshing), - ], - [ - h.div( - [h.Class("flex flex-col gap-2")], - [ - bar(h, "Saved", result.current, model.previewMetric), - bar(h, "With changes", result.proposed, model.previewMetric), - ], - ), - distributionTable(h, result.current, result.proposed, valid.bands, currency), - callout(h, { intent: "warning", icon: null, className: "py-2 text-xs" }, [ - transitionsText(result), - ]), - ], - ), - ], - ) - -// CHECK ONE CUSTOMER - -const formatWeight = (weight: number) => `${Math.round(weight)}%` - -const breakdownTable = (h: H, breakdown: Customers.HealthBreakdown): Html => - h.div( - [h.Class("flex flex-col gap-2")], - [ - dataTable(h, { - ariaLabel: "Score breakdown", - id: "health-breakdown", - isFramed: false, - rows: breakdown.components, - rowKey: (part) => part.key, - columns: [ - { - key: "part", - label: "Part", - widthClass: "w-28 whitespace-nowrap", - cell: (part) => COMPONENT_LABEL[part.key], - }, - { - key: "why", - label: "Why", - cell: (part) => - h.span( - [h.Class("text-muted-fg text-xs")], - [part.excluded ? `${part.why} · no data, weight shared` : part.why], - ), - }, - { - key: "score", - label: "Part score", - align: "right", - widthClass: "w-24", - cell: (part) => (part.score === null ? "—" : String(part.score)), - }, - { - key: "weight", - label: "Weight", - align: "right", - widthClass: "w-20", - cell: (part) => - numberCell( - h, - part.excluded ? "—" : formatWeight(part.effectiveWeight), - "text-muted-fg", - ), - footer: h.span([h.Class("font-normal text-muted-fg text-xs")], ["Score"]), - }, - { - key: "points", - label: "Points", - align: "right", - widthClass: "w-20", - cell: (part) => - part.score === null - ? "—" - : ((part.effectiveWeight * part.score) / 100).toFixed(1), - footer: h.span( - [h.Class("font-semibold")], - [breakdown.score === null ? "—" : String(breakdown.score)], - ), - }, - ], - }), - h.p( - [h.Class("text-muted-fg text-xs")], - ["Rounded to the nearest whole number. The same table appears on every customer page."], - ), - ], - ) - -const scoreText = (breakdown: Customers.HealthBreakdown) => - breakdown.score === null ? "no score" : String(breakdown.score) - -export const checkCard = (h: H, model: Model, context: Context): Html => { - const accounts: ReadonlyArray = model.accounts ?? [] - const result = Option.getOrNull(AsyncData.getData(model.preview.result)) - const sample = - context.isDirty && model.check !== null - ? (result?.samples.find((candidate) => candidate.accountId === model.check?.accountId) ?? null) - : null - const saved = model.check === null ? null : Option.getOrNull(AsyncData.getData(model.check.saved)) - const picker = h.submodel({ - slotId: "health-check-account", - model: model.checkAccount, - view: selectView, - viewInputs: { - items: accounts.map((account) => Select.item(account.id, account.name)), - ariaLabel: "Customer", - placeholder: "Pick a customer", - triggerClassName: "w-56", - }, - toParentMessage: toCheckAccountMessage, - }) - const scores: ReadonlyArray = - sample !== null - ? [ - h.span([h.Class("text-muted-fg text-xs")], [`Saved ${scoreText(sample.current)}`]), - IconChevronRight(h, { className: "size-3.5 text-muted-fg" }), - healthBadge(h, { status: sample.proposed.status, score: sample.proposed.score }), - ] - : saved !== null - ? [healthBadge(h, { status: saved.status, score: saved.score })] - : [] - const body = (): ReadonlyArray => { - if (model.check === null) - return [ - h.p([h.Class("text-muted-fg text-sm")], ["Pick a customer to see how its score is built."]), - ] - if (sample !== null) return [breakdownTable(h, sample.proposed)] - return AsyncData.match(model.check.saved, { - onIdle: () => [], - onLoading: () => [loadingState(h, { label: "Loading…", size: "sm", className: "py-4" })], - onRefreshing: (health) => breakdownOrNone(h, health, context, result !== null), - onSuccess: (health) => breakdownOrNone(h, health, context, result !== null), - onStale: ({ data: health }) => breakdownOrNone(h, health, context, result !== null), - onFailure: (reason) => [h.p([h.Class("text-muted-fg text-sm")], [commonMessage(reason).title])], - }) - } - return panel(h, {}, [ - h.div( - [h.Class("flex flex-wrap items-center gap-3")], - [ - heading(h, { variant: "subsection", level: 2 }, ["Check one customer"]), - picker, - h.span([h.Class("flex-1")]), - ...scores, - ], - ), - ...body(), - ]) -} - -const breakdownOrNone = ( - h: H, - health: Customers.HealthBreakdown | null, - context: Context, - hasPreview: boolean, -): ReadonlyArray => [ - ...(context.isDirty && hasPreview - ? [ - h.p( - [h.Class("text-muted-fg text-xs")], - [ - "Your changes keep this customer in its band. The preview details only customers that change band, so this is its saved breakdown.", - ], - ), - ] - : []), - health === null - ? h.p( - [h.Class("text-muted-fg text-sm")], - ["Not scored yet: it gets a breakdown on the next compute."], - ) - : breakdownTable(h, health), -] - -// UNSAVED CHANGES - -export const unsavedBar = ( - h: H, - model: Model, - context: Context, - valid: Customers.HealthSettings | null, -): Html => { - const isValid = valid !== null - const result = Option.getOrNull(AsyncData.getData(model.preview.result)) - const moved = result === null ? [] : [`${formatCount(movedCount(result))} customers change band`] - const isWeightProblem = context.total !== 100 - return h.div( - [ - h.Role("region"), - h.AriaLabel("Unsaved changes"), - h.Class( - "sticky bottom-0 z-10 -mx-4 -mb-6 flex flex-wrap items-center gap-3 border-border border-t bg-bg/95 px-4 py-3 backdrop-blur lg:-mx-8 lg:px-8", - ), - ], - [ - statusDot(h, { tone: isValid ? "warning" : "danger", className: "size-2" }), - h.span( - [h.Class("font-medium text-fg text-sm")], - [isValid ? "Unsaved changes" : "Can't save yet"], - ), - h.span( - [h.Class("min-w-0 flex-1 truncate text-muted-fg text-sm")], - [ - valid !== null - ? [...changesOf(context.saved, valid), ...moved].join(" · ") - : isWeightProblem - ? `Weights add up to ${context.total}%, not 100%` - : "Fix the highlighted fields", - ], - ), - button(h, { intent: "plain", size: "sm", onPress: Message.PressedDiscard() }, ["Discard"]), - ...(isWeightProblem ? [scaleButton(h, "min-h-8")] : []), - button( - h, - { - intent: "primary", - size: "sm", - isDisabled: !isValid, - isPending: model.isSaving, - onPress: Message.PressedSave(), - }, - ["Save and rescore"], - ), - ], - ) -} diff --git a/apps/web-foldkit/src/page/customers/settings/health/story.test.ts b/apps/web-foldkit/src/page/customers/settings/health/story.test.ts deleted file mode 100644 index f537bdaab..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/story.test.ts +++ /dev/null @@ -1,362 +0,0 @@ -import * as Customers from "@hazel/domain/customers" -import { - CustomerAccountId, - CustomerSettingsId, - OrganizationId, - OrganizationMemberId, - UserId, -} from "@hazel/schema" -import { Schema } from "effect" -import { Command, expectOutMessage, given, message, model, story } from "foldkit/story" -import { describe, expect, test, vi } from "vitest" -import type { Shared } from "../../../contract" -import { PageOutMessage } from "../../../out-message" -import { sharedDefaults } from "../../../test-shared" -import * as Slider from "../../../../ui/slider" -import { DelayHealthPreview, FetchHealthCheckDetail, FetchHealthDryRun, SaveHealthSettings } from "./commands" -import { numberText, parseNumber } from "./fields" -import { Message } from "./message" -import { invalidFieldsOf, isDirty, type Model, scaledWeights, validDraftOf, weightTotal } from "./model" -import { init, update } from "./update" - -// `ui/aria/*` names `document` when its modules load; the update loop never touches it. -vi.hoisted(() => { - Object.assign(globalThis, { document: globalThis.document ?? {} }) -}) - -/** Update-loop tests for the health settings: weights, bands, the debounced dry run, save and discard. */ - -const uuid = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}` -const organizationId = Schema.decodeSync(OrganizationId)(uuid(1)) -const settingsId = Schema.decodeSync(CustomerSettingsId)(uuid(2)) -const accountId = Schema.decodeSync(CustomerAccountId)(uuid(3)) - -const shared: Shared = { - auth: "SignedIn", - orgSlug: "hazel", - currentUser: { - id: Schema.decodeSync(UserId)(uuid(4)), - firstName: "Ada", - lastName: "Lovelace", - email: "ada@hazel.test", - avatarUrl: null, - isOnboarded: true, - }, - organization: { id: organizationId, name: "Hazel", slug: "hazel", logoUrl: null }, - member: { id: Schema.decodeSync(OrganizationMemberId)(uuid(5)), role: "admin" }, - nowMs: Date.UTC(2026, 10, 10, 12), - ...sharedDefaults, -} - -const DEFAULTS = Customers.DEFAULT_HEALTH_SETTINGS -const pageUpdate = (current: Model, next: Message) => update(current, next, shared) - -const loaded = (): Model => - pageUpdate( - init().model, - Message.UpdatedSettings({ settings: { id: settingsId, health: DEFAULTS, reportingCurrency: "USD" } }), - ).model - -const weight = (key: Customers.HealthComponentKey, value: number) => Message.ChangedWeight({ key, value }) - -const result = (moved: number): Customers.HealthDryRunResult => ({ - current: [{ status: "healthy", count: 10, mrrMinor: 1_000 }], - proposed: [{ status: "healthy", count: 10 - moved, mrrMinor: 1_000 }], - transitions: [{ from: "healthy", to: "at_risk", count: moved }], - samples: [ - { - accountId, - name: "Acme", - current: { score: 72, status: "healthy", components: [] }, - proposed: { score: 64, status: "at_risk", components: [] }, - }, - ], - evaluatedAccounts: 10, - totalAccounts: 10, -}) - -describe("health settings: weights", () => { - test("an edit makes a draft; the total and validity follow it", () => { - const over = pageUpdate(loaded(), weight("usage", 45)).model - expect(isDirty(over)).toBe(true) - expect(over.draft?.weights.usage).toBe(45) - expect(weightTotal(over.draft ?? DEFAULTS)).toBe(110) - expect(validDraftOf(over)).toBeNull() - expect(over.lastWeight).toBe("usage") - - const balanced = pageUpdate(over, weight("engagement", 15)).model - expect(weightTotal(balanced.draft ?? DEFAULTS)).toBe(100) - expect(validDraftOf(balanced)).not.toBeNull() - }) - - test("moving a weight back to its saved value leaves no draft", () => { - const back = [weight("usage", 40), weight("usage", 35)].reduce( - (current, next) => pageUpdate(current, next).model, - loaded(), - ) - expect(back.draft).toBeNull() - expect(isDirty(back)).toBe(false) - }) - - test("over 100 blocks saving and the dry run", () => { - const over = pageUpdate(loaded(), weight("usage", 45)) - expect(over.commands ?? []).toHaveLength(0) - expect(over.model.preview.result._tag).toBe("Idle") - expect(pageUpdate(over.model, Message.PressedSave()).commands ?? []).toHaveLength(0) - expect( - pageUpdate(over.model, Message.ElapsedHealthPreviewDelay({ version: over.model.preview.version })) - .commands ?? [], - ).toHaveLength(0) - }) - - test("Scale to 100% keeps the proportions and sums to exactly 100", () => { - expect(scaledWeights({ usage: 45, engagement: 25, billing: 25, signals: 15 })).toEqual({ - usage: 41, - engagement: 23, - billing: 23, - signals: 13, - }) - expect(scaledWeights({ usage: 1, engagement: 1, billing: 1, signals: 0 })).toEqual({ - usage: 34, - engagement: 33, - billing: 33, - signals: 0, - }) - expect(scaledWeights({ usage: 0, engagement: 0, billing: 0, signals: 0 })).toEqual({ - usage: 25, - engagement: 25, - billing: 25, - signals: 25, - }) - const scaled = pageUpdate( - pageUpdate(loaded(), weight("usage", 45)).model, - Message.PressedScaleWeights(), - ) - expect(weightTotal(scaled.model.draft ?? DEFAULTS)).toBe(100) - expect(scaled.model.lastWeight).toBeNull() - expect(scaled.commands?.[0]?.name).toBe(DelayHealthPreview.name) - }) -}) - -describe("health settings: bands and steps", () => { - test("band handles keep at risk below healthy", () => { - const handle = (id: "healthyMin" | "atRiskMin", direction: "Min" | "Max", value: number) => - Message.GotSliderMessage({ - id, - message: Slider.Message.PressedKeyboardNavigation({ direction, value }), - }) - const atRisk = pageUpdate(loaded(), handle("atRiskMin", "Max", 40)).model - expect(atRisk.draft?.bands).toEqual({ healthyMin: 70, atRiskMin: 69 }) - const healthy = pageUpdate(loaded(), handle("healthyMin", "Min", 70)).model - expect(healthy.draft?.bands).toEqual({ healthyMin: 41, atRiskMin: 40 }) - }) - - test("typed bands may cross, and then the draft is invalid", () => { - const crossed = pageUpdate( - loaded(), - Message.ChangedBand({ band: "atRiskMin", value: 80, text: "80" }), - ).model - expect(invalidFieldsOf(crossed.draft ?? DEFAULTS)).toEqual(new Set(["healthyMin", "atRiskMin"])) - expect(validDraftOf(crossed)).toBeNull() - }) - - test("steps out of order or out of range are flagged", () => { - const unordered = pageUpdate( - loaded(), - Message.ChangedStep({ - list: "daysSinceActive", - index: 1, - field: "threshold", - value: 0, - text: "0", - }), - ).model - expect(invalidFieldsOf(unordered.draft ?? DEFAULTS).has("daysSinceActive.1.threshold")).toBe(true) - const tooHigh = pageUpdate( - loaded(), - Message.ChangedStep({ list: "trend", index: 0, field: "score", value: 120, text: "120" }), - ).model - expect(invalidFieldsOf(tooHigh.draft ?? DEFAULTS).has("trend.0.score")).toBe(true) - const emptied = pageUpdate( - loaded(), - Message.ChangedScore({ field: "pastDue", value: null, text: "" }), - ).model - expect(invalidFieldsOf(emptied.draft ?? DEFAULTS).has("pastDue")).toBe(true) - expect(validDraftOf(emptied)).toBeNull() - const ratio = pageUpdate( - loaded(), - Message.ChangedStep({ - list: "activeRatio", - index: 0, - field: "threshold", - value: 0.5, - text: "50", - }), - ).model - expect(validDraftOf(ratio)?.steps.usage.activeRatio[0]).toEqual({ min: 0.5, score: 100 }) - }) -}) - -describe("health settings: typing numbers", () => { - test("a minus or a trailing point stays in the field while it is typed", () => { - const minus = pageUpdate( - loaded(), - Message.ChangedStep({ - list: "trend", - index: 0, - field: "threshold", - value: null, - text: "-", - }), - ).model - expect(numberText(minus.typing, "trend.0.threshold", null)).toBe("-") - const point = pageUpdate( - loaded(), - Message.ChangedScore({ field: "pastDue", value: 1, text: "1." }), - ).model - expect(numberText(point.typing, "pastDue", 1)).toBe("1.") - // Another value (a reset, a discard) shows the value, not the old text. - expect(numberText(point.typing, "pastDue", 5)).toBe("5") - expect(numberText(point.typing, "trend.0.score", 1)).toBe("1") - }) - - test("only plain decimals read as numbers", () => { - expect([" 12 ", "-0.5", "1.", ".5"].map(parseNumber)).toEqual([12, -0.5, 1, 0.5]) - for (const text of ["", "-", "1e2", "0x10", "Infinity", "1,5", "9".repeat(400)]) - expect(parseNumber(text)).toBeNull() - }) -}) - -describe("health settings: preview", () => { - test("only the latest draft's dry run applies", () => { - const first = pageUpdate(loaded(), weight("usage", 40)) - const firstVersion = first.model.preview.version - const second = pageUpdate( - pageUpdate(first.model, weight("engagement", 20)).model, - weight("usage", 40), - ) - const latest = second.model.preview.version - expect(latest).toBeGreaterThan(firstVersion) - expect(second.model.preview.result._tag).toBe("Loading") - - // The first delay elapses after a newer edit: nothing is fetched. - expect( - pageUpdate(second.model, Message.ElapsedHealthPreviewDelay({ version: firstVersion })).commands ?? - [], - ).toHaveLength(0) - - const fetched = pageUpdate(second.model, Message.ElapsedHealthPreviewDelay({ version: latest })) - expect(fetched.commands?.[0]).toMatchObject({ - name: FetchHealthDryRun.name, - args: { - organizationId, - version: latest, - draft: { ...DEFAULTS, weights: { ...DEFAULTS.weights, usage: 40, engagement: 20 } }, - }, - }) - - const stale = pageUpdate( - second.model, - Message.SucceededFetchHealthDryRun({ version: firstVersion, result: result(1) }), - ).model - expect(stale.preview.result._tag).toBe("Loading") - }) - - test("an answer settles the preview and picks its first sample to check", () => { - story( - pageUpdate, - given(pageUpdate(loaded(), weight("usage", 40)).model), - message(weight("engagement", 20)), - model((current) => expect(current.preview.result._tag).toBe("Loading")), - Command.resolve(DelayHealthPreview, Message.ElapsedHealthPreviewDelay({ version: 2 })), - Command.resolve( - FetchHealthDryRun, - Message.SucceededFetchHealthDryRun({ version: 2, result: result(1) }), - ), - model((current) => { - expect(current.preview.result._tag).toBe("Success") - expect(current.check?.accountId).toBe(accountId) - }), - Command.resolve( - FetchHealthCheckDetail, - Message.SucceededFetchHealthCheckDetail({ accountId, health: null }), - ), - model((current) => expect(current.check?.saved._tag).toBe("Success")), - ) - }) -}) - -describe("health settings: save, discard, reset", () => { - test("save sends the draft and toasts on success", () => { - const draft = { ...DEFAULTS, weights: { ...DEFAULTS.weights, usage: 40, engagement: 20 } } - const edited = [weight("usage", 40), weight("engagement", 20)].reduce( - (current, next) => pageUpdate(current, next).model, - loaded(), - ) - const saving = pageUpdate(edited, Message.PressedSave()) - expect(saving.model.isSaving).toBe(true) - expect(saving.commands?.[0]).toMatchObject({ - name: SaveHealthSettings.name, - args: { organizationId, settingsId, health: draft }, - }) - // The optimistic row syncs first: the draft stays until the save settles. - const synced = pageUpdate( - saving.model, - Message.UpdatedSettings({ - settings: { id: settingsId, health: draft, reportingCurrency: "USD" }, - }), - ).model - expect(synced.draft).not.toBeNull() - story( - pageUpdate, - given(synced), - message(Message.SucceededSaveHealthSettings()), - model((current) => { - expect(current.isSaving).toBe(false) - expect(current.draft).toBeNull() - }), - expectOutMessage( - PageOutMessage.RequestedToast({ - toast: { - intent: "success", - title: "Health score saved", - description: "Customers are rescored on the next compute.", - }, - }), - ), - ) - }) - - test("a failed save keeps the draft", () => { - const edited = pageUpdate( - pageUpdate(loaded(), weight("usage", 40)).model, - weight("engagement", 20), - ).model - const saving = pageUpdate(edited, Message.PressedSave()).model - const failed = pageUpdate(saving, Message.FailedSaveHealthSettings({ reason: "Offline" })) - expect(failed.model.isSaving).toBe(false) - expect(isDirty(failed.model)).toBe(true) - expect(failed.outMessage?._tag).toBe("RequestedToast") - }) - - test("discard drops the draft and the preview", () => { - const edited = pageUpdate(loaded(), weight("usage", 45)).model - const discarded = pageUpdate(edited, Message.PressedDiscard()).model - expect(discarded.draft).toBeNull() - expect(discarded.lastWeight).toBeNull() - expect(discarded.preview.result._tag).toBe("Idle") - }) - - test("reset to defaults puts the defaults in the draft", () => { - const custom = { ...DEFAULTS, bands: { healthyMin: 75, atRiskMin: 45 } } - const saved = pageUpdate( - init().model, - Message.UpdatedSettings({ - settings: { id: settingsId, health: custom, reportingCurrency: "USD" }, - }), - ).model - const reset = pageUpdate(saved, Message.PressedResetDefaults()) - expect(reset.model.draft).toEqual(DEFAULTS) - expect(reset.commands?.[0]?.name).toBe(DelayHealthPreview.name) - }) -}) diff --git a/apps/web-foldkit/src/page/customers/settings/health/subscription.ts b/apps/web-foldkit/src/page/customers/settings/health/subscription.ts deleted file mode 100644 index fa557dea0..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/subscription.ts +++ /dev/null @@ -1,72 +0,0 @@ -import type * as Customers from "@hazel/domain/customers" -import { OrganizationId } from "@hazel/schema" -import { eq } from "@tanstack/db" -import { Option, Schema, Stream } from "effect" -import { Subscription } from "foldkit" -import { customerSettingsCollection } from "~/db/collections" -import { accountsStream, withCustomersSource } from "../../../../customers/queries" -import { liveQueryStream } from "../../../../data/live-query" -import * as Slider from "../../../../ui/slider" -import type { PageSubscriptionInput } from "../../../contract" -import { Message } from "./message" -import { type Model, type SavedSettings, SliderId } from "./model" -import { SLIDER_MESSAGE } from "./update" - -type Input = PageSubscriptionInput - -/** The org's full health settings; null until the object has seeded its settings row. */ -const settingsStream = ( - organizationId: OrganizationId, - toMessage: (settings: SavedSettings | null) => M, -): Stream.Stream => - withCustomersSource( - organizationId, - liveQueryStream( - (q) => - q - .from({ settings: customerSettingsCollection }) - .where(({ settings }) => eq(settings.organizationId, organizationId)) - .findOne(), - (rows) => { - const row = rows[0] - return toMessage( - row === undefined - ? null - : { id: row.id, health: row.health, reportingCurrency: row.reportingCurrency }, - ) - }, - ), - ) - -const organization = { organizationId: Schema.NullOr(OrganizationId) } -const organizationOf = ({ shared }: Input) => ({ organizationId: shared.organization?.id ?? null }) - -const live = Subscription.make()((entry) => ({ - settings: entry(organization, { - modelToDependencies: organizationOf, - dependenciesToStream: ({ organizationId }) => - organizationId === null - ? Stream.empty - : settingsStream(organizationId, (settings) => Message.UpdatedSettings({ settings })), - }), - accounts: entry(organization, { - modelToDependencies: organizationOf, - dependenciesToStream: ({ organizationId }) => - organizationId === null - ? Stream.empty - : accountsStream(organizationId, (accounts) => Message.UpdatedAccounts({ accounts })), - }), -})) - -/** Each Slider's drag, under its own keys (`usageDragPointer`, …). */ -export const sliderSubscriptions = Subscription.aggregate()( - ...SliderId.literals.map((id) => { - const lifted = Subscription.lift(Slider.subscriptions)({ - read: ({ model }) => Option.some(model.sliders[id]), - toParentMessage: SLIDER_MESSAGE[id], - }) - return { [`${id}DragPointer`]: lifted.dragPointer, [`${id}DragEscape`]: lifted.dragEscape } - }), -) - -export const subscriptions = Subscription.aggregate()(live, sliderSubscriptions) diff --git a/apps/web-foldkit/src/page/customers/settings/health/update.ts b/apps/web-foldkit/src/page/customers/settings/health/update.ts deleted file mode 100644 index 4fc0514c0..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/update.ts +++ /dev/null @@ -1,239 +0,0 @@ -import * as Customers from "@hazel/domain/customers" -import type { CustomerAccountId } from "@hazel/schema" -import { Equal, Option, Result } from "effect" -import { Command } from "foldkit" -import * as AsyncData from "foldkit/asyncData" -import { reasonToast, successToast } from "../../../../data/actions" -import * as Select from "../../../../ui/select" -import * as Slider from "../../../../ui/slider" -import type { PageReturn, Shared } from "../../../contract" -import { PageOutMessage } from "../../../out-message" -import { DelayHealthPreview, FetchHealthCheckDetail, FetchHealthDryRun, SaveHealthSettings } from "./commands" -import { Message } from "./message" -import { - CHECK_ACCOUNT_ID, - draftOf, - type HealthDraft, - type Model, - scaledWeights, - type SliderId, - validDraftOf, - withBand, - withBandHandle, - withScore, - withStep, - withWeight, -} from "./model" - -type Return = PageReturn - -/** Module scope, one per Slider: `toParentMessage` must keep its identity across renders. */ -export const SLIDER_MESSAGE = { - usage: (message) => Message.GotSliderMessage({ id: "usage", message }), - engagement: (message) => Message.GotSliderMessage({ id: "engagement", message }), - billing: (message) => Message.GotSliderMessage({ id: "billing", message }), - signals: (message) => Message.GotSliderMessage({ id: "signals", message }), - healthyMin: (message) => Message.GotSliderMessage({ id: "healthyMin", message }), - atRiskMin: (message) => Message.GotSliderMessage({ id: "atRiskMin", message }), -} as const satisfies { readonly [Id in SliderId]: (message: Slider.Message) => Message } - -export const toCheckAccountMessage = (message: Select.Message) => Message.GotCheckAccountMessage({ message }) - -const percentSlider = (id: SliderId) => Slider.init({ id: `health-${id}`, min: 0, max: 100, step: 1 }) - -export const init = (): Return => ({ - model: { - settings: null, - draft: null, - lastWeight: null, - accounts: null, - sliders: { - usage: percentSlider("usage"), - engagement: percentSlider("engagement"), - billing: percentSlider("billing"), - signals: percentSlider("signals"), - healthyMin: percentSlider("healthyMin"), - atRiskMin: percentSlider("atRiskMin"), - }, - preview: { version: 0, result: AsyncData.Idle() }, - previewMetric: "customers", - checkAccount: Select.init({ id: CHECK_ACCOUNT_ID }), - check: null, - isSaving: false, - typing: null, - }, -}) - -/** No draft once it matches the saved settings again (kept while saving, in case the save rolls back). */ -const settled = (model: Model): Model => - !model.isSaving && - model.draft !== null && - model.settings !== null && - Equal.equals(model.draft, model.settings.health) - ? { ...model, draft: null } - : model - -/** - * A new draft: a new preview version. A valid one is scored once it stays still for - * `PREVIEW_DELAY`; without changes the saved distribution shows, and an invalid one pauses the preview. - */ -const previewed = (model: Model): Return => { - const version = model.preview.version + 1 - if (validDraftOf(model) === null) - return { model: { ...model, preview: { version, result: AsyncData.Idle() } } } - const { result } = model.preview - return { - model: { - ...model, - preview: { version, result: Option.getOrElse(AsyncData.revalidateOrLoad(result), () => result) }, - }, - commands: [DelayHealthPreview({ version })], - } -} - -const edited = (model: Model, f: (draft: HealthDraft) => HealthDraft): Return => { - const draft = draftOf(model) - return draft === null ? { model } : previewed(settled({ ...model, draft: f(draft) })) -} - -const editedWeight = (model: Model, key: Customers.HealthComponentKey, value: number): Return => - edited({ ...model, lastWeight: key }, (draft) => withWeight(draft, key, value)) - -const withCommands = (result: Return, commands: Return["commands"]): Return => ({ - ...result, - commands: [...(commands ?? []), ...(result.commands ?? [])], -}) - -const sliderChanged = (model: Model, id: SliderId, message: Slider.Message): Return => { - const result = Slider.update(model.sliders[id], message) - const next = { ...model, sliders: { ...model.sliders, [id]: result.model } } - const commands = Command.mapMessages(result.commands ?? [], SLIDER_MESSAGE[id]) - const value = result.outMessage?.value - if (value === undefined) return { model: next, commands } - const changed = - id === "healthyMin" || id === "atRiskMin" - ? edited(next, (draft) => withBandHandle(draft, id, value)) - : editedWeight(next, id, value) - return withCommands(changed, commands) -} - -/** Picks the account whose breakdown "Check one customer" shows, and loads its saved one. */ -const checked = (model: Model, shared: Shared, accountId: CustomerAccountId): Return => { - const organizationId = shared.organization?.id - const next: Model = { - ...model, - checkAccount: { ...model.checkAccount, selectedKey: Option.some(accountId) }, - check: { accountId, saved: AsyncData.Loading() }, - } - return organizationId === undefined - ? { model: next } - : { model: next, commands: [FetchHealthCheckDetail({ organizationId, accountId })] } -} - -const checkAccountChanged = (model: Model, shared: Shared, message: Select.Message): Return => { - const result = Select.update(model.checkAccount, message) - const next = { ...model, checkAccount: result.model } - const commands = Command.mapMessages(result.commands ?? [], toCheckAccountMessage) - const accountId = model.accounts?.find((account) => account.id === result.outMessage?.key)?.id - return accountId === undefined || accountId === model.check?.accountId - ? { model: next, commands } - : withCommands(checked(next, shared, accountId), commands) -} - -/** The dry run answered: the picker defaults to the first customer it moves. */ -const dryRunSucceeded = (model: Model, shared: Shared, result: Customers.HealthDryRunResult): Return => { - const next: Model = { - ...model, - preview: { - ...model.preview, - result: AsyncData.settle(model.preview.result, Result.succeed(result)), - }, - } - const first = result.samples[0] - return model.check === null && first !== undefined - ? checked(next, shared, first.accountId) - : { model: next } -} - -const discarded = (model: Model): Return => previewed({ ...model, draft: null, lastWeight: null }) - -/** Keeps what was typed in a number field (`-`, `1.`): the draft only holds the number. */ -const typed = (model: Model, field: string, text: string): Model => ({ ...model, typing: { field, text } }) - -export const update = (model: Model, message: Message, shared: Shared): Return => - Message.match(message, { - UpdatedSettings: ({ settings }) => ({ model: settled({ ...model, settings }) }), - UpdatedAccounts: ({ accounts }) => ({ model: { ...model, accounts } }), - - ChangedWeight: ({ key, value }) => editedWeight(model, key, value), - ChangedBand: ({ band, value, text }) => - edited(typed(model, band, text), (draft) => withBand(draft, band, value)), - ChangedStep: ({ list, index, field, value, text }) => - edited(typed(model, `${list}.${index}.${field}`, text), (draft) => - withStep(draft, list, index, field, value), - ), - ChangedScore: ({ field, value, text }) => - edited(typed(model, field, text), (draft) => withScore(draft, field, value)), - GotSliderMessage: ({ id, message }) => sliderChanged(model, id, message), - PressedScaleWeights: () => - edited({ ...model, lastWeight: null }, (draft) => ({ - ...draft, - weights: scaledWeights(draft.weights), - })), - PressedResetDefaults: () => - edited({ ...model, lastWeight: null }, () => Customers.DEFAULT_HEALTH_SETTINGS), - PressedDiscard: () => discarded(model), - PressedSave: () => { - const health = validDraftOf(model) - const organizationId = shared.organization?.id - if (health === null || organizationId === undefined || model.settings === null || model.isSaving) - return { model } - return { - model: { ...model, isSaving: true }, - commands: [SaveHealthSettings({ organizationId, settingsId: model.settings.id, health })], - } - }, - PressedRetryPreview: () => previewed(model), - ClickedPreviewMetric: ({ metric }) => ({ model: { ...model, previewMetric: metric } }), - GotCheckAccountMessage: ({ message }) => checkAccountChanged(model, shared, message), - - ElapsedHealthPreviewDelay: ({ version }) => { - const draft = validDraftOf(model) - const organizationId = shared.organization?.id - return version !== model.preview.version || draft === null || organizationId === undefined - ? { model } - : { model, commands: [FetchHealthDryRun({ organizationId, draft, version })] } - }, - SucceededFetchHealthDryRun: ({ version, result }) => - version === model.preview.version ? dryRunSucceeded(model, shared, result) : { model }, - FailedFetchHealthDryRun: ({ version, reason }) => - version === model.preview.version - ? { - model: { - ...model, - preview: { - ...model.preview, - result: AsyncData.settle(model.preview.result, Result.fail(reason)), - }, - }, - } - : { model }, - SucceededFetchHealthCheckDetail: ({ accountId, health }) => - model.check?.accountId === accountId - ? { model: { ...model, check: { accountId, saved: AsyncData.Success({ data: health }) } } } - : { model }, - FailedFetchHealthCheckDetail: ({ accountId, reason }) => - model.check?.accountId === accountId - ? { model: { ...model, check: { accountId, saved: AsyncData.Failure({ error: reason }) } } } - : { model }, - SucceededSaveHealthSettings: () => ({ - ...previewed(settled({ ...model, isSaving: false })), - outMessage: PageOutMessage.RequestedToast({ - toast: successToast("Health score saved", "Customers are rescored on the next compute."), - }), - }), - FailedSaveHealthSettings: ({ reason }) => ({ - model: { ...model, isSaving: false }, - outMessage: PageOutMessage.RequestedToast({ toast: reasonToast(reason) }), - }), - }) diff --git a/apps/web-foldkit/src/page/customers/settings/health/view.ts b/apps/web-foldkit/src/page/customers/settings/health/view.ts deleted file mode 100644 index 3a12bb593..000000000 --- a/apps/web-foldkit/src/page/customers/settings/health/view.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { Submodel } from "foldkit" -import { IconArrowPath } from "../../../../icons" -import { button } from "../../../../ui/button" -import { loadingState } from "../../../../ui/loader" -import type { PageViewInputs } from "../../../contract" -import { isCustomersAdmin, readOnlyNotice, settingsPage } from "../shared" -import { pageHeader } from "../../../../ui/page-header" -import { componentCard, weightsCard } from "./components-view" -import type { Context } from "./fields" -import { Message } from "./message" -import { - COMPONENTS, - dataGapsOf, - draftOf, - invalidFieldsOf, - isDirty, - type Model, - validDraftOf, - weightTotal, -} from "./model" -import { bandsCard, checkCard, distributionCard, unsavedBar } from "./preview-view" - -/** Health score settings (Wonder: Signals & Health Settings › `mao`, `aal`). */ - -const SUBTITLE = - "How each customer’s 0–100 score is built. Recomputed every hour, and every customer page shows this same breakdown." - -export const view = Submodel.defineView((model, { shared }, h) => { - const canEdit = isCustomersAdmin(shared) - const draft = draftOf(model) - if (model.settings === null || draft === null) - return settingsPage(h, [ - pageHeader(h, { title: "Health score", subtitle: SUBTITLE }), - loadingState(h, { label: "Loading health settings", className: "py-16" }), - ]) - const context: Context = { - saved: model.settings.health, - draft, - invalid: invalidFieldsOf(draft), - total: weightTotal(draft), - isDirty: isDirty(model), - canEdit, - typing: model.typing, - } - const valid = validDraftOf(model) - const gaps = model.accounts === null ? null : dataGapsOf(model.accounts) - return settingsPage(h, [ - pageHeader(h, { - title: "Health score", - subtitle: SUBTITLE, - actions: canEdit - ? [ - button( - h, - { intent: "outline", size: "sm", onPress: Message.PressedResetDefaults() }, - [IconArrowPath(h, { attributes: { "data-slot": "icon" } }), "Reset to defaults"], - ), - ] - : [], - }), - ...(canEdit ? [] : [readOnlyNotice(h, "the health score")]), - weightsCard(h, context), - h.div( - [h.Class("grid grid-cols-1 gap-4 lg:grid-cols-2")], - COMPONENTS.map((key) => componentCard(h, model, key, context, gaps)), - ), - h.div( - [h.Class("grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)]")], - [ - bandsCard(h, model, context), - distributionCard(h, model, context, valid, model.settings.reportingCurrency), - ], - ), - checkCard(h, model, context), - ...(canEdit && context.isDirty ? [unsavedBar(h, model, context, valid)] : []), - ]) -}) diff --git a/apps/web-foldkit/src/page/customers/settings/shared.ts b/apps/web-foldkit/src/page/customers/settings/shared.ts index d4be6697b..764213739 100644 --- a/apps/web-foldkit/src/page/customers/settings/shared.ts +++ b/apps/web-foldkit/src/page/customers/settings/shared.ts @@ -4,7 +4,7 @@ import { type Crumb, pageLayout } from "../../../ui/page-header" import type { Shared } from "../../contract" /** - * What the Customers settings pages (signals, health, sources, unmatched) share: who may change + * What the Customers settings pages (signals, sources, unmatched) share: who may change * settings, and the page frame (breadcrumb, title, actions, read-only notice). */ diff --git a/apps/web-foldkit/src/page/customers/settings/signals/condition-view.ts b/apps/web-foldkit/src/page/customers/settings/signals/condition-view.ts index 3be22af5b..8f7b8c713 100644 --- a/apps/web-foldkit/src/page/customers/settings/signals/condition-view.ts +++ b/apps/web-foldkit/src/page/customers/settings/signals/condition-view.ts @@ -238,31 +238,6 @@ const sentenceRows = (h: H, context: ConditionContext): ReadonlyArray => { ), ]), ] - case "health_drop": - return [ - rows(h, [ - row( - h, - context, - "Drop", - [ - "Health fell", - num(h, context, "dropPoints", "Points"), - "points or more within", - num(h, context, "windowDays", "Window in days"), - "days", - ], - ["dropPoints", "windowDays"], - ), - row( - h, - context, - "Critical", - [flag(h, context, "onCritical", "Also when it turns Critical")], - [], - ), - ]), - ] case "champion_inactive": return [ rows(h, [ diff --git a/apps/web-foldkit/src/page/customers/settings/signals/describe.ts b/apps/web-foldkit/src/page/customers/settings/signals/describe.ts index 36d003f42..ab698333c 100644 --- a/apps/web-foldkit/src/page/customers/settings/signals/describe.ts +++ b/apps/web-foldkit/src/page/customers/settings/signals/describe.ts @@ -6,7 +6,6 @@ import { IconChartBar, IconCirclePause, IconClock, - IconHeart, IconLeave, IconLoader, IconPresentationChart, @@ -35,7 +34,6 @@ export const TEMPLATE_ICON = { cancel_scheduled: IconCirclePause, trial_ending_low_activation: IconRocket, onboarding_stalled: IconLoader, - health_drop: IconHeart, champion_inactive: IconStar, near_limit: IconChartBar, seat_growth: IconUsers, @@ -52,7 +50,6 @@ export const TEMPLATE_BLURB = { cancel_scheduled: "Set to cancel at period end, or moved to a cheaper plan", trial_ending_low_activation: "Trial ends soon and only a few people are using the product", onboarding_stalled: "A new account where hardly anyone has become active yet", - health_drop: "Health score fell sharply, or entered Critical", champion_inactive: "The account's most active person stops showing up", near_limit: "A metered feature is close to the plan's limit", seat_growth: "Active users growing fast: a good moment to talk expansion", @@ -142,14 +139,6 @@ export const conditionParts = ( bold(counted(config.minActiveContacts, "contact")), " ever active", ] - case "health_drop": - return [ - "Health fell ", - bold(`${v("dropPoints")} points`), - " or more in ", - bold(counted(config.windowDays, "day")), - ...(isOn(config.onCritical) ? [", or turned ", bold("Critical")] : []), - ] case "champion_inactive": return [ "The most active user of the last ", diff --git a/apps/web-foldkit/src/page/customers/settings/signals/draft.ts b/apps/web-foldkit/src/page/customers/settings/signals/draft.ts index 815522571..c677ad9de 100644 --- a/apps/web-foldkit/src/page/customers/settings/signals/draft.ts +++ b/apps/web-foldkit/src/page/customers/settings/signals/draft.ts @@ -28,7 +28,6 @@ const CONFIG_FIELDS = { cancel_scheduled: Customers.CancelScheduledConfig.fields, trial_ending_low_activation: Customers.TrialEndingLowActivationConfig.fields, onboarding_stalled: Customers.OnboardingStalledConfig.fields, - health_drop: Customers.HealthDropConfig.fields, champion_inactive: Customers.ChampionInactiveConfig.fields, near_limit: Customers.NearLimitConfig.fields, seat_growth: Customers.SeatGrowthConfig.fields, @@ -61,7 +60,6 @@ const FIELD_KIND = new Map([ ["minAgeDays", "ageDays"], ["maxAgeDays", "ageDays"], ["minActiveContacts", "count"], - ["dropPoints", "count"], ["windowDays", "days"], ["thresholdPct", "pct"], ["growthPct", "pct"], diff --git a/apps/web-foldkit/src/page/customers/settings/signals/story.test.ts b/apps/web-foldkit/src/page/customers/settings/signals/story.test.ts index 66614a104..143798cd3 100644 --- a/apps/web-foldkit/src/page/customers/settings/signals/story.test.ts +++ b/apps/web-foldkit/src/page/customers/settings/signals/story.test.ts @@ -76,7 +76,7 @@ const ruleRoute = AppRoute.CustomersSettingsSignalRule({ orgSlug: "hazel", ruleI const newRoute = (template: RuleRow["template"]) => AppRoute.CustomersSettingsSignalNew({ orgSlug: "hazel", template: Option.some(template) }) as SignalsRoute -const settings = { lastComputedAtMs: null, bands: { healthyMin: 70, atRiskMin: 40 } } +const settings = { lastComputedAtMs: null } const usd = Message.UpdatedSettings({ settings: { ...settings, reportingCurrency: "USD" } }) const yen = Message.UpdatedSettings({ settings: { ...settings, reportingCurrency: "JPY" } }) @@ -492,11 +492,11 @@ describe("signals: the list", () => { test("Set up opens the editor for the picked template", () => { const picking = edits(withRules(listRoute), [ Message.PressedNewSignal(), - Message.ClickedTemplate({ template: "health_drop" }), + Message.ClickedTemplate({ template: "seat_growth" }), ]) expect(picking.pickerModal.isOpen).toBe(true) expect(pageUpdate(picking, Message.PressedSetUpTemplate()).outMessage).toEqual( - PageOutMessage.RequestedNavigation({ route: newRoute("health_drop"), replace: false }), + PageOutMessage.RequestedNavigation({ route: newRoute("seat_growth"), replace: false }), ) }) diff --git a/apps/web-foldkit/src/page/customers/settings/unmatched/story.test.ts b/apps/web-foldkit/src/page/customers/settings/unmatched/story.test.ts index 778cc846f..1fae1d15b 100644 --- a/apps/web-foldkit/src/page/customers/settings/unmatched/story.test.ts +++ b/apps/web-foldkit/src/page/customers/settings/unmatched/story.test.ts @@ -86,8 +86,6 @@ const account = (n: number, name: string, domain: string): AccountRow => ({ currency: "USD", trialListMrrMinor: null, trialEndsAtMs: null, - healthScore: null, - healthStatus: "unknown", seatsUsed: null, seatsLimit: null, contactCount: 0, diff --git a/apps/web-foldkit/src/page/customers/support/support.gallery.ts b/apps/web-foldkit/src/page/customers/support/support.gallery.ts index 0c826e263..3b0c36f22 100644 --- a/apps/web-foldkit/src/page/customers/support/support.gallery.ts +++ b/apps/web-foldkit/src/page/customers/support/support.gallery.ts @@ -98,7 +98,6 @@ const overviewModel = (): OverviewModel => ({ connectedProviders: CONNECTIONS.map((connection) => connection.provider), settings: { lastComputedAtMs: SETTINGS.lastComputedAt === null ? null : msOf(SETTINGS.lastComputedAt), - bands: SETTINGS.health.bands, reportingCurrency: SETTINGS.reportingCurrency, }, }) diff --git a/apps/web-foldkit/src/page/oauth-authorize/view.ts b/apps/web-foldkit/src/page/oauth-authorize/view.ts index 39fbb81f8..89b84382c 100644 --- a/apps/web-foldkit/src/page/oauth-authorize/view.ts +++ b/apps/web-foldkit/src/page/oauth-authorize/view.ts @@ -23,7 +23,7 @@ const SCOPE_ABILITIES = { "Set your status", ], "customers:read": [ - "See your organizations' customers: health, revenue, billing and signals", + "See your organizations' customers: revenue, billing and signals", "See which channels each customer is linked to", ], } satisfies Readonly>> diff --git a/apps/web-foldkit/src/route.test.ts b/apps/web-foldkit/src/route.test.ts index 10c60d7da..e053014b8 100644 --- a/apps/web-foldkit/src/route.test.ts +++ b/apps/web-foldkit/src/route.test.ts @@ -163,13 +163,12 @@ describe("customers routes", () => { ["/hazel/customers/inbox", "CustomersInbox"], ["/hazel/customers/support", "CustomersSupportReport"], ["/hazel/customers/list", "CustomersList"], - ["/hazel/customers/list?view=at_risk", "CustomersList"], + ["/hazel/customers/list?view=paying", "CustomersList"], [`/hazel/customers/${accountId}`, "CustomerDetail"], [`/hazel/customers/${accountId}?tab=billing`, "CustomerDetail"], ["/hazel/customers/settings/signals", "CustomersSettingsSignals"], ["/hazel/customers/settings/signals/new", "CustomersSettingsSignalNew"], [`/hazel/customers/settings/signals/${ruleId}`, "CustomersSettingsSignalRule"], - ["/hazel/customers/settings/health", "CustomersSettingsHealth"], ["/hazel/customers/settings/plans", "CustomersSettingsPlans"], ["/hazel/customers/settings/sla", "CustomersSettingsSla"], ["/hazel/customers/settings/feature-flags", "CustomersSettingsFeatureFlags"], @@ -484,8 +483,8 @@ describe("hrefOf", () => { CustomersList: [ [AppRoute.CustomersList({ orgSlug, view: none }), "/hazel/customers/list"], [ - AppRoute.CustomersList({ orgSlug, view: Option.some("at_risk") }), - "/hazel/customers/list?view=at_risk", + AppRoute.CustomersList({ orgSlug, view: Option.some("paying") }), + "/hazel/customers/list?view=paying", ], ], CustomerDetail: [ @@ -517,9 +516,6 @@ describe("hrefOf", () => { `/hazel/customers/settings/signals/${ruleId}`, ], ], - CustomersSettingsHealth: [ - [AppRoute.CustomersSettingsHealth({ orgSlug }), "/hazel/customers/settings/health"], - ], CustomersSettingsPlans: [ [AppRoute.CustomersSettingsPlans({ orgSlug }), "/hazel/customers/settings/plans"], ], diff --git a/apps/web-foldkit/src/route.ts b/apps/web-foldkit/src/route.ts index a404b3917..a5f3ec974 100644 --- a/apps/web-foldkit/src/route.ts +++ b/apps/web-foldkit/src/route.ts @@ -107,7 +107,7 @@ export const AppRoute = defineRouteUnion({ connectionStatus: Schema.Option(Schema.String), errorCode: Schema.Option(Schema.String), }, - /** `/$orgSlug/customers`: revenue, usage and health across the org's customers. */ + /** `/$orgSlug/customers`: revenue and usage across the org's customers. */ CustomersOverview: { orgSlug: Schema.String }, /** The ranked signal queue. */ CustomersAttention: { orgSlug: Schema.String }, @@ -115,7 +115,7 @@ export const AppRoute = defineRouteUnion({ CustomersInbox: { orgSlug: Schema.String }, /** Response times, % within SLA and breaches over a range (`docs/customers/sla.md`). */ CustomersSupportReport: { orgSlug: Schema.String }, - /** `?view=`: a saved view's id, or a built-in view's key (`BuiltInViewKey`, e.g. `at_risk`). */ + /** `?view=`: a saved view's id, or a built-in view's key (`BuiltInViewKey`, e.g. `paying`). */ CustomersList: { orgSlug: Schema.String, view: Schema.Option(Schema.String) }, /** One customer; `?tab=` picks the tab (none: overview). */ CustomerDetail: { @@ -127,7 +127,6 @@ export const AppRoute = defineRouteUnion({ /** The rule editor for a new rule; `?template=` preselects the template picked in the modal. */ CustomersSettingsSignalNew: { orgSlug: Schema.String, template: Schema.Option(SignalTemplate) }, CustomersSettingsSignalRule: { orgSlug: Schema.String, ruleId: CustomerSignalRuleId }, - CustomersSettingsHealth: { orgSlug: Schema.String }, CustomersSettingsPlans: { orgSlug: Schema.String }, CustomersSettingsSla: { orgSlug: Schema.String }, CustomersSettingsFeatureFlags: { orgSlug: Schema.String }, @@ -372,10 +371,6 @@ const routers = { slash(schemaSegment("ruleId", CustomerSignalRuleId)), Route.mapTo(AppRoute.CustomersSettingsSignalRule), ), - CustomersSettingsHealth: pipe( - orgPath("customers", "settings", "health"), - Route.mapTo(AppRoute.CustomersSettingsHealth), - ), CustomersSettingsPlans: pipe( orgPath("customers", "settings", "plans"), Route.mapTo(AppRoute.CustomersSettingsPlans), @@ -465,7 +460,6 @@ export const urlToAppRoute = Route.parseUrlWithFallback( routers.CustomersSettingsSignals, routers.CustomersSettingsSignalNew, routers.CustomersSettingsSignalRule, - routers.CustomersSettingsHealth, routers.CustomersSettingsPlans, routers.CustomersSettingsSla, routers.CustomersSettingsFeatureFlags, @@ -560,7 +554,6 @@ export const isCustomersRoute = AppRoute.isAnyOf([ "CustomersSettingsSignals", "CustomersSettingsSignalNew", "CustomersSettingsSignalRule", - "CustomersSettingsHealth", "CustomersSettingsPlans", "CustomersSettingsSla", "CustomersSettingsFeatureFlags", diff --git a/apps/web-foldkit/src/shell/customers-sidebar.ts b/apps/web-foldkit/src/shell/customers-sidebar.ts index a244301c5..5bb3014ba 100644 --- a/apps/web-foldkit/src/shell/customers-sidebar.ts +++ b/apps/web-foldkit/src/shell/customers-sidebar.ts @@ -119,7 +119,6 @@ const BUILT_IN_VIEWS: ReadonlyArray<{ readonly key: Customers.BuiltInViewKey; re { key: "my_customers", name: "My customers" }, { key: "paying", name: "Paying" }, { key: "trialing", name: "Trialing" }, - { key: "at_risk", name: "At risk" }, { key: "churned", name: "Churned" }, ] @@ -472,7 +471,6 @@ export const view = ( "CustomersSettingsSignalRule", ), ), - item("customersHealth", on("CustomersSettingsHealth")), item("customersSla", on("CustomersSettingsSla")), item("customersPlans", on("CustomersSettingsPlans")), item("customersFeatureFlags", on("CustomersSettingsFeatureFlags")), diff --git a/apps/web-foldkit/src/shell/destinations.ts b/apps/web-foldkit/src/shell/destinations.ts index 5bac7ae12..6d0caf849 100644 --- a/apps/web-foldkit/src/shell/destinations.ts +++ b/apps/web-foldkit/src/shell/destinations.ts @@ -12,7 +12,6 @@ import { IconGear, IconGridCirclePlus, IconHashtag, - IconHeart, IconIntegratio, IconKeyboard, IconLightbulb, @@ -146,11 +145,6 @@ const DESTINATIONS = define({ to: (orgSlug) => AppRoute.CustomersSettingsSignals({ orgSlug }), keywords: "rules", }, - customersHealth: { - label: "Health score", - icon: IconHeart, - to: (orgSlug) => AppRoute.CustomersSettingsHealth({ orgSlug }), - }, customersSla: { label: "Support SLAs", icon: IconClock, @@ -311,7 +305,6 @@ export const DESTINATION_GROUPS: ReadonlyArray<{ "customersSupportReport", "customersList", "customersSignals", - "customersHealth", "customersSla", "customersPlans", "customersFeatureFlags", diff --git a/docs/customers/autumn.md b/docs/customers/autumn.md index 5e552cbfd..2e96b2379 100644 --- a/docs/customers/autumn.md +++ b/docs/customers/autumn.md @@ -95,8 +95,8 @@ cannot see. **Metric keys are namespaced** `autumn.`. Ingest refuses a metric key another provider already owns (`otherOwner`), so the prefix is what keeps an Autumn feature called `events` from -colliding with a Maple event metric of the same name. The built-in keys (`active_users`, `mrr`, -`health_score`) are Hazel's and are refused outright. +colliding with a Maple event metric of the same name. The built-in keys (`active_users`, `mrr`) +are Hazel's and are refused outright. **Statuses.** Autumn reports a plan as `active` (with `past_due` beside it), `scheduled`, or `expired`, and clears `trial_ends_at` when a trial converts. So: diff --git a/docs/customers/channels.md b/docs/customers/channels.md index c16f95f51..a9be09d5a 100644 --- a/docs/customers/channels.md +++ b/docs/customers/channels.md @@ -44,8 +44,8 @@ all of them. dropped); the receiver writes only what changed. Its sender guard accepts only the org's own customers object. 4. The snapshot is sent only when its SHA-256 fingerprint (over every field) changed: after link / unlink, after a person changes an account's name or owner (one or in bulk) or a signal's status - (assign, snooze, done, dismiss, reopen), and at the end of every compute (names, numbers, - health and signals set by sources and rules; accounts a source deleted). + (assign, snooze, done, dismiss, reopen), and at the end of every compute (names, numbers and + signals set by sources and rules; accounts a source deleted). 5. Org deletion purges `customer_channel_links` with the rest of the customer data. Deleting a channel that has a customer: the `OrgObject` sends `customers.channelDeleted` (from @@ -63,8 +63,6 @@ next one, whose fingerprint differs, fills them). | Field | From | | ------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `healthStatus`, `healthScore` | The customer (the group's primary). | -| `healthWhy` | The scored component with the lowest score in its latest `customer_health_daily` (7 d). | | `ownerUserId` | The customer. | | `lifecycleStage`, `planName` | The group's rules (`group-facts.ts`): the most advanced stage; the primary's plan, else an environment's. | | `mrrMinor`, `currency` | Σ over the group (compute keeps MRR in the reporting currency). | @@ -80,12 +78,11 @@ A row projected before the glance (an org with no snapshot since the deploy: the the hour, sends one) has no stage; the card then shows only the name and the way to the customer page, not blanks that read as an empty account. -UI (`src/page/chat/customer-card.ts`): the header chip shows the health dot and the name. On +UI (`src/page/chat/customer-card.ts`): the header chip shows an office mark and the name. On desktop, hovering it shows the card after 350 ms; it stays while the pointer is on the chip or the card (200 ms grace), and a click pins it until Escape or a click outside. On a phone a tap opens -the same card in a bottom sheet. The card: logo, name (to the customer page), health badge and -stage, the health reason (or "No health score yet"), revenue and plan, owner, seats, last active, -open signals (count, top 3, "N more", the queue), then the customer page and provider links. The +the same card in a bottom sheet. The card: logo, name (to the customer page), stage, revenue and +plan, owner, seats, last active, open signals (count, top 3, "N more", the queue), then the customer page and provider links. The card takes a `support` slot between the signals and the links for support issues and SLAs (later sessions). Gallery: `customer-card.gallery.ts`. diff --git a/docs/customers/clerk.md b/docs/customers/clerk.md index fbbb9c39e..0d2d8e313 100644 --- a/docs/customers/clerk.md +++ b/docs/customers/clerk.md @@ -1,9 +1,8 @@ # Clerk data source Hazel's identity source for Customers: a Clerk **organization** is a customer account, its -**members** are that account's contacts, and **sign-ins** are the activity every usage signal and -health score reads. Adapter: `packages/customer-integrations/src/clerk/`, registered in -its `registry.ts`. It produces `IngestOp`s only — `CustomerIngest` does every write +**members** are that account's contacts, and **sign-ins** are the activity every usage signal +reads. Adapter: `packages/customer-integrations/src/clerk/`, registered in its `registry.ts`. It produces `IngestOp`s only — `CustomerIngest` does every write (`tech-design.md` §3). The Clerk organization id is the account's primary external ref, which is what lets the other @@ -101,7 +100,7 @@ moves the contacts' `lastSignInAt` / `lastSeenAt` and credits the `last_active_a **every** account the user is a member of, with `signedIn` when it is also the `last_sign_in_at` day. A user in several organizations therefore over-credits recency to the ones they were not active in; without it a Clerk-only account would have no activity day at all, read as never -active, score near critical on health and raise `onboarding_stalled` / `inactive` / +active, and raise `onboarding_stalled` / `inactive` / `champion_inactive` for customers using the product. The activity op follows its contact op, since ingest parks activity for a contact it does not know. A `last_active_at` day already past core's 400-day activity retention when the user was observed is not written (the next prune would delete diff --git a/docs/customers/maple.md b/docs/customers/maple.md index 058b05025..883f6e260 100644 --- a/docs/customers/maple.md +++ b/docs/customers/maple.md @@ -3,8 +3,7 @@ Maple is Hazel's **usage source**: the product events Maple records about an app's own users become the daily activity behind active users, usage trends, `lastActiveAt`, the champion, and the `inactive`, `usage_drop`, `onboarding_stalled` and `champion_inactive` signals. On top of that, any -event a person maps to a metric becomes a per-account daily count a chart, a signal or the health -score can read. +event a person maps to a metric becomes a per-account daily count a chart or a signal can read. It is a **custom integration**, not a product one. Maple is the product owner's own observability product, and what makes this work is that Maple stamps its product events with _Hazel's_ identity: diff --git a/docs/customers/spec.md b/docs/customers/spec.md index 45670252a..ad4002f8b 100644 --- a/docs/customers/spec.md +++ b/docs/customers/spec.md @@ -4,8 +4,8 @@ Scope: analytics, action queue and per-customer pages. Channels linked to a cust ## Principles -- **Integrations write, the product reads.** Clerk, Stripe, Autumn and Maple each write into one neutral data model through syncs (cron) or webhooks. UI, signals and health only read that model, never a provider API. -- **Explainable over magic.** Health score and signals are rule-based and show their inputs ("No sign-ins for 18 days, was 12 weekly active users"). +- **Integrations write, the product reads.** Clerk, Stripe, Autumn and Maple each write into one neutral data model through syncs (cron) or webhooks. UI and signals only read that model, never a provider API. +- **Explainable over magic.** Signals are rule-based and show their inputs ("No sign-ins for 18 days, was 12 weekly active users"). - **Silent accounts count.** Signals evaluate every account, including ones with no recent activity, which are often the ones about to churn. - **A ranked queue, not a dashboard.** "Needs attention" is a worklist with assign, snooze, done and dismiss. - **Customer = company.** An account is a B2B customer (Clerk organization). Contacts are its end users (Clerk users). @@ -22,7 +22,6 @@ All tables: `id uuid` (branded ID), `organizationId`, `createdAt`, `updatedAt`; - `ownerUserId` → Hazel user (the CSM), nullable - `lifecycleStage`: `lead | trialing | active | past_due | churned` (derived from subscriptions, overridable) - `planName`, `mrrMinor`, `currency` (denormalized from active subscriptions) -- `healthScore` 0–100, `healthStatus`: `healthy | at_risk | critical | unknown`, `healthUpdatedAt` - `seatsUsed`, `seatsLimit` (nullable) - `firstSeenAt`, `lastActiveAt` (max contact activity), `customerSince` (first paid) - `tags text[]`, `attributes jsonb` (free-form fields from sources) @@ -67,7 +66,7 @@ All tables: `id uuid` (branded ID), `organizationId`, `createdAt`, `updatedAt`; **`customer_metric_definitions`** - `key` (e.g. `events`, `api_requests`, `seats`, `dashboards_created`), `name`, `unit`, `aggregation`: `sum | max | last`, `provider`, `description` -- Built-in keys computed by Hazel, not sources: `active_users`, `mrr`, `health_score` +- Built-in keys computed by Hazel, not sources: `active_users`, `mrr` **`customer_metric_daily`**: per-account daily time series for any metric @@ -100,7 +99,6 @@ Built-in templates (seeded per org, editable): | `cancel_scheduled` | `cancelAtPeriodEnd` set, or plan downgraded | risk | | `trial_ending_low_activation` | Trial ends in ≤5 days and < 2 active users in last 7 days | risk | | `onboarding_stalled` | Account created 7–30 days ago, < 2 contacts ever active | risk | -| `health_drop` | Health score fell ≥20 points in 7 days, or entered `critical` | risk | | `champion_inactive` | Most active contact of last 30 days inactive 14 days | risk | | `near_limit` | A metered feature ≥ 90% of plan limit (Autumn) | opportunity | | `seat_growth` | Active users up ≥50% in 30 days | opportunity | @@ -121,18 +119,6 @@ the lifecycle stages (default all but churned) and the sources a customer must h - Unique open signal per `(ruleId, accountId)`. If the condition clears → `auto_resolved`. A dismissed signal re-opens only if evidence worsens by a full step. - **Priority** (queue order) = severity weight × log(MRR+1) weight × freshness. Shown as a rank, sortable by other fields. -### Health - -**`customer_health_settings`**: one row per org - -- `components jsonb`: weighted parts summing to 100% - - `usage`: active users / contacts ratio and 30-day trend - - `engagement`: days since last activity - - `billing`: payment status, overdue invoices - - `signals`: open risk signals by severity -- `bands`: healthy ≥ 70, at risk 40–69, critical < 40 (editable) -- A component with no data drops out and its weight is shared across the rest (Vitally pattern), so a Clerk-only org still gets a score. - ### Notes **`customer_notes`**: `accountId`, `authorUserId`, `body` (markdown), `pinned`, soft delete. @@ -146,14 +132,14 @@ the lifecycle stages (default all but churned) and the sources a customer must h ### Compute pipeline (cluster) - Webhook or cron sync → `CustomerIngest` service upserts (accounts, contacts, refs, subs, invoices, activity, metrics, events). Idempotent on `(provider, externalId)`. -- Hourly per org (`ClusterCron`): denormalize account fields (MRR, stage, lastActiveAt) → write today's built-in metrics → compute health → evaluate rules → open/update/auto-resolve signals → wake snoozed signals. +- Hourly per org (`ClusterCron`): denormalize account fields (MRR, stage, lastActiveAt) → write today's built-in metrics → evaluate rules → open/update/auto-resolve signals → wake snoozed signals. - Reads: - Live lists (accounts, signals, notes) via Electric + TanStack DB. - Aggregates and time series (overview charts, usage charts) via RPC. ### PR plan -1. **Core**: schema, domain models, RPC, ingest service, rollup/health/signal cron, all UI surfaces, data-source settings shell, dev seed script with realistic fake data. No live providers. +1. **Core**: schema, domain models, RPC, ingest service, rollup/signal cron, all UI surfaces, data-source settings shell, dev seed script with realistic fake data. No live providers. 2. **Clerk**: orgs → accounts, users → contacts, memberships, sessions → sign-ins/activity. Webhooks + backfill. 3. **Stripe**: customers → refs, subscriptions, invoices, events. Webhooks + backfill. 4. **Autumn**: customers, products → subscriptions, feature usage + limits → metrics (`near_limit`). Webhooks + backfill. @@ -165,10 +151,10 @@ New top-level **Customers** item in the icon dock (`nav-sidebar.tsx`), with its - Overview - Needs attention (count badge) -- Customers, plus saved views (My customers, Paying, Trialing, At risk, Churned) -- Settings: Signals, Health score, Data sources +- Customers, plus saved views (My customers, Paying, Trialing, Churned) +- Settings: Signals, Data sources -Routes: `/$orgSlug/customers` (overview), `/customers/attention`, `/customers/list`, `/customers/$accountId`, `/customers/settings/{signals,health,sources}`. +Routes: `/$orgSlug/customers` (overview), `/customers/attention`, `/customers/list`, `/customers/$accountId`, `/customers/settings/{signals,sources}`. ### 1. Overview @@ -176,7 +162,6 @@ Routes: `/$orgSlug/customers` (overview), `/customers/attention`, `/customers/li - KPI row: MRR (+Δ), paying customers, active customers (≥1 active user in 30d), WAU / MAU with stickiness (WAU÷MAU), logo churn (period), at-risk MRR (sum MRR of accounts with open high-severity risk signals). - MRR movement chart: new, expansion, contraction, churned (stacked bars) + net line. - Active users chart: DAU / WAU / MAU lines. -- Health distribution (healthy / at risk / critical counts and MRR). - Needs-attention preview: top 5 queue items, link to the queue. - Top movers: biggest usage gains and drops (account, Δ%, sparkline). - Recent churn and new customers lists. @@ -185,7 +170,7 @@ Routes: `/$orgSlug/customers` (overview), `/customers/attention`, `/customers/li ### 2. Needs attention (queue) - Tabs: Open · Snoozed · Done. Filters: kind (risk / opportunity), signal type, severity, owner (default "Mine or unowned", so a new account shows to everyone), plan. -- Rows: rank, account (logo, name, plan, MRR), signal title + plain reason, evidence mini-viz (sparkline or invoice amount), severity, age, assignee, health badge. +- Rows: rank, account (logo, name, plan, MRR), signal title + plain reason, evidence mini-viz (sparkline or invoice amount), severity, age, assignee. - Grouping toggle: one row per signal, or one row per account with its stacked signals. - Row actions: assign, snooze (tomorrow / 3 days / next week / date), mark done (outcome + note), dismiss (not useful), open customer. - Keyboard: k down / j up, a assign, i assign to me, h snooze (Linear's keys), d done, enter open. An account's signals sit together in the queue, joined by a line. @@ -194,15 +179,15 @@ Routes: `/$orgSlug/customers` (overview), `/customers/attention`, `/customers/li ### 3. Customers list -- Table: name + logo, owner, stage, plan, MRR, health (badge + score), active users 30d + sparkline, usage trend %, last active, open signals, customer since. +- Table: name + logo, owner, stage, plan, MRR, active users 30d + sparkline, usage trend %, last active, open signals, customer since. - Saved views (tabs), search, filter builder, sort, column picker, bulk assign owner / add tag. -- Health and stage colors consistent with other surfaces. +- Stage colors consistent with other surfaces. ### 4. Customer page -- Header: logo, name, domain, stage, plan, MRR, health badge, owner (editable), customer since, source chips linking out to Clerk / Stripe / Autumn / Maple. +- Header: logo, name, domain, stage, plan, MRR, owner (editable), customer since, source chips linking out to Clerk / Stripe / Autumn / Maple. - Tabs: - - **Overview**: KPI tiles (active users 30d, usage trend, MRR, seats used/limit, last active); usage chart with metric picker; health breakdown (each component, its score, weight, why); open signals with actions; subscription summary; pinned notes; recent activity. + - **Overview**: KPI tiles (active users 30d, usage trend, MRR, seats used/limit, last active); usage chart with metric picker; open signals with actions; subscription summary; pinned notes; recent activity. - **Users**: contacts table (name, email, role, last seen, sign-ins 30d, activity sparkline, status: active / dormant / never active). - **Billing**: current subscriptions, invoice table (status, amount, due, paid), payment issue banner. - **Activity**: timeline, filter by source and type. @@ -212,12 +197,11 @@ Routes: `/$orgSlug/customers` (overview), `/customers/attention`, `/customers/li ### 5. Settings - **Signals**: list of rules (enabled toggle, template, kind, severity, plain description, number of accounts matching now). Rule editor: template, thresholds, scope filter, severity, live preview of matching accounts. -- **Health score**: component weights (sliders summing to 100%), band thresholds, distribution preview. - **Data sources**: cards for Clerk, Stripe, Autumn, Maple: status, last sync, records synced, errors, sync now, connect (API key flow), webhook URL to copy. Unmatched records count with a link to resolve. ## Additions from design pass (proposed, pending approval) -Wonder file "Maple Design System", pages `Hazel Customers · *` (Foundations, Overview, Needs Attention, List, Customer Page, Signals & Health Settings, Data Sources). +Wonder file "Maple Design System", pages `Hazel Customers · *` (Foundations, Overview, Needs Attention, List, Customer Page, Signals Settings, Data Sources). ### Data model additions @@ -233,10 +217,6 @@ Wonder file "Maple Design System", pages `Hazel Customers · *` (Foundations, Ov - `connectionId`, `provider`, `entityType`, `externalId`, `label`, `valueMinor` / `eventCount30d` - `suggestedAccountId`, `confidence`, `reason`, `status` (`open | linked | ignored`) - Plus `customer_ignore_rules` (pattern) -- **New `customer_health_daily`** - - `accountId`, `day`, `score`, `status` - - `components jsonb`: per component `score`, `effectiveWeight`, `why`, `excluded` - - Powers the breakdown, "62 → 48" changes and band-change counts. - **New `customer_mrr_movements`** - `accountId`, `day`, `type` (`new | expansion | contraction | churn | reactivation`), `deltaMinor` - Powers the MRR movement chart, its tooltip and NRR/GRR. @@ -251,16 +231,14 @@ Wonder file "Maple Design System", pages `Hazel Customers · *` (Foundations, Ov - `snoozedByUserId`, `snoozedAt`, `snoozeNote`, `snoozeEvidence` - `dismissReason` - **Signal rules**: `updatedBy`, `lastTriggeredAt`, `matchingCount`. Template metadata: required sources and friendly names. -- **Health settings**: scoring steps per input, signal deductions per severity, excluded rules (`health_drop`), `updatedBy`. - **Notes**: `editedAt`, optional `signalId`. - **New `customer_saved_views`**: `name`, `filters jsonb`, `sort`, `columns`, `ownerUserId` (null = shared), `position`. - **Integration connections** - Status fields: `lastSuccessAt`, `lastErrorAt`, `consecutiveFailures` - Provider `config jsonb`: Maple activity events, metric mappings, identity keys, lookback; Stripe metadata key, domain match toggle - **Sync runs**: `progress {step, done, total}`, structured `error {code, httpStatus}`. -- **Events**: `actorUserId`, plus types `health.status_changed`, `contact.first_active`, `signal.assigned`. +- **Events**: `actorUserId`, plus types `contact.first_active`, `signal.assigned`. ### Endpoints implied - Dry-run a draft rule: match count, MRR, top accounts with evidence, why others don't match, queue delta. -- Dry-run health settings: distribution, how many accounts change band, sample breakdown. diff --git a/docs/customers/stripe.md b/docs/customers/stripe.md index 413a0a895..4dbf54ad6 100644 --- a/docs/customers/stripe.md +++ b/docs/customers/stripe.md @@ -3,7 +3,7 @@ Hazel's billing source for Customers: a Stripe **customer** lands on the account an identity source already created, and its **subscriptions** and **invoices** become the MRR, the plan, the trial and the payment state that the billing signals (`payment_failed`, `cancel_scheduled`, -`trial_ending_low_activation`) and the health score's billing component read. Adapter: +`trial_ending_low_activation`) read. Adapter: `packages/customer-integrations/src/stripe/`, registered in its `registry.ts`. It produces `IngestOp`s only — `CustomerIngest` does every write (`tech-design.md` §3). @@ -183,7 +183,7 @@ currency like JPY is right by construction. - Items are summed, then the subscription's coupons are applied: a `percent_off` always, an `amount_off` only in the subscription's own currency, spread over the primary item's cadence (1 200.00 off a yearly subscription is 100.00 a month). The sum before discounts stays as - `listMrrMinor`, which is what a trial is ranked by (`trialListMrrMinor`, `tech-design.md` §4.6). + `listMrrMinor`, which is what a trial is ranked by (`trialListMrrMinor`, `tech-design.md` §4.5). Discounts are expanded wherever a subscription is read (`expand[]=discounts`), webhooks included, so their coupons always apply. - The amount is rounded once, at the end, and never goes below zero. diff --git a/docs/customers/tech-design.md b/docs/customers/tech-design.md index 4065089d8..71997ea7f 100644 --- a/docs/customers/tech-design.md +++ b/docs/customers/tech-design.md @@ -63,7 +63,7 @@ its own store `customers`. Why not the `OrgObject`: -- **Change-log churn.** Hourly compute rewrites health/priority fields on thousands of accounts and +- **Change-log churn.** Hourly compute rewrites rollup/priority fields on thousands of accounts and signals. In the org store every change goes through the `_changes` log every chat socket flushes (and the 50k/7d retention): customers compute would push chat clients into resets. - **Snapshot weight.** Every org member's org socket would snapshot all accounts and signals on @@ -131,34 +131,33 @@ convention: SQLite text, read as `Date`); a `day` is `YYYY-MM-DD` UTC text; JSON `jsonb()` with ISO strings inside (`IsoTimestamp`); synced tables carry `organizationId` (client filter), internal ones don't. Partial unique indexes in `tables/extra-indexes.ts`. -| Table | Purpose / key points | Transport | -| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `customer_accounts` | Customer company. `domains[]`, owner, `lifecycleStage` (+ `lifecycleStageOverride`), plan, `mrrMinor`, `trialListMrrMinor`, `trialEndsAt`, health (score/status/updatedAt), seats, `contactCount`, `activeUsers30d`, `activeUsersTrendPct`, `openRiskHigh/Medium/Low`, `openOpportunities`, champion/last-active contact, `firstSeenAt`, `lastActiveAt`, `customerSince`, `churnedAt`, `tags[]`, `attributes`, `fieldSources` | **synced** | -| `customer_contacts` | End users. Spec fields + `joinedAt`, `firstActiveAt`, `eventCount30d`, `isBillingContact`, `fieldSources` | RPC (per account, paged) | -| `customer_external_refs` | Provider record ↔ account/contact. `accountId` on every ref; `matchMethod`, `matchedByUserId`, `matchedAt`, `lastSyncedAt`, `staleAt`. Unique `(provider, externalId)` for accounts, `(provider, externalId, accountId)` for contacts. Several refs per provider per account allowed | RPC (in `account.detail`) | -| `customer_subscriptions` | Spec + `listMrrMinor`, `cancellationReason`, `paymentMethod{brand,last4,exp}`, `observedAt`. Unique `(provider, externalId)` | RPC | -| `customer_invoices` | Spec + `upcoming` status (`externalId = upcoming:`), `nextRetryAt`, `declineReason`, `observedAt` | RPC | -| `customer_activity_daily` | PK `(contactId, day)`; each provider writes only its fields | internal | -| `customer_metric_definitions` | Unique `key`; built-ins `active_users`, `active_users_30d`, `mrr`, `health_score` | **synced** (metric picker) | -| `customer_metric_daily` | PK `(accountId, metricKey, day)`, `value`, `limitValue` (metered plan limit) | RPC | -| `customer_org_daily` | PK `day`: MRR, paying/trialing/active accounts, DAU/WAU/MAU, health counts, at-risk MRR — the overview's source | RPC | -| `customer_events` | Timeline; unique `(provider, externalId)` when set; `actorUserId` | RPC (paged) | -| `customer_mrr_movements` | One per account per day max; `type`, `deltaMinor`, from/to | RPC | -| `customer_signal_rules` | Spec + `updatedBy`, `lastTriggeredAt`, `matchingCount`; `config` = `RuleConfig` (tagged by template) | **synced** | -| `customer_signals` | Queue items. Spec + `template`, `openingEvidence`, `actionEvidence`, `priorityScore`, `openedAt`, snooze fields, `dismissReason`, `reopenCount` , `closedAt`. One unclosed episode per `(ruleId, accountId)` | **synced** (unclosed + closed ≤ 30 d); older via `customers.signals.history` | -| `customer_settings` | One row: `health` (`HealthSettings`), `reportingCurrency`, `addOnPlans`, `overageInMrr`, `lastComputedAt`, `updatedBy` (spec's `customer_health_settings`) | **synced** | -| `customer_health_daily` | PK `(accountId, day)`: score, status, `breakdown` (`HealthBreakdown`) | RPC | -| `customer_notes` | Spec + `editedAt`, `signalId` | **synced** | -| `customer_saved_views` | `ownerUserId` null = shared, `builtInKey`, `filters`/`sort`/`columns`, `position` | **synced** (shared + own) | -| `customer_connections` | One per provider (reconnect reuses: stable webhook URL). Status, config, `hasWebhookSecret`, last sync/success/error, `consecutiveFailures`, `nextSyncAt`, `backfilledAt`, `stats`, `disconnectedAt`. **No secrets** | **synced** | -| `customer_connection_secrets` | Encrypted API key + webhook secret (`IntegrationEncryption`) | internal, never synced | -| `customer_sync_runs` | Spec + `progress`, structured `error`, `cursor`, `failedAttempts` | **synced** (last 7 d) | -| `customer_unmatched_records` | Spec + `email`, `domain`, `payload` (the op, replayed on link). Unique `(provider, entityType, externalId)` | RPC | -| `customer_ignore_rules` | `provider?`, `entityType`, `field`, glob `pattern` | RPC | -| `customer_members` | Projection `(userId, role)` | internal | +| Table | Purpose / key points | Transport | +| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `customer_accounts` | Customer company. `domains[]`, owner, `lifecycleStage` (+ `lifecycleStageOverride`), plan, `mrrMinor`, `trialListMrrMinor`, `trialEndsAt`, seats, `contactCount`, `activeUsers30d`, `activeUsersTrendPct`, `openRiskHigh/Medium/Low`, `openOpportunities`, champion/last-active contact, `firstSeenAt`, `lastActiveAt`, `customerSince`, `churnedAt`, `tags[]`, `attributes`, `fieldSources` | **synced** | +| `customer_contacts` | End users. Spec fields + `joinedAt`, `firstActiveAt`, `eventCount30d`, `isBillingContact`, `fieldSources` | RPC (per account, paged) | +| `customer_external_refs` | Provider record ↔ account/contact. `accountId` on every ref; `matchMethod`, `matchedByUserId`, `matchedAt`, `lastSyncedAt`, `staleAt`. Unique `(provider, externalId)` for accounts, `(provider, externalId, accountId)` for contacts. Several refs per provider per account allowed | RPC (in `account.detail`) | +| `customer_subscriptions` | Spec + `listMrrMinor`, `cancellationReason`, `paymentMethod{brand,last4,exp}`, `observedAt`. Unique `(provider, externalId)` | RPC | +| `customer_invoices` | Spec + `upcoming` status (`externalId = upcoming:`), `nextRetryAt`, `declineReason`, `observedAt` | RPC | +| `customer_activity_daily` | PK `(contactId, day)`; each provider writes only its fields | internal | +| `customer_metric_definitions` | Unique `key`; built-ins `active_users`, `active_users_30d`, `mrr` | **synced** (metric picker) | +| `customer_metric_daily` | PK `(accountId, metricKey, day)`, `value`, `limitValue` (metered plan limit) | RPC | +| `customer_org_daily` | PK `day`: MRR, paying/trialing/active accounts, DAU/WAU/MAU, at-risk MRR — the overview's source | RPC | +| `customer_events` | Timeline; unique `(provider, externalId)` when set; `actorUserId` | RPC (paged) | +| `customer_mrr_movements` | One per account per day max; `type`, `deltaMinor`, from/to | RPC | +| `customer_signal_rules` | Spec + `updatedBy`, `lastTriggeredAt`, `matchingCount`; `config` = `RuleConfig` (tagged by template) | **synced** | +| `customer_signals` | Queue items. Spec + `template`, `openingEvidence`, `actionEvidence`, `priorityScore`, `openedAt`, snooze fields, `dismissReason`, `reopenCount` , `closedAt`. One unclosed episode per `(ruleId, accountId)` | **synced** (unclosed + closed ≤ 30 d); older via `customers.signals.history` | +| `customer_settings` | One row: `reportingCurrency`, `addOnPlans`, `overageInMrr`, `lastComputedAt`, `updatedBy` | **synced** | +| `customer_notes` | Spec + `editedAt`, `signalId` | **synced** | +| `customer_saved_views` | `ownerUserId` null = shared, `builtInKey`, `filters`/`sort`/`columns`, `position` | **synced** (shared + own) | +| `customer_connections` | One per provider (reconnect reuses: stable webhook URL). Status, config, `hasWebhookSecret`, last sync/success/error, `consecutiveFailures`, `nextSyncAt`, `backfilledAt`, `stats`, `disconnectedAt`. **No secrets** | **synced** | +| `customer_connection_secrets` | Encrypted API key + webhook secret (`IntegrationEncryption`) | internal, never synced | +| `customer_sync_runs` | Spec + `progress`, structured `error`, `cursor`, `failedAttempts` | **synced** (last 7 d) | +| `customer_unmatched_records` | Spec + `email`, `domain`, `payload` (the op, replayed on link). Unique `(provider, entityType, externalId)` | RPC | +| `customer_ignore_rules` | `provider?`, `entityType`, `field`, glob `pattern` | RPC | +| `customer_members` | Projection `(userId, role)` | internal | Domain shapes: `packages/domain/src/customers/` (`enums`, `models` — row models for synced and RPC -rows, `evidence`, `rules`, `health`, `views`, `connections`, `ingest`, `analytics`), exported as +rows, `evidence`, `rules`, `views`, `connections`, `ingest`, `analytics`), exported as `@hazel/domain/customers`. ## 3. Ingest API (`apps/backend/src/worker/objects/customers/ingest.ts`) @@ -210,13 +209,13 @@ Rules: Clerk organization stays its own account (an environment, e.g. a US and an EU region, named by `customer_accounts.environment`, set in Hazel only), and accounts link into a group with one primary (`primaryAccountId` on the others; no chains, a primary with environments cannot be - unlinked). Rollups and health stay per account. Signals are evaluated per group: an environment + unlinked). Rollups stay per account. Signals are evaluated per group: an environment is skipped, and its primary is evaluated over the group's combined facts (`group-facts.ts`: contacts and activity unioned with a person in several environments counted once by email, - billing together, metrics summed per day, the most advanced stage, the primary's health), so + billing together, metrics summed per day, the most advanced stage), so "logins stopped" does not fire for one environment while another still has logins. Signals are only written on the primary: linking closes the joining accounts' unclosed signals, `setPrimary` - moves the group's to the new primary. Compute and the dry runs load whole groups per chunk. + moves the group's to the new primary. Compute and the rule dry run load whole groups per chunk. - **Field precedence:** `FIELD_PRECEDENCE` (`hazel` manual edit > clerk > stripe > autumn > maple for name; per field), recorded in `fieldSources`; domains merge (never removed); fixed in v1. - **Deletes:** `account.deleted` / `contact.removed` → ref `staleAt` (+ the op's `observedAt` as @@ -324,7 +323,7 @@ Rules: subscription's start (after its trial), a usage-billed one at MRR 0 included. `billsByUsage` changes no MRR, so it writes no movement; the paying-accounts count and the MRR history still count MRR > 0 only. A `payingOnly` rule scope covers a usage-billed account. -- Built-in metrics for today: `active_users` (DAU), `active_users_30d`, `mrr`, later `health_score`. +- Built-in metrics for today: `active_users` (DAU), `active_users_30d`, `mrr`. - MRR movements (yesterday's `mrr` vs today's): 0→>0 `new` (or `reactivation` if `churnedAt` set before), >0→0 `churn`, up `expansion`, down `contraction`. A source switch holds the movement (none is written that run: a migration, not revenue) only when `mrrSource` changed **and** the new source bills @@ -342,25 +341,7 @@ Rules: - Autumn counts for MRR once its first backfill finished and, after a reconnect, once a run started since (`lastSuccessAt` ≥ `connectedAt`) succeeded: what it imported before the disconnect is stale. -### 4.3 Health (`packages/domain/src/customers/health.ts`) - -- Components, each 0–100 or excluded (no data): - - `usage` = 60% ratio step(activeUsers30d ÷ max(contactCount, 1)) + 40% trend step - (`activeUsersTrendPct`). Excluded without any activity source data for the org (an activity - connection, none of them connected and delivering, §4.4). - - `engagement` = step(days since `lastActiveAt`). Excluded like usage. - - `billing` = min of applicable: past_due/unpaid 20, invoice > 7 d overdue 30, overdue 60, - cancel scheduled 40, else 100. Excluded without a billing source or with no subscription. - - `signals` = 100 − Σ deduction per open risk signal (high 30 / medium 15 / low 5), floor 0; - templates in `excludedTemplates` ignored (default `health_drop`, `near_limit`, `seat_growth`, `churned`). -- Redistribution: `effectiveWeight_i = w_i / Σ w_available × 100`. Score = round(Σ eff × score). - No score (status `unknown`) when only `signals` is available, or the account is not a customer - (stage **lead** or **churned**: nothing to retain). -- Bands: `healthy ≥ healthyMin (70)`, `at_risk ≥ atRiskMin (40)`, else `critical`. -- Writes `customer_health_daily[today]` (breakdown with `why`), account health fields, and a - `health.status_changed` event on band change. - -### 4.4 Signal evaluation (`packages/domain/src/customers/rules.ts`, `evidence.ts`) +### 4.3 Signal evaluation (`packages/domain/src/customers/rules.ts`, `evidence.ts`) Every enabled rule × every in-scope, non-churned account (silent accounts included) that Needs attention covers (`customer_settings.attention`: its stage is one of `stages`, and it has an account @@ -383,7 +364,6 @@ Needs attention coverage: they evaluate every non-churned account in the rule's | `cancel_scheduled` | `cancelAtPeriodEnd`, or contraction in 14 d | `delta` (minor) | takes effect ≤ 7 d / — | | `trial_ending_low_activation` | trial ends ≤ 5 d, < 2 active in 7 d | `ratio` | ≤ 2 d left / 0 active | | `onboarding_stalled` | first seen 7–30 d ago, < 2 contacts ever active | `ratio` | age ≥ 21 d / 0 active | -| `health_drop` | −20 pts in 7 d, or entered critical | `delta` (points) | −35 pts / −50 pts | | `champion_inactive` | champion (30 d) inactive 14 d | `last_active` | as `inactive` | | `near_limit` | metered metric ≥ 90% of limit | `limit` | ≥ 100% / ≥ 120% | | `seat_growth` | activeUsers30d +50% vs 30 d ago, from ≥ 3 | `delta` (users) | +100% / +200% | @@ -395,10 +375,10 @@ Needs attention coverage: they evaluate every non-churned account in the rule's - Title = template name (or the rule's name if renamed); reason = one plain sentence from evidence ("No activity for 18 days; 12 weekly active users before"). -### 4.5 Signal lifecycle (per `(rule, account)`, one unclosed row) +### 4.4 Signal lifecycle (per `(rule, account)`, one unclosed row) - Condition true, no unclosed row → **open** (new row, `signal.opened` event), unless the rule is - in baseline mode (§4.7). + in baseline mode (§4.6). - **open**: update evidence/severity/priority each run. Condition false → `auto_resolved`, `closedAt`. - **snoozed**: wakes to open at `snoozedUntil`; wakes **early** when `evidence.step > actionEvidence.step` or severity rose ("got worse", event `signal.woke`). Condition false → @@ -412,7 +392,7 @@ Needs attention coverage: they evaluate every non-churned account in the rule's - Account counters (`openRisk*`, `openOpportunities`) and rule `matchingCount`/`lastTriggeredAt` updated at the end of evaluation. -### 4.6 Priority +### 4.5 Priority `priorityScore = severityWeight × valueWeight × freshness` @@ -423,7 +403,7 @@ Needs attention coverage: they evaluate every non-churned account in the rule's - `freshness = max(0.5, 1 − ageDays/28)`, age from `openedAt`. - Queue order = `priorityScore desc`, rank shown 1..n. -### 4.7 Backfill must not flood +### 4.6 Backfill must not flood - `finishRun` of a successful `backfill` adds its connection to meta `baselineFor`; the next compute (and every compute while a backfill younger than 24 h is running; retryable failures keep it @@ -434,16 +414,14 @@ Needs attention coverage: they evaluate every non-churned account in the rule's - Time-bounded templates (`payment_failed`, `cancel_scheduled`, `trial_ending_low_activation`) open normally: they are actionable now. -### 4.8 Dry runs (read RPCs; pure functions shared with compute) +### 4.7 Rule dry run (a read RPC; pure functions shared with compute) - `customers.rule.dryRun`: match count, MRR, top 10 matches with evidence, non-match reasons histogram (out of scope / below threshold / no data / missing source), queue delta vs the rule's current signals. -- `customers.health.dryRun`: current vs proposed distribution, transitions, sample breakdowns. -- Both evaluate at most 8 chunks of accounts (2,000) and stop after 5 s: the result carries - `evaluatedAccounts` of `totalAccounts`, and the editors say "Preview based on X of Y customers". -- Evaluation and scoring are pure (`(snapshot, config) → result`) so compute, dry runs and unit - tests share them. +- It evaluates at most 8 chunks of accounts (2,000) and stops after 5 s: the result carries + `evaluatedAccounts` of `totalAccounts`, and the editor says "Preview based on X of Y customers". +- Evaluation is pure (`(snapshot, config) → result`) so compute, the dry run and unit tests share it. ## 5. Webhooks, secrets and pulls (framework only) @@ -491,14 +469,13 @@ Needs attention coverage: they evaluate every non-churned account in the rule's `/$org/customers/attention`, `CustomersList` `/$org/customers/list?view=`, `CustomerDetail` `/$org/customers/$accountId?tab=` (`overview|users|billing|activity|notes`), `CustomersSettingsSignals` `/$org/customers/settings/signals` (+ `/new`, `/$ruleId`), - `CustomersSettingsHealth` `/$org/customers/settings/health`, `CustomersSettingsPlans` - `/$org/customers/settings/plans`, `CustomersSettingsSources` + `CustomersSettingsPlans` `/$org/customers/settings/plans`, `CustomersSettingsSources` `/$org/customers/settings/sources`, `CustomersSourceDetail` `…/sources/$provider`, `CustomersUnmatched` `…/sources/unmatched`. Literal segments before `$accountId` in `oneOf`. `OrgSection` gains `"Customers"`; `isCustomersRoute`; `titleOf`; `route.test.ts` examples. - **Shell:** "Customers" item in `navRail` (`src/shell/app-shell.ts:53`) and mobile nav; secondary sidebar `src/shell/customers-sidebar.ts` (Overview, Needs attention + count badge, Customers + - saved views, Settings: Signals, Health score, Data sources); `app/view.ts` `sectionBody` / + saved views, Settings: Signals, Data sources); `app/view.ts` `sectionBody` / `secondarySidebar` branches. - **Data:** entering any customers route calls `openCustomersSource(orgId)` (shell subscription); live lists via `liveQueryStream` over the customer collections filtered by `organizationId`; @@ -522,20 +499,19 @@ variables directly (no canvas color resolution), and render in the gallery and s `hbar-chart.ts`), `meter` (limit), `deltaPill`. - Hover: charts emit `HoveredIndex(index | null)` through a caller-supplied message; the page keeps the index and renders the tooltip (`chartTooltip`). No chart owns state. -- Colors: Wonder tokens `hazel/chart-new|expansion|contraction|churn|healthy|at-risk|critical| - series-1..3|grid` → CSS variables in `src/core/styles/theme.css`. +- Colors: Wonder tokens `hazel/chart-new|expansion|contraction|churn|series-1..3|grid` → CSS + variables in `src/core/styles/theme.css`. ### 6.3 Components (Wonder "Maple Design System", pages `Hazel Customers · *`) From _Foundations_ (artboards in parentheses) → `src/customers/ui/`: -- `healthBadge` (Health Badge States: label, score, compact dot), `severityChip` / `kindChip` - (Severity And Kind Chips), `stageBadge` (Lifecycle Stage Badges, trial detail), `sourceChip` / +- `severityChip` / `kindChip` (Severity And Kind Chips), `stageBadge` (Lifecycle Stage Badges, trial detail), `sourceChip` / `sourceMark` (Source Chips: chip, link chip, mark tiles; Brandfetch-free brand marks per `hazel/logo-*` tokens), `companyLogo` (Avatars And Company Logos: sizes, tint fallback), `kpiTile` (KPI Tile Variants), sparklines (Sparkline Variants, Evidence Row), `lineChart` (Line - Chart Active Users), `stackedBarChart` (Stacked Bar Chart MRR Movement), `distributionBar` - (Distribution Bar Health), `dataTable` (Table Customers States: sortable header, selection, + Chart Active Users), `stackedBarChart` (Stacked Bar Chart MRR Movement), `distributionBar`, + `dataTable` (Table Customers States: sortable header, selection, skeleton), `queueRow` (Queue Row Signal States), `filterBar` / `rangePicker` / `viewTabs` (Filter Bar And Tabs), `snoozeMenu` / `rowActionsMenu` (Menus Snooze And Row Actions), `emptyState` variants (Empty State Variants), `connectCard` (Integration Connect Cards), @@ -547,12 +523,12 @@ Pages (artboards): 12-month range. - _Needs Attention_: open/mine, grouped by account, selected + side panel preview, snooze menu, mark done dialog (outcome + note), snoozed tab, done tab, all clear. Keys j/k/a/s/d/enter. -- _List_: all, at-risk view, filter builder popover, column picker, bulk selection bar + assign +- _List_: all, filter builder popover, column picker, bulk selection bar + assign owner menu, row hover card, no results, first run. - _Customer Page_: overview/users/billing/activity/notes tabs, billing payment failed banner, header - actions menu, health breakdown with excluded component. -- _Signals & Health Settings_: rules list, template picker modal, rule editor (inactive, usage - drop) with live preview, health settings with unsaved-changes bar, weights validation error. + actions menu. +- _Signals Settings_: rules list, template picker modal, rule editor (inactive, usage drop) with + live preview. - _Data Sources_: overview cards, connect (API key) modal, source detail (Clerk), unmatched records resolver, Maple source settings, test-connection failure. @@ -589,7 +565,7 @@ request changes. ### (a) Backend — `apps/backend/**`, `packages/domain/src/customers/**` (fixes only) -- Owns: `apps/backend/src/worker/objects/customers/**` (ingest impl, compute, evaluation, health, +- Owns: `apps/backend/src/worker/objects/customers/**` (ingest impl, compute, evaluation, priority, lifecycle, pulls/alarm deadlines, access, seed generator), `rpc/handlers/customers.ts` (replace the stubs), `worker/objects/effects/customers-effects.ts`, `worker/objects/sources/customers-source.ts`, `routes/customers-webhooks.http.ts` (new) + its @@ -601,13 +577,13 @@ request changes. migration; do not edit `0001_initial` once committed — before the first commit, regenerating is fine), and `packages/domain/src/customers/**` + `rpc/customers.ts` contract changes (announce them to b/c/d). -- Order: access + members → ingest → rollups → health → evaluation/lifecycle/priority → read RPCs → - mutations → dry runs → seed → webhook/pull framework. +- Order: access + members → ingest → rollups → evaluation/lifecycle/priority → read RPCs → + mutations → rule dry run → seed → webhook/pull framework. ### (b) Design system, charts, lab — frontend kit - Owns: `src/customers/ui/**`, `src/customers/charts/**`, `src/customers/format.ts` (money, %, - relative days), `src/lab/**`, the `/lab` switch in `src/entry.ts`, chart/health color tokens in + relative days), `src/lab/**`, the `/lab` switch in `src/entry.ts`, chart color tokens in `src/core/styles/theme.css`, `src/customers/customers.gallery.ts`. - Delivers first (others consume): badges/chips, kpiTile, sparklines, charts, dataTable, queueRow, evidenceViz, menus, empty states, connectCard; then lab fixtures (`src/lab/fixtures/customers.ts`) @@ -627,7 +603,7 @@ request changes. ### (d) Pages B — list, customer page, settings - Owns: `src/page/customers/list/**`, `src/page/customers/detail/**`, - `src/page/customers/settings/{signals,health,sources,unmatched}/**`, and their lab entries. + `src/page/customers/settings/{signals,sources,unmatched}/**`, and their lab entries. - Uses c's routes/queries/actions and b's kit; asks c for route/registry changes. **Integration order:** contracts (done) → b kit primitives + c routes/shell skeleton (parallel) → @@ -642,12 +618,11 @@ mutations/compute → end-to-end pass on `alchemy:dev` with the demo seed. - **Ingest:** matching order table-driven (ref, shared id, domain, ambiguous, ignore rule, create), idempotent replays (apply twice → `Unchanged`, no `_changes` rows), precedence, unmatched → link replay, reconnect keeps removed refs removed, another provider account sweeps the old one. -- **Compute (pure, fixtures):** rollup formulas, MRR movements, health components + - redistribution + bands + churned → unknown, each template's match/evidence/step, lifecycle state - machine (open → snooze → wake worse, done stays muted while true, dismissed reopen on step, auto +- **Compute (pure, fixtures):** rollup formulas, MRR movements, each template's + match/evidence/step, lifecycle state machine (open → snooze → wake worse, done stays muted while true, dismissed reopen on step, auto resolve, baseline after backfill), priority ordering incl. no-MRR and trials. - **Frontend:** story tests for page updates, scene tests for key flows (snooze from queue, mark done - dialog, rule editor dry-run, health weights validation, connect modal errors), route examples, + dialog, rule editor dry-run, connect modal errors), route examples, lab registry test, gallery screenshots of the kit. - **DB:** `schema-ddl.test.ts` (store in sync with its snapshot). diff --git a/packages/customer-integrations/src/maple/presentation.ts b/packages/customer-integrations/src/maple/presentation.ts index 762667e31..bd2ca4ce0 100644 --- a/packages/customer-integrations/src/maple/presentation.ts +++ b/packages/customer-integrations/src/maple/presentation.ts @@ -54,7 +54,7 @@ export const presentation: PresentationOf = { key: "metricMappings", title: "Per-account metrics", description: - "A daily count per account of each mapped event, under its metric key. Usable in charts, signals and health.", + "A daily count per account of each mapped event, under its metric key. Usable in charts and signals.", emptyText: "No event is mapped to a metric yet.", columns: [ { key: "event", label: "Event", placeholder: "dashboard_created" }, diff --git a/packages/customer-integrations/src/stripe/adapter.ts b/packages/customer-integrations/src/stripe/adapter.ts index 300706ca4..e7f14de19 100644 --- a/packages/customer-integrations/src/stripe/adapter.ts +++ b/packages/customer-integrations/src/stripe/adapter.ts @@ -2,7 +2,7 @@ * The Stripe data source (`docs/customers/tech-design.md` §5), Hazel's billing source for * Customers: Stripe customers land on the accounts the identity source created, and their * subscriptions and invoices become the MRR, the plan, the trial and the payment state every - * billing signal and the health score's billing component read. + * billing signal reads. * * Connecting needs a Stripe **restricted key** (`rk_live_…` / `rk_test_…`, with the account id * entered next to it, or a secret key) with read access to customers, products, prices, diff --git a/packages/db/snapshots/customers.json b/packages/db/snapshots/customers.json index 00b79df44..5511c12cf 100644 --- a/packages/db/snapshots/customers.json +++ b/packages/db/snapshots/customers.json @@ -1,5 +1,5 @@ { - "migration": "0026_customer_contacts_email_lower", + "migration": "0027_remove_customer_health_score", "entities": [ { "kind": "table", @@ -85,13 +85,6 @@ "columns": ["id"] } }, - { - "kind": "table", - "name": "customer_health_daily", - "primaryKey": { - "columns": ["accountId", "day"] - } - }, { "kind": "table", "name": "customer_ignore_rules", @@ -372,38 +365,11 @@ "notNull": false, "default": null }, - { - "kind": "column", - "table": "customer_accounts", - "name": "healthScore", - "position": 14, - "type": "integer", - "notNull": false, - "default": null - }, - { - "kind": "column", - "table": "customer_accounts", - "name": "healthStatus", - "position": 15, - "type": "text", - "notNull": true, - "default": "'unknown'" - }, - { - "kind": "column", - "table": "customer_accounts", - "name": "healthUpdatedAt", - "position": 16, - "type": "text", - "notNull": false, - "default": null - }, { "kind": "column", "table": "customer_accounts", "name": "seatsUsed", - "position": 17, + "position": 14, "type": "integer", "notNull": false, "default": null @@ -412,7 +378,7 @@ "kind": "column", "table": "customer_accounts", "name": "seatsLimit", - "position": 18, + "position": 15, "type": "integer", "notNull": false, "default": null @@ -421,7 +387,7 @@ "kind": "column", "table": "customer_accounts", "name": "contactCount", - "position": 19, + "position": 16, "type": "integer", "notNull": true, "default": "0" @@ -430,7 +396,7 @@ "kind": "column", "table": "customer_accounts", "name": "activeUsers30d", - "position": 20, + "position": 17, "type": "integer", "notNull": true, "default": "0" @@ -439,7 +405,7 @@ "kind": "column", "table": "customer_accounts", "name": "activeUsersTrendPct", - "position": 21, + "position": 18, "type": "real", "notNull": false, "default": null @@ -448,7 +414,7 @@ "kind": "column", "table": "customer_accounts", "name": "openRiskHigh", - "position": 22, + "position": 19, "type": "integer", "notNull": true, "default": "0" @@ -457,7 +423,7 @@ "kind": "column", "table": "customer_accounts", "name": "openRiskMedium", - "position": 23, + "position": 20, "type": "integer", "notNull": true, "default": "0" @@ -466,7 +432,7 @@ "kind": "column", "table": "customer_accounts", "name": "openRiskLow", - "position": 24, + "position": 21, "type": "integer", "notNull": true, "default": "0" @@ -475,7 +441,7 @@ "kind": "column", "table": "customer_accounts", "name": "openOpportunities", - "position": 25, + "position": 22, "type": "integer", "notNull": true, "default": "0" @@ -484,7 +450,7 @@ "kind": "column", "table": "customer_accounts", "name": "championContactId", - "position": 26, + "position": 23, "type": "text", "notNull": false, "default": null @@ -493,7 +459,7 @@ "kind": "column", "table": "customer_accounts", "name": "championInactiveSince", - "position": 27, + "position": 24, "type": "text", "notNull": false, "default": null @@ -502,7 +468,7 @@ "kind": "column", "table": "customer_accounts", "name": "lastActiveContactId", - "position": 28, + "position": 25, "type": "text", "notNull": false, "default": null @@ -511,7 +477,7 @@ "kind": "column", "table": "customer_accounts", "name": "firstSeenAt", - "position": 29, + "position": 26, "type": "text", "notNull": true, "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" @@ -520,7 +486,7 @@ "kind": "column", "table": "customer_accounts", "name": "lastActiveAt", - "position": 30, + "position": 27, "type": "text", "notNull": false, "default": null @@ -529,7 +495,7 @@ "kind": "column", "table": "customer_accounts", "name": "customerSince", - "position": 31, + "position": 28, "type": "text", "notNull": false, "default": null @@ -538,7 +504,7 @@ "kind": "column", "table": "customer_accounts", "name": "churnedAt", - "position": 32, + "position": 29, "type": "text", "notNull": false, "default": null @@ -547,7 +513,7 @@ "kind": "column", "table": "customer_accounts", "name": "tags", - "position": 33, + "position": 30, "type": "text", "notNull": true, "default": "'[]'" @@ -556,7 +522,7 @@ "kind": "column", "table": "customer_accounts", "name": "attributes", - "position": 34, + "position": 31, "type": "text", "notNull": true, "default": "'{}'" @@ -565,7 +531,7 @@ "kind": "column", "table": "customer_accounts", "name": "featureFlags", - "position": 35, + "position": 32, "type": "text", "notNull": true, "default": "'{}'" @@ -574,7 +540,7 @@ "kind": "column", "table": "customer_accounts", "name": "attentionMutedAt", - "position": 36, + "position": 33, "type": "text", "notNull": false, "default": null @@ -583,7 +549,7 @@ "kind": "column", "table": "customer_accounts", "name": "attentionMutedUntil", - "position": 37, + "position": 34, "type": "text", "notNull": false, "default": null @@ -592,7 +558,7 @@ "kind": "column", "table": "customer_accounts", "name": "attentionMutedByUserId", - "position": 38, + "position": 35, "type": "text", "notNull": false, "default": null @@ -601,7 +567,7 @@ "kind": "column", "table": "customer_accounts", "name": "fieldSources", - "position": 39, + "position": 36, "type": "text", "notNull": true, "default": "'{}'" @@ -610,7 +576,7 @@ "kind": "column", "table": "customer_accounts", "name": "primaryAccountId", - "position": 40, + "position": 37, "type": "text", "notNull": false, "default": null @@ -619,7 +585,7 @@ "kind": "column", "table": "customer_accounts", "name": "environment", - "position": 41, + "position": 38, "type": "text", "notNull": false, "default": null @@ -628,7 +594,7 @@ "kind": "column", "table": "customer_accounts", "name": "companyProfile", - "position": 42, + "position": 39, "type": "text", "notNull": false, "default": null @@ -637,7 +603,7 @@ "kind": "column", "table": "customer_accounts", "name": "companyCheckedAt", - "position": 43, + "position": 40, "type": "text", "notNull": false, "default": null @@ -646,7 +612,7 @@ "kind": "column", "table": "customer_accounts", "name": "createdAt", - "position": 44, + "position": 41, "type": "text", "notNull": true, "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" @@ -655,7 +621,7 @@ "kind": "column", "table": "customer_accounts", "name": "updatedAt", - "position": 45, + "position": 42, "type": "text", "notNull": true, "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" @@ -664,7 +630,7 @@ "kind": "column", "table": "customer_accounts", "name": "deletedAt", - "position": 46, + "position": 43, "type": "text", "notNull": false, "default": null @@ -1857,51 +1823,6 @@ "notNull": true, "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" }, - { - "kind": "column", - "table": "customer_health_daily", - "name": "accountId", - "position": 0, - "type": "text", - "notNull": true, - "default": null - }, - { - "kind": "column", - "table": "customer_health_daily", - "name": "day", - "position": 1, - "type": "text", - "notNull": true, - "default": null - }, - { - "kind": "column", - "table": "customer_health_daily", - "name": "score", - "position": 2, - "type": "integer", - "notNull": false, - "default": null - }, - { - "kind": "column", - "table": "customer_health_daily", - "name": "status", - "position": 3, - "type": "text", - "notNull": true, - "default": null - }, - { - "kind": "column", - "table": "customer_health_daily", - "name": "breakdown", - "position": 4, - "type": "text", - "notNull": true, - "default": null - }, { "kind": "column", "table": "customer_ignore_rules", @@ -3135,38 +3056,11 @@ "notNull": true, "default": "0" }, - { - "kind": "column", - "table": "customer_org_daily", - "name": "healthy", - "position": 8, - "type": "integer", - "notNull": true, - "default": "0" - }, - { - "kind": "column", - "table": "customer_org_daily", - "name": "atRisk", - "position": 9, - "type": "integer", - "notNull": true, - "default": "0" - }, - { - "kind": "column", - "table": "customer_org_daily", - "name": "critical", - "position": 10, - "type": "integer", - "notNull": true, - "default": "0" - }, { "kind": "column", "table": "customer_org_daily", "name": "atRiskMrrMinor", - "position": 11, + "position": 8, "type": "integer", "notNull": true, "default": "0" @@ -3324,20 +3218,11 @@ "notNull": true, "default": null }, - { - "kind": "column", - "table": "customer_settings", - "name": "health", - "position": 2, - "type": "text", - "notNull": true, - "default": null - }, { "kind": "column", "table": "customer_settings", "name": "attention", - "position": 3, + "position": 2, "type": "text", "notNull": true, "default": "'{\"stages\":[\"lead\",\"trialing\",\"active\",\"past_due\"],\"requiredSources\":[\"stripe\"]}'" @@ -3346,7 +3231,7 @@ "kind": "column", "table": "customer_settings", "name": "reportingCurrency", - "position": 4, + "position": 3, "type": "text", "notNull": true, "default": "'usd'" @@ -3355,7 +3240,7 @@ "kind": "column", "table": "customer_settings", "name": "addOnPlans", - "position": 5, + "position": 4, "type": "text", "notNull": true, "default": "'[]'" @@ -3364,7 +3249,7 @@ "kind": "column", "table": "customer_settings", "name": "overageInMrr", - "position": 6, + "position": 5, "type": "integer", "notNull": true, "default": "false" @@ -3373,7 +3258,7 @@ "kind": "column", "table": "customer_settings", "name": "businessHours", - "position": 7, + "position": 6, "type": "text", "notNull": true, "default": "'{\"timeZone\":\"UTC\",\"days\":[1,2,3,4,5],\"start\":\"09:00\",\"end\":\"17:00\"}'" @@ -3382,7 +3267,7 @@ "kind": "column", "table": "customer_settings", "name": "lastComputedAt", - "position": 8, + "position": 7, "type": "text", "notNull": false, "default": null @@ -3391,7 +3276,7 @@ "kind": "column", "table": "customer_settings", "name": "updatedBy", - "position": 9, + "position": 8, "type": "text", "notNull": false, "default": null @@ -3400,7 +3285,7 @@ "kind": "column", "table": "customer_settings", "name": "createdAt", - "position": 10, + "position": 9, "type": "text", "notNull": true, "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" @@ -3409,7 +3294,7 @@ "kind": "column", "table": "customer_settings", "name": "updatedAt", - "position": 11, + "position": 10, "type": "text", "notNull": true, "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" @@ -4537,13 +4422,6 @@ "unique": false, "columns": ["\"deletedAt\""] }, - { - "kind": "index", - "table": "customer_accounts", - "name": "customer_accounts_health_idx", - "unique": false, - "columns": ["\"healthStatus\""] - }, { "kind": "index", "table": "customer_accounts", @@ -4691,13 +4569,6 @@ "unique": true, "columns": ["\"key\""] }, - { - "kind": "index", - "table": "customer_health_daily", - "name": "customer_health_daily_day_idx", - "unique": false, - "columns": ["\"day\""] - }, { "kind": "index", "table": "customer_impersonations", diff --git a/packages/db/snapshots/org.json b/packages/db/snapshots/org.json index 53d3f9af1..50be71030 100644 --- a/packages/db/snapshots/org.json +++ b/packages/db/snapshots/org.json @@ -1,5 +1,5 @@ { - "migration": "0015_dm_last_message", + "migration": "0016_remove_customer_health_score", "entities": [ { "kind": "table", @@ -1026,38 +1026,11 @@ "notNull": true, "default": "(strftime('%Y-%m-%d %H:%M:%f', 'now'))" }, - { - "kind": "column", - "table": "channel_customers", - "name": "healthStatus", - "position": 6, - "type": "text", - "notNull": true, - "default": "'unknown'" - }, - { - "kind": "column", - "table": "channel_customers", - "name": "healthScore", - "position": 7, - "type": "integer", - "notNull": false, - "default": null - }, - { - "kind": "column", - "table": "channel_customers", - "name": "healthWhy", - "position": 8, - "type": "text", - "notNull": false, - "default": null - }, { "kind": "column", "table": "channel_customers", "name": "lifecycleStage", - "position": 9, + "position": 6, "type": "text", "notNull": false, "default": null @@ -1066,7 +1039,7 @@ "kind": "column", "table": "channel_customers", "name": "planName", - "position": 10, + "position": 7, "type": "text", "notNull": false, "default": null @@ -1075,7 +1048,7 @@ "kind": "column", "table": "channel_customers", "name": "mrrMinor", - "position": 11, + "position": 8, "type": "integer", "notNull": false, "default": null @@ -1084,7 +1057,7 @@ "kind": "column", "table": "channel_customers", "name": "currency", - "position": 12, + "position": 9, "type": "text", "notNull": false, "default": null @@ -1093,7 +1066,7 @@ "kind": "column", "table": "channel_customers", "name": "ownerUserId", - "position": 13, + "position": 10, "type": "text", "notNull": false, "default": null @@ -1102,7 +1075,7 @@ "kind": "column", "table": "channel_customers", "name": "seatsUsed", - "position": 14, + "position": 11, "type": "integer", "notNull": false, "default": null @@ -1111,7 +1084,7 @@ "kind": "column", "table": "channel_customers", "name": "seatsLimit", - "position": 15, + "position": 12, "type": "integer", "notNull": false, "default": null @@ -1120,7 +1093,7 @@ "kind": "column", "table": "channel_customers", "name": "lastActiveDay", - "position": 16, + "position": 13, "type": "text", "notNull": false, "default": null @@ -1129,7 +1102,7 @@ "kind": "column", "table": "channel_customers", "name": "openSignalCount", - "position": 17, + "position": 14, "type": "integer", "notNull": true, "default": "0" @@ -1138,7 +1111,7 @@ "kind": "column", "table": "channel_customers", "name": "topSignals", - "position": 18, + "position": 15, "type": "text", "notNull": true, "default": "'[]'" @@ -1147,7 +1120,7 @@ "kind": "column", "table": "channel_customers", "name": "sourceLinks", - "position": 19, + "position": 16, "type": "text", "notNull": true, "default": "'[]'" @@ -1156,7 +1129,7 @@ "kind": "column", "table": "channel_customers", "name": "company", - "position": 20, + "position": 17, "type": "text", "notNull": false, "default": null diff --git a/packages/db/src/migrations.generated.ts b/packages/db/src/migrations.generated.ts index e9da30d16..f64702303 100644 --- a/packages/db/src/migrations.generated.ts +++ b/packages/db/src/migrations.generated.ts @@ -376,6 +376,14 @@ export const generatedMigrations: Record \'health\' ORDER BY "key")) WHERE EXISTS (SELECT 1 FROM json_each("customer_saved_views"."columns") WHERE "value" = \'health\')', + 'UPDATE "customer_saved_views" SET "sort" = \'{"column":"mrr","direction":"desc"}\' WHERE json_extract("sort", \'$.column\') = \'health\'', + 'DROP INDEX IF EXISTS "customer_accounts_health_idx"', + 'ALTER TABLE "customer_accounts" DROP COLUMN "healthScore"', + 'ALTER TABLE "customer_accounts" DROP COLUMN "healthStatus"', + 'ALTER TABLE "customer_accounts" DROP COLUMN "healthUpdatedAt"', + 'ALTER TABLE "customer_org_daily" DROP COLUMN "healthy"', + 'ALTER TABLE "customer_org_daily" DROP COLUMN "atRisk"', + 'ALTER TABLE "customer_org_daily" DROP COLUMN "critical"', + 'ALTER TABLE "customer_settings" DROP COLUMN "health"', + 'DROP TABLE IF EXISTS "customer_health_daily"', + ], + }, ], } diff --git a/packages/db/src/stores.ts b/packages/db/src/stores.ts index c5f99ad4e..3e68dac62 100644 --- a/packages/db/src/stores.ts +++ b/packages/db/src/stores.ts @@ -112,7 +112,7 @@ export const userTables = [ /** * `CustomersObject`, one per organization (`docs/customers/tech-design.md`): customer accounts, - * their billing and usage, signals, health and data sources. + * their billing and usage, signals and data sources. */ export const customersTables = [ schema.customerAccountsTable, @@ -130,7 +130,6 @@ export const customersTables = [ schema.customerSignalsTable, schema.customerSettingsTable, schema.customerSlaPoliciesTable, - schema.customerHealthDailyTable, schema.customerNotesTable, schema.customerSavedViewsTable, schema.customerViewLayoutsTable, diff --git a/packages/db/src/tables/channel-customers.ts b/packages/db/src/tables/channel-customers.ts index 02a60096f..7a5971369 100644 --- a/packages/db/src/tables/channel-customers.ts +++ b/packages/db/src/tables/channel-customers.ts @@ -2,13 +2,13 @@ * An `OrgObject`'s projection of its `CustomersObject`'s channel links * (`docs/customers/channels.md`), written only by `org.setChannelCustomers` (a full, versioned * snapshot). Chat shows a channel's customer from it without opening the Customers source: the - * name, and the account at a glance (health, stage, plan, MRR, owner, seats, last active day, open + * name, and the account at a glance (stage, plan, MRR, owner, seats, last active day, open * signals, provider links). * * The glance columns came after the table (objects migrate lazily, old snapshots lack them): all * nullable or defaulted. */ -import { type CompanyProfile, HealthStatus, LifecycleStage } from "@hazel/domain/customers" +import { type CompanyProfile, LifecycleStage } from "@hazel/domain/customers" import type { ChannelCustomer as ChannelCustomerModel } from "@hazel/domain/models" import { ChannelId, CustomerAccountId, OrganizationId, UserId } from "@hazel/schema" import * as SQLite from "@maple-dev/effect-orm/sqlite" @@ -23,9 +23,6 @@ export const channelCustomersTable = SQLite.table("channel_customers", { /** The customer's logo (its account's `logoUrl`); null when it has none. */ accountLogoUrl: SQLite.nullable(SQLite.text), updatedAt: SQLite.column(timestamptz, { defaultExpr: SQLite.timestampNow }), - healthStatus: SQLite.column(textEnum(HealthStatus.literals), { default: "unknown" }), - healthScore: SQLite.nullable(SQLite.integer), - healthWhy: SQLite.nullable(SQLite.text), lifecycleStage: SQLite.nullable(textEnum(LifecycleStage.literals)), planName: SQLite.nullable(SQLite.text), mrrMinor: SQLite.nullable(SQLite.integer), diff --git a/packages/db/src/tables/customers.ts b/packages/db/src/tables/customers.ts index 85fda6de7..d3b613936 100644 --- a/packages/db/src/tables/customers.ts +++ b/packages/db/src/tables/customers.ts @@ -18,8 +18,6 @@ import type { SlaState, SlaTargets, ConnectionConfig, - HealthBreakdown, - HealthSettings, RuleConfig, RuleScope, SignalEvidence, @@ -41,7 +39,6 @@ import { BillingInterval, BuiltInViewKey, ConnectionStatus, - HealthStatus, IgnoreRuleField, InvoiceStatus, IssuePriority, @@ -113,7 +110,7 @@ const count = () => SQLite.column(SQLite.integer, { default: 0 }) // Identity // --------------------------------------------------------------------------- -/** A B2B customer. Billing, usage and health fields are denormalized by compute. */ +/** A B2B customer. Billing and usage fields are denormalized by compute. */ export const customerAccountsTable = SQLite.table("customer_accounts", { columns: { id: id(CustomerAccountId), @@ -138,9 +135,6 @@ export const customerAccountsTable = SQLite.table("customer_accounts", { /** List price of the trial's plan per month: ranks trials in the queue (they have no MRR yet). */ trialListMrrMinor: SQLite.nullable(SQLite.integer), trialEndsAt: SQLite.nullable(timestamptz), - healthScore: SQLite.nullable(SQLite.integer), - healthStatus: SQLite.column(textEnum(HealthStatus.literals), { default: "unknown" }), - healthUpdatedAt: SQLite.nullable(timestamptz), seatsUsed: SQLite.nullable(SQLite.integer), seatsLimit: SQLite.nullable(SQLite.integer), contactCount: count(), @@ -202,7 +196,6 @@ export const customerAccountsTable = SQLite.table("customer_accounts", { SQLite.index("customer_accounts_primary_idx", ["primaryAccountId"]), SQLite.index("customer_accounts_owner_idx", ["ownerUserId"]), SQLite.index("customer_accounts_stage_idx", ["lifecycleStage"]), - SQLite.index("customer_accounts_health_idx", ["healthStatus"]), SQLite.index("customer_accounts_deleted_at_idx", ["deletedAt"]), ], }) @@ -504,9 +497,6 @@ export const customerOrgDailyTable = SQLite.table("customer_org_daily", { dau: count(), wau: count(), mau: count(), - healthy: count(), - atRisk: count(), - critical: count(), atRiskMrrMinor: money(), }, primaryKey: ["day"], @@ -523,7 +513,7 @@ export const customerEventsTable = SQLite.table("customer_events", { accountId: uuid(CustomerAccountId), contactId: SQLite.nullable(uuid(CustomerContactId)), provider: SQLite.text, - /** Dotted, e.g. `subscription.canceled`, `signal.opened`, `health.status_changed`. */ + /** Dotted, e.g. `subscription.canceled`, `signal.opened`. */ type: SQLite.text, title: SQLite.text, data: SQLite.column(jsonb>(), { default: {} }), @@ -654,15 +644,14 @@ export type CustomerSignal = SQLite.SelectRowOf export type NewCustomerSignal = SQLite.InsertRowOf // --------------------------------------------------------------------------- -// Health +// Settings and SLA policies // --------------------------------------------------------------------------- -/** One row: the org's health configuration, reporting currency and compute bookkeeping. */ +/** One row: the org's reporting currency, attention scope and compute bookkeeping. */ export const customerSettingsTable = SQLite.table("customer_settings", { columns: { id: id(CustomerSettingsId), organizationId: uuid(OrganizationId), - health: jsonb(), /** Which customers Needs attention covers (`AttentionSettings`). */ attention: SQLite.column(jsonb(), { default: DEFAULT_ATTENTION_SETTINGS }), /** MRR in other currencies is left out of org totals (no FX in v1). */ @@ -708,19 +697,6 @@ export const customerSlaPoliciesTable = SQLite.table("customer_sla_policies", { }) export type CustomerSlaPolicy = SQLite.SelectRowOf -export const customerHealthDailyTable = SQLite.table("customer_health_daily", { - columns: { - accountId: uuid(CustomerAccountId), - day, - score: SQLite.nullable(SQLite.integer), - status: textEnum(HealthStatus.literals), - breakdown: jsonb(), - }, - primaryKey: ["accountId", "day"], - indexes: [SQLite.index("customer_health_daily_day_idx", ["day"])], -}) -export type CustomerHealthDay = SQLite.SelectRowOf - // --------------------------------------------------------------------------- // Notes and views // --------------------------------------------------------------------------- diff --git a/packages/domain/src/customers/analytics.ts b/packages/domain/src/customers/analytics.ts index b3ff3eed1..cb9b732ef 100644 --- a/packages/domain/src/customers/analytics.ts +++ b/packages/domain/src/customers/analytics.ts @@ -1,5 +1,5 @@ /** - * What the read RPCs answer: aggregates, time series, per-account detail and dry runs + * What the read RPCs answer: aggregates, time series, per-account detail and the rule dry run * (`docs/customers/tech-design.md` §2 "RPC-only"). Live lists come from the synced collections. */ import { CustomerAccountId } from "@hazel/schema" @@ -9,13 +9,11 @@ import { ContactActivityStatus, CustomerProvider, CustomersRange, - HealthStatus, LifecycleStage, SignalSeverity, SubscriptionStatus, } from "./enums" import { Day, SeriesPoint, SignalEvidence } from "./evidence" -import { HealthBreakdown } from "./health" import { Account, Contact, Event, ExternalRef, Invoice, Subscription } from "./models" /** A page of `items`; pass `nextCursor` back as `cursor` for the next one (null: no more). */ @@ -86,13 +84,6 @@ export const ActiveUsersPoint = Schema.Struct({ }) export type ActiveUsersPoint = typeof ActiveUsersPoint.Type -export const HealthDistributionRow = Schema.Struct({ - status: HealthStatus, - count: Schema.Int, - mrrMinor: Schema.Int, -}) -export type HealthDistributionRow = typeof HealthDistributionRow.Type - export const AccountBrief = Schema.Struct({ accountId: CustomerAccountId, name: Schema.String, @@ -134,7 +125,6 @@ export const OverviewResult = Schema.Struct({ kpis: OverviewKpis, mrrMovements: Schema.Array(MrrMovementBucket), activeUsers: Schema.Array(ActiveUsersPoint), - healthDistribution: Schema.Array(HealthDistributionRow), topMovers: Schema.Struct({ gainers: Schema.Array(Mover), decliners: Schema.Array(Mover) }), recentChurn: Schema.Array(AccountBrief), recentNew: Schema.Array(AccountBrief), @@ -177,17 +167,6 @@ export const AccountDetail = Schema.Struct({ upcomingInvoice: Schema.NullOr(Invoice.Schema), /** Open and past-due invoices (the payment issue banner). */ openInvoices: Schema.Array(Invoice.Schema), - /** Today's breakdown; null before the first compute. */ - health: Schema.NullOr(HealthBreakdown), - /** 90 days of the health score (a day without a score is 0, for the chart). */ - healthSeries: Schema.Array(SeriesPoint), - /** - * The scores actually recorded in those 90 days, oldest first: a day missing here was never - * scored (`score` null: scored without enough data). Optional: older answers lack it. - */ - healthScores: Schema.optionalKey( - Schema.Array(Schema.Struct({ day: Day, score: Schema.NullOr(Schema.Finite) })), - ), /** 30 days of daily active users. */ activeUsersSeries: Schema.Array(SeriesPoint), /** The most active contacts and admins, ≤ 5: who to reach. */ @@ -215,7 +194,7 @@ export const Sparkline = Schema.Struct({ export type Sparkline = typeof Sparkline.Type // --------------------------------------------------------------------------- -// Dry runs +// Rule dry run // --------------------------------------------------------------------------- export const RuleMatch = Schema.Struct({ @@ -248,21 +227,3 @@ export const RuleDryRunResult = Schema.Struct({ ...DryRunCoverage.fields, }) export type RuleDryRunResult = typeof RuleDryRunResult.Type - -export const HealthDryRunResult = Schema.Struct({ - current: Schema.Array(HealthDistributionRow), - proposed: Schema.Array(HealthDistributionRow), - /** Accounts per `(from, to)` status pair that changes. */ - transitions: Schema.Array(Schema.Struct({ from: HealthStatus, to: HealthStatus, count: Schema.Int })), - /** A few accounts that change band, with both breakdowns. */ - samples: Schema.Array( - Schema.Struct({ - accountId: CustomerAccountId, - name: Schema.String, - current: HealthBreakdown, - proposed: HealthBreakdown, - }), - ), - ...DryRunCoverage.fields, -}) -export type HealthDryRunResult = typeof HealthDryRunResult.Type diff --git a/packages/domain/src/customers/enums.ts b/packages/domain/src/customers/enums.ts index ff455a548..89c1032ca 100644 --- a/packages/domain/src/customers/enums.ts +++ b/packages/domain/src/customers/enums.ts @@ -22,9 +22,6 @@ export type SourceCapability = typeof SourceCapability.Type export const LifecycleStage = Schema.Literals(["lead", "trialing", "active", "past_due", "churned"]) export type LifecycleStage = typeof LifecycleStage.Type -export const HealthStatus = Schema.Literals(["healthy", "at_risk", "critical", "unknown"]) -export type HealthStatus = typeof HealthStatus.Type - export const SubscriptionStatus = Schema.Literals([ "trialing", "active", @@ -76,7 +73,6 @@ export const SignalTemplate = Schema.Literals([ "cancel_scheduled", "trial_ending_low_activation", "onboarding_stalled", - "health_drop", "champion_inactive", "near_limit", "seat_growth", @@ -117,9 +113,6 @@ export type UnmatchedStatus = typeof UnmatchedStatus.Type export const MrrMovementType = Schema.Literals(["new", "expansion", "contraction", "churn", "reactivation"]) export type MrrMovementType = typeof MrrMovementType.Type -export const HealthComponentKey = Schema.Literals(["usage", "engagement", "billing", "signals"]) -export type HealthComponentKey = typeof HealthComponentKey.Type - /** How a signal's evidence is drawn (queue mini-viz, side panel chart). */ export const EvidenceViz = Schema.Literals([ "amount", @@ -137,7 +130,7 @@ export const ContactActivityStatus = Schema.Literals(["active", "dormant", "neve export type ContactActivityStatus = typeof ContactActivityStatus.Type /** The seeded shared views; admins may edit them, nobody deletes them. */ -export const BuiltInViewKey = Schema.Literals(["my_customers", "paying", "trialing", "at_risk", "churned"]) +export const BuiltInViewKey = Schema.Literals(["my_customers", "paying", "trialing", "churned"]) export type BuiltInViewKey = typeof BuiltInViewKey.Type /** The overview's range picker. */ diff --git a/packages/domain/src/customers/evidence.ts b/packages/domain/src/customers/evidence.ts index 1981eeeb6..86b3838b7 100644 --- a/packages/domain/src/customers/evidence.ts +++ b/packages/domain/src/customers/evidence.ts @@ -114,10 +114,10 @@ export const LimitEvidence = Schema.TaggedStruct("limit", { accountId: Schema.optionalKey(CustomerAccountId), }) -/** `cancel_scheduled`, `health_drop`, `seat_growth`: a value that moved from `from` to `to`. */ +/** `cancel_scheduled`, `seat_growth`: a value that moved from `from` to `to`. */ export const DeltaEvidence = Schema.TaggedStruct("delta", { step: EvidenceStep, - unit: Schema.Literals(["minor", "points", "users"]), + unit: Schema.Literals(["minor", "users"]), from: Schema.Finite, to: Schema.Finite, changePct: Schema.NullOr(Schema.Finite), @@ -125,7 +125,7 @@ export const DeltaEvidence = Schema.TaggedStruct("delta", { currency: Schema.NullOr(Schema.String), /** When it takes effect (a scheduled cancellation's period end). */ effectiveAt: Schema.NullOr(IsoTimestamp), - /** E.g. plan names, health statuses. */ + /** E.g. plan names. */ fromLabel: Schema.NullOr(Schema.String), toLabel: Schema.NullOr(Schema.String), reason: Schema.NullOr(Schema.String), diff --git a/packages/domain/src/customers/health.ts b/packages/domain/src/customers/health.ts deleted file mode 100644 index ecd005b65..000000000 --- a/packages/domain/src/customers/health.ts +++ /dev/null @@ -1,143 +0,0 @@ -/** - * The health score's settings and its explained result (`docs/customers/tech-design.md` §4). - * - * Each component scores 0–100 from its inputs through threshold steps; components without data - * drop out and their weight is shared across the rest; the score is the weighted sum, banded into - * a status. Churned accounts get no score (`unknown`). - */ -import { Schema } from "effect" -import { HealthComponentKey, HealthStatus, SignalTemplate } from "./enums" - -const Score = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 100 })) - -/** First step whose `min` ≤ the input wins; sorted by `min` descending (no `Infinity`: stored as JSON). */ -export const MinStep = Schema.Struct({ min: Schema.Finite, score: Score }) -export type MinStep = typeof MinStep.Type - -/** First step whose `max` ≥ the input wins; steps are sorted by `max` ascending. */ -export const MaxStep = Schema.Struct({ max: Schema.Finite, score: Score }) -export type MaxStep = typeof MaxStep.Type - -export const HealthWeights = Schema.Struct({ - usage: Score, - engagement: Score, - billing: Score, - signals: Score, -}) -export type HealthWeights = typeof HealthWeights.Type - -export const HealthBands = Schema.Struct({ - /** Score ≥ this is `healthy`. */ - healthyMin: Score, - /** Score ≥ this (and below `healthyMin`) is `at_risk`; below is `critical`. */ - atRiskMin: Score, -}) -export type HealthBands = typeof HealthBands.Type - -export const HealthSteps = Schema.Struct({ - usage: Schema.Struct({ - /** Share of the inputs: `activeRatio` (60%) and `trend` (40%). */ - activeRatioWeight: Score, - /** Active users (30d) ÷ contacts, 0–1. */ - activeRatio: Schema.Array(MinStep), - /** Active users trend, percent (7d avg vs prior 28d avg). */ - trend: Schema.Array(MinStep), - }), - engagement: Schema.Struct({ - /** Days since the account's last activity. */ - daysSinceActive: Schema.Array(MaxStep), - }), - billing: Schema.Struct({ - pastDue: Score, - overdueOverWeek: Score, - overdue: Score, - cancelScheduled: Score, - ok: Score, - }), - signals: Schema.Struct({ - /** Subtracted from 100 per open risk signal of that severity, floored at 0. */ - high: Score, - medium: Score, - low: Score, - }), -}) -export type HealthSteps = typeof HealthSteps.Type - -/** The org's health configuration (stored in `customer_settings`). */ -export const HealthSettings = Schema.Struct({ - weights: HealthWeights.check( - Schema.makeFilter((weights) => - weights.usage + weights.engagement + weights.billing + weights.signals === 100 - ? undefined - : "Weights must sum to 100", - ), - ), - bands: HealthBands.check( - Schema.makeFilter((bands) => - bands.atRiskMin < bands.healthyMin ? undefined : "The at-risk band must start below healthy", - ), - ), - steps: HealthSteps, - /** Templates whose signals the `signals` component ignores (avoids `health_drop` feeding itself). */ - excludedTemplates: Schema.Array(SignalTemplate), -}) -export type HealthSettings = typeof HealthSettings.Type - -export const DEFAULT_HEALTH_SETTINGS: HealthSettings = { - weights: { usage: 35, engagement: 25, billing: 25, signals: 15 }, - bands: { healthyMin: 70, atRiskMin: 40 }, - steps: { - usage: { - activeRatioWeight: 60, - activeRatio: [ - { min: 0.6, score: 100 }, - { min: 0.4, score: 75 }, - { min: 0.2, score: 50 }, - { min: 0.0001, score: 25 }, - { min: 0, score: 0 }, - ], - trend: [ - { min: 10, score: 100 }, - { min: -10, score: 75 }, - { min: -30, score: 40 }, - { min: -1_000_000, score: 10 }, - ], - }, - engagement: { - daysSinceActive: [ - { max: 1, score: 100 }, - { max: 3, score: 90 }, - { max: 7, score: 75 }, - { max: 14, score: 50 }, - { max: 30, score: 25 }, - { max: 1_000_000, score: 0 }, - ], - }, - billing: { pastDue: 20, overdueOverWeek: 30, overdue: 60, cancelScheduled: 40, ok: 100 }, - signals: { high: 30, medium: 15, low: 5 }, - }, - excludedTemplates: ["health_drop", "near_limit", "seat_growth", "churned"], -} - -/** One component of an account's score, and why. */ -export const HealthComponentResult = Schema.Struct({ - key: HealthComponentKey, - /** Null when the component had no data (`excluded`). */ - score: Schema.NullOr(Score), - /** The configured weight, percent. */ - weight: Score, - /** After redistributing the excluded components' weight, percent (0 when excluded). */ - effectiveWeight: Schema.Finite, - excluded: Schema.Boolean, - /** Plain-language inputs, e.g. "4 of 12 contacts active in 30 days; trend −18%". */ - why: Schema.String, -}) -export type HealthComponentResult = typeof HealthComponentResult.Type - -/** An account's score on a day (`customer_health_daily`, and the breakdown on the customer page). */ -export const HealthBreakdown = Schema.Struct({ - score: Schema.NullOr(Score), - status: HealthStatus, - components: Schema.Array(HealthComponentResult), -}) -export type HealthBreakdown = typeof HealthBreakdown.Type diff --git a/packages/domain/src/customers/index.ts b/packages/domain/src/customers/index.ts index 1e802952c..511bccbb2 100644 --- a/packages/domain/src/customers/index.ts +++ b/packages/domain/src/customers/index.ts @@ -1,6 +1,6 @@ /** * The Customers area's shared contracts (`docs/customers/tech-design.md`): enums, row models, JSON - * documents (evidence, rule configs, health settings, views, connection config), the ingest ops + * documents (evidence, rule configs, views, connection config), the ingest ops * and the read results. The RPCs are `../rpc/customers.ts`. */ export * from "./analytics" @@ -10,7 +10,6 @@ export * from "./company" export * from "./connections" export * from "./enums" export * from "./evidence" -export * from "./health" export * from "./ingest" export * from "./models" export * from "./rules" diff --git a/packages/domain/src/customers/models.ts b/packages/domain/src/customers/models.ts index 3a5d966ed..067c9c10a 100644 --- a/packages/domain/src/customers/models.ts +++ b/packages/domain/src/customers/models.ts @@ -46,7 +46,6 @@ import { ConnectionStatus, CustomerProvider, CustomerSource, - HealthStatus, IgnoreRuleField, InvoiceStatus, IssuePriority, @@ -67,7 +66,6 @@ import { UnmatchedStatus, } from "./enums" import { SignalEvidence } from "./evidence" -import { HealthSettings } from "./health" import { AttentionSettings, RuleConfig, RuleScope } from "./rules" import { BusinessHours, SlaAppliesTo, SlaHours, SlaState, SlaTargets } from "./sla" import { CompanyProfile } from "./company" @@ -99,9 +97,6 @@ class AccountModel extends M.Class("CustomerAccount")({ currency: S.String, trialListMrrMinor: S.NullOr(S.Int), trialEndsAt: NullDate, - healthScore: S.NullOr(S.Int), - healthStatus: HealthStatus, - healthUpdatedAt: NullDate, seatsUsed: S.NullOr(S.Int), seatsLimit: S.NullOr(S.Int), contactCount: S.Int, @@ -369,7 +364,6 @@ export type ViewLayout = typeof ViewLayout.Schema.Type class SettingsModel extends M.Class("CustomerSettings")({ id: M.Generated(CustomerSettingsId), organizationId: OrganizationId, - health: HealthSettings, /** Which customers Needs attention covers. */ attention: AttentionSettings, reportingCurrency: S.String, diff --git a/packages/domain/src/customers/rules.ts b/packages/domain/src/customers/rules.ts index f2f943dbb..9a4e465ce 100644 --- a/packages/domain/src/customers/rules.ts +++ b/packages/domain/src/customers/rules.ts @@ -66,13 +66,6 @@ export const OnboardingStalledConfig = Schema.TaggedStruct("onboarding_stalled", ), ) -/** Health fell ≥ `dropPoints` within `windowDays`, or (with `onCritical`) entered `critical`. */ -export const HealthDropConfig = Schema.TaggedStruct("health_drop", { - dropPoints: Count, - windowDays: Days, - onCritical: Schema.Boolean, -}) - /** The most active contact of the last `windowDays` has been inactive for `inactiveDays`. */ export const ChampionInactiveConfig = Schema.TaggedStruct("champion_inactive", { windowDays: Days, @@ -115,7 +108,6 @@ export const RuleConfig = Schema.Union([ CancelScheduledConfig, TrialEndingLowActivationConfig, OnboardingStalledConfig, - HealthDropConfig, ChampionInactiveConfig, NearLimitConfig, SeatGrowthConfig, @@ -183,8 +175,6 @@ export interface TemplateMeta { * time-bounded, act-now templates (billing, trials). */ readonly baselineOnBackfill: boolean - /** Signals of this template are left out of the health score's `signals` component by default. */ - readonly excludedFromHealth: boolean } /** Each template's metadata, keyed by its own name. */ @@ -201,7 +191,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "activity", viz: "last_active", baselineOnBackfill: true, - excludedFromHealth: false, }, usage_drop: { template: "usage_drop", @@ -220,7 +209,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "activity", viz: "series", baselineOnBackfill: true, - excludedFromHealth: false, }, payment_failed: { template: "payment_failed", @@ -232,7 +220,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "billing", viz: "amount", baselineOnBackfill: false, - excludedFromHealth: false, }, cancel_scheduled: { template: "cancel_scheduled", @@ -244,7 +231,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "billing", viz: "delta", baselineOnBackfill: false, - excludedFromHealth: false, }, trial_ending_low_activation: { template: "trial_ending_low_activation", @@ -261,7 +247,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "billing", viz: "ratio", baselineOnBackfill: false, - excludedFromHealth: false, }, onboarding_stalled: { template: "onboarding_stalled", @@ -273,19 +258,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "activity", viz: "ratio", baselineOnBackfill: true, - excludedFromHealth: false, - }, - health_drop: { - template: "health_drop", - kind: "risk", - name: "Health dropped", - description: "Health fell {dropPoints} points in {windowDays} days, or turned critical", - defaultSeverity: "medium", - defaultConfig: { _tag: "health_drop", dropPoints: 20, windowDays: 7, onCritical: true }, - requiredCapability: null, - viz: "delta", - baselineOnBackfill: true, - excludedFromHealth: true, }, champion_inactive: { template: "champion_inactive", @@ -297,7 +269,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "activity", viz: "last_active", baselineOnBackfill: true, - excludedFromHealth: false, }, near_limit: { template: "near_limit", @@ -309,7 +280,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "meteredLimits", viz: "limit", baselineOnBackfill: true, - excludedFromHealth: true, }, seat_growth: { template: "seat_growth", @@ -321,7 +291,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "activity", viz: "delta", baselineOnBackfill: true, - excludedFromHealth: true, }, churned: { template: "churned", @@ -333,7 +302,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: "billing", viz: "delta", baselineOnBackfill: false, - excludedFromHealth: true, }, response_overdue: { template: "response_overdue", @@ -345,7 +313,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: null, viz: "overdue", baselineOnBackfill: false, - excludedFromHealth: false, }, resolution_overdue: { template: "resolution_overdue", @@ -357,7 +324,6 @@ export const TEMPLATES: TemplateTable = { requiredCapability: null, viz: "overdue", baselineOnBackfill: false, - excludedFromHealth: false, }, } diff --git a/packages/domain/src/customers/views.ts b/packages/domain/src/customers/views.ts index 16f58c6f0..bcddf31df 100644 --- a/packages/domain/src/customers/views.ts +++ b/packages/domain/src/customers/views.ts @@ -5,7 +5,7 @@ import { UserId } from "@hazel/schema" import { Schema } from "effect" import { EmployeeRange } from "./company" -import { HealthStatus, LifecycleStage } from "./enums" +import { LifecycleStage } from "./enums" export const ListColumn = Schema.Literals([ "name", @@ -13,7 +13,6 @@ export const ListColumn = Schema.Literals([ "stage", "plan", "mrr", - "health", "active_users_30d", "usage_trend", "last_active", @@ -34,7 +33,6 @@ export const DEFAULT_LIST_COLUMNS: ReadonlyArray = [ "stage", "plan", "mrr", - "health", "active_users_30d", "usage_trend", "last_active", @@ -51,7 +49,6 @@ export const ViewFilters = Schema.Struct({ /** Accounts with no owner. */ unowned: Schema.optionalKey(Schema.Boolean), lifecycleStages: Schema.optionalKey(Schema.Array(LifecycleStage).check(Schema.isMaxLength(20))), - healthStatuses: Schema.optionalKey(Schema.Array(HealthStatus).check(Schema.isMaxLength(20))), planNames: Schema.optionalKey( Schema.Array(Schema.String.check(Schema.isMaxLength(100))).check(Schema.isMaxLength(50)), ), diff --git a/packages/domain/src/models/channel-customer-model.ts b/packages/domain/src/models/channel-customer-model.ts index 0dc996fb0..3628bb492 100644 --- a/packages/domain/src/models/channel-customer-model.ts +++ b/packages/domain/src/models/channel-customer-model.ts @@ -2,19 +2,13 @@ * A linked channel's customer as the `OrgObject` holds it (`channel_customers`, projected by the * `CustomersObject`): what chat shows on the channel. Keyed by `channelId`. * - * Beyond the name, the account at a glance (`docs/customers/channels.md`, "In the channel"): health - * and why, stage, plan, MRR, owner, seats, last active day, open signals and the provider deep - * links. A row written before these existed (or by an older snapshot) has them null or empty. + * Beyond the name, the account at a glance (`docs/customers/channels.md`, "In the channel"): stage, + * plan, MRR, owner, seats, last active day, open signals and the provider deep links. A row written + * before these existed (or by an older snapshot) has them null or empty. */ import { ChannelId, CustomerAccountId, CustomerSignalId, OrganizationId, UserId } from "@hazel/schema" import { Schema as S } from "effect" -import { - CustomerProvider, - HealthStatus, - LifecycleStage, - SignalKind, - SignalSeverity, -} from "../customers/enums" +import { CustomerProvider, LifecycleStage, SignalKind, SignalSeverity } from "../customers/enums" import { CompanyProfile } from "../customers/company" import { JsonDate } from "./utils" @@ -42,10 +36,6 @@ export const Schema = S.Struct({ accountName: S.String, /** Optional: rows synced or cached before logos were projected have none. */ accountLogoUrl: S.optional(S.NullOr(S.String)), - healthStatus: HealthStatus, - healthScore: S.NullOr(S.Int), - /** The weakest health component's plain reason; null without a score. */ - healthWhy: S.NullOr(S.String), lifecycleStage: S.NullOr(LifecycleStage), planName: S.NullOr(S.String), /** Summed over the customer's environments in its currency. */ diff --git a/packages/domain/src/rpc/customers.ts b/packages/domain/src/rpc/customers.ts index 9020de8eb..a0381246f 100644 --- a/packages/domain/src/rpc/customers.ts +++ b/packages/domain/src/rpc/customers.ts @@ -2,7 +2,7 @@ * The Customers RPCs (`docs/customers/tech-design.md` §2, §6). Every payload names its * `organizationId`: the api Worker routes the call to that org's `CustomersObject`. * - * - `CustomerReadRpcs`: aggregates, time series, per-account detail, history pages, dry runs. + * - `CustomerReadRpcs`: aggregates, time series, per-account detail, history pages, the rule dry run. * - `CustomerQueueRpcs`: the work any member does (signals, notes, owners, tags). * - `CustomerAdminRpcs`: settings, rules, views, data sources (admins and owners; personal views * for anyone). @@ -36,7 +36,6 @@ import { Rpc, RpcGroup } from "effect/rpc" import { AccountDetail, ContactRow, - HealthDryRunResult, MetricSeries, OverviewResult, Page, @@ -50,14 +49,12 @@ import { CustomerProvider, CustomerSource, CustomersRange, - HealthStatus, IssuePriority, IssueStatus, LifecycleStage, SignalOutcome, SignalStatus, } from "../customers/enums" -import { HealthSettings } from "../customers/health" import { Account, ChannelLink, @@ -246,18 +243,17 @@ const write = customersRpc("customers:write") // --------------------------------------------------------------------------- export class CustomerReadRpcs extends RpcGroup.make( - /** KPIs, MRR movements, active users, health distribution, movers, recent churn and new. */ + /** KPIs, MRR movements, active users, movers, recent churn and new. */ read("customers.overview", { range: CustomersRange }, OverviewResult), /** * Live accounts, highest MRR first, for a client without the synced store (an agent): `query` - * matches the name or a domain; `healthStatuses` and `lifecycleStages` keep only those. + * matches the name or a domain; `lifecycleStages` keeps only those. */ read( "customers.accounts.list", { query: Schema.optionalKey(Text(200)), - healthStatuses: Schema.optionalKey(Schema.Array(HealthStatus).check(Schema.isMaxLength(4))), lifecycleStages: Schema.optionalKey(Schema.Array(LifecycleStage).check(Schema.isMaxLength(5))), ...PageRequest, }, @@ -267,7 +263,7 @@ export class CustomerReadRpcs extends RpcGroup.make( /** Everything the customer page shows beyond the synced account row. */ read("customers.account.detail", { accountId: CustomerAccountId }, AccountDetail, CustomersNotFoundError), - /** Daily series of metrics (`active_users`, `mrr`, `health_score`, source metrics) over `range`. */ + /** Daily series of metrics (`active_users`, `mrr`, source metrics) over `range`. */ read( "customers.account.series", { accountId: CustomerAccountId, metricKeys: Schema.Array(Schema.String), range: CustomersRange }, @@ -342,9 +338,6 @@ export class CustomerReadRpcs extends RpcGroup.make( RuleDryRunResult, ), - /** Score every account under draft health settings, without writing. */ - read("customers.health.dryRun", { draft: HealthSettings }, HealthDryRunResult), - read( "customers.unmatched.list", { @@ -642,11 +635,10 @@ export class CustomerAdminRpcs extends RpcGroup.make( /** Its open signals close (`auto_resolved`). */ write("customers.rule.delete", { ruleId: CustomerSignalRuleId }, Tx, CustomersNotFoundError), - /** Health weights, bands, steps; who Needs attention covers; the reporting currency; add-on plans. Recomputes soon. */ + /** Who Needs attention covers; the reporting currency; add-on plans. Recomputes soon. */ write( "customers.settings.update", { - health: Schema.optionalKey(HealthSettings), attention: Schema.optionalKey(AttentionSettings), /** An ISO 4217 code, e.g. `usd`. */ reportingCurrency: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^[A-Za-z]{3}$/))),