Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

12.9 KB
Raw Blame
// Server admin › Billing: a bill's page shows what was paid from the ledger's money (never seconds), links its
// invoices to the Stripe Dashboard, and offers only the actions that can run.
import type { AdminBillDetail, SelfServeData } from '@linedesk/actions'
import { SIGNUP_DEFAULTS } from '@linedesk/db/types'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'

const data: Record<string, unknown> = {}
const useQuery = vi.fn((key: string | null) => ({
  data: key ? data[key] : undefined,
  error: null,
  reload: async () => {},
}))
vi.mock('../cachedQuery.ts', async original => ({
  ...(await original<object>()),
  useQuery,
  setQueryData: () => {},
  refreshQuery: async () => {},
}))
const admin = vi.hoisted(() => ({ calls: [] as unknown[], answers: {} as Record<string, unknown> }))
vi.mock('./api.ts', async original => ({
  ...(await original<object>()),
  runAdmin: async (name: string, input: unknown) => {
    admin.calls.push([name, input])
    return admin.answers[name]
  },
}))

const { Billing, billActions, SelfServeCard, SignupRulesCard, setSelfServe, setStripeTax } = await import(
  './Billing.tsx'
)
const { i18n } = await import('../i18n/index.tsx')

const bill: AdminBillDetail = {
  id: 'bill_1',
  kind: 'cloud',
  status: 'comped',
  interval: 'month',
  owner: { id: 'u1', email: '[email protected]', name: 'Mike Brennan' },
  workspaces: [{ id: 'ws1', name: 'Brightwater Plumbing & Heating', extraCalls: 10, busyCallers: 0 }],
  balanceMicros: 12_500_000,
  reservedMicros: 0,
  heldForReviewAt: null,
  cardRiskLevel: 'elevated',
  createdAt: '2026-11-01T10:00:00.000Z',
  stripeCustomerId: 'cus_1',
  stripeSubscriptionId: 'sub_1',
  dashboardUrl: 'https://dashboard.stripe.com/test',
  trialEndsAt: null,
  currentPeriodStart: '2026-11-01T00:00:00.000Z',
  currentPeriodEnd: '2026-12-01T00:00:00.000Z',
  autoRecharge: true,
  rechargeThresholdCents: 500,
  rechargeAmountCents: 2000,
  rechargeCapBaseCents: 5000,
  rechargeCapCents: 5000,
  concurrentCallsCap: null,
  rulesConcurrentCalls: 4,
  suspendReason: null,
  rechargeFailedAt: null,
  // A comped bill's calls record their seconds at $0: paid shows $0.00, not the seconds' price.
  usage: [{ workspaceId: 'ws1', workspaceName: 'Brightwater Plumbing & Heating', seconds: 600, paidMicros: 0 }],
  ledger: [],
  recharges: [],
  invoices: [
    {
      invoiceId: 'in_1',
      kind: 'recharge',
      number: 'LD-0001',
      status: 'paid',
      totalCents: 2000,
      taxCents: 0,
      createdAt: '2026-11-02T10:00:00.000Z',
    },
  ],
  refundable: [],
  members: [{ id: 'u1', email: '[email protected]', name: 'Mike Brennan' }],
  otherBills: [],
  unbilledWorkspaces: [],
}

const render = () =>
  renderToStaticMarkup(
    <Billing id="bill_1" onOpen={() => {}} notify={() => {}} keysRef={{ current: null }} data={null} />,
  )

test("a bill's page: paid from the ledger, invoices in the Stripe Dashboard, only the actions that can run", () => {
  data['admin.billing.bill.bill_1'] = bill
  const html = render()
  expect(html).toContain('$0.00')
  expect(html).toContain('href="https://dashboard.stripe.com/test/invoices/in_1"')
  expect(html).toContain('href="https://dashboard.stripe.com/test/customers/cus_1"')
  expect(html).toContain('href="#admin/workspaces/ws1"')
  // The extra calls at the same time the owner bought (LIN-450): on the bill and per workspace.
  expect(html).toContain('10 extra calls bought')
  expect(html).toContain('+10')
  // Comped: Resume and Suspend, no Comp again (the actions sit in the page header: a button, or in its ⋯ menu).
  const actions = billActions(i18n().t, bill, () => {})
  const labels = actions.map(a => a.label)
  expect(labels).toContain('Resume…')
  expect(labels).toContain('Suspend…')
  expect(labels).not.toContain('Comp…')
  expect(actions.filter(a => !a.menu).map(a => a.id)).toEqual(['credit', 'refund', 'resume'])
  // Nothing paid is left to refund, and nobody else to give the bill to: both say why (the Refund button's on the page).
  expect(actions.find(a => a.id === 'refund')?.disabledReason).toBe('No payment has anything left to refund.')
  expect(actions.find(a => a.id === 'owner')?.disabledReason).toBe('No other member to give it to.')
  expect(html).toContain('No payment has anything left to refund.')
  // Radar's risk of the trial's card check is shown, not only stored.
  expect(html).toContain('Radar risk')
  expect(html).toContain('Elevated')
})

