stock-bot/apps/stock/web-app/src/features/research/ResearchProjectPage.tsx

647 lines
23 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from 'react';
import { Link, useParams, useSearchParams } from 'react-router-dom';
import { updateResearchProjectSchema } from '@stock-bot/stock-config/research';
import type {
ResearchArtifact,
ResearchHypothesis,
ResearchProject,
StrategyRecord,
} from '@stock-bot/types';
import { Card } from '@/components/ui/Card';
import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm';
import { confirmDiscard, useUnsavedWarning } from '../strategies/components/useUnsavedWarning';
import { strategyApi } from '../strategies/services/strategyApi';
import { CreateResearchEntry } from './components/CreateResearchEntry';
import { ResearchEntry } from './components/ResearchEntry';
import { researchApi, ResearchApiError } from './services/researchApi';
type Section = 'project' | 'strategies' | 'hypotheses' | 'artifacts' | 'catalog';
const initialErrors: Record<Section, string> = {
project: '',
strategies: '',
hypotheses: '',
artifacts: '',
catalog: '',
};
export function ResearchProjectPage() {
const { projectId } = useParams();
return projectId ? (
<ProjectWorkspace key={projectId} projectId={projectId} />
) : (
<p role="alert">Missing research project.</p>
);
}
function ProjectWorkspace({ projectId }: { projectId: string }) {
const [params, setParams] = useSearchParams();
const mounted = useRef(false);
const pending = useRef(false);
const [project, setProject] = useState<ResearchProject | null>(null);
const [strategies, setStrategies] = useState<StrategyRecord[]>([]);
const [catalog, setCatalog] = useState<StrategyRecord[]>([]);
const [hypotheses, setHypotheses] = useState<ResearchHypothesis[]>([]);
const [artifacts, setArtifacts] = useState<ResearchArtifact[]>([]);
const [errors, setErrors] = useState(initialErrors);
const [loading, setLoading] = useState(true);
const [refresh, setRefresh] = useState(0);
const [selectionEpoch, setSelectionEpoch] = useState(0);
const [showArchived, setShowArchived] = useState(false);
const [editing, setEditing] = useState<{
title: string;
description: string;
expectedRevision: number;
} | null>(null);
const [creator, setCreator] = useState<'hypothesis' | 'note' | null>(null);
const [createDirty, setCreateDirty] = useState(false);
const [entryDirty, setEntryDirty] = useState(false);
const [strategyId, setStrategyId] = useState('');
const [saving, setSaving] = useState(false);
const [mutationError, setMutationError] = useState('');
const [conflict, setConflict] = useState(false);
const dirty = Boolean(editing) || createDirty || entryDirty;
useUnsavedWarning(dirty);
const reload = useCallback(() => setRefresh(value => value + 1), []);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
useEffect(() => {
let current = true;
const controller = new AbortController();
setLoading(true);
setErrors(initialErrors);
const failed = (section: Section, cause: unknown) => {
if (current) {
setErrors(previous => ({
...previous,
[section]: cause instanceof Error ? cause.message : `Could not load ${section}`,
}));
}
};
void Promise.allSettled([
researchApi
.getProject(projectId, controller.signal)
.then(({ project: value }) => {
if (value.id !== projectId) {
throw new Error('The response belongs to another project.');
}
if (current) {
setProject(value);
}
})
.catch(cause => failed('project', cause)),
researchApi
.listStrategies(projectId, controller.signal)
.then(({ strategies: value }) => {
if (current) {
setStrategies(value);
}
})
.catch(cause => failed('strategies', cause)),
researchApi
.listHypotheses(projectId, true, controller.signal)
.then(({ hypotheses: value }) => {
if (value.some(item => item.projectId !== projectId)) {
throw new Error('Hypotheses belong to another project.');
}
if (current) {
setHypotheses(value);
}
})
.catch(cause => failed('hypotheses', cause)),
researchApi
.listArtifacts(projectId, true, controller.signal)
.then(({ artifacts: value }) => {
if (value.some(item => item.projectId !== projectId)) {
throw new Error('Research entries belong to another project.');
}
if (current) {
setArtifacts(value);
}
})
.catch(cause => failed('artifacts', cause)),
strategyApi
.list(controller.signal)
.then(({ strategies: value }) => {
if (current) {
setCatalog(value);
}
})
.catch(cause => failed('catalog', cause)),
]).finally(() => {
if (current) {
setLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [projectId, refresh]);
const select = (kind: 'hypothesis' | 'artifact', id: string, revisionId?: string | null) => {
if (!confirmDiscard(dirty)) {
return;
}
setEditing(null);
setCreator(null);
setCreateDirty(false);
setEntryDirty(false);
if (params.get(kind) === id && params.get('revision') === (revisionId ?? null)) {
setSelectionEpoch(value => value + 1);
}
setParams({ [kind]: id, ...(revisionId ? { revision: revisionId } : {}) });
};
const mutateProject = async (archived?: boolean) => {
if (
!project ||
loading ||
pending.current ||
errors.project ||
conflict ||
(archived === undefined && !editing)
) {
return;
}
if (
archived !== undefined &&
(!confirmDiscard(dirty) ||
!window.confirm(`${archived ? 'Archive' : 'Restore'} this project?`))
) {
return;
}
pending.current = true;
setSaving(true);
setMutationError('');
try {
const body =
archived === undefined ? editing : { expectedRevision: project.revision, archived };
if (!body) {
return;
}
const input = updateResearchProjectSchema.parse(body);
const { project: updated } = await researchApi.updateProject(projectId, input);
if (
updated.id !== projectId ||
updated.ownerPrincipal !== project.ownerPrincipal ||
updated.revision !== input.expectedRevision + 1 ||
updated.title !== (input.title ?? project.title) ||
updated.description !== (input.description ?? project.description) ||
updated.archived !== (input.archived ?? project.archived)
) {
throw new ResearchApiError('The saved project update could not be verified.', null);
}
if (mounted.current) {
setProject(updated);
setEditing(null);
setConflict(false);
if (archived !== undefined) {
setCreator(null);
setCreateDirty(false);
setEntryDirty(false);
setSelectionEpoch(value => value + 1);
}
reload();
}
} catch (cause) {
if (mounted.current) {
setMutationError(cause instanceof Error ? cause.message : 'Could not update project');
setConflict(
!(cause instanceof ResearchApiError) || cause.status === 409 || cause.ambiguous
);
}
} finally {
pending.current = false;
if (mounted.current) {
setSaving(false);
}
}
};
const membership = async (id: string, remove: boolean) => {
if (
!project ||
project.archived ||
loading ||
saving ||
pending.current ||
editing ||
errors.project ||
errors.strategies ||
conflict
) {
return;
}
pending.current = true;
setSaving(true);
setMutationError('');
try {
if (remove) {
await researchApi.unlinkStrategy(projectId, id);
} else {
await researchApi.linkStrategy(projectId, id);
}
if (mounted.current) {
setStrategyId('');
reload();
}
} catch (cause) {
if (mounted.current) {
setMutationError(
cause instanceof Error ? cause.message : 'Could not update linked strategies'
);
reload();
}
} finally {
pending.current = false;
if (mounted.current) {
setSaving(false);
}
}
};
const discardAndReloadProject = () => {
if (saving || !confirmDiscard(dirty)) {
return;
}
setLoading(true);
setEditing(null);
setCreator(null);
setCreateDirty(false);
setEntryDirty(false);
setSelectionEpoch(value => value + 1);
setConflict(false);
setMutationError('');
reload();
};
const hypothesisId = params.get('hypothesis');
const artifactId = params.get('artifact');
const selection =
hypothesisId && !artifactId
? { kind: 'hypothesis' as const, id: hypothesisId }
: artifactId && !hypothesisId
? { kind: 'artifact' as const, id: artifactId }
: null;
const visibleHypotheses = hypotheses.filter(
item => showArchived || project?.archived || !item.archived
);
const visibleArtifacts = artifacts.filter(
item => showArchived || project?.archived || !item.archived
);
const canWrite =
project && !project.archived && !errors.project && !loading && !saving && !conflict;
const projectWriteBlocked = conflict
? 'Review the saved project before another update.'
: saving
? 'Updating project.'
: loading
? 'Refreshing project.'
: errors.project
? 'Project status could not be verified.'
: '';
const sectionError = (section: Section) =>
errors[section] && (
<div>
<p role="alert" className="text-error">
{section}: {errors[section]}
</p>
<button className={actionClass} onClick={reload}>
Retry {section}
</button>
</div>
);
return (
<div
className="space-y-5 text-text-primary"
onClickCapture={event => {
if ((event.target as HTMLElement).closest('a') && !confirmDiscard(dirty)) {
event.preventDefault();
event.stopPropagation();
}
}}
>
<div className="flex flex-wrap gap-4">
<Link className="text-primary-500" to="/research">
Research projects
</Link>
<Link className="text-primary-500" to="/backtests">
Backtesting workbench
</Link>
<button className={actionClass} onClick={reload} disabled={saving}>
Refresh project
</button>
</div>
{loading && <p role="status">Loading research workspace...</p>}
{sectionError('project')}
{project && (
<>
<Card className="p-4 space-y-3">
<h1 className="text-lg font-bold">{project.title}</h1>
<p className="whitespace-pre-wrap text-text-secondary">
{project.description || 'No description yet.'}
</p>
<p className="text-xs text-text-muted">
Project revision {project.revision} · Owner: {project.ownerPrincipal} · Updated{' '}
{project.updatedAt}
</p>
{project.archived && (
<p role="status">
Archived project. Records, history and evidence remain available; restore the
project to make changes.
</p>
)}
{!editing && canWrite && (
<button
className={actionClass}
onClick={() => {
if (confirmDiscard(dirty)) {
setCreator(null);
setCreateDirty(false);
setParams({});
setEditing({
title: project.title,
description: project.description,
expectedRevision: project.revision,
});
setConflict(false);
setMutationError('');
}
}}
>
Edit project
</button>
)}{' '}
<button
className={actionClass}
disabled={saving || loading || Boolean(errors.project) || conflict}
onClick={() => void mutateProject(!project.archived)}
>
{project.archived ? 'Restore project' : 'Archive project'}
</button>
{editing && !project.archived && (
<form
aria-label="Edit research project"
className="space-y-3"
onSubmit={event => {
event.preventDefault();
void mutateProject();
}}
>
<label className="block">
Project title
<input
aria-label="Project title"
className={fieldClass}
value={editing.title}
onChange={event => setEditing({ ...editing, title: event.target.value })}
disabled={saving || conflict}
required
/>
</label>
<label className="block">
Project description
<textarea
aria-label="Project description"
className={fieldClass}
value={editing.description}
onChange={event => setEditing({ ...editing, description: event.target.value })}
disabled={saving || conflict}
/>
</label>
<button
type="submit"
className={actionClass}
disabled={!canWrite || conflict || !editing.title.trim()}
>
Save project
</button>{' '}
<button
type="button"
className={actionClass}
disabled={saving}
onClick={() => {
if (conflict) {
discardAndReloadProject();
} else if (confirmDiscard(true)) {
setEditing(null);
setMutationError('');
setConflict(false);
}
}}
>
Discard project edits
</button>
</form>
)}
{mutationError && (
<p role="alert" className="text-error">
{mutationError}
</p>
)}
{conflict && (
<div role="status">
<p>
Review the saved project before another update. Your draft has been preserved.
</p>
<button className={actionClass} disabled={saving} onClick={discardAndReloadProject}>
Discard edits and reload project
</button>
</div>
)}
</Card>
<Card className="p-4 space-y-3">
<h2 className="font-semibold">Linked strategies</h2>
{sectionError('strategies')}
{!loading && !errors.strategies && !strategies.length && (
<p>
No strategies linked. Link a strategy, then choose an immutable version for a
backtest.
</p>
)}
{!errors.strategies && (
<ul className="space-y-2">
{strategies.map(strategy => (
<li key={strategy.id} className="flex flex-wrap gap-3 items-center">
<Link className="text-primary-500" to={`/strategies/${strategy.id}`}>
{strategy.name}
</Link>
{strategy.archived && <span className="text-xs">Archived strategy</span>}
{canWrite && (
<button
className={actionClass}
disabled={Boolean(editing)}
onClick={() => void membership(strategy.id, true)}
aria-label={`Unlink ${strategy.name}`}
>
Unlink
</button>
)}
</li>
))}
</ul>
)}
{sectionError('catalog')}
{canWrite && !errors.catalog && !errors.strategies && (
<div className="flex flex-wrap gap-2">
<label>
Strategy to link
<select
className={fieldClass}
aria-label="Strategy to link"
value={strategyId}
disabled={Boolean(editing)}
onChange={event => setStrategyId(event.target.value)}
>
<option value="">Select strategy</option>
{catalog
.filter(
item => !item.archived && !strategies.some(link => link.id === item.id)
)
.map(item => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<button
className={actionClass}
disabled={!strategyId || Boolean(editing)}
onClick={() => void membership(strategyId, false)}
>
Link strategy
</button>
</div>
)}
<Link className="text-primary-500 text-sm" to="/strategies">
Browse strategy catalog
</Link>
</Card>
<label className="flex gap-2">
<input
type="checkbox"
checked={showArchived}
onChange={event => setShowArchived(event.target.checked)}
/>
Show archived research entries
</label>
<div className="grid gap-4 lg:grid-cols-2">
<Card className="p-4 space-y-3">
<h2 className="font-semibold">Hypotheses</h2>
{sectionError('hypotheses')}
{canWrite && (
<button
className={actionClass}
onClick={() => {
if (confirmDiscard(dirty)) {
setEditing(null);
setCreator('hypothesis');
setParams({});
}
}}
>
New hypothesis
</button>
)}
{!loading && !errors.hypotheses && !visibleHypotheses.length && (
<p>No hypotheses yet.</p>
)}
{!errors.hypotheses && (
<ul className="space-y-2">
{visibleHypotheses.map(item => (
<li key={item.id}>
<button
className="text-primary-500"
onClick={() => select('hypothesis', item.id)}
>
{item.latestRevision.title}
</button>
{item.archived && <span className="ml-2 text-xs">Archived</span>}
<p className="text-xs">
Unvalidated · Revision {item.latestRevision.ordinal} · Declared{' '}
{item.latestRevision.contentOrigin}
</p>
</li>
))}
</ul>
)}
</Card>
<Card className="p-4 space-y-3">
<h2 className="font-semibold">Notes and findings</h2>
{sectionError('artifacts')}
{canWrite && (
<button
className={actionClass}
onClick={() => {
if (confirmDiscard(dirty)) {
setEditing(null);
setCreator('note');
setParams({});
}
}}
>
New note
</button>
)}
<p className="text-sm text-text-secondary">
Save findings from a completed backtest result to attach exact evidence.
</p>
{!loading && !errors.artifacts && !visibleArtifacts.length && (
<p>No notes or findings yet.</p>
)}
{!errors.artifacts && (
<ul className="space-y-2">
{visibleArtifacts.map(item => (
<li key={item.id}>
<button
className="text-primary-500"
onClick={() => select('artifact', item.id)}
>
{item.latestRevision.title}
</button>
{item.archived && <span className="ml-2 text-xs">Archived</span>}
<p className="text-xs">
{item.kind} · Unvalidated · Revision {item.latestRevision.ordinal}
</p>
</li>
))}
</ul>
)}
</Card>
</div>
{creator && (
<CreateResearchEntry
key={creator}
projectId={projectId}
kind={creator}
writeBlocked={project.archived ? 'Archived project.' : projectWriteBlocked}
onDirty={setCreateDirty}
onClose={() => setCreator(null)}
onRefresh={reload}
onCreated={id => {
setCreator(null);
setCreateDirty(false);
setParams({ [creator === 'hypothesis' ? 'hypothesis' : 'artifact']: id });
reload();
}}
/>
)}
{hypothesisId && artifactId && <p role="alert">Select one research entry at a time.</p>}
{selection && (
<ResearchEntry
key={`${selection.kind}:${selection.id}:${params.get('revision') ?? 'latest'}:${selectionEpoch}`}
projectId={projectId}
id={selection.id}
kind={selection.kind}
revisionId={params.get('revision')}
archived={project.archived}
writeBlocked={projectWriteBlocked}
hypotheses={hypotheses}
onDirty={setEntryDirty}
onRefresh={reload}
onSelectRevision={id => select(selection.kind, selection.id, id)}
/>
)}
</>
)}
</div>
);
}