Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions ui-react/src/lib/datasets/upload-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,36 @@ export function closeConsumers(
}
return found;
}

export interface GuidedSetupLinkInput {
datasetId: string;
variable: { label: string } | null;
exact: UploadConsumer[];
close: CloseConsumer[];
title: string;
startDate: string;
endDate: string;
/** Only set when the user picked a catalog region; a drawn box is derived from the dataset instead. */
regionId?: string;
}

/**
* The guided model setup URL for a just-uploaded dataset. The exact consumers
* travel as `modelIds` (recommended), the close matches as `closeModelIds`, and
* `modelNames` maps ids to readable names. Nothing here confirms anything: the
* wizard still asks the user to frame the question.
*/
export function guidedSetupLink(input: GuidedSetupLinkInput): string {
const params = new URLSearchParams({ datasetId: input.datasetId });
if (input.exact.length) params.set('modelIds', input.exact.map((c) => c.id).join(','));
if (input.close.length) params.set('closeModelIds', input.close.map((c) => c.id).join(','));
const names: Record<string, string> = {};
for (const c of [...input.exact, ...input.close]) names[c.id] = c.name;
if (Object.keys(names).length) params.set('modelNames', JSON.stringify(names));
if (input.variable) params.set('variable', input.variable.label);
if (input.title.trim()) params.set('goal', input.title.trim());
if (input.startDate) params.set('startDate', input.startDate);
if (input.endDate) params.set('endDate', input.endDate);
if (input.regionId) params.set('regionId', input.regionId);
return `/modeling/problem-statements/start?${params.toString()}`;
}
21 changes: 19 additions & 2 deletions ui-react/src/pages/datasets/DatasetUploadPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ import {
} from '@/lib/ckan-upload';
import { useDebouncedValue } from '@/hooks/useDebouncedValue';
import { useSemanticSearch, useSimilarVariables } from '@/hooks/useSemanticSearch';
import { closeConsumers, consumersOfVariable } from '@/lib/datasets/upload-preview';
import {
closeConsumers,
consumersOfVariable,
guidedSetupLink,
} from '@/lib/datasets/upload-preview';
import { unionBoundingBox, type BoundingBox } from '@/lib/geo/bbox';
import { standardVariableName } from '@/lib/standard-variable-display';
import { useAuth } from '@/lib/auth/useAuth';
Expand Down Expand Up @@ -304,7 +308,20 @@ export function DatasetUploadPage() {
</Link>
</Button>
<Button asChild>
<Link to="/modeling/problem-statements">Use in a thread</Link>
<Link
to={guidedSetupLink({
datasetId: done.datasetId,
variable,
exact: consumers,
close: closeMatches,
title,
startDate,
endDate,
regionId: mode === 'region' ? regionId : undefined,
})}
>
Use in a thread
</Link>
</Button>
<Button variant="ghost" onClick={reset}>
Upload another
Expand Down
29 changes: 25 additions & 4 deletions ui-react/src/pages/datasets/__tests__/DatasetUploadPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -409,10 +409,9 @@ describe('DatasetUploadPage', () => {
expect(sent).toHaveLength(1);
expect(screen.getByText('dynamo-upload-x')).toBeInTheDocument();
expect(screen.getByTestId('upload-state')).toHaveTextContent('Private');
expect(screen.getByRole('link', { name: 'Use in a thread' })).toHaveAttribute(
'href',
'/modeling/problem-statements',
);
const href = screen.getByRole('link', { name: 'Use in a thread' }).getAttribute('href')!;
expect(href.startsWith('/modeling/problem-statements/start?')).toBe(true);
expect(new URLSearchParams(href.split('?')[1]).get('datasetId')).toBe('dynamo-upload-x');
expect(screen.getByRole('link', { name: /dataset page/ })).toHaveAttribute(
'href',
'/datasets/browse/dynamo-upload-x',
Expand Down Expand Up @@ -493,6 +492,28 @@ describe('DatasetUploadPage', () => {
expect(screen.getByTestId('who-can-use')).toHaveTextContent('Rain flow');
});

it('"Use in a thread" opens guided setup with the dataset, exact models and close matches', async () => {
semantic = (u) =>
u.includes('/similar?')
? json({ target: 'svo', id: 'sv-1', results: [{ id: 'sv-2', label: 'rainfall_amount' }] })
: json({ results: [] });
await fill([csv('only.csv')]);
await screen.findByTestId('close-matches');
await userEvent.click(screen.getByRole('button', { name: 'Upload' }));
await screen.findByTestId('upload-success');
const href = screen.getByRole('link', { name: 'Use in a thread' }).getAttribute('href')!;
expect(href.startsWith('/modeling/problem-statements/start?')).toBe(true);
const params = new URLSearchParams(href.split('?')[1]);
expect(params.get('datasetId')).toBe('dynamo-upload-x');
expect(params.get('modelIds')?.split(',')).toEqual(['flow-1', 'model-1']);
expect(params.get('closeModelIds')).toBe('flow-2');
expect(params.get('variable')).toBe('precipitation_flux');
expect(params.get('goal')).toBe('Rain 2020');
expect(params.get('startDate')).toBe('2020-01-01');
expect(params.get('endDate')).toBe('2020-12-31');
expect(JSON.parse(params.get('modelNames')!)).toMatchObject({ 'flow-2': 'Wet flow' });
});

it('hides the suggestion sections quietly when the service is down', async () => {
semantic = () => json({ error: 'down' }, 503);
renderPage();
Expand Down
75 changes: 69 additions & 6 deletions ui-react/src/pages/modeling/GuidedModelSetup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,16 @@ function initialIds(value: string | null, searchValue: string | null): string[]
return [...new Set(values)];
}

function modelNamesParam(value: string | null): Record<string, string> {
if (!value) return {};
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' ? (parsed as Record<string, string>) : {};
} catch {
return {};
}
}

function dateInputValue(value: Date | null | undefined): string {
if (!value) return '';
const date = value instanceof Date ? value : new Date(value);
Expand Down Expand Up @@ -152,11 +162,29 @@ export function GuidedModelSetup({
const [setThreadModels] = useSetThreadModelsMutation();
const [updateThread] = useUpdateThreadMutation();

const [goal, setGoal] = useState('');
// An upload hands over what it already knows. These only seed the fields;
// the user still edits them and confirms.
const uploadedVariable = searchParams.get('variable');
const closeModelIds = useMemo(
() => initialIds(null, searchParams.get('closeModelIds')),
[searchParams],
);
const modelNames = useMemo(() => modelNamesParam(searchParams.get('modelNames')), [searchParams]);
const recommendedForData = uploadedVariable
? startingModelIds.filter((id) => !closeModelIds.includes(id))
: [];
const contextModelIds = startingModelIds.filter(
(id) => !recommendedForData.includes(id) && !closeModelIds.includes(id),
);
const nameOf = (id: string) => displayLabel(id, modelNames[id]);

const [goal, setGoal] = useState(() => searchParams.get('goal') ?? '');
const [outcome, setOutcome] = useState('');
const [regionId, setRegionId] = useState('');
const [startDate, setStartDate] = useState('2000-01-01');
const [endDate, setEndDate] = useState(new Date().toISOString().slice(0, 10));
const [regionId, setRegionId] = useState(() => searchParams.get('regionId') ?? '');
const [startDate, setStartDate] = useState(() => searchParams.get('startDate') || '2000-01-01');
const [endDate, setEndDate] = useState(
() => searchParams.get('endDate') || new Date().toISOString().slice(0, 10),
);
const [selectedDatasetMetadata, setSelectedDatasetMetadata] = useState<Dataset[]>([]);
const [destination, setDestination] = useState<'new' | 'existing'>('new');
const [existingProblemStatementId, setExistingProblemStatementId] = useState('');
Expand Down Expand Up @@ -444,11 +472,11 @@ export function GuidedModelSetup({
</div>
</div>

{(modelId || datasetId) && (
{(startingModelIds.length > 0 || startingDatasetIds.length > 0) && (
<section className="rounded-lg border bg-muted/30 p-4" aria-label="Starting context">
<div className="mb-2 text-sm font-semibold">Starting context</div>
<div className="flex flex-wrap gap-2 text-sm">
{startingModelIds.map((id) => (
{contextModelIds.map((id) => (
<button
key={`model-${id}`}
type="button"
Expand All @@ -475,6 +503,41 @@ export function GuidedModelSetup({
</section>
)}

{uploadedVariable && (recommendedForData.length > 0 || closeModelIds.length > 0) && (
<section className="rounded-lg border p-5" aria-label="Models for your uploaded data">
<h2 className="mb-1 font-semibold">Models that can use your data</h2>
<p className="mb-4 text-sm text-muted-foreground">
Pick the ones to carry into setup. Nothing is saved until you confirm.
</p>
<div className="grid gap-5 md:grid-cols-2">
<RecommendationGroup title="Recommended" empty="No model takes this variable exactly.">
{recommendedForData.map((id) => (
<RecommendationCard
key={id}
title={nameOf(id)}
evidence={`Takes ${uploadedVariable}, the variable of your uploaded data`}
checked={selectedModelIds.has(id)}
onToggle={() => toggle(setSelectedModelIds, id)}
/>
))}
</RecommendationGroup>
{closeModelIds.length > 0 && (
<RecommendationGroup title="Close matches" empty="">
{closeModelIds.map((id) => (
<RecommendationCard
key={id}
title={nameOf(id)}
evidence="Close match, not an exact fit"
checked={selectedModelIds.has(id)}
onToggle={() => toggle(setSelectedModelIds, id)}
/>
))}
</RecommendationGroup>
)}
</div>
</section>
)}

<section className="rounded-lg border p-5">
<div className="mb-4 flex items-center gap-2">
<Sparkles className="h-5 w-5 text-blue-600" />
Expand Down
65 changes: 65 additions & 0 deletions ui-react/src/pages/modeling/__tests__/GuidedModelSetup.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,69 @@ describe('GuidedModelSetup', () => {
});
expect(screen.getByText(/prefilled from the selected dataset metadata/i)).toBeInTheDocument();
});

describe('opened from an upload', () => {
const entry =
'/modeling/problem-statements/start?datasetId=my-upload' +
'&modelIds=flow-1,model-1&closeModelIds=flow-2&variable=precipitation_flux' +
'&modelNames=' +
encodeURIComponent(JSON.stringify({ 'flow-1': 'Rain flow', 'flow-2': 'Wet flow' })) +
'&goal=Rain%202020&startDate=2020-01-01&endDate=2020-12-31';
const regionsMock = {
request: { query: LIST_TOP_REGIONS },
result: { data: { region: [] } },
};

it('preselects the dataset and lists recommended models first, with the reason', () => {
renderWithProviders(<GuidedModelSetup />, {
initialEntries: [entry],
apolloMocks: [regionsMock],
});
expect(screen.getByRole('button', { name: /dataset: my-upload ✓/i })).toBeInTheDocument();
expect(fetchDatasetDetail).toHaveBeenCalledWith('my-upload');
const section = screen.getByRole('region', { name: 'Models for your uploaded data' });
const text = section.textContent ?? '';
expect(text.indexOf('Recommended')).toBeLessThan(text.indexOf('Close matches'));
expect(text.indexOf('Rain flow')).toBeLessThan(text.indexOf('Wet flow'));
expect(text).toContain('Takes precipitation_flux, the variable of your uploaded data');
expect(text).toContain('Close match, not an exact fit');
expect(screen.getByRole('button', { name: /Rain flow/ })).toHaveAttribute(
'aria-pressed',
'true',
);
expect(screen.getByRole('button', { name: /Wet flow/ })).toHaveAttribute(
'aria-pressed',
'false',
);
});

it('prefills the question and period, leaves them editable and confirms nothing', async () => {
const user = userEvent.setup();
renderWithProviders(<GuidedModelSetup />, {
initialEntries: [entry],
apolloMocks: [regionsMock],
});
const goal = screen.getByLabelText(/what are you trying/i);
expect(goal).toHaveValue('Rain 2020');
expect(screen.getByLabelText('Start date *')).toHaveValue('2020-01-01');
expect(screen.getByLabelText('End date *')).toHaveValue('2020-12-31');
await user.clear(goal);
await user.type(goal, 'Something else');
expect(goal).toHaveValue('Something else');
expect(screen.queryByRole('button', { name: /confirm and start setup/i })).toBeNull();
});

it('lets a close match be added to the selection', async () => {
const user = userEvent.setup();
renderWithProviders(<GuidedModelSetup />, {
initialEntries: [entry],
apolloMocks: [regionsMock],
});
await user.click(screen.getByRole('button', { name: /Wet flow/ }));
expect(screen.getByRole('button', { name: /Wet flow/ })).toHaveAttribute(
'aria-pressed',
'true',
);
});
});
});
Loading