Skip to content
Open
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
17 changes: 17 additions & 0 deletions .changeset/34221-unpaid-org-limit-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
'@object-ui/console': patch
---

feat(console): the create-workspace dialog shows the unpaid-organization limit refusal and its next step

Clause-②: yes (widening) — `@object-ui/i18n` gains `organization.errors.unpaidOrganizationLimitReached` and `organization.viewPlans` in every locale
Metadata-protocol: none

The hosted control plane refuses a create past its cap on free organizations with 403 `UNPAID_ORGANIZATION_LIMIT_REACHED`. The body carries a sentence in the request's language (`message` and `userMessage`) and `details.next_step`, either `upgrade_to_team` or `contact_support`. The create-workspace dialog now recognizes this code:

- It shows the control plane's own `userMessage`, which names the next step. A refusal that arrives without one shows the console's sentence instead (new key `organization.errors.unpaidOrganizationLimitReached`, in all eleven console locales). That sentence names no number and no plan.
- When the next step is `upgrade_to_team` and the host serves its upgrade entry (`upgradeUrl` on `/api/v1/runtime/config`), the dialog also shows a link to it (new key `organization.viewPlans`). The console never builds that address itself. If the host serves no entry, no link is shown and the sentence alone gives the step. A `contact_support` step shows no link, because the sentence already names the contact address.

better-auth's own organization-limit refusal (`YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS`) and every other code behave as before. Nothing to migrate.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@
* words are the host's, never the console's (ADR-0060: the console draws a
* generic block and names no product).
*
* A create refused past the hosted control plane's cap on free organizations
* (`UNPAID_ORGANIZATION_LIMIT_REACHED`) shows the control plane's own sentence,
* which names the next step. When that step is upgrading one of the account's
* Free organizations and the host serves its upgrade entry
* (`getUpgradeUrl()`), the dialog also draws a link to it. The console never
* composes that address: no served entry, no link, and the sentence alone
* carries the step.
*
* @module
*/

Expand All @@ -43,7 +51,8 @@ import type { OrganizationEditionChoice } from '@objectstack/spec/api';
import { useObjectTranslation } from '@object-ui/i18n';
import { Loader2 } from 'lucide-react';
import { provisionProductionEnvironment } from './provisionEnvironment.js';
import { resolveOrgErrorMessage } from './orgErrorMessage.js';
import { readOrgCreateNextStep, resolveOrgErrorMessage } from './orgErrorMessage.js';
import { getUpgradeUrl } from '../../runtime-config.js';
import { emailDomain, isPublicMailboxDomain, registrableLabel } from '../../utils/emailDomain.js';

/**
Expand Down Expand Up @@ -211,6 +220,9 @@ export function CreateWorkspaceDialog({
const slug = nameToSlug(name);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// The host's upgrade entry, set only for a refusal whose next step is an
// upgrade and only when the host serves one.
const [upgradeUrl, setUpgradeUrl] = useState<string | undefined>(undefined);
// Defense-in-depth: the toolbar button that opens this dialog is already
// hidden when `multiOrgEnabled === false`, but if a future caller opens the
// dialog by another path we still want to fail fast with a friendly message
Expand Down Expand Up @@ -247,6 +259,7 @@ export function CreateWorkspaceDialog({
setName(defaultNameRef.current);
setEdition(undefined);
setError(null);
setUpgradeUrl(undefined);
}
}, [open]);

Expand All @@ -265,6 +278,7 @@ export function CreateWorkspaceDialog({

setIsSubmitting(true);
setError(null);
setUpgradeUrl(undefined);

try {
const org = await createWithGeneratedSlug(
Expand Down Expand Up @@ -304,6 +318,7 @@ export function CreateWorkspaceDialog({
defaultValue: 'Failed to create organization',
}),
);
setUpgradeUrl(readOrgCreateNextStep(err) === 'upgrade_to_team' ? getUpgradeUrl() : undefined);
} finally {
setIsSubmitting(false);
}
Expand Down Expand Up @@ -376,6 +391,17 @@ export function CreateWorkspaceDialog({
{error}
</p>
)}
{error && upgradeUrl && (
<a
href={upgradeUrl}
target="_blank"
rel="noopener noreferrer"
data-testid="workspace-create-upgrade"
className="text-sm font-medium underline underline-offset-2 hover:no-underline"
>
{t('organization.viewPlans', { defaultValue: 'View plans and upgrade' })}
</a>
)}
</div>

<DialogFooter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ vi.mock('../provisionEnvironment', () => ({
provisionProductionEnvironment: vi.fn(),
}));

/** The host's served upgrade entry (`getUpgradeUrl()`); `undefined` is a host that serves none. */
let servedUpgradeUrl: string | undefined;
vi.mock('../../../runtime-config', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getUpgradeUrl: () => servedUpgradeUrl,
}));