test("a bill's page shows its Stripe customer's name and email, once Stripe answered", () => {
  data['admin.billing.bill.bill_1'] = bill
  data['admin.billing.customer.bill_1'] = {
    name: 'Brightwater Plumbing & Heating',
    email: '[email protected]',
  }
  const html = render()
  expect(html).toContain('Brightwater Plumbing &amp; Heating')
  expect(html).toContain('[email protected]')
  delete data['admin.billing.customer.bill_1']
})

test('without Stripe in effect a refund says it needs Stripe, and the bill links nowhere outside', () => {
  data['admin.billing.bill.bill_1'] = { ...bill, dashboardUrl: null }
  const html = render()
  expect(html).toContain('Refunds need billing through Stripe.')
  expect(html).not.toContain('dashboard.stripe.com')
  expect(html).toContain('LD-0001')
})

const selfServe = (over: Partial<SelfServeData>): SelfServeData => ({
  on: true,
  billingInEffect: true,
  open: true,
  closedBecause: null,
  turnstileReady: true,
  rules: SIGNUP_DEFAULTS,
  defaults: SIGNUP_DEFAULTS,
  problems: [],
  termsMissing: [],
  ...over,
})
const renderList = (tab: string | null) =>
  renderToStaticMarkup(<Billing id={tab} onOpen={() => {}} notify={() => {}} keysRef={{ current: null }} data={null} />)
/** Self-serve sign-up and its limits: on Server admin › Sign-up & access (Billing › Sign-up from LIN-693 until the nav groups). */
const renderSignup = () =>
  renderToStaticMarkup(
    <>
      <SelfServeCard notify={() => {}} />
      <SignupRulesCard notify={() => {}} />
    </>,
  )

test('sign-up switched on without Turnstile keys says plainly that it is closed, and why', () => {
  data['admin.billing.selfServe'] = selfServe({
    open: false,
    closedBecause: 'bot_check_missing',
    turnstileReady: false,
  })
  const html = renderSignup()
  expect(html).toContain('Closed')
  expect(html).toContain('Sign-up is switched on but closed: the bot check (Cloudflare Turnstile) has no keys.')
  // The bot check's keys are connected under Providers, like every service's (LIN-693).
  expect(html).toContain('href="#admin/providers/bot_check"')
  // Adding the keys is the fix; the page never points to switching the bot check off.
  expect(html).not.toContain('turn the bot check off')
  expect(html).not.toContain('The bot check is off.')
})

test('sign-up switched on without the terms in the environment is closed and names the variables (A9)', () => {
  data['admin.billing.selfServe'] = selfServe({
    open: false,
    closedBecause: 'terms_missing',
    termsMissing: ['TERMS_VERSION', 'PRIVACY_URL'],
  })
  const html = renderSignup()
  expect(html).toContain('Closed')
  expect(html).toContain('Sign-up is switched on but closed: set TERMS_VERSION, PRIVACY_URL in the server')
})

test('with the bot check off, the sign-up limits warn that only the limits protect the server', () => {
  data['admin.billing.selfServe'] = selfServe({ rules: { ...SIGNUP_DEFAULTS, turnstile: false } })
  const html = renderSignup()
  expect(html).toContain('The bot check is off. Anyone, bots included, can ask for sign-up codes')
})

test('open sign-up says so, and its limits are editable with plain labels', () => {
  data['admin.billing.selfServe'] = selfServe({})
  const html = renderSignup()
  expect(html).toContain('aria-checked="true" aria-label="Self-serve sign-up"')
  expect(html).not.toContain('>Closed<')
  expect(html).toContain('Anyone can sign up and start a trial now.')
  expect(html).not.toContain('switched on but closed')
  expect(html).toContain('Sign-up limits')
  expect(html).toContain('Sign-up codes per email address, per hour')
  expect(html).toContain('Blocked email domains')
  expect(html).toContain('Hold for review at Radar risk')
})

test('the bills list filters by status with chips (no counts) and colour badges', () => {
  data['admin.billing.bills'] = [{ ...bill, status: 'trialing' }]
  const html = renderList('bills')
  expect(html).toContain('aria-pressed="true"')
  expect(html).toContain('k-badge-info')
  // Only statuses that have bills get a chip, without a count (like every chip row).
  expect(html).toContain('>Trial</button>')
  expect(html).not.toContain('k-chip-n')
  expect(html).not.toContain('>Past due</button>')
  // Nothing canceled: no "All bills" chip, it would show the same.
  expect(html).not.toContain('>All bills</button>')
})

