Skip to content
Draft
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
11 changes: 2 additions & 9 deletions app/src/api/simulationAssociation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ export interface UserSimulationStore {
findByUser: (userId: string, countryId?: string) => Promise<UserSimulation[]>;
findById: (userId: string, simulationId: string) => Promise<UserSimulation | null>;
update: (userSimulationId: string, updates: Partial<UserSimulation>) => Promise<UserSimulation>;
// The below are not yet implemented, but keeping for future use
// delete(userSimulationId: string): Promise<void>;
delete: (userId: string, simulationId: string) => Promise<void>;
}

export class ApiSimulationStore implements UserSimulationStore {
Expand Down Expand Up @@ -88,8 +87,6 @@ export class ApiSimulationStore implements UserSimulationStore {
);
}

// Not yet implemented, but keeping for future use
/*
async delete(userId: string, simulationId: string): Promise<void> {
const response = await fetch(`/api/user-simulation-associations/${userId}/${simulationId}`, {
method: 'DELETE',
Expand All @@ -99,7 +96,6 @@ export class ApiSimulationStore implements UserSimulationStore {
throw new Error('Failed to delete association');
}
}
*/
}

export class LocalStorageSimulationStore implements UserSimulationStore {
Expand Down Expand Up @@ -179,14 +175,11 @@ export class LocalStorageSimulationStore implements UserSimulationStore {
return updated;
}

// Not yet implemented, but keeping for future use
/*
async delete(userId: string, simulationId: string): Promise<void> {
const simulations = this.getStoredSimulations();
const filtered = simulations.filter(
a => !(a.userId === userId && a.simulationId === simulationId)
(association) => !(association.userId === userId && association.simulationId === simulationId)
);
this.setStoredSimulations(filtered);
}
*/
}
90 changes: 73 additions & 17 deletions app/src/api/societyWideCalculation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BASE_URL } from '@/constants';
import { ReportOutputSocietyWideUK } from '@/types/metadata/ReportOutputSocietyWideUK';
import { ReportOutputSocietyWideUS } from '@/types/metadata/ReportOutputSocietyWideUS';
import type { BudgetWindowReportOutput } from '@/types/report/BudgetWindowReportOutput';

export type SocietyWideReportOutput = ReportOutputSocietyWideUS | ReportOutputSocietyWideUK;

Expand All @@ -9,6 +10,7 @@ export interface SocietyWideCalculationParams {
region: string; // Must include a region; "us" for US nationwide, two-letter state code for US states
time_period: string; // Four-digit year
dataset?: string; // Optional dataset parameter; defaults to API's default dataset
version?: string; // Optional API/model version parameter
}

