Skip to content

feat: rebuild Accounts page into componentized grid layout - #140

Merged
terranalon merged 13 commits into
mainfrom
feat/accounts-page
Jun 13, 2026
Merged

terranalon merged 13 commits into
mainfrom
feat/accounts-page

Conversation

@terranalon

Copy link
Copy Markdown
Owner

Summary

  • Replace monolithic Accounts.jsx (900 lines) with a grid-card layout matching the accounts-playground mock
  • New useAccountsData hook fetches accounts + dashboard summary + positions in parallel, enriching each account with value, allocation %, sync status, and per-account holdings (pivoted from the positions endpoint — no N+1 calls)
  • New component directory components/accounts/: AllocationStrip, AccountCard, AccountGrid, AccountSidebar, constants, icons
  • AccountWizard integration preserved; slide-over sidebar matches TransactionDetailSidebar pattern

Test plan

  • Grid cards render with broker logo, value, allocation %, top holdings pills, sync dot
  • Allocation strip shows stacked bar + per-account badges
  • Clicking a card opens the sidebar with summary + holdings list + P&L
  • "View Details" in sidebar navigates to /accounts/:id
  • "Add Account" button and dashed placeholder card open AccountWizard
  • Wizard close triggers data refresh
  • Loading skeletons display while fetching
  • Empty state shows when no accounts exist
  • Error state shows with retry button

Closes #127

🤖 Generated with Claude Code

Replace monolithic accordion-card Accounts.jsx (900 lines) with a
componentized grid layout matching the accounts-playground mock.

New components:
- AllocationStrip: stacked bar showing per-account portfolio share
- AccountCard: grid card with broker logo, value, holdings pills, sync status
- AccountGrid: auto-fill grid + dashed add-account placeholder card
- AccountSidebar: slide-over with summary, holdings list, and P&L

New hook:
- useAccountsData: fetches accounts + dashboard summary + positions in
  parallel, enriches accounts with values/allocation/sync, groups
  positions by account_id for per-account holdings without N+1 calls

AccountWizard integration preserved; broker-data fetch removed (unused
in new architecture).

Closes #127

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@terranalon

Copy link
Copy Markdown
Owner Author

Code review

Found 2 issues:

  1. getSyncStatus returns a text- class for the unknown state, but the sync dot uses bg- classes — the dot will be invisible for any account where lastSync is null. Every other return value in the function is a bg- class (bg-[var(--positive)], bg-[var(--warning)], bg-[var(--negative)]), so the unknown case should use bg-[var(--text-faint)] instead.

function getSyncStatus(lastSync) {
if (!lastSync) return { status: 'unknown', color: 'text-[var(--text-faint)]' };
const diffDays = Math.floor((Date.now() - new Date(lastSync)) / 86400000);
if (diffDays <= 7) return { status: 'green', color: 'bg-[var(--positive)]' };
if (diffDays <= 30) return { status: 'amber', color: 'bg-[var(--warning)]' };
return { status: 'red', color: 'bg-[var(--negative)]' };
}