const createOrganization = vi.fn();
const getAuthConfig = vi.fn();
/** Extra `useAuth()` fields a case sets: `user`, `organizations`, `isOrganizationsLoading`. */
Expand Down Expand Up @@ -77,6 +84,7 @@ beforeEach(() => {
browserZone = BROWSER_ZONE;
packLang = null;
authState = {};
servedUpgradeUrl = undefined;
zoneReader = vi
.spyOn(Intl.DateTimeFormat.prototype, 'resolvedOptions')
.mockImplementation(function (this: Intl.DateTimeFormat) {
Expand Down Expand Up @@ -413,6 +421,74 @@ describe('the organization-limit refusal is shown in the session language (objec
}
});

describe('the unpaid-organization limit refusal shows its sentence and next step (objectstack#34221)', () => {
// The hosted control plane's 403, as `toAuthError` carries it: `code`,
// the request-language sentence as `message` and `userMessage`, and
// `details.next_step` (cloud#4308).
const UPGRADE_URL = 'https://cloud.example.test/billing';
const ZH_SENTENCE =
'你已拥有 2 个免费组织,每个账号最多 2 个。要再创建组织,请先把其中一个 Free 组织升级到 Team:Team 组织不占这个名额。被邀请加入的组织不计入。';
const unpaidRefusal = (nextStep: string, withUserMessage = true) =>
Object.assign(new Error(ZH_SENTENCE), {
code: 'UNPAID_ORGANIZATION_LIMIT_REACHED',
status: 403,
...(withUserMessage ? { userMessage: ZH_SENTENCE } : {}),
details: { unpaid_organization_limit: 2, unpaid_organizations: 2, next_step: nextStep },
});

async function submitRefused(err: Error) {
createOrganization.mockRejectedValue(err);
render(<CreateWorkspaceDialog open onOpenChange={() => {}} />);
await settleAuthConfig();
fillAndSubmit();
return screen.findByTestId('workspace-create-error');
}

it("upgrade_to_team: shows the producer's sentence and a link to the host's upgrade entry, without retrying", async () => {
packLang = 'zh-Hans';
servedUpgradeUrl = UPGRADE_URL;
const shown = await submitRefused(unpaidRefusal('upgrade_to_team'));
expect(shown).toHaveTextContent(ZH_SENTENCE);
const link = screen.getByTestId('workspace-create-upgrade');
expect(link).toHaveAttribute('href', UPGRADE_URL);
expect(link).toHaveTextContent((builtInLocales['zh-Hans'] as { organization: { viewPlans: string } }).organization.viewPlans);
expect(createOrganization).toHaveBeenCalledTimes(1);
expect(provisionMock).not.toHaveBeenCalled();
});

it('upgrade_to_team on a host that serves no upgrade entry: the sentence alone, no link', async () => {
const shown = await submitRefused(unpaidRefusal('upgrade_to_team'));
expect(shown).toHaveTextContent(ZH_SENTENCE);
expect(screen.queryByTestId('workspace-create-upgrade')).toBeNull();
});

it('contact_support: the sentence (which names the address), no upgrade link', async () => {
servedUpgradeUrl = UPGRADE_URL;
await submitRefused(unpaidRefusal('contact_support'));
expect(screen.queryByTestId('workspace-create-upgrade')).toBeNull();
});

it('a refusal without userMessage shows the console pack sentence', async () => {
packLang = 'zh-Hans';
const shown = await submitRefused(unpaidRefusal('upgrade_to_team', false));
const expected = (builtInLocales['zh-Hans'] as { organization: { errors: Record<string, string> } }).organization
.errors.unpaidOrganizationLimitReached;
expect(typeof expected).toBe('string');
expect(shown).toHaveTextContent(expected);
});

it("CONTROL: better-auth's organization-limit refusal draws no upgrade link", async () => {
servedUpgradeUrl = UPGRADE_URL;
await submitRefused(
Object.assign(new Error('You have reached the maximum number of organizations'), {
code: 'YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS',
status: 403,
}),
);
expect(screen.queryByTestId('workspace-create-upgrade')).toBeNull();
});
});

describe("draws the host's organization-create choices (objectstack#31988)", () => {
// Host-shaped words: the console spells none of its own, so a case reads
// the text it was served back off the dialog (ADR-0060).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { describe, it, expect } from 'vitest';
import {
ORG_ERROR_MESSAGE_KEYS,
orgDeleteRefusalRows,
readOrgCreateNextStep,
readOrgDeleteRefusal,
resolveOrgErrorMessage,
} from '../orgErrorMessage';
Expand Down Expand Up @@ -222,6 +223,83 @@ describe('#28124 — YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS (the p
});
});

describe('objectstack#34221 — UNPAID_ORGANIZATION_LIMIT_REACHED (the hosted cap on free organizations)', () => {
// The cloud control plane refuses a create past its cap with 403 and a flat
// `{ code, message, userMessage, details: { unpaid_organization_limit,
// unpaid_organizations, next_step } }`, the sentence in the request's
// language (cloud#4308, cloud PR #4626). The auth client's `toAuthError`
// carries `code`, `userMessage` and `details` onto the thrown error.
const CODE = 'UNPAID_ORGANIZATION_LIMIT_REACHED';
const KEY = 'organization.errors.unpaidOrganizationLimitReached';
const ZH_SENTENCE =
'你已拥有 2 个免费组织,每个账号最多 2 个。要再创建组织,请先把其中一个 Free 组织升级到 Team:Team 组织不占这个名额。被邀请加入的组织不计入。';
const refusal = (fields: { userMessage?: string; details?: unknown; message?: string }) =>
Object.assign(new Error(fields.message ?? ZH_SENTENCE), {
code: CODE,
status: 403,
...(fields.userMessage !== undefined ? { userMessage: fields.userMessage } : {}),
...(fields.details !== undefined ? { details: fields.details } : {}),
});
const packValue = (lang: string): unknown =>
KEY.split('.').reduce<unknown>(
(n, k) => (n as Record<string, unknown> | undefined)?.[k],
builtInLocales[lang as keyof typeof builtInLocales],
);

it("shows the producer's localized userMessage, not the console pack sentence", () => {
const shown = resolveOrgErrorMessage(refusal({ userMessage: ZH_SENTENCE }), tZh);
expect(shown).toBe(ZH_SENTENCE);
expect(shown).not.toBe(packValue('zh-Hans'));
});

it('falls back to the console pack sentence when the refusal carries no userMessage', () => {
const shown = resolveOrgErrorMessage(
refusal({ message: 'You own 2 free organizations, and one account may own at most 2.' }),
tZh,
);
expect(shown).toBe(packValue('zh-Hans'));
expect(shown).toMatch(/\p{Script=Han}/u);
});

it('a blank userMessage is no sentence: the pack fallback is shown', () => {
expect(resolveOrgErrorMessage(refusal({ userMessage: ' ' }), tZh)).toBe(packValue('zh-Hans'));
});

it('every pack defines the fallback with its own sentence and no number in it', () => {
const en = packValue('en');
for (const lang of Object.keys(builtInLocales)) {
const value = packValue(lang);
expect(typeof value, `${lang} lacks ${KEY}`).toBe('string');
expect(value as string, `${lang} names a number the console does not know`).not.toMatch(/\p{Nd}/u);
if (lang !== 'en') expect(value, `${lang} still serves the English sentence`).not.toBe(en);
}
});

it('reads the next step from details.next_step, for this code only', () => {
expect(readOrgCreateNextStep(refusal({ details: { next_step: 'upgrade_to_team' } }))).toBe('upgrade_to_team');
expect(readOrgCreateNextStep(refusal({ details: { next_step: 'contact_support' } }))).toBe('contact_support');
// A step this console does not know, no details, or another code: no step.
expect(readOrgCreateNextStep(refusal({ details: { next_step: 'buy_more' } }))).toBeUndefined();
expect(readOrgCreateNextStep(refusal({}))).toBeUndefined();
expect(
readOrgCreateNextStep(
Object.assign(withCode('YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS', 'x'), {
details: { next_step: 'upgrade_to_team' },
}),
),
).toBeUndefined();
expect(readOrgCreateNextStep(new Error('upgrade_to_team'))).toBeUndefined();
});

it("CONTROL: better-auth's organization-limit code still maps to its pack sentence and ignores userMessage", () => {
const err = Object.assign(
withCode('YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS', 'You have reached the maximum number of organizations'),
{ userMessage: 'a sentence the console must not show for this row' },
);
expect(resolveOrgErrorMessage(err, tZh)).toBe(at('organization.errors.organizationLimitReached'));
});
});

describe('#4474 — the mapping table itself', () => {
it('every mapped code resolves to a key the zh pack actually defines', () => {
// Guards the class of typo that only shows up as a raw i18n key on screen,
Expand All @@ -243,6 +321,8 @@ describe('#4474 — the mapping table itself', () => {
'ORGANIZATION_ALREADY_EXISTS',
'ORGANIZATION_CREATION_DISABLED',
'ORGANIZATION_SLUG_ALREADY_TAKEN',
// objectstack#34221: the hosted control plane's cap on free organizations (cloud#4308).
'UNPAID_ORGANIZATION_LIMIT_REACHED',
// objectstack#33650: better-auth 1.7.12 `create-invitation` refuses an address that already holds a membership.
'USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION',
'USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION',
Expand Down
Loading
Loading