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.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
Server admin: put a workspace on no bill onto an existing bill (PR 2045)
Janikedf69877fba3
diff --git a/apps/api/src/billing-admin.ts b/apps/api/src/billing-admin.tsindex b2308501..e868ee98 100644--- a/apps/api/src/billing-admin.ts+++ b/apps/api/src/billing-admin.ts@@ -331,6 +331,18 @@ async function billDetail(tx: Tx, billId: string): Promise<AdminBillDetail> {.leftJoin(user, eq(user.id, billing_accounts.owner_user_id)).where(ne(billing_accounts.id, billId)).orderBy(user.email)+ // Workspaces on no bill (made in Server admin › Workspaces) that this bill can take over: not a partner's client,+ // and a partner bill takes none (moveWorkspace refuses both).+ const unbilled =+ bill.kind === 'partner' || bill.status === 'canceled'+ ? []+ : await tx+ .select({ id: organization.id, name: organization.name })+ .from(organization)+ .where(+ and(isNull(organization.billingAccountId), isNull(organization.partnerId), isNull(organization.disabledAt)),+ )+ .orderBy(organization.name)return {...row!,stripeCustomerId: bill.stripe_customer_id,@@ -396,6 +408,7 @@ async function billDetail(tx: Tx, billId: string): Promise<AdminBillDetail> {refundable: await refundablePayments(tx, billId),members,otherBills: others.map(o => ({ id: o.id, kind: o.kind, status: o.status, owner: o.owner })),+ unbilledWorkspaces: unbilled,}}@@ -883,12 +896,21 @@ async function followSeats(provider: BillingProvider, bill: Bill, grows: boolean})}-async function moveSeats(provider: BillingProvider, from: Bill, to: Bill, requestId: string, extraCalls: boolean) {+async function moveSeats(+ provider: BillingProvider,+ from: Bill | null,+ to: Bill,+ requestId: string,+ extraCalls: boolean,+) {// The source shrinks first: a target charged while the source still counts the workspace is what M2 was about.- for (const [bill, grows] of [- [from, false],- [to, true],- ] as const) {+ const steps: (readonly [Bill, boolean])[] = from+ ? [+ [from, false],+ [to, true],+ ]+ : [[to, true]]+ for (const [bill, grows] of steps) {await followSeats(provider, bill, grows, requestId).catch(e =>console.error(`ALERT billing seats: bill ${bill.id} not updated after a move (${requestId})`, e),)@@ -920,19 +942,27 @@ async function moveWorkspace(.from(billing_accounts).where(eq(billing_accounts.id, input.toBillingAccountId))if (target?.kind === 'partner') throw new Reject(CLIENT_STAYS_ON_PARTNER_BILL)- if (!seen.bill) throw Reject.t('server.api.billingAdmin.moveNoBill')if (seen.bill === input.toBillingAccountId) throw Reject.t('server.api.billingAdmin.moveSameBill')- // Both balance rows, in id order (the lock order of every bill path; two moves never deadlock).- for (const id of [seen.bill, input.toBillingAccountId].sort()) await lockBalance(tx, id)+ // Both balance rows, in id order (the lock order of every bill path; two moves never deadlock). A workspace on no bill+ // (made in Server admin › Workspaces, free) has only the target's: it joins that bill and pays from then on.+ for (const id of [seen.bill, input.toBillingAccountId].filter((id): id is string => !!id).sort())+ await lockBalance(tx, id)// Read again under the locks (security review of #919, L3): a move that ran meanwhile changed it, and this one would// act on a bill the workspace already left.const [workspace] = await tx- .select({ id: organization.id, bill: organization.billingAccountId, extraCalls: organization.extraCalls })+ .select({+ id: organization.id,+ bill: organization.billingAccountId,+ partnerId: organization.partnerId,+ extraCalls: organization.extraCalls,+ }).from(organization).where(eq(organization.id, input.workspaceId)).for('update')- if (workspace?.bill !== seen.bill) throw Reject.t('server.api.billingAdmin.moveMovedMeanwhile')- const from = await billOrReject(tx, seen.bill)+ if (!workspace || workspace.bill !== seen.bill) throw Reject.t('server.api.billingAdmin.moveMovedMeanwhile')+ // A partner given meanwhile (with billing off a client can be on no bill): it stays with its partner.+ if (workspace.partnerId) throw new Reject(CLIENT_STAYS_ON_PARTNER_BILL)+ const from = seen.bill ? await billOrReject(tx, seen.bill) : nullconst to = await billOrReject(tx, input.toBillingAccountId)if (to.status === 'canceled') throw Reject.t('server.api.billingAdmin.moveToCanceled')// A bill in its trial (or still before Checkout) holds at most the sign-up rules' trial workspaces (security review of@@ -952,7 +982,7 @@ async function moveWorkspace(.innerJoin(calls, eq(calls.id, call_reservations.call_id)).where(eq(calls.workspace_id, workspace.id))if ((running?.n ?? 0) > 0) throw Reject.t('server.api.billingAdmin.moveCallsRunning')- const seats = !!from.stripe_subscription_id || !!to.stripe_subscription_id+ const seats = !!from?.stripe_subscription_id || !!to.stripe_subscription_idconst provider = seats ? await stripeOrReject(tx, providerOverride ?? undefined) : nullif (provider && !onCommit) throw new Error('billing.moveWorkspace changes seats after the commit: no onCommit given')await tx@@ -966,7 +996,7 @@ async function moveWorkspace(}).where(eq(organization.id, workspace.id))if (provider) onCommit!(() => moveSeats(provider, from, to, input.requestId, workspace.extraCalls > 0))- return { from: from.id, to: to.id }+ return { from: from?.id ?? null, to: to.id }}/**diff --git a/apps/api/src/workspace-delete-plan.ts b/apps/api/src/workspace-delete-plan.tsindex 56b747c9..634de2f8 100644--- a/apps/api/src/workspace-delete-plan.ts+++ b/apps/api/src/workspace-delete-plan.ts@@ -114,10 +114,17 @@ export async function endPlanWithDelete(prepared: EndingPlan | null | undefined,now: string,): Promise<boolean> {- const [row] = await tx- .select({ billId: organization.billingAccountId })- .from(organization)- .where(eq(organization.id, workspaceId))+ const read = (lock: boolean) => {+ const q = tx+ .select({ billId: organization.billingAccountId })+ .from(organization)+ .where(eq(organization.id, workspaceId))+ return lock ? q.for('update') : q+ }+ let [row] = await read(false)+ // A workspace on no bill: its row locked, so a move onto a bill (billing.moveWorkspace, which locks the row after the+ // target's balance) waits for the delete and then finds it gone; or it committed first and the bill is seen here.+ if (!row?.billId) [row] = await read(true)if (!row?.billId) return false// The bill's lock order (ledger.ts): its balance row first, so a workspace moved onto it waits or is seen here.await lockBalance(tx, row.billId)diff --git a/apps/api/test/billing-admin.test.ts b/apps/api/test/billing-admin.test.tsindex 33722104..64287eb7 100644--- a/apps/api/test/billing-admin.test.ts+++ b/apps/api/test/billing-admin.test.ts@@ -1297,6 +1297,33 @@ describe('moving a workspace', () => {expect(org?.billingAccountId).toBe(a.billId)})+ test('a workspace on no bill (free) joins a bill: listed on it first, then only the target seat follows in Stripe', async () => {+ const free = await createWorkspace('Cedar Street Dental')+ const to = await billWith({ stripe_subscription_id: rid('sub'), interval: 'month' })+ const stripe = fakeStripe(new Map())+ setBillingAdminProvider(stripe.provider)+ const detail = await act(operator, 'billing.adminBill', { billingAccountId: to.billId })+ expect(detail.body.data.unbilledWorkspaces).toContainEqual({+ id: free.id,+ name: 'Cedar Street Dental',+ })+ const requestId = rid('req')+ const input = { workspaceId: free.id, toBillingAccountId: to.billId, reason, requestId }+ expect((await act(operator, 'billing.moveWorkspace', input)).status).toBe(200)+ const [org] = await db.select().from(organization).where(eq(organization.id, free.id))+ expect(org?.billingAccountId).toBe(to.billId)+ expect(stripe.seats).toEqual([+ {+ subscriptionId: (await billRow(to.billId)).stripe_subscription_id,+ quantity: 2,+ prorationBehavior: 'create_prorations',+ idempotencyKey: `move_${requestId}_${to.billId}`,+ },+ ])+ const after = await act(operator, 'billing.adminBill', { billingAccountId: to.billId })+ expect(after.body.data.unbilledWorkspaces.map((w: { id: string }) => w.id)).not.toContain(free.id)+ })+test('bills without a subscription move without Stripe; not onto a canceled bill', async () => {const from = await billWith({ stripe_customer_id: null })const to = await billWith({ stripe_customer_id: null })diff --git a/apps/web/src/admin/Billing.test.tsx b/apps/web/src/admin/Billing.test.tsxindex 05c0c024..d33c70ea 100644--- a/apps/web/src/admin/Billing.test.tsx+++ b/apps/web/src/admin/Billing.test.tsx@@ -76,6 +76,7 @@ const bill: AdminBillDetail = {refundable: [],members: [{ id: 'u1', email: '[email protected]', name: 'Mike Brennan' }],otherBills: [],+ unbilledWorkspaces: [],}const render = () =>diff --git a/apps/web/src/admin/Billing.tsx b/apps/web/src/admin/Billing.tsxindex eb3dc0c4..7f30c1e2 100644--- a/apps/web/src/admin/Billing.tsx+++ b/apps/web/src/admin/Billing.tsx@@ -1432,6 +1432,7 @@ type Open =| { kind: 'concurrency' }| { kind: 'owner' }| { kind: 'move' }+ | { kind: 'attach' }const LEDGER_KIND: Record<AdminBillDetail['ledger'][number]['kind'], MessageKey> = {usage: msg('admin.bills.ledger.kind.usage'),@@ -1562,6 +1563,15 @@ export function billActions(t: Translate, bill: AdminBillDetail, open: (what: Op: undefined,run: async () => open({ kind: 'move' }),},+ {+ id: 'attach',+ menu: true,+ label: t('admin.bills.action.attach'),+ icon: 'plus',+ tip: t('admin.bills.action.attachTip'),+ disabledReason: !bill.unbilledWorkspaces.length ? t('admin.bills.action.noUnbilled') : undefined,+ run: async () => open({ kind: 'attach' }),+ },]}@@ -1951,7 +1961,9 @@ function BillDialog({ bill, open, notify, done, onClose }: DialogProps) {: '',)const [member, setMember] = useState(bill.members.find(m => m.id !== bill.owner.id)?.id ?? '')- const [workspace, setWorkspace] = useState(bill.workspaces[0]?.id ?? '')+ const [workspace, setWorkspace] = useState(+ (open.kind === 'attach' ? bill.unbilledWorkspaces[0]?.id : bill.workspaces[0]?.id) ?? '',+ )const targets = bill.otherBills.filter(b => b.status !== 'canceled')const [target, setTarget] = useState(targets[0]?.id ?? '')const [fieldError, setFieldError] = useState<string | null>(null)@@ -2238,6 +2250,36 @@ function BillDialog({ bill, open, notify, done, onClose }: DialogProps) {</FormField></ReasonDialog>)+ case 'attach':+ return (+ <ReasonDialog+ {...props}+ title={t('admin.bills.attach.title')}+ description={t('admin.bills.attach.text')}+ submit={t('admin.bills.attach.submit')}+ check={() => (workspace ? null : t('admin.bills.attach.pick'))}+ run={async (reason, requestId) => {+ await runAdmin('billing.moveWorkspace', {+ workspaceId: workspace,+ toBillingAccountId: billingAccountId,+ reason,+ requestId,+ })+ const name = bill.unbilledWorkspaces.find(w => w.id === workspace)?.name ?? ''+ return done(t('admin.bills.attach.done', { name }))+ }}+ >+ <FormField id="adm-bill-unbilled" label={t('admin.bills.move.workspace')}>+ <Select+ id="adm-bill-unbilled"+ value={workspace}+ onChange={setWorkspace}+ label={t('admin.bills.move.workspace')}+ options={bill.unbilledWorkspaces.map(w => ({ value: w.id, label: w.name }))}+ />+ </FormField>+ </ReasonDialog>+ )}}diff --git a/packages/actions/src/billing-admin.ts b/packages/actions/src/billing-admin.tsindex 75293290..bbe17ef8 100644--- a/packages/actions/src/billing-admin.ts+++ b/packages/actions/src/billing-admin.ts@@ -182,7 +182,7 @@ export const billingSetConcurrency = defineAction({export const billingMoveWorkspace = defineAction({name: 'billing.moveWorkspace',description:- 'Move a workspace to another bill: refused while it has calls running. The seat quantities of both subscriptions follow in Stripe.',+ 'Move a workspace to another bill, or put a workspace on no bill (free) on one: refused while it has calls running. The seat quantities of both subscriptions follow in Stripe.',input: z.object({ workspaceId: z.string().min(1).max(100), toBillingAccountId: billId, reason, requestId }),permission: 'instance:admin',})@@ -340,6 +340,8 @@ export type AdminBillDetail = AdminBillRow & {members: { id: string; email: string; name: string }[]/** Every other bill, to move a workspace to. */otherBills: { id: string; owner: string | null; kind: 'cloud' | 'partner'; status: AdminBillStatus }[]+ /** Workspaces on no bill (free) that this bill can take over with billing.moveWorkspace; none on a partner bill. */+ unbilledWorkspaces: { id: string; name: string }[]}export type AdminStripeEvent = {diff --git a/packages/i18n/locales/de/server.json b/packages/i18n/locales/de/server.jsonindex 73bdbb73..a07210ed 100644--- a/packages/i18n/locales/de/server.json+++ b/packages/i18n/locales/de/server.json@@ -12,7 +12,6 @@"api.billingAdmin.entryNoPeriod": "Diese Abrechnung hat gerade keinen Abrechnungszeitraum: Ein Eintrag braucht einen.","api.billingAdmin.moveCallsRunning": "Im Workspace laufen gerade Anrufe: Verschieb ihn, sobald sie beendet sind.","api.billingAdmin.moveMovedMeanwhile": "Der Workspace wurde inzwischen zu einer anderen Abrechnung verschoben: Lade neu und sieh noch einmal nach.",- "api.billingAdmin.moveNoBill": "Dieser Workspace hat keine Abrechnung; verschoben wird nur zwischen Abrechnungen.","api.billingAdmin.moveSameBill": "Der Workspace ist schon in dieser Abrechnung.","api.billingAdmin.moveToCanceled": "Ein Workspace kann nicht zu einer gekündigten Abrechnung verschoben werden.","api.billingAdmin.noBill": "keine Abrechnung mit dieser ID",diff --git a/packages/i18n/locales/en/admin.json b/packages/i18n/locales/en/admin.jsonindex 734a3e15..4164613d 100644--- a/packages/i18n/locales/en/admin.json+++ b/packages/i18n/locales/en/admin.json@@ -385,6 +385,8 @@"billing.liveRefused": "This is a dev install: live Stripe keys are refused. Use a test key.","billing.switch": "Bill workspaces through Stripe","billing.testMode": "Test mode: Stripe charges nothing.",+ "bills.action.attach": "Add workspace…",+ "bills.action.attachTip": "Put a workspace that is on no bill on this bill: it pays from then on","bills.action.cap": "Recharge cap…","bills.action.capTip": "Set how much auto recharge may charge in a month","bills.action.comp": "Comp…",@@ -398,6 +400,7 @@"bills.action.needsStripe": "Refunds need billing through Stripe.","bills.action.noOtherBill": "No other bill to move to.","bills.action.noOtherMember": "No other member to give it to.",+ "bills.action.noUnbilled": "No workspace without a bill.","bills.action.nothingToRefund": "No payment has anything left to refund.","bills.action.owner": "Transfer owner…","bills.action.ownerTip": "Give this bill to a member of its workspaces",@@ -414,6 +417,11 @@"bills.amount.placeholder": "$20.00","bills.amount.positive": "Enter an amount above zero.","bills.amount.zero": "Enter an amount other than zero.",+ "bills.attach.done": "{name} is on this bill now",+ "bills.attach.pick": "Pick the workspace.",+ "bills.attach.submit": "Add",+ "bills.attach.text": "For a workspace made in Server admin › Workspaces, which is free until then. Its calls and numbers are billed to this bill from now on, and the subscription gets a seat more in Stripe.",+ "bills.attach.title": "Add a workspace to this bill","bills.badge.held": "Held for review","bills.cap.done": "Recharge cap base set to {amount}","bills.cap.label": "Base, in dollars",diff --git a/packages/i18n/locales/en/server.json b/packages/i18n/locales/en/server.jsonindex fa5ba93b..61f51e66 100644--- a/packages/i18n/locales/en/server.json+++ b/packages/i18n/locales/en/server.json@@ -12,7 +12,6 @@"api.billingAdmin.entryNoPeriod": "This bill has no billing period now: an entry needs one.","api.billingAdmin.moveCallsRunning": "The workspace has calls running: move it once they ended.","api.billingAdmin.moveMovedMeanwhile": "The workspace moved to another bill meanwhile: reload and look again.",- "api.billingAdmin.moveNoBill": "This workspace is on no bill; moving is between bills.","api.billingAdmin.moveSameBill": "The workspace is on this bill already.","api.billingAdmin.moveToCanceled": "A workspace cannot move to a canceled bill.","api.billingAdmin.noBill": "no bill with this id",diff --git a/packages/i18n/locales/es/server.json b/packages/i18n/locales/es/server.jsonindex fd5b2047..dfa0dcdc 100644--- a/packages/i18n/locales/es/server.json+++ b/packages/i18n/locales/es/server.json@@ -12,7 +12,6 @@"api.billingAdmin.entryNoPeriod": "Esta factura no tiene ahora un período de facturación: un movimiento necesita uno.","api.billingAdmin.moveCallsRunning": "El espacio de trabajo tiene llamadas en curso: muévelo cuando terminen.","api.billingAdmin.moveMovedMeanwhile": "Mientras tanto, el espacio de trabajo pasó a otra factura: recarga y vuelve a revisar.",- "api.billingAdmin.moveNoBill": "Este espacio de trabajo no está en ninguna factura; solo se mueve entre facturas.","api.billingAdmin.moveSameBill": "El espacio de trabajo ya está en esta factura.","api.billingAdmin.moveToCanceled": "Un espacio de trabajo no puede pasar a una factura cancelada.","api.billingAdmin.noBill": "no hay ninguna factura con este id",diff --git a/packages/i18n/locales/fr/server.json b/packages/i18n/locales/fr/server.jsonindex d943d6af..2cc2a914 100644--- a/packages/i18n/locales/fr/server.json+++ b/packages/i18n/locales/fr/server.json@@ -12,7 +12,6 @@"api.billingAdmin.entryNoPeriod": "Cette facture n'a pas de période de facturation en ce moment : une écriture en nécessite une.","api.billingAdmin.moveCallsRunning": "L'espace de travail a des appels en cours : déplacez-le une fois qu'ils sont terminés.","api.billingAdmin.moveMovedMeanwhile": "L'espace de travail a été déplacé vers une autre facture entre-temps : rechargez la page et vérifiez à nouveau.",- "api.billingAdmin.moveNoBill": "Cet espace de travail ne fait partie d'aucune facture ; le déplacement se fait d'une facture à l'autre.","api.billingAdmin.moveSameBill": "L'espace de travail fait déjà partie de cette facture.","api.billingAdmin.moveToCanceled": "Un espace de travail ne peut pas être déplacé vers une facture résiliée.","api.billingAdmin.noBill": "aucune facture avec cet id",diff --git a/packages/i18n/locales/ja/server.json b/packages/i18n/locales/ja/server.jsonindex 33f1e0d1..7a4ce1ba 100644--- a/packages/i18n/locales/ja/server.json+++ b/packages/i18n/locales/ja/server.json@@ -12,7 +12,6 @@"api.billingAdmin.entryNoPeriod": "この請求には現在請求期間がありません。記録には請求期間が必要です。","api.billingAdmin.moveCallsRunning": "このワークスペースでは通話中です。通話が終わってから移動してください。","api.billingAdmin.moveMovedMeanwhile": "その間にワークスペースが別の請求に移動しました。再読み込みしてもう一度確認してください。",- "api.billingAdmin.moveNoBill": "このワークスペースはどの請求にも含まれていません。移動は請求間で行います。","api.billingAdmin.moveSameBill": "このワークスペースはすでにこの請求に含まれています。","api.billingAdmin.moveToCanceled": "キャンセルされた請求にはワークスペースを移動できません。","api.billingAdmin.noBill": "このIDの請求はありません",diff --git a/packages/i18n/locales/pt-BR/server.json b/packages/i18n/locales/pt-BR/server.jsonindex cf9427b6..94bb27b2 100644--- a/packages/i18n/locales/pt-BR/server.json+++ b/packages/i18n/locales/pt-BR/server.json@@ -12,7 +12,6 @@"api.billingAdmin.entryNoPeriod": "Esta fatura não tem período de cobrança agora: um lançamento precisa de um.","api.billingAdmin.moveCallsRunning": "O espaço de trabalho tem chamadas em andamento: mova-o quando elas terminarem.","api.billingAdmin.moveMovedMeanwhile": "Nesse meio-tempo, o espaço de trabalho passou para outra fatura: recarregue e confira de novo.",- "api.billingAdmin.moveNoBill": "Este espaço de trabalho não está em nenhuma fatura; a mudança é sempre entre faturas.","api.billingAdmin.moveSameBill": "O espaço de trabalho já está nesta fatura.","api.billingAdmin.moveToCanceled": "Um espaço de trabalho não pode ser movido para uma fatura cancelada.","api.billingAdmin.noBill": "nenhuma fatura com este id",