(Consumers: AccountCard.jsx#L64-L67, AccountSidebar.jsx#L120-L124)

  1. selectedAccount is a stale snapshot after refresh() is called — selectedAccount is set once on card click and never re-derived. After the wizard closes and refresh() re-fetches accounts, the sidebar still displays the old value, allocationPct, and lastSyncFormatted from the pre-refresh snapshot. The fix is to look up the live account by ID before passing to the sidebar: accounts.find(a => a.id === selectedAccount.id) ?? null.

}, [showWizard, selectedPortfolioId]);
const handleCardClick = (account) => setSelectedAccount(account);
const handleCloseSidebar = () => setSelectedAccount(null);
const handleAddAccount = () => setShowWizard(true);
if (loading) {

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

- Fix getSyncStatus unknown case using text- class instead of bg- (score 85)
- Fix stale selectedAccount snapshot after refresh via accounts.find() live lookup (score 85)
- Add limit: 100 to /accounts fetch to match backend max and avoid silent 50-account truncation (score 75)
- Track positionsTruncated from /positions has_more and surface in sidebar when >100 positions (score 75)
- Restore management actions in AccountSidebar: rename (inline), delete (confirmation), upload data, API credentials (score 75)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@terranalon

Copy link
Copy Markdown
Owner Author

Code review

Found 4 issues:

  1. handleDelete always calls DELETE /accounts/{id} (permanent deletion) regardless of whether the account belongs to multiple portfolios. The old code checked portfolio_ids.length > 1 and called DELETE /portfolios/{pid}/accounts/{id} (unlink only) for shared accounts. This is a data-loss regression — deleting a shared account destroys it across all portfolios instead of just unlinking it from the current one.

const handleDelete = async (accountId) => {
const res = await api(`/accounts/${accountId}`, { method: 'DELETE' });
if (res.ok) {
setSelectedAccount(null);
refresh();
}
};

  1. ApiCredentialsModal receives hasCredentials={false} unconditionally. The modal branches on this prop — false always renders the credential entry form, true renders an "API Connected" confirmation with a settings link. Users who already have API credentials configured will always see the blank entry form instead of the connected state.

{/* API credentials modal */}
<ApiCredentialsModal
isOpen={showApiCredentials}
onClose={() => {
setShowApiCredentials(false);
setActiveModalAccount(null);
}}
account={activeModalAccount}
onCredentialsSaved={refresh}
hasCredentials={false}
/>
</PageContainer>

  1. handleDelete and handleRename have no error path — if the API returns a 4xx/5xx, nothing happens: no feedback, no state reset. In AccountSidebar, handleDeleteConfirm resets isDeleting and showDeleteConfirm unconditionally, so on failure the spinner and confirmation UI disappear silently.

const handleDelete = async (accountId) => {
const res = await api(`/accounts/${accountId}`, { method: 'DELETE' });
if (res.ok) {
setSelectedAccount(null);
refresh();
}
};
const handleRename = async (accountId, newName) => {
const res = await api(`/accounts/${accountId}`, {
method: 'PUT',
body: JSON.stringify({ name: newName }),
});
if (res.ok) refresh();
};

const handleDeleteConfirm = async () => {
setIsDeleting(true);
await onDelete?.(account.id);
setIsDeleting(false);
setShowDeleteConfirm(false);
};

  1. BatchUploadModal has a two-callback contract: onClose (dismiss) and onComplete (import finalized). The new code omits onComplete and puts refresh() inside onClose. This means refresh() fires on every close — including cancel and X-button clicks — not just after a successful import.

<BatchUploadModal
isOpen={showBatchUpload}
onClose={() => {
setShowBatchUpload(false);
setActiveModalAccount(null);
refresh();
}}
accountId={activeModalAccount?.id}
brokerType={activeModalAccount?.broker_type}
supportedFormats={getBrokerConfig(activeModalAccount?.broker_type)?.supportedFormats || []}
/>

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

- Fix handleDelete to use unlink endpoint for shared accounts (portfolio_ids.length > 1)
  uses DELETE /portfolios/{pid}/accounts/{id} instead of always hard-deleting
- Fix hasCredentials hardcoded false: fetch GET /brokers/{type}/credentials/{id}
  before opening ApiCredentialsModal; restore onGoToSettings navigation
- Fix silent failures: handleDelete/handleRename now throw on non-ok response;
  AccountSidebar.handleDeleteConfirm catches and shows inline error, only resets
  spinner on the error path (success closes sidebar naturally)
- Fix BatchUploadModal two-callback contract: refresh() moved to onComplete,
  onClose only handles modal state cleanup (no spurious refresh on cancel)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@terranalon

Copy link
Copy Markdown
Owner Author

Code review

Found 3 issues:

  1. AccountSidebar local state (renameError, deleteError, showDeleteConfirm, isDeleting) is never reset when the account prop changes to a different account. If a rename or delete fails on Account A, those error messages persist when the user opens Account B. A useEffect keyed on account?.id is needed to clear this state on account switch.

const [editingName, setEditingName] = useState(false);
const [nameValue, setNameValue] = useState('');
const [renameError, setRenameError] = useState(null);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [deleteError, setDeleteError] = useState(null);
if (!account) return null;

  1. BatchUploadModal is unconditionally mounted (not conditionally rendered with &&), so its sessionId = useState(() => crypto.randomUUID()) initializes once at page load and never resets. A user who opens the upload modal, cancels, then reopens will reuse the same session ID for a new batch — the backend will associate both uploads to the same session, which can cause incorrect transaction batching or finalization conflicts.

<BatchUploadModal
isOpen={showBatchUpload}
onClose={() => {
setShowBatchUpload(false);
setActiveModalAccount(null);
}}
onComplete={() => {
setShowBatchUpload(false);
setActiveModalAccount(null);
refresh();
}}
accountId={activeModalAccount?.id}
brokerType={activeModalAccount?.broker_type}

onComplete,
}) {
const [sessionId] = useState(() => crypto.randomUUID());
const [uploads, setUploads] = useState([]);
const [isUploading, setIsUploading] = useState(false);

  1. if (!account) return null fires immediately when the parent sets selectedAccount to null after a successful delete. This unmounts the component before the CSS slide-out transition (translate-x-full, 200ms) can play — the sidebar content vanishes with a pop instead of animating away. The isOpen flag is derived from !!account, so both the null-guard and the transition trigger on the same render.

const isOpen = !!account;
const navigate = useNavigate();
useSlideover(isOpen, onClose);
const [editingName, setEditingName] = useState(false);
const [nameValue, setNameValue] = useState('');
const [renameError, setRenameError] = useState(null);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const [deleteError, setDeleteError] = useState(null);
if (!account) return null;

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

- Reset all local sidebar state (rename/delete/error) when switching accounts
  via useEffect keyed on account?.id; null guard skips reset during close animation
- Preserve sidebar content during 200ms slide-out by keeping last non-null
  account in a ref (renderAccount = account ?? prevAccountRef.current)
- Conditionally render BatchUploadModal so sessionId is freshly generated
  on each open instead of reusing the same session across uploads

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@terranalon

Copy link
Copy Markdown
Owner Author

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

🤖 Generated with Claude Code

terranalon and others added 6 commits May 23, 2026 12:17
When the user presses Escape to cancel an inline rename, removing the
input from the DOM triggers onBlur -> commitRename, silently saving the
change. A cancelRenameRef flag is set before setEditingName(false) so
commitRename exits early when called from blur after Escape.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
positionsTruncated was a portfolio-wide flag that triggered a misleading
warning inside individual account holdings cards — an account with 3
positions would show "Portfolio has more than 100 positions" whenever
the total portfolio exceeded the limit.

Replace with a per-account check: compare renderAccount.holdingCount
(from dashboard summary) against holdings.length. The warning now only
appears for accounts whose holdings are actually truncated, and the
message shows exact counts ("Showing X of Y positions").

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Fix account name clipping: X button is now absolute-positioned,
  freeing full header width for the name; View Details moves to sit
  beside the value number
- Cap holdings preview at 5 (top by market value); show "+N more"
  footer when the account has additional positions
- Add Recent Activity card: fetches last 5 transactions across all
  types (trades/dividends/forex/cash) filtered by account_id, with
  a skeleton loading state

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…links

- Remove holdings count from card title
- Remove Upload Data and API Credentials actions (moved to account details page)
- Remove dead BatchUploadModal, ApiCredentialsModal, and related state
  from Accounts.jsx
- Add "View all holdings" footer button → /accounts/:id?tab=holdings
- Add "View all activity" footer button → /accounts/:id?tab=transactions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The useEffect only handled tab=settings; holdings and transactions
were silently ignored, leaving the page on the Overview tab.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ebar

- AccountCard: trash icon in footer footer triggers an inline overlay
  confirmation (stopPropagation prevents opening the sidebar); handles
  shared vs. owned accounts (Remove vs. Delete label)
- AccountGrid: thread onDelete through to AccountCard
- AccountSidebar: remove Manage section entirely (delete state,
  handlers, ActionButton helper, onDelete prop, TrashIcon import)
- Accounts.jsx: pass onDelete to AccountGrid, drop from AccountSidebar

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@terranalon

Copy link
Copy Markdown
Owner Author

Code review

Found 1 issue:

  1. Pressing Escape to cancel a rename also closes the entire sidebar. The rename input's onKeyDown Escape branch cancels the edit but never calls e.stopPropagation(), so the event bubbles to the document-level keydown listener in useSlideover (useSlideover.js#L22, if (e.key === 'Escape') onClose?.()), which fires onClose and dismisses the panel. Add e.stopPropagation() to the Escape branch so cancelling a rename keeps the sidebar open.

onKeyDown={(e) => {
if (e.key === 'Enter') commitRename();
if (e.key === 'Escape') {
cancelRenameRef.current = true;
setEditingName(false);
}
}}
className="text-xl font-semibold bg-transparent border-b border-[var(--accent-primary)] outline-none w-full"

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

@terranalon

Copy link
Copy Markdown
Owner Author

Code review (additional findings)

Posting the remaining issues that scored 75 confidence (the issue above scored 90). These are genuine but lower-severity than the Escape/rename bug:

  1. positionsTruncated is computed but never consumed — the hook fetches /positions?limit=100, records has_more into positionsTruncated, and returns it, but Accounts.jsx never destructures it. A user with more than 100 distinct positions will silently see incomplete holdings pills, a wrong allocation strip, and an incomplete sidebar "Top Holdings" — with no warning.

fetchJson(`/accounts${buildQuery({ is_active: true, limit: 100, ...shared })}`, 'accounts'),
fetchJson(`/dashboard/summary${buildQuery(withCurrency)}`, 'dashboard'),
fetchJson(`/positions${buildQuery({ ...withCurrency, limit: 100 })}`, 'positions'),
]);
if (cancelled) return;
setRawAccounts(accountsData.items);
setDashboardAccounts(dashboardData.accounts || []);
setPositions(positionsData.items || []);
setPositionsTruncated(positionsData.has_more || false);