test('the bills list hides canceled bills by default; the Canceled and All bills chips show them', () => {
  data['admin.billing.bills'] = [
    { ...bill, id: 'bill_live', status: 'active' },
    {
      ...bill,
      id: 'bill_gone',
      status: 'canceled',
      owner: { id: 'u2', email: '[email protected]', name: 'Gone Owner' },
    },
  ]
  const html = renderList('bills')
  expect(html).toContain('>Current</button>')
  expect(html).toContain('>Canceled</button>')
  expect(html).toContain('>All bills</button>')
  expect(html).toContain('[email protected]')
  expect(html).not.toContain('[email protected]')
})

test("Billing's own page: lines like Features under Operations and Setup, each a link to its page; no tab strip", () => {
  data['admin.billing.summary'] = {
    billing: { stripeConnected: false },
    selfServe: { on: false, open: false, closedBecause: null, termsMissing: [] },
    bills: { pending_payment: 0, trialing: 1, active: 3, past_due: 1, suspended: 1, canceled: 0, comped: 0 },
    held: 1,
    newTrials: 1,
    events: { waiting: 1, failed: 1, unhandled: 1 },
    automaticTax: false,
  }
  const html = renderList(null)
  expect(html).toContain('<h3 class="k-line-group">Operations</h3>')
  expect(html).toContain('<h3 class="k-line-group">Setup</h3>')
  expect(html.indexOf('Operations')).toBeLessThan(html.indexOf('Setup'))
  // Operations' three lines; Setup: the billing switch, Stripe Tax (both lines here, no Stripe page), Prices and rules.
  expect(html.match(/class="k-card k-feature"/g)).toHaveLength(6)
  expect(html).toContain('aria-label="Bill workspaces through Stripe"')
  expect(html).toContain('aria-label="Stripe Tax"')
  expect(html).not.toContain('href="#admin/billing/stripe"')
  expect(html).toContain('href="#admin/billing/rules"><span>Change</span></a>')
  expect(html).toContain('href="#admin/billing/review"><span>Open</span></a>')
  expect(html).toContain('href="#admin/billing/bills?status=')
  expect(html).toContain('href="#admin/billing/events')
  // Sign-up has one place, Sign-up &amp; access: no line for it here.
  expect(html).not.toContain('href="#admin/access"')
  expect(html).not.toContain('href="#admin/billing/signup"')
  // The states, as badges in the marks' tones: failed events need the admin, owing and held bills a look.
  expect(html).toContain('<span class="k-badge k-badge-warning">1 held</span>')
  expect(html).toContain('<span class="k-badge k-badge-warning">2 owe money</span>')
  expect(html).toContain('<span class="k-badge k-badge-danger">2 need a look</span>')
  expect(html).not.toContain('ib-tab')
  expect(html).not.toContain('Bills by status')
})

test('a part of Billing shows only that part: no status line, no tabs above it', () => {
  data['admin.billing.bills'] = [{ ...bill, status: 'trialing' }]
  const html = renderList('bills')
  expect(html).not.toContain('ib-tab')
  expect(html).not.toContain('Not connected')
})

describe('the Stripe Tax and self-serve sign-up switches act at once, without asking why (Janik, 2026-11-26)', () => {
  test('Stripe Tax: saves only its own field, says what it means, and asks for the address count only when turned on', async () => {
    admin.calls = []
    admin.answers = {
      'billingRules.set': { effective: { automaticTax: true } },
      'billing.adminTaxAddressMissing': { taxAddressMissing: 2 },
    }
    const missing: (number | null)[] = []
    const text = await setStripeTax(true, count => missing.push(count))
    expect(text).toBe('Stripe Tax is on: running subscriptions are taxed from their next invoice')
    expect(admin.calls[0]).toEqual(['billingRules.set', { rules: { automaticTax: true } }])
    await vi.waitFor(() => expect(missing).toEqual([null, 2]))
    admin.calls = []
    expect(await setStripeTax(false)).toBe(
      'Stripe Tax is off: running subscriptions stop collecting tax from their next invoice',
    )
    expect(admin.calls).toEqual([['billingRules.set', { rules: { automaticTax: false } }]])
  })

  test('self-serve sign-up: one call with only the switch, the toast says the new state', async () => {
    admin.calls = []
    admin.answers = { 'signup.setSelfServe': selfServe({ on: true }) }
    expect(await setSelfServe(true)).toBe('Self-serve sign-up is on')
    expect(admin.calls).toEqual([['signup.setSelfServe', { on: true }]])
  })
})