Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

refactor(cloudcp): split Pulse Account account runtime

rcourtmanb016548c8b0e
diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.json
index a7142e6e93..b89f84e695 100644
--- a/internal/cloudcp/portal/dist/build_manifest.json
+++ b/internal/cloudcp/portal/dist/build_manifest.json
@@ -1,5 +1,5 @@
{
- "source_hash": "fa9579f943be9f038eb58d746c28ed9bd8b04f65441c327560693d31e79c84b7",
+ "source_hash": "e975d762ce667cc33f6bb4651deca4537fe493922b6e2b15147fd4a1af43307d",
"build_inputs": [
"package.json",
"tsconfig.json",
diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.js
index 16173c83e4..a4ef0eafb2 100644
--- a/internal/cloudcp/portal/dist/portal_app.js
+++ b/internal/cloudcp/portal/dist/portal_app.js
@@ -375,73 +375,140 @@
// src/account_controller.ts
function installAccountController(deps) {
- const getAccountAPIBasePath = () => deps.store.getBootstrap().account_api_base_path;
- const getPortalAPIBasePath = () => deps.store.getBootstrap().portal_api_base_path;
- const getPortalPath = () => deps.store.getBootstrap().portal_path;
- const refreshOrRedirect = async () => {
+ document.addEventListener("click", function(event) {
+ var actionEl = asHTMLElement(event.target)?.closest("[data-action]");
+ if (!actionEl) return;
+ var action = actionEl.getAttribute("data-action") || "";
+ var accountID = actionEl.getAttribute("data-account-id") || "";
+ switch (action) {
+ case "toggle-add-workspace":
+ event.preventDefault();
+ deps.runtime.toggleAddWorkspace(accountID);
+ return;
+ case "open-billing":
+ event.preventDefault();
+ void deps.runtime.openBilling(accountID);
+ return;
+ case "toggle-team":
+ event.preventDefault();
+ deps.runtime.toggleTeam(accountID);
+ return;
+ case "invite-member":
+ event.preventDefault();
+ void deps.runtime.inviteMember(accountID);
+ return;
+ case "create-workspace":
+ event.preventDefault();
+ void deps.runtime.createWorkspace(accountID);
+ return;
+ case "workspace-manage":
+ event.preventDefault();
+ void deps.runtime.manageWorkspace(
+ event,
+ accountID,
+ actionEl.getAttribute("data-workspace-id") || "",
+ actionEl.getAttribute("data-workspace-state") || "",
+ actionEl.getAttribute("data-workspace-name") || ""
+ );
+ return;
+ case "remove-member":
+ event.preventDefault();
+ void deps.runtime.removeMember(
+ accountID,
+ actionEl.getAttribute("data-user-id") || "",
+ actionEl.getAttribute("data-member-email") || ""
+ );
+ return;
+ default:
+ return;
+ }
+ });
+ document.addEventListener("change", function(event) {
+ var target = asHTMLElement(event.target);
+ if (!target || target.getAttribute("data-action") !== "change-role") return;
+ void deps.runtime.changeRole(
+ target.getAttribute("data-account-id") || "",
+ target.getAttribute("data-user-id") || "",
+ target.value
+ );
+ });
+ }
+
+ // src/account_runtime.ts
+ function installAccountRuntime(deps) {
+ var getAccountAPIBasePath = function() {
+ return deps.store.getBootstrap().account_api_base_path;
+ };
+ var getPortalAPIBasePath = function() {
+ return deps.store.getBootstrap().portal_api_base_path;
+ };
+ var getPortalPath = function() {
+ return deps.store.getBootstrap().portal_path;
+ };
+ var refreshOrRedirect = async function() {
if (!await deps.refreshBootstrap()) {
window.location.href = getPortalPath();
return false;
}
return true;
};
- const renderAccountRuntime = () => {
+ var renderAccountRuntime = function() {
renderAccountUI(deps.store.getAccountState());
};
- const loadTeam = async (accountID) => {
- const section = getElement("team-section-" + accountID);
+ var loadTeam = async function(accountID) {
+ var section = getElement("team-section-" + accountID);
if (!section) return;
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamVisible = true;
entry.teamLoading = true;
entry.teamError = "";
entry.teamMembers = [];
});
try {
- const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members");
+ var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members");
if (!r.ok) {
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamLoading = false;
entry.teamError = "Failed to load team.";
});
return;
}
- const members = await r.json();
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ var members = await r.json();
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamLoading = false;
entry.teamError = "";
entry.teamMembers = Array.isArray(members) ? members : [];
});
} catch {
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamLoading = false;
entry.teamError = "Network error.";
});
}
};
- const refreshAccountTeamSection = async (accountID) => {
+ var refreshAccountTeamSection = async function(accountID) {
if (!await refreshOrRedirect()) {
return false;
}
- const section = getElement("team-section-" + accountID);
+ var section = getElement("team-section-" + accountID);
if (!section) {
return true;
}
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamVisible = true;
});
await loadTeam(accountID);
return true;
};
- const toggleAddWorkspace = (accountID) => {
- let shouldFocus = false;
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ var toggleAddWorkspace = function(accountID) {
+ var shouldFocus = false;
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.addWorkspaceOpen = !entry.addWorkspaceOpen;
shouldFocus = entry.addWorkspaceOpen;
});
@@ -449,32 +516,34 @@
focusElement("ws-name-" + accountID);
}
};
- const createWorkspace = async (accountID) => {
- const nameEl = getElement("ws-name-" + accountID);
+ var createWorkspace = async function(accountID) {
+ var nameEl = getElement("ws-name-" + accountID);
if (!nameEl) return;
- const name = nameEl.value.trim();
+ var name = nameEl.value.trim();
if (!name) {
nameEl.focus();
return;
}
- const spinner = getElement("ws-spinner-" + accountID);
+ var spinner = getElement("ws-spinner-" + accountID);
if (spinner) spinner.style.display = "block";
try {
- const resp = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants", {
+ var resp = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ display_name: name })
});
if (!resp.ok) {
- const err = await resp.json().catch(() => ({}));
+ var err = await resp.json().catch(function() {
+ return {};
+ });
deps.showToast(err && err.error || "Failed to create workspace", true);
return;
}
if (!await refreshOrRedirect()) {
return;
}
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.addWorkspaceOpen = false;
});
deps.showToast("Workspace created!");
@@ -484,14 +553,14 @@
if (spinner) spinner.style.display = "none";
}
};
- const suspendOrDelete = async (evt, accountID, tenantID, state, name) => {
+ var manageWorkspace = async function(evt, accountID, tenantID, state, name) {
evt.stopPropagation();
- const action = state === "active" ? "Suspend" : "Delete";
+ var action = state === "active" ? "Suspend" : "Delete";
if (!window.confirm(action + ' workspace "' + name + '"?')) return;
- const method = state === "active" ? "PATCH" : "DELETE";
- const body = state === "active" ? JSON.stringify({ state: "suspended" }) : void 0;
+ var method = state === "active" ? "PATCH" : "DELETE";
+ var body = state === "active" ? JSON.stringify({ state: "suspended" }) : void 0;
try {
- const response = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants/" + tenantID, {
+ var response = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants/" + tenantID, {
method,
headers: body ? { "Content-Type": "application/json" } : {},
body
@@ -508,15 +577,17 @@
deps.showToast("Network error.", true);
}
};
- const openBilling = async (accountID) => {
+ var openBilling = async function(accountID) {
try {
- const r = await fetch(getPortalAPIBasePath() + "/billing?account_id=" + encodeURIComponent(accountID), { method: "POST" });
+ var r = await fetch(getPortalAPIBasePath() + "/billing?account_id=" + encodeURIComponent(accountID), { method: "POST" });
if (!r.ok) {
- const err = await r.json().catch(() => ({}));
+ var err = await r.json().catch(function() {
+ return {};
+ });
deps.showToast(err && err.error || "Failed to open billing portal.", true);
return;
}
- const data = await r.json();
+ var data = await r.json();
if (data && data.url) {
window.location.href = data.url;
} else {
@@ -526,10 +597,10 @@
deps.showToast("Network error.", true);
}
};
- const toggleTeam = (accountID) => {
- let nextVisible = false;
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ var toggleTeam = function(accountID) {
+ var nextVisible = false;
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
entry.teamVisible = !entry.teamVisible;
nextVisible = entry.teamVisible;
});
@@ -537,17 +608,17 @@
void loadTeam(accountID);
}
};
- const inviteMember = async (accountID) => {
- const emailEl = getElement("invite-email-" + accountID);
- const roleEl = getElement("invite-role-" + accountID);
+ var inviteMember = async function(accountID) {
+ var emailEl = getElement("invite-email-" + accountID);
+ var roleEl = getElement("invite-role-" + accountID);
if (!emailEl || !roleEl) return;
- const email = emailEl.value.trim();
+ var email = emailEl.value.trim();
if (!email) {
emailEl.focus();
return;
}
try {
- const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members", {
+ var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, role: roleEl.value })
@@ -557,7 +628,7 @@
return;
}
if (!r.ok) {
- const err = await r.text();
+ var err = await r.text();
deps.showToast(err || "Failed to invite member.", true);
return;
}
@@ -570,9 +641,9 @@
deps.showToast("Network error.", true);
}
};
- const changeRole = async (accountID, userID, newRole) => {
+ var changeRole = async function(accountID, userID, newRole) {
try {
- const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
+ var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ role: newRole })
@@ -596,10 +667,10 @@
await loadTeam(accountID);
}
};
- const removeMember = async (accountID, userID, email) => {
+ var removeMember = async function(accountID, userID, email) {
if (!window.confirm("Remove " + email + " from this account?")) return;
try {
- const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
+ var r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
method: "DELETE"
});
if (r.status === 409) {
@@ -618,65 +689,18 @@
deps.showToast("Network error.", true);
}
};
- document.addEventListener("click", function(event) {
- const actionEl = asHTMLElement(event.target)?.closest("[data-action]");
- if (!actionEl) return;
- const action = actionEl.getAttribute("data-action") || "";
- const accountID = actionEl.getAttribute("data-account-id") || "";
- switch (action) {
- case "toggle-add-workspace":
- event.preventDefault();
- toggleAddWorkspace(accountID);
- return;
- case "open-billing":
- event.preventDefault();
- void openBilling(accountID);
- return;
- case "toggle-team":
- event.preventDefault();
- toggleTeam(accountID);
- return;
- case "invite-member":
- event.preventDefault();
- void inviteMember(accountID);
- return;
- case "create-workspace":
- event.preventDefault();
- void createWorkspace(accountID);
- return;
- case "workspace-manage":
- event.preventDefault();
- void suspendOrDelete(
- event,
- accountID,
- actionEl.getAttribute("data-workspace-id") || "",
- actionEl.getAttribute("data-workspace-state") || "",
- actionEl.getAttribute("data-workspace-name") || ""
- );
- return;
- case "remove-member":
- event.preventDefault();
- void removeMember(
- accountID,
- actionEl.getAttribute("data-user-id") || "",
- actionEl.getAttribute("data-member-email") || ""
- );
- return;
- default:
- return;
- }
- });
- document.addEventListener("change", function(event) {
- const target = asHTMLElement(event.target);
- if (!target || target.getAttribute("data-action") !== "change-role") return;
- void changeRole(
- target.getAttribute("data-account-id") || "",
- target.getAttribute("data-user-id") || "",
- target.value
- );
- });
deps.store.subscribeAccount(renderAccountRuntime);
deps.store.subscribeBootstrap(renderAccountRuntime);
+ return {
+ toggleAddWorkspace,
+ openBilling,
+ toggleTeam,
+ inviteMember,
+ createWorkspace,
+ manageWorkspace,
+ removeMember,
+ changeRole
+ };
}
// src/auth_controller.ts
@@ -927,11 +951,14 @@
installAuthController({
store: portalStore
});
- installAccountController({
+ var accountRuntime = installAccountRuntime({
store: portalStore,
refreshBootstrap,
showToast
});
+ installAccountController({
+ runtime: accountRuntime
+ });
portalStore.subscribeBootstrap(function() {
renderPortalApp();
});
diff --git a/internal/cloudcp/portal/frontend/src/account_controller.test.ts b/internal/cloudcp/portal/frontend/src/account_controller.test.ts
index c4d59db09b..050e147b55 100644
--- a/internal/cloudcp/portal/frontend/src/account_controller.test.ts
+++ b/internal/cloudcp/portal/frontend/src/account_controller.test.ts
@@ -1,142 +1,61 @@
-import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { installAccountController } from './account_controller';
-import { createPortalStore } from './store';
-import type { PortalBootstrapData } from './types';
-
-function jsonResponse(payload: unknown, ok = true, status = ok ? 200 : 500) {
- return {
- ok,
- status,
- json: vi.fn().mockResolvedValue(payload),
- text: vi.fn().mockResolvedValue(typeof payload === 'string' ? payload : JSON.stringify(payload)),
- };
-}
-
-async function flushAsync() {
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- await Promise.resolve();
- await new Promise(function(resolve) {
- setTimeout(resolve, 0);
- });
-}
-
-const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | 'accounts'> = {
- public_site_url: 'https://pulserelay.pro',
- support_email: '[email protected]',
- commercial_api_base_url: 'https://license.pulserelay.pro',
- portal_path: '/portal',
- bootstrap_path: '/api/portal/bootstrap',
- magic_link_request_path: '/api/public/magic-link/request',
- signup_path: '/signup',
- logout_path: '/auth/logout',
- account_api_base_path: '/api/accounts',
- portal_api_base_path: '/api/portal',
-};
-
-const deps = {
- store: createPortalStore(bootstrapDefaults, {
- authenticated: true,
- email: '[email protected]',
- }),
- refreshBootstrap: vi.fn(),
- showToast: vi.fn(),
-};
describe('account controller', function() {
- beforeAll(function() {
- installAccountController(deps);
- });
-
beforeEach(function() {
document.body.innerHTML = '';
vi.restoreAllMocks();
- deps.store.setBootstrap({
- authenticated: true,
- email: '[email protected]',
- });
- deps.store.updateAccountState(function(accountState) {
- accountState.byAccountID = {};
- }, { notify: false });
- deps.refreshBootstrap = vi.fn().mockResolvedValue(true);
- deps.showToast = vi.fn();
});
- it('creates a workspace through the managed account action flow', async function() {
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ tenant_id: 't_123' })));
+ it('routes account actions to the matching runtime handlers', function() {
+ var runtime = {
+ toggleAddWorkspace: vi.fn(),
+ openBilling: vi.fn(),
+ toggleTeam: vi.fn(),
+ inviteMember: vi.fn(),
+ createWorkspace: vi.fn(),
+ manageWorkspace: vi.fn(),
+ removeMember: vi.fn(),
+ changeRole: vi.fn(),
+ };
+
+ installAccountController({ runtime: runtime });
document.body.innerHTML =
'<button id="toggle" data-action="toggle-add-workspace" data-account-id="acct_1">Toggle</button>' +
- '<div id="add-ws-form-acct_1" class="add-workspace-form">' +
- '<input id="ws-name-acct_1" value="Acme Corp">' +
- '<div id="ws-spinner-acct_1" style="display:none"></div>' +
+ '<button id="billing" data-action="open-billing" data-account-id="acct_1">Billing</button>' +
+ '<button id="team" data-action="toggle-team" data-account-id="acct_1">Team</button>' +
+ '<button id="invite" data-action="invite-member" data-account-id="acct_1">Invite</button>' +
'<button id="create" data-action="create-workspace" data-account-id="acct_1">Create</button>' +
- '</div>';
+ '<button id="manage" data-action="workspace-manage" data-account-id="acct_1" data-workspace-id="ws_1" data-workspace-state="active" data-workspace-name="Alpha">Manage</button>' +
+ '<button id="remove" data-action="remove-member" data-account-id="acct_1" data-user-id="u1" data-member-email="[email protected]">Remove</button>' +
+ '<select id="role" data-action="change-role" data-account-id="acct_1" data-user-id="u1"><option value="admin">Admin</option></select>';
document.getElementById('toggle')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- expect(document.getElementById('add-ws-form-acct_1')?.classList.contains('visible')).toBe(true);
- expect(deps.store.getAccountState().byAccountID.acct_1.addWorkspaceOpen).toBe(true);
-
- document.getElementById('create')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- await flushAsync();
+ expect(runtime.toggleAddWorkspace).toHaveBeenCalledWith('acct_1');
- expect(fetch).toHaveBeenCalledWith(
- '/api/accounts/acct_1/tenants',
- expect.objectContaining({
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ display_name: 'Acme Corp' }),
- })
- );
- expect(deps.refreshBootstrap).toHaveBeenCalled();
- expect(deps.showToast).toHaveBeenCalledWith('Workspace created!');
- expect(deps.store.getAccountState().byAccountID.acct_1.addWorkspaceOpen).toBe(false);
- expect((document.getElementById('ws-spinner-acct_1') as HTMLElement).style.display).toBe('none');
- });
+ document.getElementById('billing')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(runtime.openBilling).toHaveBeenCalledWith('acct_1');
- it('loads and updates team membership from delegated team actions', async function() {
- vi.stubGlobal(
- 'fetch',
- vi.fn()
- .mockResolvedValueOnce(jsonResponse([{ email: '[email protected]', role: 'owner', user_id: 'u1' }]))
- .mockResolvedValueOnce(jsonResponse({}))
- .mockResolvedValueOnce(jsonResponse([{ email: '[email protected]', role: 'admin', user_id: 'u1' }]))
- );
+ document.getElementById('team')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(runtime.toggleTeam).toHaveBeenCalledWith('acct_1');
- document.body.innerHTML =
- '<button id="team-toggle" data-action="toggle-team" data-account-id="acct_1">Team</button>' +
- '<div id="team-section-acct_1" class="team-section" data-actor-role="owner">' +
- '<table><tbody id="team-list-acct_1"></tbody></table>' +
- '<input id="invite-email-acct_1">' +
- '<select id="invite-role-acct_1"><option value="admin">Admin</option></select>' +
- '</div>';
+ document.getElementById('invite')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(runtime.inviteMember).toHaveBeenCalledWith('acct_1');
- document.getElementById('team-toggle')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
- await flushAsync();
+ document.getElementById('create')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(runtime.createWorkspace).toHaveBeenCalledWith('acct_1');
- expect(deps.store.getAccountState().byAccountID.acct_1.teamVisible).toBe(true);
- expect(deps.store.getAccountState().byAccountID.acct_1.teamMembers).toHaveLength(1);
- var roleSelect = document.querySelector('[data-action="change-role"]') as HTMLSelectElement | null;
- expect(roleSelect).not.toBeNull();
- expect(roleSelect?.value).toBe('owner');
+ document.getElementById('manage')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(runtime.manageWorkspace).toHaveBeenCalledWith(expect.any(MouseEvent), 'acct_1', 'ws_1', 'active', 'Alpha');
- roleSelect!.value = 'admin';
- roleSelect!.dispatchEvent(new Event('change', { bubbles: true }));
- await flushAsync();
+ document.getElementById('remove')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(runtime.removeMember).toHaveBeenCalledWith('acct_1', 'u1', '[email protected]');
- expect(fetch).toHaveBeenNthCalledWith(1, '/api/accounts/acct_1/members');
- expect(fetch).toHaveBeenNthCalledWith(
- 2,
- '/api/accounts/acct_1/members/u1',
- expect.objectContaining({
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ role: 'admin' }),
- })
- );
- expect(deps.refreshBootstrap).toHaveBeenCalled();
- expect(deps.showToast).toHaveBeenCalledWith('Role updated.');
+ var role = document.getElementById('role') as HTMLSelectElement;
+ role.value = 'admin';
+ role.dispatchEvent(new Event('change', { bubbles: true }));
+ expect(runtime.changeRole).toHaveBeenCalledWith('acct_1', 'u1', 'admin');
});
});
diff --git a/internal/cloudcp/portal/frontend/src/account_controller.ts b/internal/cloudcp/portal/frontend/src/account_controller.ts
index a267601d1a..1db1331fc0 100644
--- a/internal/cloudcp/portal/frontend/src/account_controller.ts
+++ b/internal/cloudcp/portal/frontend/src/account_controller.ts
@@ -1,301 +1,41 @@
-import { asHTMLElement, focusElement, getElement, renderAccountUI as renderAccountUIState } from './account_view';
-import { ensurePortalAccountUIEntry } from './state';
-import type { PortalStore } from './store';
-import type { PortalTeamMember } from './types';
+import { asHTMLElement } from './account_view';
+import type { AccountRuntime } from './account_runtime';
export interface AccountControllerDeps {
- store: PortalStore;
- refreshBootstrap(): Promise<boolean>;
- showToast(message: string, isError?: boolean): void;
+ runtime: AccountRuntime;
}
export function installAccountController(deps: AccountControllerDeps): void {
- const getAccountAPIBasePath = (): string => deps.store.getBootstrap().account_api_base_path;
- const getPortalAPIBasePath = (): string => deps.store.getBootstrap().portal_api_base_path;
- const getPortalPath = (): string => deps.store.getBootstrap().portal_path;
-
- const refreshOrRedirect = async (): Promise<boolean> => {
- if (!await deps.refreshBootstrap()) {
- window.location.href = getPortalPath();
- return false;
- }
- return true;
- };
-
- const renderAccountRuntime = (): void => {
- renderAccountUIState(deps.store.getAccountState());
- };
-
- const loadTeam = async (accountID: string): Promise<void> => {
- const section = getElement<HTMLElement>('team-section-' + accountID);
- if (!section) return;
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamVisible = true;
- entry.teamLoading = true;
- entry.teamError = '';
- entry.teamMembers = [];
- });
- try {
- const r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members');
- if (!r.ok) {
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamLoading = false;
- entry.teamError = 'Failed to load team.';
- });
- return;
- }
- const members = await r.json() as PortalTeamMember[];
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamLoading = false;
- entry.teamError = '';
- entry.teamMembers = Array.isArray(members) ? members : [];
- });
- } catch {
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamLoading = false;
- entry.teamError = 'Network error.';
- });
- }
- };
-
- const refreshAccountTeamSection = async (accountID: string): Promise<boolean> => {
- if (!await refreshOrRedirect()) {
- return false;
- }
- const section = getElement<HTMLElement>('team-section-' + accountID);
- if (!section) {
- return true;
- }
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamVisible = true;
- });
- await loadTeam(accountID);
- return true;
- };
-
- const toggleAddWorkspace = (accountID: string): void => {
- let shouldFocus = false;
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.addWorkspaceOpen = !entry.addWorkspaceOpen;
- shouldFocus = entry.addWorkspaceOpen;
- });
- if (shouldFocus) {
- focusElement('ws-name-' + accountID);
- }
- };
-
- const createWorkspace = async (accountID: string): Promise<void> => {
- const nameEl = getElement<HTMLInputElement>('ws-name-' + accountID);
- if (!nameEl) return;
- const name = nameEl.value.trim();
- if (!name) {
- nameEl.focus();
- return;
- }
- const spinner = getElement<HTMLElement>('ws-spinner-' + accountID);
- if (spinner) spinner.style.display = 'block';
- try {
- const resp = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ display_name: name }),
- });
- if (!resp.ok) {
- const err = await resp.json().catch(() => ({}));
- deps.showToast((err && err.error) || 'Failed to create workspace', true);
- return;
- }
- if (!await refreshOrRedirect()) {
- return;
- }
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.addWorkspaceOpen = false;
- });
- deps.showToast('Workspace created!');
- } catch {
- deps.showToast('Network error. Please try again.', true);
- } finally {
- if (spinner) spinner.style.display = 'none';
- }
- };
-
- const suspendOrDelete = async (evt: Event, accountID: string, tenantID: string, state: string, name: string): Promise<void> => {
- evt.stopPropagation();
- const action = state === 'active' ? 'Suspend' : 'Delete';
- if (!window.confirm(action + ' workspace "' + name + '"?')) return;
- const method = state === 'active' ? 'PATCH' : 'DELETE';
- const body = state === 'active' ? JSON.stringify({ state: 'suspended' }) : undefined;
- try {
- const response = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants/' + tenantID, {
- method,
- headers: body ? { 'Content-Type': 'application/json' } : {},
- body,
- });
- if (!response.ok) {
- deps.showToast('Failed to ' + action.toLowerCase() + ' workspace.', true);
- return;
- }
- if (!await refreshOrRedirect()) {
- return;
- }
- deps.showToast(action + 'd workspace.');
- } catch {
- deps.showToast('Network error.', true);
- }
- };
-
- const openBilling = async (accountID: string): Promise<void> => {
- try {
- const r = await fetch(getPortalAPIBasePath() + '/billing?account_id=' + encodeURIComponent(accountID), { method: 'POST' });
- if (!r.ok) {
- const err = await r.json().catch(() => ({}));
- deps.showToast((err && err.error) || 'Failed to open billing portal.', true);
- return;
- }
- const data = await r.json();
- if (data && data.url) {
- window.location.href = data.url;
- } else {
- deps.showToast('Failed to open billing portal.', true);
- }
- } catch {
- deps.showToast('Network error.', true);
- }
- };
-
- const toggleTeam = (accountID: string): void => {
- let nextVisible = false;
- deps.store.updateAccountState((accountState) => {
- const entry = ensurePortalAccountUIEntry(accountState, accountID);
- entry.teamVisible = !entry.teamVisible;
- nextVisible = entry.teamVisible;
- });
- if (nextVisible) {
- void loadTeam(accountID);
- }
- };
-
- const inviteMember = async (accountID: string): Promise<void> => {
- const emailEl = getElement<HTMLInputElement>('invite-email-' + accountID);
- const roleEl = getElement<HTMLSelectElement>('invite-role-' + accountID);
- if (!emailEl || !roleEl) return;
- const email = emailEl.value.trim();
- if (!email) {
- emailEl.focus();
- return;
- }
- try {
- const r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ email, role: roleEl.value }),
- });
- if (r.status === 409) {
- deps.showToast('Member already exists.', true);
- return;
- }
- if (!r.ok) {
- const err = await r.text();
- deps.showToast(err || 'Failed to invite member.', true);
- return;
- }
- emailEl.value = '';
- if (!await refreshAccountTeamSection(accountID)) {
- return;
- }
- deps.showToast('Member invited!');
- } catch {
- deps.showToast('Network error.', true);
- }
- };
-
- const changeRole = async (accountID: string, userID: string, newRole: string): Promise<void> => {
- try {
- const r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ role: newRole }),
- });
- if (r.status === 409) {
- deps.showToast('Cannot demote last owner.', true);
- await loadTeam(accountID);
- return;
- }
- if (!r.ok) {
- deps.showToast('Failed to update role.', true);
- await loadTeam(accountID);
- return;
- }
- if (!await refreshAccountTeamSection(accountID)) {
- return;
- }
- deps.showToast('Role updated.');
- } catch {
- deps.showToast('Network error.', true);
- await loadTeam(accountID);
- }
- };
-
- const removeMember = async (accountID: string, userID: string, email: string): Promise<void> => {
- if (!window.confirm('Remove ' + email + ' from this account?')) return;
- try {
- const r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
- method: 'DELETE',
- });
- if (r.status === 409) {
- deps.showToast('Cannot remove last owner.', true);
- return;
- }
- if (!r.ok) {
- deps.showToast('Failed to remove member.', true);
- return;
- }
- if (!await refreshAccountTeamSection(accountID)) {
- return;
- }
- deps.showToast('Member removed.');
- } catch {
- deps.showToast('Network error.', true);
- }
- };
-
document.addEventListener('click', function(event) {
- const actionEl = asHTMLElement(event.target)?.closest('[data-action]');
+ var actionEl = asHTMLElement(event.target)?.closest('[data-action]');
if (!actionEl) return;
- const action = actionEl.getAttribute('data-action') || '';
- const accountID = actionEl.getAttribute('data-account-id') || '';
+ var action = actionEl.getAttribute('data-action') || '';
+ var accountID = actionEl.getAttribute('data-account-id') || '';
switch (action) {
case 'toggle-add-workspace':
event.preventDefault();
- toggleAddWorkspace(accountID);
+ deps.runtime.toggleAddWorkspace(accountID);
return;
case 'open-billing':
event.preventDefault();
- void openBilling(accountID);
+ void deps.runtime.openBilling(accountID);
return;
case 'toggle-team':
event.preventDefault();
- toggleTeam(accountID);
+ deps.runtime.toggleTeam(accountID);
return;
case 'invite-member':
event.preventDefault();
- void inviteMember(accountID);
+ void deps.runtime.inviteMember(accountID);
return;
case 'create-workspace':
event.preventDefault();
- void createWorkspace(accountID);
+ void deps.runtime.createWorkspace(accountID);
return;
case 'workspace-manage':
event.preventDefault();
- void suspendOrDelete(
+ void deps.runtime.manageWorkspace(
event,
accountID,
actionEl.getAttribute('data-workspace-id') || '',
@@ -305,7 +45,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
return;
case 'remove-member':
event.preventDefault();
- void removeMember(
+ void deps.runtime.removeMember(
accountID,
actionEl.getAttribute('data-user-id') || '',
actionEl.getAttribute('data-member-email') || '',
@@ -317,15 +57,12 @@ export function installAccountController(deps: AccountControllerDeps): void {
});
document.addEventListener('change', function(event) {
- const target = asHTMLElement(event.target) as HTMLSelectElement | null;
+ var target = asHTMLElement(event.target) as HTMLSelectElement | null;
if (!target || target.getAttribute('data-action') !== 'change-role') return;
- void changeRole(
+ void deps.runtime.changeRole(
target.getAttribute('data-account-id') || '',
target.getAttribute('data-user-id') || '',
target.value,
);
});
-
- deps.store.subscribeAccount(renderAccountRuntime);
- deps.store.subscribeBootstrap(renderAccountRuntime);
}
diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.test.ts b/internal/cloudcp/portal/frontend/src/account_runtime.test.ts
new file mode 100644
index 0000000000..97ea3f378d
--- /dev/null
+++ b/internal/cloudcp/portal/frontend/src/account_runtime.test.ts
@@ -0,0 +1,140 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { installAccountRuntime } from './account_runtime';
+import { createPortalStore } from './store';
+import type { PortalBootstrapData } from './types';
+
+function jsonResponse(payload: unknown, ok = true, status = ok ? 200 : 500) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ text: vi.fn().mockResolvedValue(typeof payload === 'string' ? payload : JSON.stringify(payload)),
+ };
+}
+
+async function flushAsync() {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ await new Promise(function(resolve) {
+ setTimeout(resolve, 0);
+ });
+}
+
+const bootstrapDefaults: Omit<PortalBootstrapData, 'authenticated' | 'email' | 'accounts'> = {
+ public_site_url: 'https://pulserelay.pro',
+ support_email: '[email protected]',
+ commercial_api_base_url: 'https://license.pulserelay.pro',
+ portal_path: '/portal',
+ bootstrap_path: '/api/portal/bootstrap',
+ magic_link_request_path: '/api/public/magic-link/request',
+ signup_path: '/signup',
+ logout_path: '/auth/logout',
+ account_api_base_path: '/api/accounts',
+ portal_api_base_path: '/api/portal',
+};
+
+const deps = {
+ store: createPortalStore(bootstrapDefaults, {
+ authenticated: true,
+ email: '[email protected]',
+ }),
+ refreshBootstrap: vi.fn(),
+ showToast: vi.fn(),
+};
+
+describe('account runtime', function() {
+ var runtime: ReturnType<typeof installAccountRuntime>;
+
+ beforeAll(function() {
+ runtime = installAccountRuntime(deps);
+ });
+
+ beforeEach(function() {
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+ deps.store.setBootstrap({
+ authenticated: true,
+ email: '[email protected]',
+ });
+ deps.store.updateAccountState(function(accountState) {
+ accountState.byAccountID = {};
+ }, { notify: false });
+ deps.refreshBootstrap = vi.fn().mockResolvedValue(true);
+ deps.showToast = vi.fn();
+ });
+
+ it('creates a workspace through the managed account action flow', async function() {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ tenant_id: 't_123' })));
+
+ document.body.innerHTML =
+ '<div id="add-ws-form-acct_1" class="add-workspace-form">' +
+ '<input id="ws-name-acct_1" value="Acme Corp">' +
+ '<div id="ws-spinner-acct_1" style="display:none"></div>' +
+ '</div>';
+
+ runtime.toggleAddWorkspace('acct_1');
+ expect(document.getElementById('add-ws-form-acct_1')?.classList.contains('visible')).toBe(true);
+ expect(deps.store.getAccountState().byAccountID.acct_1.addWorkspaceOpen).toBe(true);
+
+ await runtime.createWorkspace('acct_1');
+ await flushAsync();
+
+ expect(fetch).toHaveBeenCalledWith(
+ '/api/accounts/acct_1/tenants',
+ expect.objectContaining({
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ display_name: 'Acme Corp' }),
+ })
+ );
+ expect(deps.refreshBootstrap).toHaveBeenCalled();
+ expect(deps.showToast).toHaveBeenCalledWith('Workspace created!');
+ expect(deps.store.getAccountState().byAccountID.acct_1.addWorkspaceOpen).toBe(false);
+ expect((document.getElementById('ws-spinner-acct_1') as HTMLElement).style.display).toBe('none');
+ });
+
+ it('loads and updates team membership from runtime actions', async function() {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn()
+ .mockResolvedValueOnce(jsonResponse([{ email: '[email protected]', role: 'owner', user_id: 'u1' }]))
+ .mockResolvedValueOnce(jsonResponse({}))
+ .mockResolvedValueOnce(jsonResponse([{ email: '[email protected]', role: 'admin', user_id: 'u1' }]))
+ );
+
+ document.body.innerHTML =
+ '<div id="team-section-acct_1" class="team-section" data-actor-role="owner">' +
+ '<table><tbody id="team-list-acct_1"></tbody></table>' +
+ '<input id="invite-email-acct_1">' +
+ '<select id="invite-role-acct_1"><option value="admin">Admin</option></select>' +
+ '</div>';
+
+ runtime.toggleTeam('acct_1');
+ await flushAsync();
+
+ expect(deps.store.getAccountState().byAccountID.acct_1.teamVisible).toBe(true);
+ expect(deps.store.getAccountState().byAccountID.acct_1.teamMembers).toHaveLength(1);
+ var roleSelect = document.querySelector('[data-action="change-role"]') as HTMLSelectElement | null;
+ expect(roleSelect).not.toBeNull();
+ expect(roleSelect?.value).toBe('owner');
+
+ await runtime.changeRole('acct_1', 'u1', 'admin');
+ await flushAsync();
+
+ expect(fetch).toHaveBeenNthCalledWith(1, '/api/accounts/acct_1/members');
+ expect(fetch).toHaveBeenNthCalledWith(
+ 2,
+ '/api/accounts/acct_1/members/u1',
+ expect.objectContaining({
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ role: 'admin' }),
+ })
+ );
+ expect(deps.refreshBootstrap).toHaveBeenCalled();
+ expect(deps.showToast).toHaveBeenCalledWith('Role updated.');
+ });
+});
diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.ts b/internal/cloudcp/portal/frontend/src/account_runtime.ts
new file mode 100644
index 0000000000..618a4bca99
--- /dev/null
+++ b/internal/cloudcp/portal/frontend/src/account_runtime.ts
@@ -0,0 +1,301 @@
+import { focusElement, getElement, renderAccountUI as renderAccountUIState } from './account_view';
+import { ensurePortalAccountUIEntry } from './state';
+import type { PortalStore } from './store';
+import type { PortalTeamMember } from './types';
+
+export interface AccountRuntimeDeps {
+ store: PortalStore;
+ refreshBootstrap(): Promise<boolean>;
+ showToast(message: string, isError?: boolean): void;
+}
+
+export interface AccountRuntime {
+ toggleAddWorkspace(accountID: string): void;
+ openBilling(accountID: string): Promise<void>;
+ toggleTeam(accountID: string): void;
+ inviteMember(accountID: string): Promise<void>;
+ createWorkspace(accountID: string): Promise<void>;
+ manageWorkspace(event: Event, accountID: string, tenantID: string, state: string, name: string): Promise<void>;
+ removeMember(accountID: string, userID: string, email: string): Promise<void>;
+ changeRole(accountID: string, userID: string, newRole: string): Promise<void>;
+}
+
+export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime {
+ var getAccountAPIBasePath = function(): string {
+ return deps.store.getBootstrap().account_api_base_path;
+ };
+
+ var getPortalAPIBasePath = function(): string {
+ return deps.store.getBootstrap().portal_api_base_path;
+ };
+
+ var getPortalPath = function(): string {
+ return deps.store.getBootstrap().portal_path;
+ };
+
+ var refreshOrRedirect = async function(): Promise<boolean> {
+ if (!await deps.refreshBootstrap()) {
+ window.location.href = getPortalPath();
+ return false;
+ }
+ return true;
+ };
+
+ var renderAccountRuntime = function(): void {
+ renderAccountUIState(deps.store.getAccountState());
+ };
+
+ var loadTeam = async function(accountID: string): Promise<void> {
+ var section = getElement<HTMLElement>('team-section-' + accountID);
+ if (!section) return;
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamVisible = true;
+ entry.teamLoading = true;
+ entry.teamError = '';
+ entry.teamMembers = [];
+ });
+ try {
+ var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members');
+ if (!r.ok) {
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamLoading = false;
+ entry.teamError = 'Failed to load team.';
+ });
+ return;
+ }
+ var members = await r.json() as PortalTeamMember[];
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamLoading = false;
+ entry.teamError = '';
+ entry.teamMembers = Array.isArray(members) ? members : [];
+ });
+ } catch {
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamLoading = false;
+ entry.teamError = 'Network error.';
+ });
+ }
+ };
+
+ var refreshAccountTeamSection = async function(accountID: string): Promise<boolean> {
+ if (!await refreshOrRedirect()) {
+ return false;
+ }
+ var section = getElement<HTMLElement>('team-section-' + accountID);
+ if (!section) {
+ return true;
+ }
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamVisible = true;
+ });
+ await loadTeam(accountID);
+ return true;
+ };
+
+ var toggleAddWorkspace = function(accountID: string): void {
+ var shouldFocus = false;
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.addWorkspaceOpen = !entry.addWorkspaceOpen;
+ shouldFocus = entry.addWorkspaceOpen;
+ });
+ if (shouldFocus) {
+ focusElement('ws-name-' + accountID);
+ }
+ };
+
+ var createWorkspace = async function(accountID: string): Promise<void> {
+ var nameEl = getElement<HTMLInputElement>('ws-name-' + accountID);
+ if (!nameEl) return;
+ var name = nameEl.value.trim();
+ if (!name) {
+ nameEl.focus();
+ return;
+ }
+ var spinner = getElement<HTMLElement>('ws-spinner-' + accountID);
+ if (spinner) spinner.style.display = 'block';
+ try {
+ var resp = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ display_name: name }),
+ });
+ if (!resp.ok) {
+ var err = await resp.json().catch(function() { return {}; });
+ deps.showToast((err && err.error) || 'Failed to create workspace', true);
+ return;
+ }
+ if (!await refreshOrRedirect()) {
+ return;
+ }
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.addWorkspaceOpen = false;
+ });
+ deps.showToast('Workspace created!');
+ } catch {
+ deps.showToast('Network error. Please try again.', true);
+ } finally {
+ if (spinner) spinner.style.display = 'none';
+ }
+ };
+
+ var manageWorkspace = async function(evt: Event, accountID: string, tenantID: string, state: string, name: string): Promise<void> {
+ evt.stopPropagation();
+ var action = state === 'active' ? 'Suspend' : 'Delete';
+ if (!window.confirm(action + ' workspace "' + name + '"?')) return;
+ var method = state === 'active' ? 'PATCH' : 'DELETE';
+ var body = state === 'active' ? JSON.stringify({ state: 'suspended' }) : undefined;
+ try {
+ var response = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants/' + tenantID, {
+ method: method,
+ headers: body ? { 'Content-Type': 'application/json' } : {},
+ body: body,
+ });
+ if (!response.ok) {
+ deps.showToast('Failed to ' + action.toLowerCase() + ' workspace.', true);
+ return;
+ }
+ if (!await refreshOrRedirect()) {
+ return;
+ }
+ deps.showToast(action + 'd workspace.');
+ } catch {
+ deps.showToast('Network error.', true);
+ }
+ };
+
+ var openBilling = async function(accountID: string): Promise<void> {
+ try {
+ var r = await fetch(getPortalAPIBasePath() + '/billing?account_id=' + encodeURIComponent(accountID), { method: 'POST' });
+ if (!r.ok) {
+ var err = await r.json().catch(function() { return {}; });
+ deps.showToast((err && err.error) || 'Failed to open billing portal.', true);
+ return;
+ }
+ var data = await r.json();
+ if (data && data.url) {
+ window.location.href = data.url;
+ } else {
+ deps.showToast('Failed to open billing portal.', true);
+ }
+ } catch {
+ deps.showToast('Network error.', true);
+ }
+ };
+
+ var toggleTeam = function(accountID: string): void {
+ var nextVisible = false;
+ deps.store.updateAccountState(function(accountState) {
+ var entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamVisible = !entry.teamVisible;
+ nextVisible = entry.teamVisible;
+ });
+ if (nextVisible) {
+ void loadTeam(accountID);
+ }
+ };
+
+ var inviteMember = async function(accountID: string): Promise<void> {
+ var emailEl = getElement<HTMLInputElement>('invite-email-' + accountID);
+ var roleEl = getElement<HTMLSelectElement>('invite-role-' + accountID);
+ if (!emailEl || !roleEl) return;
+ var email = emailEl.value.trim();
+ if (!email) {
+ emailEl.focus();
+ return;
+ }
+ try {
+ var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ email: email, role: roleEl.value }),
+ });
+ if (r.status === 409) {
+ deps.showToast('Member already exists.', true);
+ return;
+ }
+ if (!r.ok) {
+ var err = await r.text();
+ deps.showToast(err || 'Failed to invite member.', true);
+ return;
+ }
+ emailEl.value = '';
+ if (!await refreshAccountTeamSection(accountID)) {
+ return;
+ }
+ deps.showToast('Member invited!');
+ } catch {
+ deps.showToast('Network error.', true);
+ }
+ };
+
+ var changeRole = async function(accountID: string, userID: string, newRole: string): Promise<void> {
+ try {
+ var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ role: newRole }),
+ });
+ if (r.status === 409) {
+ deps.showToast('Cannot demote last owner.', true);
+ await loadTeam(accountID);
+ return;
+ }
+ if (!r.ok) {
+ deps.showToast('Failed to update role.', true);
+ await loadTeam(accountID);
+ return;
+ }
+ if (!await refreshAccountTeamSection(accountID)) {
+ return;
+ }
+ deps.showToast('Role updated.');
+ } catch {
+ deps.showToast('Network error.', true);
+ await loadTeam(accountID);
+ }
+ };
+
+ var removeMember = async function(accountID: string, userID: string, email: string): Promise<void> {
+ if (!window.confirm('Remove ' + email + ' from this account?')) return;
+ try {
+ var r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
+ method: 'DELETE',
+ });
+ if (r.status === 409) {
+ deps.showToast('Cannot remove last owner.', true);
+ return;
+ }
+ if (!r.ok) {
+ deps.showToast('Failed to remove member.', true);
+ return;
+ }
+ if (!await refreshAccountTeamSection(accountID)) {
+ return;
+ }
+ deps.showToast('Member removed.');
+ } catch {
+ deps.showToast('Network error.', true);
+ }
+ };
+
+ deps.store.subscribeAccount(renderAccountRuntime);
+ deps.store.subscribeBootstrap(renderAccountRuntime);
+
+ return {
+ toggleAddWorkspace: toggleAddWorkspace,
+ openBilling: openBilling,
+ toggleTeam: toggleTeam,
+ inviteMember: inviteMember,
+ createWorkspace: createWorkspace,
+ manageWorkspace: manageWorkspace,
+ removeMember: removeMember,
+ changeRole: changeRole,
+ };
+}
diff --git a/internal/cloudcp/portal/frontend/src/shell.ts b/internal/cloudcp/portal/frontend/src/shell.ts
index 46c7d03718..8c75adb0e5 100644
--- a/internal/cloudcp/portal/frontend/src/shell.ts
+++ b/internal/cloudcp/portal/frontend/src/shell.ts
@@ -4,6 +4,7 @@ import {
} from './runtime';
import { createAnonymousBootstrap } from './store';
import { installAccountController } from './account_controller';
+import { installAccountRuntime } from './account_runtime';
import { installAuthController } from './auth_controller';
import {
renderAuthenticatedPortalHTML,
@@ -77,12 +78,16 @@ installAuthController({
store: portalStore,
});
-installAccountController({
+var accountRuntime = installAccountRuntime({
store: portalStore,
refreshBootstrap: refreshBootstrap,
showToast: showToast
});
+installAccountController({
+ runtime: accountRuntime,
+});
+
portalStore.subscribeBootstrap(function() {
renderPortalApp();
});