export interface SocietyWideCalculationResponse {
Expand All @@ -19,23 +21,50 @@ export interface SocietyWideCalculationResponse {
error?: string;
}

export async function fetchSocietyWideCalculation(
countryId: string,
reformPolicyId: string,
baselinePolicyId: string,
params: SocietyWideCalculationParams
): Promise<SocietyWideCalculationResponse> {
export interface BudgetWindowCalculationParams {
region: string;
start_year: string;
window_size: number;
dataset?: string;
version?: string | null;
}

export interface BudgetWindowCalculationResponse {
status: 'computing' | 'ok' | 'error';
result: BudgetWindowReportOutput | null;
progress?: number;
completed_years?: string[];
computing_years?: string[];
queued_years?: string[];
message?: string | null;
error?: string;
}

export class CalculationRequestError extends Error {
status: number;
body: string;

constructor(message: string, status: number, body = '') {
super(message);
this.name = 'CalculationRequestError';
this.status = status;
this.body = body;
}
}

function buildQueryString<T extends object>(params: T): string {
const queryParams = new URLSearchParams();

Object.entries(params).forEach(([key, value]) => {
Object.entries(params as Record<string, string | number | undefined>).forEach(([key, value]) => {
if (value !== undefined) {
queryParams.append(key, String(value));
}
});

const queryString = queryParams.toString();
const url = `${BASE_URL}/${countryId}/economy/${reformPolicyId}/over/${baselinePolicyId}${queryString ? `?${queryString}` : ''}`;
return queryParams.toString();
}

async function fetchCalculationResponse<T>(url: string, logPrefix: string): Promise<T> {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
Expand All @@ -49,16 +78,43 @@ export async function fetchSocietyWideCalculation(
} catch {
// ignore
}
console.error(
`[fetchSocietyWideCalculation] ${response.status} ${response.statusText}`,
url,
console.error(`${logPrefix} ${response.status} ${response.statusText}`, url, body);
throw new CalculationRequestError(
`Society-wide calculation failed (${response.status}): ${body || response.statusText}`,
response.status,
body
);
throw new Error(
`Society-wide calculation failed (${response.status}): ${body || response.statusText}`
);
}

const data = await response.json();
return data;
return response.json();
}

export async function fetchSocietyWideCalculation(
countryId: string,
reformPolicyId: string,
baselinePolicyId: string,
params: SocietyWideCalculationParams
): Promise<SocietyWideCalculationResponse> {
const queryString = buildQueryString(params);
const url = `${BASE_URL}/${countryId}/economy/${reformPolicyId}/over/${baselinePolicyId}${queryString ? `?${queryString}` : ''}`;

return fetchCalculationResponse<SocietyWideCalculationResponse>(
url,
'[fetchSocietyWideCalculation]'
);
}

export async function fetchBudgetWindowSocietyWideCalculation(
countryId: string,
reformPolicyId: string,
baselinePolicyId: string,
params: BudgetWindowCalculationParams
): Promise<BudgetWindowCalculationResponse> {
const queryString = buildQueryString(params);
const url = `${BASE_URL}/${countryId}/economy/${reformPolicyId}/over/${baselinePolicyId}/budget-window${queryString ? `?${queryString}` : ''}`;

return fetchCalculationResponse<BudgetWindowCalculationResponse>(
url,
'[fetchBudgetWindowSocietyWideCalculation]'
);
}
28 changes: 15 additions & 13 deletions app/src/components/report/ReportActionButtons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,21 @@ export function ReportActionButtons({
</TooltipTrigger>
<TooltipContent side="bottom">View/edit report</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
aria-label="Reproduce in Python"
onClick={onReproduce}
>
<IconCode size={18} />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Reproduce in Python</TooltipContent>
</Tooltip>
{onReproduce && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
aria-label="Reproduce in Python"
onClick={onReproduce}
>
<IconCode size={18} />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Reproduce in Python</TooltipContent>
</Tooltip>
)}
<ShareButton onClick={onShare} />
</Group>
);
Expand Down
1 change: 1 addition & 0 deletions app/src/hooks/useAggregatedCalculationStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ export function useAggregatedCalculationStatus(

return new QueryObserver<CalcStatus>(queryClient, {
queryKey,
enabled: false,
});
});

Expand Down
1 change: 1 addition & 0 deletions app/src/hooks/useCalculationStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function useSingleCalculationStatus(calcId: string, targetType: 'report' | 'simu
// Create observer that watches this query key
const observer = new QueryObserver<CalcStatus>(queryClient, {
queryKey,
enabled: false,
});

// Subscribe to cache updates
Expand Down
5 changes: 5 additions & 0 deletions app/src/hooks/useCreateReport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Geography } from '@/types/ingredients/Geography';
import { Household } from '@/types/ingredients/Household';
import { Simulation } from '@/types/ingredients/Simulation';
import { ReportCreationPayload } from '@/types/payloads';
import { isBudgetWindowReportYear } from '@/utils/reportTiming';

interface CreateReportAndBeginCalculationParams {
countryId: (typeof countryIds)[number];
Expand Down Expand Up @@ -96,6 +97,10 @@ export function useCreateReport(reportLabel?: string) {
const household = populations?.household1;
const geography = populations?.geography1;

if (isBudgetWindowReportYear(report.year)) {
return;
}

if (!simulation1) {
console.warn('[useCreateReport] No simulation1 provided, cannot start calculation');
return;
Expand Down
21 changes: 19 additions & 2 deletions app/src/pages/ReportOutput.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@ import { useSharedReportData } from '@/hooks/useSharedReportData';
import { useUserReportById } from '@/hooks/useUserReports';
import { formatReportTimestamp } from '@/utils/dateUtils';
import { resolveDefaultReportOutputSubpage } from '@/utils/reportOutputSubpage';
import { isBudgetWindowReportYear } from '@/utils/reportTiming';
import {
buildSharePath,
createShareData,
extractShareDataFromUrl,
getShareDataUserReportId,
} from '@/utils/shareUtils';
import {
BUDGET_WINDOW_SUBPAGE,
resolveBudgetWindowSubpage,
} from './report-output/budget-window/budgetWindowUtils';
import { HouseholdReportOutput } from './report-output/HouseholdReportOutput';
import ReportOutputLayout from './report-output/ReportOutputLayout';
import { SocietyWideReportOutput } from './report-output/SocietyWideReportOutput';
Expand Down Expand Up @@ -112,9 +117,17 @@ export default function ReportOutputPage({
: simulations?.[0]?.populationType === 'geography'
? 'societyWide'
: undefined;
const isBudgetWindowReport =
outputType === 'societyWide' && isBudgetWindowReportYear(report?.year || '');

// Active subpage and view from URL params
const activeTab = resolveDefaultReportOutputSubpage(outputType, subpage);
const defaultResolvedSubpage = resolveDefaultReportOutputSubpage(outputType, subpage, {
societyWideDefaultSubpage: isBudgetWindowReport ? BUDGET_WINDOW_SUBPAGE : undefined,
});
const activeTab =
isBudgetWindowReport && outputType === 'societyWide'
? resolveBudgetWindowSubpage(defaultResolvedSubpage)
: defaultResolvedSubpage;
const activeView = view || '';

// Format the report creation timestamp using the current country's locale
Expand Down Expand Up @@ -185,6 +198,10 @@ export default function ReportOutputPage({

// Handle reproduce button click - navigate to reproduce in Python content
const handleReproduce = () => {
if (isBudgetWindowReport) {
return;
}

const id = isSharedView ? shareDataUserReportId : userReportId;
if (id) {
const basePath = `/${countryId}/report-output/${id}/reproduce`;
Expand Down Expand Up @@ -301,7 +318,7 @@ export default function ReportOutputPage({
onShare={handleShare}
onSave={handleSave}
onView={!isSharedView ? handleView : undefined}
onReproduce={handleReproduce}
onReproduce={!isBudgetWindowReport ? handleReproduce : undefined}
>
<ErrorBoundary
fallback={(error, errorInfo) => (
Expand Down
Loading
Loading