(Hook returns it: useAccountsData.js#L147; page omits it from the destructure)

const {
accounts, accountHoldings, totalValue,
loading, error, currency, refresh,
} = useAccountsData();

  1. Delete failure on AccountCard gives the user no feedback — handleConfirm catches errors from onDelete but only resets isDeleting/showConfirm; there is no toast or inline error. The card overlay is the only delete path in this PR, so a failed delete (500/network) silently dismisses the confirmation with no indication it failed. Contrast with the sidebar rename, which surfaces failures inline via renameError.

const handleConfirm = async (e) => {
e.stopPropagation();
setIsDeleting(true);
try {
await onDelete?.(account.id);
} catch {
setIsDeleting(false);
setShowConfirm(false);
}
};

  1. Holdings list collapses during the sidebar slide-out animation — AccountSidebar preserves account metadata via prevAccountRef so the header/value stay visible during the 200ms close, but the holdings prop drops to [] immediately because liveSelectedAccount becomes null. The "Top Holdings" section (gated on visibleHoldings.length > 0) vanishes abruptly while the rest of the panel is still sliding out. Preserving holdings in a ref (mirroring prevAccountRef) would fix the jank.

account={liveSelectedAccount}
holdings={liveSelectedAccount ? accountHoldings.get(liveSelectedAccount.id) || [] : []}

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

terranalon and others added 3 commits June 13, 2026 12:51
… jank

- AccountSidebar: add e.stopPropagation() on Escape in rename input so
  the event doesn't bubble to useSlideover's document listener and close
  the entire panel when the user is just cancelling a rename
- AccountCard: add deleteError state; surface API error message inside
  the confirmation overlay instead of silently dismissing it
- Accounts.jsx: mirror prevAccountRef pattern for holdings so the Top
  Holdings card stays visible during the 200ms sidebar slide-out after
  liveSelectedAccount becomes null

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When the portfolio has more than 100 positions the /positions endpoint
truncates the response, leaving holdings pills, the allocation strip,
and the sidebar previews silently incomplete. Re-add positionsTruncated
to the useAccountsData destructure and show an amber banner above the
allocation strip so the user knows the data is partial.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The banner previously said 'Open an account to see its full breakdown,'
which was ambiguous: the sidebar's Top Holdings is derived from the same
truncated /positions?limit=100 response and is just as partial. Point the
user at the account's full details page (separate per-account fetch) and
note that allocation is partial too.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@terranalon
terranalon merged commit 12f4de2 into main Jun 13, 2026
4 checks passed
@terranalon
terranalon deleted the feat/accounts-page branch June 13, 2026 10:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Implement accounts page

1 participant