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): move Pulse Account account UI into store

rcourtmanadc2d4267da7
diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.json
index c6d992c3ff..5686ccee4b 100644
--- a/internal/cloudcp/portal/dist/build_manifest.json
+++ b/internal/cloudcp/portal/dist/build_manifest.json
@@ -1,5 +1,5 @@
{
- "source_hash": "b26f5b1d646f0ae7064f345dbd67a88ca9a15298b8b6fb0a945fc73435b1484b",
+ "source_hash": "c5820ed501462e9b98f77f96c6295641a192d8abb092e09e70a71e77b1fc8bb9",
"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 c3aa4b23a7..e61c39e4b9 100644
--- a/internal/cloudcp/portal/dist/portal_app.js
+++ b/internal/cloudcp/portal/dist/portal_app.js
@@ -28,6 +28,23 @@
error: ""
};
}
+ function createPortalAccountState() {
+ return {
+ byAccountID: {}
+ };
+ }
+ function ensurePortalAccountUIEntry(accountState, accountID) {
+ if (!accountState.byAccountID[accountID]) {
+ accountState.byAccountID[accountID] = {
+ addWorkspaceOpen: false,
+ teamVisible: false,
+ teamLoading: false,
+ teamError: "",
+ teamMembers: []
+ };
+ }
+ return accountState.byAccountID[accountID];
+ }
function createPortalServiceState() {
return {
openPanelID: "",
@@ -137,10 +154,12 @@
}
function createPortalStore(bootstrapDefaults2, initialBootstrap) {
var bootstrapState = normalizeBootstrap(bootstrapDefaults2, initialBootstrap);
+ var accountState = createPortalAccountState();
var loginState = createPortalLoginState();
var serviceState = createPortalServiceState();
syncLoginStateBootstrapEmail(loginState, bootstrapState.email || "");
syncServiceStateBootstrapEmail(serviceState, bootstrapState.email || "");
+ var accountSubscribers = /* @__PURE__ */ new Set();
var bootstrapSubscribers = /* @__PURE__ */ new Set();
var loginSubscribers = /* @__PURE__ */ new Set();
var serviceSubscribers = /* @__PURE__ */ new Set();
@@ -153,6 +172,9 @@
getBootstrap: function() {
return bootstrapState;
},
+ getAccountState: function() {
+ return accountState;
+ },
getLoginState: function() {
return loginState;
},
@@ -166,6 +188,13 @@
notify(bootstrapSubscribers);
return bootstrapState;
},
+ updateAccountState: function(mutator, options) {
+ mutator(accountState);
+ if (!options || options.notify !== false) {
+ notify(accountSubscribers);
+ }
+ return accountState;
+ },
updateLoginState: function(mutator, options) {
mutator(loginState);
if (!options || options.notify !== false) {
@@ -186,6 +215,12 @@
bootstrapSubscribers.delete(listener);
};
},
+ subscribeAccount: function(listener) {
+ accountSubscribers.add(listener);
+ return function() {
+ accountSubscribers.delete(listener);
+ };
+ },
subscribeLogin: function(listener) {
loginSubscribers.add(listener);
return function() {
@@ -249,76 +284,130 @@
tbody.appendChild(tr);
}
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 () => {
if (!await deps.refreshBootstrap()) {
- window.location.href = deps.getPortalPath();
+ window.location.href = getPortalPath();
return false;
}
return true;
};
- const loadTeam = async (accountID) => {
- const tbody = getElement("team-list-" + accountID);
+ const renderAddWorkspaceSection = (accountID) => {
+ const form = getElement("add-ws-form-" + accountID);
+ if (!form) return;
+ const entry = ensurePortalAccountUIEntry(deps.store.getAccountState(), accountID);
+ form.classList.toggle("visible", entry.addWorkspaceOpen);
+ };
+ const renderTeamSection = (accountID) => {
const section = getElement("team-section-" + accountID);
- if (!tbody || !section) return;
+ const tbody = getElement("team-list-" + accountID);
+ if (!section || !tbody) return;
+ const entry = ensurePortalAccountUIEntry(deps.store.getAccountState(), accountID);
const actorRole = section.getAttribute("data-actor-role") || "";
const isOwner = actorRole === "owner";
- setTbodyMessage(tbody, "Loading\u2026", false);
+ section.classList.toggle("visible", entry.teamVisible);
+ if (!entry.teamVisible) {
+ return;
+ }
+ if (entry.teamLoading) {
+ setTbodyMessage(tbody, "Loading\u2026", false);
+ return;
+ }
+ if (entry.teamError) {
+ setTbodyMessage(tbody, entry.teamError, true);
+ return;
+ }
+ if (!entry.teamMembers.length) {
+ setTbodyMessage(tbody, "No team members.", false);
+ return;
+ }
+ const allRoles = ["owner", "admin", "tech", "read_only"];
+ const nonOwnerRoles = ["admin", "tech", "read_only"];
+ tbody.textContent = "";
+ for (let i = 0; i < entry.teamMembers.length; i += 1) {
+ const member = entry.teamMembers[i];
+ const tr = document.createElement("tr");
+ const tdEmail = document.createElement("td");
+ tdEmail.textContent = member.email;
+ tr.appendChild(tdEmail);
+ const tdRole = document.createElement("td");
+ if (member.role === "owner" && !isOwner) {
+ tdRole.textContent = "owner";
+ } else {
+ const sel = document.createElement("select");
+ const roles = isOwner ? allRoles : nonOwnerRoles;
+ for (let j = 0; j < roles.length; j += 1) {
+ const opt = document.createElement("option");
+ opt.value = roles[j];
+ opt.textContent = roles[j].replace("_", " ");
+ if (member.role === roles[j]) opt.selected = true;
+ sel.appendChild(opt);
+ }
+ sel.setAttribute("data-action", "change-role");
+ sel.setAttribute("data-account-id", accountID);
+ sel.setAttribute("data-user-id", member.user_id);
+ tdRole.appendChild(sel);
+ }
+ tr.appendChild(tdRole);
+ const tdAction = document.createElement("td");
+ if (!(member.role === "owner" && !isOwner)) {
+ const btn = document.createElement("button");
+ btn.type = "button";
+ btn.className = "btn-remove";
+ btn.textContent = "Remove";
+ btn.setAttribute("data-action", "remove-member");
+ btn.setAttribute("data-account-id", accountID);
+ btn.setAttribute("data-user-id", member.user_id);
+ btn.setAttribute("data-member-email", member.email);
+ tdAction.appendChild(btn);
+ }
+ tr.appendChild(tdAction);
+ tbody.appendChild(tr);
+ }
+ };
+ const renderAccountUI = () => {
+ const state = deps.store.getAccountState();
+ const accountIDs = Object.keys(state.byAccountID);
+ for (let i = 0; i < accountIDs.length; i += 1) {
+ renderAddWorkspaceSection(accountIDs[i]);
+ renderTeamSection(accountIDs[i]);
+ }
+ };
+ const loadTeam = async (accountID) => {
+ const section = getElement("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(deps.getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members");
+ const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members");
if (!r.ok) {
- setTbodyMessage(tbody, "Failed to load team.", true);
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamLoading = false;
+ entry.teamError = "Failed to load team.";
+ });
return;
}
const members = await r.json();
- if (!members || members.length === 0) {
- setTbodyMessage(tbody, "No team members.", false);
- return;
- }
- const allRoles = ["owner", "admin", "tech", "read_only"];
- const nonOwnerRoles = ["admin", "tech", "read_only"];
- tbody.textContent = "";
- for (let i = 0; i < members.length; i += 1) {
- const member = members[i];
- const tr = document.createElement("tr");
- const tdEmail = document.createElement("td");
- tdEmail.textContent = member.email;
- tr.appendChild(tdEmail);
- const tdRole = document.createElement("td");
- if (member.role === "owner" && !isOwner) {
- tdRole.textContent = "owner";
- } else {
- const sel = document.createElement("select");
- const roles = isOwner ? allRoles : nonOwnerRoles;
- for (let j = 0; j < roles.length; j += 1) {
- const opt = document.createElement("option");
- opt.value = roles[j];
- opt.textContent = roles[j].replace("_", " ");
- if (member.role === roles[j]) opt.selected = true;
- sel.appendChild(opt);
- }
- sel.setAttribute("data-action", "change-role");
- sel.setAttribute("data-account-id", accountID);
- sel.setAttribute("data-user-id", member.user_id);
- tdRole.appendChild(sel);
- }
- tr.appendChild(tdRole);
- const tdAction = document.createElement("td");
- if (!(member.role === "owner" && !isOwner)) {
- const btn = document.createElement("button");
- btn.type = "button";
- btn.className = "btn-remove";
- btn.textContent = "Remove";
- btn.setAttribute("data-action", "remove-member");
- btn.setAttribute("data-account-id", accountID);
- btn.setAttribute("data-user-id", member.user_id);
- btn.setAttribute("data-member-email", member.email);
- tdAction.appendChild(btn);
- }
- tr.appendChild(tdAction);
- tbody.appendChild(tr);
- }
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamLoading = false;
+ entry.teamError = "";
+ entry.teamMembers = Array.isArray(members) ? members : [];
+ });
} catch {
- setTbodyMessage(tbody, "Network error.", true);
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamLoading = false;
+ entry.teamError = "Network error.";
+ });
}
};
const refreshAccountTeamSection = async (accountID) => {
@@ -329,16 +418,21 @@
if (!section) {
return true;
}
- section.classList.add("visible");
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamVisible = true;
+ });
await loadTeam(accountID);
return true;
};
const toggleAddWorkspace = (accountID) => {
- const form = getElement("add-ws-form-" + accountID);
- if (!form) return;
- const visible = form.classList.contains("visible");
- form.classList.toggle("visible", !visible);
- if (!visible) {
+ let shouldFocus = false;
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.addWorkspaceOpen = !entry.addWorkspaceOpen;
+ shouldFocus = entry.addWorkspaceOpen;
+ });
+ if (shouldFocus) {
const input = getElement("ws-name-" + accountID);
if (input) input.focus();
}
@@ -354,7 +448,7 @@
const spinner = getElement("ws-spinner-" + accountID);
if (spinner) spinner.style.display = "block";
try {
- const resp = await fetch(deps.getAccountAPIBasePath() + "/" + accountID + "/tenants", {
+ const resp = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ display_name: name })
@@ -367,6 +461,10 @@
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);
@@ -381,7 +479,7 @@
const method = state === "active" ? "PATCH" : "DELETE";
const body = state === "active" ? JSON.stringify({ state: "suspended" }) : void 0;
try {
- const response = await fetch(deps.getAccountAPIBasePath() + "/" + accountID + "/tenants/" + tenantID, {
+ const response = await fetch(getAccountAPIBasePath() + "/" + accountID + "/tenants/" + tenantID, {
method,
headers: body ? { "Content-Type": "application/json" } : {},
body
@@ -400,7 +498,7 @@
};
const openBilling = async (accountID) => {
try {
- const r = await fetch(deps.getPortalAPIBasePath() + "/billing?account_id=" + encodeURIComponent(accountID), { method: "POST" });
+ 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);
@@ -417,11 +515,13 @@
}
};
const toggleTeam = (accountID) => {
- const section = getElement("team-section-" + accountID);
- if (!section) return;
- const visible = section.classList.contains("visible");
- section.classList.toggle("visible", !visible);
- if (!visible) {
+ let nextVisible = false;
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamVisible = !entry.teamVisible;
+ nextVisible = entry.teamVisible;
+ });
+ if (nextVisible) {
void loadTeam(accountID);
}
};
@@ -435,7 +535,7 @@
return;
}
try {
- const r = await fetch(deps.getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members", {
+ const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, role: roleEl.value })
@@ -460,7 +560,7 @@
};
const changeRole = async (accountID, userID, newRole) => {
try {
- const r = await fetch(deps.getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
+ const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ role: newRole })
@@ -487,7 +587,7 @@
const removeMember = async (accountID, userID, email) => {
if (!window.confirm("Remove " + email + " from this account?")) return;
try {
- const r = await fetch(deps.getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
+ const r = await fetch(getAccountAPIBasePath() + "/" + encodeURIComponent(accountID) + "/members/" + encodeURIComponent(userID), {
method: "DELETE"
});
if (r.status === 409) {
@@ -563,6 +663,8 @@
target.value
);
});
+ deps.store.subscribeAccount(renderAccountUI);
+ deps.store.subscribeBootstrap(renderAccountUI);
}
// src/auth_controller.ts
@@ -814,15 +916,7 @@
store: portalStore
});
installAccountController({
- getAccountAPIBasePath: function() {
- return portalStore.getBootstrap().account_api_base_path;
- },
- getPortalAPIBasePath: function() {
- return portalStore.getBootstrap().portal_api_base_path;
- },
- getPortalPath: function() {
- return portalStore.getBootstrap().portal_path;
- },
+ store: portalStore,
refreshBootstrap,
showToast
});
diff --git a/internal/cloudcp/portal/frontend/src/account_controller.test.ts b/internal/cloudcp/portal/frontend/src/account_controller.test.ts
index 56a3c4e44c..c4d59db09b 100644
--- a/internal/cloudcp/portal/frontend/src/account_controller.test.ts
+++ b/internal/cloudcp/portal/frontend/src/account_controller.test.ts
@@ -1,6 +1,8 @@
import { beforeAll, 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 {
@@ -21,10 +23,24 @@ async function flushAsync() {
});
}
+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 = {
- getAccountAPIBasePath: vi.fn(),
- getPortalAPIBasePath: vi.fn(),
- getPortalPath: vi.fn(),
+ store: createPortalStore(bootstrapDefaults, {
+ authenticated: true,
+ email: '[email protected]',
+ }),
refreshBootstrap: vi.fn(),
showToast: vi.fn(),
};
@@ -37,9 +53,13 @@ describe('account controller', function() {
beforeEach(function() {
document.body.innerHTML = '';
vi.restoreAllMocks();
- deps.getAccountAPIBasePath = vi.fn().mockReturnValue('/api/accounts');
- deps.getPortalAPIBasePath = vi.fn().mockReturnValue('/api/portal');
- deps.getPortalPath = vi.fn().mockReturnValue('/portal');
+ 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();
});
@@ -57,6 +77,7 @@ describe('account controller', function() {
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();
@@ -71,6 +92,7 @@ describe('account controller', function() {
);
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');
});
@@ -94,6 +116,8 @@ describe('account controller', function() {
document.getElementById('team-toggle')?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
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');
diff --git a/internal/cloudcp/portal/frontend/src/account_controller.ts b/internal/cloudcp/portal/frontend/src/account_controller.ts
index b48b755d9a..312a6c0920 100644
--- a/internal/cloudcp/portal/frontend/src/account_controller.ts
+++ b/internal/cloudcp/portal/frontend/src/account_controller.ts
@@ -1,7 +1,9 @@
+import { ensurePortalAccountUIEntry } from './state';
+import type { PortalStore } from './store';
+import type { PortalTeamMember } from './types';
+
export interface AccountControllerDeps {
- getAccountAPIBasePath(): string;
- getPortalAPIBasePath(): string;
- getPortalPath(): string;
+ store: PortalStore;
refreshBootstrap(): Promise<boolean>;
showToast(message: string, isError?: boolean): void;
}
@@ -28,79 +30,139 @@ function setTbodyMessage(tbody: HTMLElement, msg: string, isError: boolean): voi
}
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 = deps.getPortalPath();
+ window.location.href = getPortalPath();
return false;
}
return true;
};
- const loadTeam = async (accountID: string): Promise<void> => {
- const tbody = getElement<HTMLElement>('team-list-' + accountID);
+ const renderAddWorkspaceSection = (accountID: string): void => {
+ const form = getElement<HTMLElement>('add-ws-form-' + accountID);
+ if (!form) return;
+ const entry = ensurePortalAccountUIEntry(deps.store.getAccountState(), accountID);
+ form.classList.toggle('visible', entry.addWorkspaceOpen);
+ };
+
+ const renderTeamSection = (accountID: string): void => {
const section = getElement<HTMLElement>('team-section-' + accountID);
- if (!tbody || !section) return;
+ const tbody = getElement<HTMLElement>('team-list-' + accountID);
+ if (!section || !tbody) return;
+ const entry = ensurePortalAccountUIEntry(deps.store.getAccountState(), accountID);
const actorRole = section.getAttribute('data-actor-role') || '';
const isOwner = actorRole === 'owner';
- setTbodyMessage(tbody, 'Loading…', false);
- try {
- const r = await fetch(deps.getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members');
- if (!r.ok) {
- setTbodyMessage(tbody, 'Failed to load team.', true);
- return;
+ section.classList.toggle('visible', entry.teamVisible);
+
+ if (!entry.teamVisible) {
+ return;
+ }
+ if (entry.teamLoading) {
+ setTbodyMessage(tbody, 'Loading…', false);
+ return;
+ }
+ if (entry.teamError) {
+ setTbodyMessage(tbody, entry.teamError, true);
+ return;
+ }
+ if (!entry.teamMembers.length) {
+ setTbodyMessage(tbody, 'No team members.', false);
+ return;
+ }
+
+ const allRoles = ['owner', 'admin', 'tech', 'read_only'];
+ const nonOwnerRoles = ['admin', 'tech', 'read_only'];
+ tbody.textContent = '';
+ for (let i = 0; i < entry.teamMembers.length; i += 1) {
+ const member = entry.teamMembers[i];
+ const tr = document.createElement('tr');
+ const tdEmail = document.createElement('td');
+ tdEmail.textContent = member.email;
+ tr.appendChild(tdEmail);
+
+ const tdRole = document.createElement('td');
+ if (member.role === 'owner' && !isOwner) {
+ tdRole.textContent = 'owner';
+ } else {
+ const sel = document.createElement('select');
+ const roles = isOwner ? allRoles : nonOwnerRoles;
+ for (let j = 0; j < roles.length; j += 1) {
+ const opt = document.createElement('option');
+ opt.value = roles[j];
+ opt.textContent = roles[j].replace('_', ' ');
+ if (member.role === roles[j]) opt.selected = true;
+ sel.appendChild(opt);
+ }
+ sel.setAttribute('data-action', 'change-role');
+ sel.setAttribute('data-account-id', accountID);
+ sel.setAttribute('data-user-id', member.user_id);
+ tdRole.appendChild(sel);
}
- const members = await r.json();
- if (!members || members.length === 0) {
- setTbodyMessage(tbody, 'No team members.', false);
- return;
+ tr.appendChild(tdRole);
+
+ const tdAction = document.createElement('td');
+ if (!(member.role === 'owner' && !isOwner)) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'btn-remove';
+ btn.textContent = 'Remove';
+ btn.setAttribute('data-action', 'remove-member');
+ btn.setAttribute('data-account-id', accountID);
+ btn.setAttribute('data-user-id', member.user_id);
+ btn.setAttribute('data-member-email', member.email);
+ tdAction.appendChild(btn);
}
- const allRoles = ['owner', 'admin', 'tech', 'read_only'];
- const nonOwnerRoles = ['admin', 'tech', 'read_only'];
- tbody.textContent = '';
- for (let i = 0; i < members.length; i += 1) {
- const member = members[i];
- const tr = document.createElement('tr');
- const tdEmail = document.createElement('td');
- tdEmail.textContent = member.email;
- tr.appendChild(tdEmail);
+ tr.appendChild(tdAction);
+ tbody.appendChild(tr);
+ }
+ };
- const tdRole = document.createElement('td');
- if (member.role === 'owner' && !isOwner) {
- tdRole.textContent = 'owner';
- } else {
- const sel = document.createElement('select');
- const roles = isOwner ? allRoles : nonOwnerRoles;
- for (let j = 0; j < roles.length; j += 1) {
- const opt = document.createElement('option');
- opt.value = roles[j];
- opt.textContent = roles[j].replace('_', ' ');
- if (member.role === roles[j]) opt.selected = true;
- sel.appendChild(opt);
- }
- sel.setAttribute('data-action', 'change-role');
- sel.setAttribute('data-account-id', accountID);
- sel.setAttribute('data-user-id', member.user_id);
- tdRole.appendChild(sel);
- }
- tr.appendChild(tdRole);
+ const renderAccountUI = (): void => {
+ const state = deps.store.getAccountState();
+ const accountIDs = Object.keys(state.byAccountID);
+ for (let i = 0; i < accountIDs.length; i += 1) {
+ renderAddWorkspaceSection(accountIDs[i]);
+ renderTeamSection(accountIDs[i]);
+ }
+ };
- const tdAction = document.createElement('td');
- if (!(member.role === 'owner' && !isOwner)) {
- const btn = document.createElement('button');
- btn.type = 'button';
- btn.className = 'btn-remove';
- btn.textContent = 'Remove';
- btn.setAttribute('data-action', 'remove-member');
- btn.setAttribute('data-account-id', accountID);
- btn.setAttribute('data-user-id', member.user_id);
- btn.setAttribute('data-member-email', member.email);
- tdAction.appendChild(btn);
- }
- tr.appendChild(tdAction);
- tbody.appendChild(tr);
+ 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 {
- setTbodyMessage(tbody, 'Network error.', true);
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamLoading = false;
+ entry.teamError = 'Network error.';
+ });
}
};
@@ -112,17 +174,22 @@ export function installAccountController(deps: AccountControllerDeps): void {
if (!section) {
return true;
}
- section.classList.add('visible');
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamVisible = true;
+ });
await loadTeam(accountID);
return true;
};
const toggleAddWorkspace = (accountID: string): void => {
- const form = getElement<HTMLElement>('add-ws-form-' + accountID);
- if (!form) return;
- const visible = form.classList.contains('visible');
- form.classList.toggle('visible', !visible);
- if (!visible) {
+ let shouldFocus = false;
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.addWorkspaceOpen = !entry.addWorkspaceOpen;
+ shouldFocus = entry.addWorkspaceOpen;
+ });
+ if (shouldFocus) {
const input = getElement<FormValueElement>('ws-name-' + accountID);
if (input) input.focus();
}
@@ -139,7 +206,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
const spinner = getElement<HTMLElement>('ws-spinner-' + accountID);
if (spinner) spinner.style.display = 'block';
try {
- const resp = await fetch(deps.getAccountAPIBasePath() + '/' + accountID + '/tenants', {
+ const resp = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ display_name: name }),
@@ -152,6 +219,10 @@ export function installAccountController(deps: AccountControllerDeps): void {
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);
@@ -167,7 +238,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
const method = state === 'active' ? 'PATCH' : 'DELETE';
const body = state === 'active' ? JSON.stringify({ state: 'suspended' }) : undefined;
try {
- const response = await fetch(deps.getAccountAPIBasePath() + '/' + accountID + '/tenants/' + tenantID, {
+ const response = await fetch(getAccountAPIBasePath() + '/' + accountID + '/tenants/' + tenantID, {
method,
headers: body ? { 'Content-Type': 'application/json' } : {},
body,
@@ -187,7 +258,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
const openBilling = async (accountID: string): Promise<void> => {
try {
- const r = await fetch(deps.getPortalAPIBasePath() + '/billing?account_id=' + encodeURIComponent(accountID), { method: 'POST' });
+ 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);
@@ -205,11 +276,13 @@ export function installAccountController(deps: AccountControllerDeps): void {
};
const toggleTeam = (accountID: string): void => {
- const section = getElement<HTMLElement>('team-section-' + accountID);
- if (!section) return;
- const visible = section.classList.contains('visible');
- section.classList.toggle('visible', !visible);
- if (!visible) {
+ let nextVisible = false;
+ deps.store.updateAccountState((accountState) => {
+ const entry = ensurePortalAccountUIEntry(accountState, accountID);
+ entry.teamVisible = !entry.teamVisible;
+ nextVisible = entry.teamVisible;
+ });
+ if (nextVisible) {
void loadTeam(accountID);
}
};
@@ -224,7 +297,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
return;
}
try {
- const r = await fetch(deps.getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members', {
+ const r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, role: roleEl.value }),
@@ -250,7 +323,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
const changeRole = async (accountID: string, userID: string, newRole: string): Promise<void> => {
try {
- const r = await fetch(deps.getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
+ const r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ role: newRole }),
@@ -278,7 +351,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
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(deps.getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
+ const r = await fetch(getAccountAPIBasePath() + '/' + encodeURIComponent(accountID) + '/members/' + encodeURIComponent(userID), {
method: 'DELETE',
});
if (r.status === 409) {
@@ -357,4 +430,7 @@ export function installAccountController(deps: AccountControllerDeps): void {
target.value,
);
});
+
+ deps.store.subscribeAccount(renderAccountUI);
+ deps.store.subscribeBootstrap(renderAccountUI);
}
diff --git a/internal/cloudcp/portal/frontend/src/shell.ts b/internal/cloudcp/portal/frontend/src/shell.ts
index 469851aa6e..46c7d03718 100644
--- a/internal/cloudcp/portal/frontend/src/shell.ts
+++ b/internal/cloudcp/portal/frontend/src/shell.ts
@@ -78,15 +78,7 @@ installAuthController({
});
installAccountController({
- getAccountAPIBasePath: function() {
- return portalStore.getBootstrap().account_api_base_path;
- },
- getPortalAPIBasePath: function() {
- return portalStore.getBootstrap().portal_api_base_path;
- },
- getPortalPath: function() {
- return portalStore.getBootstrap().portal_path;
- },
+ store: portalStore,
refreshBootstrap: refreshBootstrap,
showToast: showToast
});
diff --git a/internal/cloudcp/portal/frontend/src/state.ts b/internal/cloudcp/portal/frontend/src/state.ts
index 621758b7e9..0644ae6a0a 100644
--- a/internal/cloudcp/portal/frontend/src/state.ts
+++ b/internal/cloudcp/portal/frontend/src/state.ts
@@ -1,4 +1,6 @@
import type {
+ PortalAccountState,
+ PortalAccountUIEntry,
PortalLoginState,
PortalServiceFlowID,
PortalServiceState,
@@ -38,6 +40,25 @@ export function createPortalLoginState(): PortalLoginState {
};
}
+export function createPortalAccountState(): PortalAccountState {
+ return {
+ byAccountID: {},
+ };
+}
+
+export function ensurePortalAccountUIEntry(accountState: PortalAccountState, accountID: string): PortalAccountUIEntry {
+ if (!accountState.byAccountID[accountID]) {
+ accountState.byAccountID[accountID] = {
+ addWorkspaceOpen: false,
+ teamVisible: false,
+ teamLoading: false,
+ teamError: '',
+ teamMembers: [],
+ };
+ }
+ return accountState.byAccountID[accountID];
+}
+
export function createPortalServiceState(): PortalServiceState {
return {
openPanelID: '',
diff --git a/internal/cloudcp/portal/frontend/src/store.ts b/internal/cloudcp/portal/frontend/src/store.ts
index 7c226aaf24..71cb18b095 100644
--- a/internal/cloudcp/portal/frontend/src/store.ts
+++ b/internal/cloudcp/portal/frontend/src/store.ts
@@ -1,10 +1,11 @@
import {
+ createPortalAccountState,
createPortalLoginState,
createPortalServiceState,
syncLoginStateBootstrapEmail,
syncServiceStateBootstrapEmail,
} from './state';
-import type { PortalBootstrapData, PortalLoginState, PortalServiceState } from './types';
+import type { PortalAccountState, PortalBootstrapData, PortalLoginState, PortalServiceState } from './types';
interface MutationOptions {
notify?: boolean;
@@ -12,11 +13,14 @@ interface MutationOptions {
export interface PortalStore {
getBootstrap(): PortalBootstrapData;
+ getAccountState(): PortalAccountState;
getLoginState(): PortalLoginState;
getServiceState(): PortalServiceState;
setBootstrap(nextBootstrap: Partial<PortalBootstrapData> | PortalBootstrapData): PortalBootstrapData;
+ updateAccountState(mutator: (state: PortalAccountState) => void, options?: MutationOptions): PortalAccountState;
updateLoginState(mutator: (state: PortalLoginState) => void, options?: MutationOptions): PortalLoginState;
updateServiceState(mutator: (state: PortalServiceState) => void, options?: MutationOptions): PortalServiceState;
+ subscribeAccount(listener: () => void): () => void;
subscribeBootstrap(listener: () => void): () => void;
subscribeLogin(listener: () => void): () => void;
subscribeServices(listener: () => void): () => void;
@@ -47,10 +51,12 @@ export function createPortalStore(
initialBootstrap: Partial<PortalBootstrapData> | null | undefined
): PortalStore {
var bootstrapState = normalizeBootstrap(bootstrapDefaults, initialBootstrap);
+ var accountState = createPortalAccountState();
var loginState = createPortalLoginState();
var serviceState = createPortalServiceState();
syncLoginStateBootstrapEmail(loginState, bootstrapState.email || '');
syncServiceStateBootstrapEmail(serviceState, bootstrapState.email || '');
+ var accountSubscribers = new Set<() => void>();
var bootstrapSubscribers = new Set<() => void>();
var loginSubscribers = new Set<() => void>();
var serviceSubscribers = new Set<() => void>();
@@ -65,6 +71,9 @@ export function createPortalStore(
getBootstrap: function() {
return bootstrapState;
},
+ getAccountState: function() {
+ return accountState;
+ },
getLoginState: function() {
return loginState;
},
@@ -78,6 +87,13 @@ export function createPortalStore(
notify(bootstrapSubscribers);
return bootstrapState;
},
+ updateAccountState: function(mutator, options) {
+ mutator(accountState);
+ if (!options || options.notify !== false) {
+ notify(accountSubscribers);
+ }
+ return accountState;
+ },
updateLoginState: function(mutator, options) {
mutator(loginState);
if (!options || options.notify !== false) {
@@ -98,6 +114,12 @@ export function createPortalStore(
bootstrapSubscribers.delete(listener);
};
},
+ subscribeAccount: function(listener) {
+ accountSubscribers.add(listener);
+ return function() {
+ accountSubscribers.delete(listener);
+ };
+ },
subscribeLogin: function(listener) {
loginSubscribers.add(listener);
return function() {
diff --git a/internal/cloudcp/portal/frontend/src/types.ts b/internal/cloudcp/portal/frontend/src/types.ts
index 97792465c7..7c801c0535 100644
--- a/internal/cloudcp/portal/frontend/src/types.ts
+++ b/internal/cloudcp/portal/frontend/src/types.ts
@@ -40,6 +40,24 @@ export interface PortalLoginState {
error: string;
}
+export interface PortalTeamMember {
+ email: string;
+ role: string;
+ user_id: string;
+}
+
+export interface PortalAccountUIEntry {
+ addWorkspaceOpen: boolean;
+ teamVisible: boolean;
+ teamLoading: boolean;
+ teamError: string;
+ teamMembers: PortalTeamMember[];
+}
+
+export interface PortalAccountState {
+ byAccountID: Record<string, PortalAccountUIEntry>;
+}
+
export type PortalServiceFlowID = 'manage' | 'retrieve' | 'export' | 'delete';
export interface ServiceStatus {