Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 7 additions & 22 deletions apps/backend/src/routes/mcp.http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -708,8 +708,6 @@ describe("MCP server", () => {
'["globex.com"]',
"Scale",
129_900,
"at_risk",
41,
"active",
1,
)
Expand All @@ -720,9 +718,7 @@ describe("MCP server", () => {
'["initech.io"]',
"Team",
19_900,
"healthy",
88,
"active",
"trialing",
0,
)
const evidence = JSON.stringify({
Expand All @@ -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()
Expand All @@ -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,
})
Expand All @@ -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)

Expand All @@ -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({
Expand Down
45 changes: 3 additions & 42 deletions apps/backend/src/routes/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import {
type ContactRow,
CustomersRange,
type Event as CustomerEvent,
HealthStatus,
type Invoice,
type Kpi,
LifecycleStage,
Expand Down Expand Up @@ -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<HealthStatus>
lifecycleStages?: ReadonlyArray<LifecycleStage>
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -706,12 +702,6 @@ const pageOut = <A, R>(key: string, page: PageOf<A>, row: (a: A) => R) =>

const customerDetail = (detail: AccountDetail, signals: PageOf<Signal>) => {
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),
Expand All @@ -729,23 +719,6 @@ const customerDetail = (detail: AccountDetail, signals: PageOf<Signal>) => {
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),
Expand Down Expand Up @@ -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),
Expand All @@ -867,7 +835,7 @@ const customerTools: ReadonlyArray<Tool> = [
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(
Expand All @@ -892,18 +860,13 @@ const customerTools: ReadonlyArray<Tool> = [
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] },
Expand All @@ -916,12 +879,10 @@ const customerTools: ReadonlyArray<Tool> = [
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<PageOf<Account>>(
ctx,
Expand All @@ -936,7 +897,7 @@ const customerTools: ReadonlyArray<Tool> = [
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") }, [
Expand Down
28 changes: 9 additions & 19 deletions apps/backend/src/rpc/handlers/customers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* - Settings, rules, shared views, data sources, unmatched records, the demo seed: admins and owners.
*
* Mutations answer the `customers:<orgId>` 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"
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -598,8 +589,7 @@ const ACTION_EVENT = {
reopen: ["signal.reopened", "Reopened"],
} satisfies Record<SignalAction, readonly [string, string]>

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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
Loading
Loading