-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathPolicyEngine.jsx
More file actions
440 lines (405 loc) · 14.6 KB
/
PolicyEngine.jsx
File metadata and controls
440 lines (405 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import Home from "./pages/Home";
import Research from "./pages/Research";
import About from "./pages/About";
import Supporters from "./pages/Supporters";
import {
Navigate,
Outlet,
Route,
Routes,
useSearchParams,
} from "react-router-dom";
import Donate from "./pages/Donate";
import { useLocation } from "react-router-dom";
import BlogPage from "./pages/BlogPage";
import AppPage from "./pages/AppPage";
import { COUNTRY_BASELINE_POLICIES, COUNTRY_CODES } from "./data/countries";
import { useEffect, useState, lazy, Suspense } from "react";
import {
copySearchParams,
countryApiCall,
updateMetadata,
useAuthenticatedApiCall,
} from "./api/call";
import LoadingCentered from "./layout/LoadingCentered";
import ErrorPage from "./layout/ErrorPage";
import Header from "./layout/Header";
import Testimonials from "./pages/Testimonials";
import CalculatorInterstitial from "./pages/CalculatorInterstitial";
import CitizensEconomicCouncil from "./applets/CitizensEconomicCouncil";
import APIDocumentationPage from "./pages/learn/APIDocumentationPage";
import SimulationsPage from "./pages/Simulations";
import CookieConsent from "./modals/CookieConsent";
import TrafwaCalculator from "./applets/TrafwaCalculator";
import StateEitcsCtcs from "./applets/StateEitcsCtcs";
import AuthCallback from "./layout/AuthCallback";
import UserProfilePage from "./pages/UserProfilePage";
import PrivacyPage from "./pages/PrivacyPage";
import TACPage from "./pages/TermsAndConditions";
import { useAuth0 } from "@auth0/auth0-react";
import { ConfigProvider } from "antd";
import style from "./style";
import RedirectToCountry from "./routing/RedirectToCountry";
import CountryIdLayout from "./routing/CountryIdLayout";
import RedirectBlogPost from "./routing/RedirectBlogPost";
import { StatusPage } from "./pages/StatusPage";
import ManifestosComparison from "./applets/ManifestosComparison";
import DeveloperLayout from "./pages/DeveloperLayout";
import DeveloperHome from "./pages/DeveloperHome";
import CTCComparison from "./applets/CTCComparison";
import CTCCalculator from "./applets/CTCCalculator";
import GiveCalc from "./applets/GiveCalc";
import { wrappedResponseJson } from "./data/wrappedJson";
import US2024ElectionCalculator from "./applets/US2024ElectionCalculator";
import SALTernative from "./applets/SALTernative";
import AIPage from "./pages/learn/AI";
import MicrosimPage from "./pages/learn/MicrosimPage";
import EducationPage from "./pages/learn/EducationPage";
import OpenSourcePage from "./pages/learn/OpenSourcePage";
import BenefitAccessPage from "./pages/learn/BenefitAccessPage";
import { updateDeprecatedSearchParams } from "./routing/updateDeprecatedSearchParams";
import Jobs from "./pages/Jobs";
const PolicyPage = lazy(() => import("./pages/PolicyPage"));
const HouseholdPage = lazy(() => import("./pages/HouseholdPage"));
function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
export default function PolicyEngine() {
// This will either return the country ID or null,
// but the page is guaranteed to redirect to an ID
const countryId = extractCountryId();
const [searchParams, setSearchParams] = useSearchParams();
const updatedSearchParams = updateDeprecatedSearchParams(searchParams);
if (updatedSearchParams) {
// If we have updated search params, set them
setSearchParams(updatedSearchParams);
}
const householdId = searchParams.get("household");
let defaultBaselinePolicy = 1;
if (COUNTRY_CODES.includes(countryId)) {
defaultBaselinePolicy = COUNTRY_BASELINE_POLICIES[countryId];
}
const reformPolicyId = searchParams.get("reform") || defaultBaselinePolicy;
const baselinePolicyId =
searchParams.get("baseline") || defaultBaselinePolicy;
const [metadata, setMetadata] = useState(null);
const [metadataError, setMetadataError] = useState(false);
const [baselinePolicy, setBaselinePolicy] = useState({
id: baselinePolicyId,
label: null,
data: null,
});
const [reformPolicy, setReformPolicy] = useState({
id: reformPolicyId,
label: null,
data: null,
});
const policy = {
baseline: baselinePolicy,
reform: reformPolicy,
};
const [hasShownHouseholdPopup, setHasShownHouseholdPopup] = useState(false);
const [userProfile, setUserProfile] = useState({});
const { authenticatedApiCall } = useAuthenticatedApiCall();
// Update the metadata state when something happens to
// the countryId (e.g. the user changes the country).
useEffect(() => {
// If we're accessing the page without a country ID,
// our router will handle redirecting to a country ID;
// this process is guaranteed, thus we will just not fetch
// in this situation
if (!countryId) {
return;
}
async function asyncUpdateMetadata() {
try {
const metadata = await updateMetadata(countryId);
if (!metadata) {
setMetadataError(true);
setMetadata(null);
} else {
setMetadata(metadata);
setMetadataError(false);
}
} catch (e) {
console.error(e);
setMetadataError(true);
setMetadata(null);
}
}
asyncUpdateMetadata();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [countryId]);
// Get the baseline policy data when the baseline policy ID changes.
useEffect(() => {
if (metadata) {
countryApiCall(countryId, `/policy/${baselinePolicyId}`)
.then((res) => wrappedResponseJson(res))
.then((dataHolder) => {
if (dataHolder.result.label === "None") {
dataHolder.result.label = null;
}
setBaselinePolicy({
data: dataHolder.result.policy_json,
label: dataHolder.result.label,
id: baselinePolicyId,
});
});
}
}, [baselinePolicyId, countryId, metadata]);
// Get the reform policy data when the reform policy ID changes.
useEffect(() => {
if (metadata) {
countryApiCall(countryId, `/policy/${reformPolicyId}`)
.then((res) => wrappedResponseJson(res))
.then((dataHolder) => {
if (dataHolder.result.label === "None") {
dataHolder.result.label = null;
}
setReformPolicy({
data: dataHolder.result.policy_json,
label: dataHolder.result.label,
id: reformPolicyId,
});
});
}
}, [countryId, reformPolicyId, metadata]);
useEffect(() => {
if (searchParams.get("renamed") && reformPolicyId) {
countryApiCall(countryId, `/policy/${reformPolicyId}`)
.then((res) => wrappedResponseJson(res))
.then((dataHolder) => {
setReformPolicy({
data: dataHolder.result.policy_json,
label: dataHolder.result.label,
id: reformPolicyId,
});
let newSearch = copySearchParams(searchParams);
newSearch.delete("renamed");
setSearchParams(newSearch);
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [countryId, searchParams.get("renamed")]);
// When metadata exists and a user is logged in, fetch user profile
const { isAuthenticated, user } = useAuth0();
useEffect(() => {
async function fetchUserProfile() {
const USER_PROFILE_PATH = `/${countryId}/user-profile`;
// Determine if user already exists in user profile db
try {
const resGet = await authenticatedApiCall(
USER_PROFILE_PATH + `?auth0_id=${user.sub}`,
);
const resGetJson = await resGet.json();
if (resGet.status === 200) {
return resGetJson.result;
} else if (resGet.status === 404 && resGetJson.status === "ok") {
// If not, create user first, then fetch user
const body = {
auth0_id: user.sub,
primary_country: countryId,
user_since: Date.now(),
};
const resPost = await authenticatedApiCall(
USER_PROFILE_PATH,
body,
"POST",
);
const resPostJson = await resPost.json();
if (resPost.status !== 201) {
console.error(
`Error while trying to create new user with auth0_id ${user.sub}`,
);
console.error(resPostJson);
return;
}
return resPostJson.result;
} else {
console.error(
`Error while attempting to fetch user profile for user ${user.sub}`,
);
console.error(resGetJson);
return;
}
} catch (err) {
console.error(
`Connection error while attempting to fetch user profile for user ${user.sub}: ${err}`,
);
return;
}
}
if (countryId && isAuthenticated && user?.sub) {
fetchUserProfile().then((userProfile) => setUserProfile(userProfile));
}
}, [countryId, user?.sub, isAuthenticated, authenticatedApiCall]);
const loadingPage = (
<>
<Header />
<LoadingCentered />
</>
);
const householdPage = (
<Suspense fallback={loadingPage}>
<Header />
<HouseholdPage
metadata={metadata}
householdId={householdId}
policy={policy}
hasShownHouseholdPopup={hasShownHouseholdPopup}
setHasShownHouseholdPopup={setHasShownHouseholdPopup}
/>
</Suspense>
);
const errorPage = <ErrorPage />;
const policyPage = (
<Suspense fallback={loadingPage}>
<Header />
<PolicyPage
metadata={metadata}
householdId={householdId}
policy={policy}
userProfile={userProfile}
/>
</Suspense>
);
// If the path is /, redirect to /[countryId]
// If the path is /[countryId], render the homepage
// If the path is /[countryId]/about, render the about page
// If the path is /[countryId]/research, render the research page
// If the path is not recognized, redirect to /[countryId]
// If the path is /[countryId]/jobs, render the jobs page
return (
<ConfigProvider
theme={{
token: {
borderRadius: 0,
colorPrimary: style.colors.BLUE,
fontFamily: "Roboto Serif",
},
}}
>
<ScrollToTop />
<CookieConsent />
<Routes>
{/* Redirect from / to /[countryId] */}
<Route path="/" element={<RedirectToCountry />} />
<Route path="/callback" element={<AuthCallback />} />
<Route path="/:countryId" element={<CountryIdLayout />}>
<Route index={true} element={<Home />} />
<Route path="about" element={<About />} />
<Route path="jobs" element={<Jobs />} />
<Route path="supporters" element={<Supporters />} />
<Route path="testimonials" element={<Testimonials />} />
<Route path="calculator" element={<CalculatorInterstitial />} />
<Route path="simulations" element={<SimulationsPage />} />
<Route path="developer-tools" element={<DeveloperLayout />}>
<Route index element={<DeveloperHome />} />
<Route path="simulations" element={<SimulationsPage />} />
<Route path="api_status" element={<StatusPage />} />
</Route>
<Route path="research" element={<Outlet />}>
<Route index={true} element={<Research />} />
<Route path=":postName" element={<BlogPage />} />
</Route>
<Route path="donate" element={<Donate />} />
<Route path="privacy" element={<PrivacyPage />} />
<Route path="terms" element={<TACPage />} />
<Route path="ai" element={<AIPage />} />
<Route path="microsim" element={<MicrosimPage />} />
<Route path="benefits" element={<BenefitAccessPage />} />
<Route path="education" element={<EducationPage />} />
<Route path="open-source" element={<OpenSourcePage />} />
<Route path=":appName" element={<AppPage />} />
<Route
path="household/*"
element={
metadataError ? errorPage : metadata ? householdPage : loadingPage
}
/>
<Route
path="policy/*"
element={
metadataError ? errorPage : metadata ? policyPage : loadingPage
}
/>
<Route
path="profile"
element={
!userProfile ? (
<ErrorPage />
) : (
<Navigate to={`/${countryId}/profile/${userProfile.user_id}`} />
)
}
/>
<Route
path="profile/:user_id"
element={
<UserProfilePage
metadata={metadata}
authedUserProfile={userProfile}
metadataError={metadataError}
/>
}
/>
<Route
path="api"
element={<APIDocumentationPage metadata={metadata} />}
/>
{/* redirect from /countryId/blog/slug to /countryId/research/slug */}
<Route path="blog/:postName" element={<RedirectBlogPost />} />
</Route>
<Route path="/uk/cec" element={<CitizensEconomicCouncil />} />
<Route path="/uk/2024-manifestos" element={<ManifestosComparison />} />
<Route
path="/us/trafwa-ctc-calculator"
element={<TrafwaCalculator />}
/>
<Route path="/us/state-eitcs-ctcs" element={<StateEitcsCtcs />} />
<Route
path="/us/child-tax-credit-2024-election-calculator"
element={<CTCComparison />}
/>
<Route
path="/us/child-tax-credit-calculator"
element={<CTCCalculator />}
/>
<Route path="/us/givecalc" element={<GiveCalc />} />
<Route
path="/us/2024-election-calculator"
element={<US2024ElectionCalculator />}
/>
<Route path="/us/salternative" element={<SALTernative />} />
{/* Redirect for unrecognized paths */}
<Route path="*" element={<Navigate to={`/${countryId}`} />} />
</Routes>
</ConfigProvider>
);
}
/**
* Extracts country ID from path or returns null if one doesn't exist
* @returns {String|null}
*/
function extractCountryId() {
const path = window.location.pathname;
const pathParts = path.split("/").filter((item) => item.length > 0);
// If valid, return the normal country ID
if (pathParts.length > 0 && COUNTRY_CODES.includes(pathParts[0])) {
return pathParts[0];
}
// If we have an invalid ID (e.g., "undefined" or "garbage"),
// the router will redirect to "us", so return that as country ID
else if (pathParts.length > 0) {
return "us";
}
// Otherwise, we're on the standard page; return null and allow
// router to redirect
else {
return null;
}
}