From baaa2e1c57c4c174ede8671cf652b089db163b42 Mon Sep 17 00:00:00 2001 From: Emmanuel Raviart <emmanuel@raviart.com> Date: Mon, 28 Oct 2024 19:48:19 +0100 Subject: [PATCH] Split config into public_config & private_config --- example.env | 105 +++++++------- .../config.ts => auditors/public_config.ts} | 99 ++----------- src/lib/calculations.svelte.ts | 18 +-- .../BudgetSimulationSharingModal.svelte | 5 +- src/lib/components/ModificationsPanel.svelte | 24 ++-- src/lib/components/NavBar.svelte | 3 +- src/lib/components/ReformsChanges.svelte | 18 ++- .../TestCaseSimulationSharingModal.svelte | 8 +- .../components/WaterfallCompareView.svelte | 6 +- src/lib/components/WaterfallPlainView.svelte | 9 +- src/lib/components/WaterfallView.svelte | 9 +- src/lib/components/legifrance/LienView.svelte | 8 +- .../components/parameters/ArticleModal.svelte | 5 +- .../parameters/ParameterView.svelte | 5 +- .../test_cases/OilSpendingBill.svelte | 4 +- .../test_cases/TestCaseCompareView.svelte | 23 ++- .../components/test_cases/TestCaseEdit.svelte | 12 +- .../TestCaseEditVariablesSearch.svelte | 6 +- .../test_cases/TestCaseFilters.svelte | 19 +-- .../test_cases/TestCaseGraph.svelte | 8 +- .../test_cases/TestCaseGraphXlsxExport.svelte | 10 +- .../test_cases/TestCasePictos.svelte | 5 +- .../test_cases/TestCaseSummary.svelte | 21 +-- .../components/test_cases/TestCaseView.svelte | 38 +++-- .../transverse_pages/OpenGraph.svelte | 5 +- .../components/variables/FormulaView.svelte | 4 +- .../variables/InflationLawButton.svelte | 7 +- .../variables/InflationLawDetails.svelte | 11 +- .../variables/InflationLawInfoModal.svelte | 5 +- .../variables/VariableDetail.svelte | 7 +- .../components/variables/VariableInput.svelte | 13 +- .../VariableReferredParameters.svelte | 84 ++++++----- .../VariableReferredScaleParameter.svelte | 10 +- .../VariableReferredValueParameter.svelte | 10 +- .../variables/VariableValueChange.svelte | 14 +- .../components/variables/VariableView.svelte | 4 +- src/lib/public_config.ts | 100 +++++++++++++ src/lib/server/auditors/server_config.ts | 131 ++++++++++++++++++ src/lib/server/budgets.ts | 6 +- src/lib/server/config.ts | 108 --------------- src/lib/server/openid_connect_handler.ts | 6 +- src/lib/server/server_config.ts | 64 +++++++++ src/lib/server/test_cases.ts | 8 +- src/lib/server/user_handler.ts | 6 +- src/routes/+error.svelte | 5 +- src/routes/+layout.server.ts | 58 +------- src/routes/+layout.svelte | 43 +++--- src/routes/+page.svelte | 22 ++- src/routes/accueil/+page.svelte | 9 +- src/routes/auth/login/+server.ts | 4 +- src/routes/auth/login_callback/+server.ts | 26 ++-- src/routes/auth/logout/+server.ts | 4 +- src/routes/auth/logout_callback/+server.ts | 4 +- src/routes/budgets/+server.ts | 18 +-- src/routes/budgets/demands/+server.ts | 9 +- src/routes/budgets/simulations/+server.ts | 6 +- .../simulations/[simulation]/+page.server.ts | 4 +- .../budgets/simulations/index/+server.ts | 4 +- src/routes/contribuer/+page.svelte | 9 +- src/routes/entities/+page.svelte | 11 +- src/routes/fonctionnement/+page.svelte | 9 +- src/routes/parameters/+page.svelte | 13 +- .../parameters/[parameter]/+page.svelte | 4 +- src/routes/parameters/[parameter]/+server.ts | 6 +- .../parameters/[parameter]/edit/+page.svelte | 4 +- .../parameters/[parameter]/edit/+page.ts | 5 +- src/routes/robots.txt/+server.ts | 4 +- src/routes/test_cases/+server.ts | 4 +- .../simulations/[simulation]/+page.svelte | 6 +- src/routes/variables/+page.svelte | 11 +- src/routes/variables/[variable]/+page.svelte | 4 +- .../[variable]/inputs/[date]/+page.svelte | 5 +- .../[variable]/parameters/[date]/+page.svelte | 14 +- .../variables/[variable]/xlsx/+page.svelte | 4 +- src/scripts/clear_simulations_cache.ts | 4 +- 75 files changed, 728 insertions(+), 676 deletions(-) rename src/lib/{server/auditors/config.ts => auditors/public_config.ts} (69%) create mode 100644 src/lib/public_config.ts create mode 100644 src/lib/server/auditors/server_config.ts delete mode 100644 src/lib/server/config.ts create mode 100644 src/lib/server/server_config.ts diff --git a/example.env b/example.env index 42dd53018..a9a5ece8a 100644 --- a/example.env +++ b/example.env @@ -1,18 +1,7 @@ # To use this file, rename it to `.env`. -# Are advanced & experimental features enabled? -# ADVANCED=false - # Are search robots allowed to index this site? -# ALLOW_ROBOTS=false - -# Public HTTP(S) URLs of LexImpact Socio-Fiscal API server -API_BASE_URLS="https://simulateur-socio-fiscal.leximpact.dev/api/" -# API_BASE_URLS="http://localhost:8000" - -# Public HTTP(S) URL of LexImpact Socio-Fiscal UI server (aka this application) -# BASE_URL="https://simulateur-socio-fiscal.leximpact.dev/" -BASE_URL="http://localhost:5173" +ALLOW_ROBOTS=false # Private (for connected users) HTTP(S) URL of LexImpact Socio-Fiscal Budget server # BUDGET_API_URL="https://SECRET.DOMAIN.NAME/state_simulation" @@ -26,76 +15,86 @@ BASE_URL="http://localhost:5173" # Secret key used to sign JSON web tokens sent to Budget API # BUDGET_JWT_SECRET="SECRET" +# GitHub access token used for parameters edition +# Caution, this token is private and must be kept secret. +# GITHUB_PERSONAL_ACCESS_TOKEN="GITHUB_PERSONAL_ACCESS_TOKEN" +GITHUB_PERSONAL_ACCESS_TOKEN= + +# Secret key used to sign & verify JSON web token used to store user informations in cookie +JWT_SECRET="SECRET" + +# OpenID Connect configuration +# OPENID_CONNECT_CLIENT_ID="OAUTH2_CLIENT_ID" +# OPENID_CONNECT_CLIENT_SECRET="OAUTH2_CLIENT_SECRET" +# OPENID_CONNECT_ISSUER_URL="https://IDENTITY_PROVIDER/PATH/TO/REALM" + +# Are advanced & experimental features enabled? +# PUBLIC_ADVANCED=false + +# Public HTTP(S) URLs of LexImpact Socio-Fiscal API server +PUBLIC_API_BASE_URLS="https://simulateur-socio-fiscal.leximpact.dev/api/" +# PUBLIC_API_BASE_URLS="http://localhost:8000" + +# Public HTTP(S) URL of LexImpact Socio-Fiscal UI server (aka this application) +# PUBLIC_BASE_URL="https://simulateur-socio-fiscal.leximpact.dev/" +PUBLIC_BASE_URL="http://localhost:5173" + # Key for children in a family -CHILDREN_KEY="enfants" +PUBLIC_CHILDREN_KEY="enfants" # Key for family entity -FAMILY_KEY="famille" - -# GitHub access token used for parameters edition -# Caution, this token is private and must be kept secret. -GITHUB_PERSONAL_ACCESS_TOKEN=null +PUBLIC_FAMILY_KEY="famille" # Comma-separated list of entities ("familles", "foyers_fiscaux", "menages" for France) # that should not be shown when editing test cases -HIDDEN_ENTITIES=menages +PUBLIC_HIDDEN_ENTITIES=menages # Key for household entity -HOUSEHOLD_KEY="menage" - -# Secret key used to sign & verify JSON web token used to store user informations in cookie -JWT_SECRET="SECRET" +PUBLIC_HOUSEHOLD_KEY="menage" # URL of web service that provides Legifrance data (law articles, etc) -LEGAL_URL="https://legal.tricoteuses.fr/" +PUBLIC_LEGAL_URL="https://legal.tricoteuses.fr/" # Matomo analytics configuration -# MATOMO_SITE_ID=123 -# MATOMO_URL="https://MATOMO_SERVER/" +# PUBLIC_MATOMO_SITE_ID=123 +PUBLIC_MATOMO_SITE_ID= +PUBLIC_MATOMO_URL="https://MATOMO_SERVER/" # Prepend the site domain to the page title when tracking (optional, default = false). -# MATOMO_PREPEND_DOMAIN=true +PUBLIC_MATOMO_PREPEND_DOMAIN=true # Track visitors accross a domain (for example, example.com & its subdomains (optional). -# MATOMO_SUBDOMAINS="*.DOMAIN" - -# OpenID Connect configuration -# OPENID_CONNECT_CLIENT_ID="OAUTH2_CLIENT_ID" -# OPENID_CONNECT_CLIENT_SECRET="OAUTH2_CLIENT_SECRET" -# OPENID_CONNECT_ISSUER_URL="https://IDENTITY_PROVIDER/PATH/TO/REALM" +PUBLIC_MATOMO_SUBDOMAINS="*.DOMAIN" # Description of OpenFisca country repository -OPENFISCA_BRANCH="master" -OPENFISCA_GROUP="openfisca" -OPENFISCA_PROJECT="openfisca-france" -OPENFISCA_REPOSITORY_RAW_URL_TEMPLATE="https://raw.githubusercontent.com/${group}/${project}/${branch}/${path}" -OPENFISCA_REPOSITORY_URL_TEMPLATE="https://github.com/${group}/${project}/blob/${branch}/${path}" +PUBLIC_OPENFISCA_BRANCH="master" +PUBLIC_OPENFISCA_GROUP="openfisca" +PUBLIC_OPENFISCA_PROJECT="openfisca-france" +PUBLIC_OPENFISCA_REPOSITORY_RAW_URL_TEMPLATE="https://raw.githubusercontent.com/${group}/${project}/${branch}/${path}" +PUBLIC_OPENFISCA_REPOSITORY_URL_TEMPLATE="https://github.com/${group}/${project}/blob/${branch}/${path}" # URL of portal site (used when clicking on left logo in menu bar) -PORTAL_URL="https://leximpact.an.fr/" - -# Set to true when application is behind a proxy -PROXY=false +PUBLIC_PORTAL_URL="https://leximpact.an.fr/" # Optional name of default reform to use # Reform name must belong to a name of an OpenFisca reform in metadata.json -# REFORM=reforme_test_1 +# PUBLIC_REFORM=reforme_test_1 # Optional name of revaluation reform to use # Reform name must belong to a name of an OpenFisca reform in metadata.json -# REFORM_REVALUATION=contrefactuel_plf +# PUBLIC_REFORM_REVALUATION=contrefactuel_plf # Show intro balloons. -SHOW_TUTORIAL=true +PUBLIC_SHOW_TUTORIAL=true + +# Key for taxable household (aka "foyer fiscal") entity +PUBLIC_TAXABLE_HOUSEHOLD_KEY="foyer_fiscal" + +# URL of autocompleter of French communes +PUBLIC_TERRITOIRES_URL="https://territoires.leximpact.dev/" + +PUBLIC_TITLE="Simulateur socio-fiscal" # Directory containing cache of budget simulations SIMULATIONS_BUDGET_DIR="../simulations_budget" # Directory containing cache of test cases simulations SIMULATIONS_TEST_CASES_DIR="../simulations_cas_types" - -# Key for taxable household (aka "foyer fiscal") entity -TAXABLE_HOUSEHOLD_KEY="foyer_fiscal" - -# URL of autocompleter of French communes -TERRITOIRES_URL="https://territoires.leximpact.dev/" - -TITLE="Simulateur socio-fiscal" diff --git a/src/lib/server/auditors/config.ts b/src/lib/auditors/public_config.ts similarity index 69% rename from src/lib/server/auditors/config.ts rename to src/lib/auditors/public_config.ts index 823d02997..c2d04a30e 100644 --- a/src/lib/server/auditors/config.ts +++ b/src/lib/auditors/public_config.ts @@ -16,7 +16,7 @@ import { type Audit, } from "@auditors/core" -export function auditConfig( +export function auditPublicConfig( audit: Audit, dataUnknown: unknown, ): [unknown, unknown] { @@ -31,7 +31,7 @@ export function auditConfig( const errors: { [key: string]: unknown } = {} const remainingKeys = new Set(Object.keys(data)) - for (const key of ["advanced", "allowRobots", "proxy", "showTutorial"]) { + for (const key of ["advanced", "showTutorial"]) { audit.attribute( data, key, @@ -54,47 +54,35 @@ export function auditConfig( auditUnique, auditRequire, ) - for (const key of ["baseUrl", "legalUrl", "portalUrl", "territoiresUrl"]) { + for (const key of [ + "appTitle", + "childrenKey", + "familyEntityKey", + "householdEntityKey", + "taxableHouseholdEntityKey", + ]) { audit.attribute( data, key, true, errors, remainingKeys, - auditHttpUrl, + auditTrimString, auditRequire, ) } - for (const key of ["budgetApiUrl", "budgetDemandPipelineUrl"]) { - audit.attribute(data, key, true, errors, remainingKeys, auditHttpUrl) - } - for (const key of [ - "childrenKey", - "familyEntityKey", - "householdEntityKey", - "jwtSecret", - "simulationsBudgetDir", - "simulationsTestCasesDir", - "taxableHouseholdEntityKey", - "title", - ]) { + for (const key of ["baseUrl", "legalUrl", "portalUrl", "territoiresUrl"]) { audit.attribute( data, key, true, errors, remainingKeys, - auditTrimString, + auditHttpUrl, auditRequire, ) } - for (const key of [ - "budgetDemandPipelineToken", - "budgetJwtSecret", - "githubPersonalAccessToken", - "reformName", - "revaluationName", - ]) { + for (const key of ["reformName", "revaluationName"]) { audit.attribute(data, key, true, errors, remainingKeys, auditTrimString) } audit.attribute( @@ -118,14 +106,6 @@ export function auditConfig( auditRepositoryConfig, auditRequire, ) - audit.attribute( - data, - "openIdConnect", - true, - errors, - remainingKeys, - auditOpenIdConnect, - ) return audit.reduceRemaining(data, errors, remainingKeys) } @@ -225,55 +205,6 @@ export function auditRepositoryConfig( return audit.reduceRemaining(data, errors, remainingKeys) } -function auditOpenIdConnect( - audit: Audit, - dataUnknown: unknown, -): [unknown, unknown] { - if (dataUnknown == null) { - return [dataUnknown, null] - } - if (typeof dataUnknown !== "object") { - return audit.unexpectedType(dataUnknown, "object") - } - - const data = { ...dataUnknown } - const errors: { [key: string]: unknown } = {} - const remainingKeys = new Set(Object.keys(data)) - - // for (const key of [ - // "cert", - // "decryptionCertificatePath", - // "decryptionPrivateKeyPath", - // "identifierFormat", - // "signatureCertificatePath", - // "signaturePrivateKeyPath", - // ]) { - // audit.attribute(data, key, true, errors, remainingKeys, auditTrimString) - // } - for (const key of ["clientId", "clientSecret"]) { - audit.attribute( - data, - key, - true, - errors, - remainingKeys, - auditTrimString, - auditRequire, - ) - } - audit.attribute( - data, - "issuerUrl", - true, - errors, - remainingKeys, - auditHttpUrl, - auditRequire, - ) - - return audit.reduceRemaining(data, errors, remainingKeys) -} - -export function validateConfig(data: unknown): [unknown, unknown] { - return auditConfig(cleanAudit, data) +export function validatePublicConfig(data: unknown): [unknown, unknown] { + return auditPublicConfig(cleanAudit, data) } diff --git a/src/lib/calculations.svelte.ts b/src/lib/calculations.svelte.ts index 549ad37a2..85ad0fed0 100644 --- a/src/lib/calculations.svelte.ts +++ b/src/lib/calculations.svelte.ts @@ -2,10 +2,12 @@ import type { Evaluation } from "$lib/decompositions" import type { ParametricReform } from "$lib/reforms" import type { VariableValueByCalculationName } from "$lib/variables" import { entityByKey } from "./entities" +import publicConfig from "./public_config" import type { SituationWithAxes } from "./situations" export type CalculationName = "amendment" | "bill" | "law" | "revaluation" +const { reformName, revaluationName } = publicConfig export const calculationNames: CalculationName[] = [ "law", "revaluation", @@ -168,7 +170,7 @@ function calculateTestCases({}: { const revaluationSituationIndex = situationIndexByCalculationName.revaluation if ( revaluationSituationIndex !== undefined && - $revaluationName !== undefined + revaluationName !== undefined ) { const calculation: Calculation = (newCalculationByName.revaluation = { running: true, @@ -182,12 +184,12 @@ function calculateTestCases({}: { } calculation.input = { ...message, - reform: $revaluationName, + reform: revaluationName, situation, variables: [ ...summaryCalculatedVariablesName, ...otherCalculatedVariablesName, - ...(nonVirtualVariablesNameByReformName[$revaluationName] ?? + ...(nonVirtualVariablesNameByReformName[revaluationName] ?? nonVirtualVariablesName), ], } @@ -208,12 +210,12 @@ function calculateTestCases({}: { } calculation.input = { ...message, - reform: $billName, + reform: reformName, situation, variables: [ ...summaryCalculatedVariablesName, ...otherCalculatedVariablesName, - ...(nonVirtualVariablesNameByReformName[$billName] ?? + ...(nonVirtualVariablesNameByReformName[reformName] ?? nonVirtualVariablesName), ], } @@ -280,13 +282,13 @@ function calculateTestCases({}: { calculation.input = { ...message, parametric_reform: $parametricReform, - reform: $billName ?? $revaluationName, // Will be removed when $billName and $revaluationName are undefined. + reform: reformName ?? revaluationName, // Will be removed when reformName and revaluationName are undefined. situation, variables: [ ...summaryCalculatedVariablesName, ...otherCalculatedVariablesName, - ...(nonVirtualVariablesNameByReformName[$billName as string] ?? - nonVirtualVariablesNameByReformName[$revaluationName as string] ?? + ...(nonVirtualVariablesNameByReformName[reformName as string] ?? + nonVirtualVariablesNameByReformName[revaluationName as string] ?? nonVirtualVariablesName), ], } diff --git a/src/lib/components/BudgetSimulationSharingModal.svelte b/src/lib/components/BudgetSimulationSharingModal.svelte index 5349e3d46..f192ebaf1 100644 --- a/src/lib/components/BudgetSimulationSharingModal.svelte +++ b/src/lib/components/BudgetSimulationSharingModal.svelte @@ -5,10 +5,10 @@ import { getContext, mount, unmount } from "svelte" import type { Writable } from "svelte/store" - import { page } from "$app/stores" import type { BudgetSimulation } from "$lib/budgets" import CopyClipboard from "$lib/components/CopyClipboard.svelte" import type { DisplayMode } from "$lib/displays" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import { budgetEditableParametersName } from "$lib/variables" @@ -17,6 +17,7 @@ isOpen?: boolean } + const { baseUrl } = publicConfig let { displayMode, isOpen = $bindable(false) }: Props = $props() const budgetSimulation = getContext("budgetSimulation") as Writable< @@ -36,7 +37,7 @@ let url = $derived( new URL( `/budgets/simulations/${$budgetSimulation?.hash}`, - $page.data.baseUrl, + baseUrl, ).toString(), ) diff --git a/src/lib/components/ModificationsPanel.svelte b/src/lib/components/ModificationsPanel.svelte index 51a14923f..77aa46605 100644 --- a/src/lib/components/ModificationsPanel.svelte +++ b/src/lib/components/ModificationsPanel.svelte @@ -20,6 +20,7 @@ } from "$lib/decompositions" import type { DisplayMode } from "$lib/displays" import { rootParameter, rootParameterByReformName } from "$lib/parameters" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import { extractInputInstantsFromTestCases, @@ -36,9 +37,9 @@ displayMode: DisplayMode } + const { reformName, revaluationName } = publicConfig let { displayMode }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> const decompositionByName = getContext( "decompositionByName", ) as Writable<DecompositionByName> @@ -56,9 +57,6 @@ const parametricReform = getContext( "parametricReform", ) as Writable<ParametricReform> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > const testCases = getContext("testCases") as Writable<Situation[]> const valuesByCalculationNameByVariableNameArray = getContext( "valuesByCalculationNameByVariableNameArray", @@ -75,9 +73,9 @@ $testCases = structuredClone(testCasesCore) $decompositionByName = buildDecompositionByNameFromCore( - $billName === undefined + reformName === undefined ? decompositionCoreByName - : (decompositionCoreByNameByReformName[$billName] ?? + : (decompositionCoreByNameByReformName[reformName] ?? decompositionCoreByName), ) as DecompositionByName $evaluationByNameArray = new Array($testCases.length).fill({}) @@ -108,23 +106,23 @@ ), ) let revaluationParameterByName = $derived( - $revaluationName === undefined + revaluationName === undefined ? undefined : Object.fromEntries( - [...walkParameters(rootParameterByReformName[$revaluationName])].map( + [...walkParameters(rootParameterByReformName[revaluationName])].map( (parameter) => [parameter.name, parameter], ), ), ) let revaluationOrLawParameterByName = $derived( - $revaluationName === undefined + revaluationName === undefined ? parameterByName : revaluationParameterByName, ) let revaluationParametersFiltered = $derived( - $revaluationName === undefined + revaluationName === undefined ? [] - : [...walkParameters(rootParameterByReformName[$revaluationName])].filter( + : [...walkParameters(rootParameterByReformName[revaluationName])].filter( (parameter) => !parameter.name?.startsWith("inflateurs") && parameterByName[parameter.name] !== undefined && @@ -141,9 +139,9 @@ ), ) let billParametersFiltered = $derived( - $billName === undefined + reformName === undefined ? [] - : [...walkParameters(rootParameterByReformName[$billName])].filter( + : [...walkParameters(rootParameterByReformName[reformName])].filter( (parameter) => { if (parameter.name?.startsWith("inflateurs")) { return false diff --git a/src/lib/components/NavBar.svelte b/src/lib/components/NavBar.svelte index d2e9c528f..e90de7f26 100644 --- a/src/lib/components/NavBar.svelte +++ b/src/lib/components/NavBar.svelte @@ -20,9 +20,11 @@ import type { DisplayMode } from "$lib/displays" import { trackSearchVariable } from "$lib/matomo" import type { NavbarConfig } from "$lib/navbar" + import publicConfig from "$lib/public_config" import WithLinkedVariablesSearchWorker from "$lib/search/search_worker_variables_with_linked?worker" import { newSimulationUrl } from "$lib/urls" + const { portalUrl } = publicConfig const billActive = getContext("billActive") as Writable<boolean> const displayMode = getContext("displayMode") as Writable< DisplayMode | undefined @@ -74,7 +76,6 @@ let isSearchInProgress = false let focused = $state(false) let pendingQuery: string | null = null - const portalUrl = $page.data.portalUrl let preventBlur = $state(false) const searchVariableName = getContext("searchVariableName") as Writable< string | undefined diff --git a/src/lib/components/ReformsChanges.svelte b/src/lib/components/ReformsChanges.svelte index 4a1f62295..c8f5d9a51 100644 --- a/src/lib/components/ReformsChanges.svelte +++ b/src/lib/components/ReformsChanges.svelte @@ -22,6 +22,7 @@ rootParameter, rootParameterByReformName, } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { ParameterReformChangeType, type ParametricReform, @@ -40,6 +41,7 @@ revaluationParametersFiltered: Parameter[] } + const { reformName, revaluationName } = publicConfig let { billParametersFiltered, displayMode, @@ -47,7 +49,6 @@ }: Props = $props() const billActive = getContext("billActive") as Writable<boolean> - const billName = getContext("billName") as Writable<string | undefined> let billParametersListOpen = $state(false) const budgetDate = getContext("budgetDate") as Writable<string> const decompositionByName = getContext( @@ -56,9 +57,6 @@ const parametricReform = getContext( "parametricReform", ) as Writable<ParametricReform> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > let revaluationParametersListOpen = $state(false) const yearPLF = getContext("yearPLF") as Writable<number> @@ -110,13 +108,13 @@ : undefined } // $: billChanges = - // $billName === undefined ? undefined : reformChangesByName[$billName] + // reformName === undefined ? undefined : reformChangesByName[reformName] // Note: A reform parameters tree is always more complete than a parameters tree before reform. // And the children of a reform node parameter always contain the children of the node parameter // before reform (albeit with some different value parameters). let billRootParameter = $derived( - rootParameterByReformName[$billName] ?? rootParameter, + rootParameterByReformName[reformName] ?? rootParameter, ) // function* walkParametersChangeName(parameterChange, ids: string[] = []) { // if (Object.keys(parameterChange).length === 1) { @@ -143,7 +141,7 @@ // Note: A reform variable is always more complete than a variable before reform. // But it may contain different formulas, with different parameters & variables. let billVariableSummaryByName = $derived( - variableSummaryByNameByReformName[$billName] ?? variableSummaryByName, + variableSummaryByNameByReformName[reformName] ?? variableSummaryByName, ) let decompositionVariableSummaryByName = $derived( Object.fromEntries( @@ -363,7 +361,7 @@ <span> Indexation sur l'inflation à {getInflatorLatestValueFormatted( parameter, - $revaluationName, + revaluationName, )} </span> </div> @@ -489,7 +487,7 @@ <span> Indexation d'usage par le PLF {$yearPLF} à {getInflatorLatestValueFormatted( parameter, - $billName, + reformName, )} </span> </div> @@ -505,7 +503,7 @@ ></div> {/if} <!-- <h5 class="text-sm"> - {reformMetadataByName[$billName].label} : + {reformMetadataByName[reformName].label} : </h5> <ul class="list-inside"> {#each Object.values(billChanges?.editable_processed_parameters ?? {}) as rootParameterChange} diff --git a/src/lib/components/TestCaseSimulationSharingModal.svelte b/src/lib/components/TestCaseSimulationSharingModal.svelte index 01f60249d..6ed12280e 100644 --- a/src/lib/components/TestCaseSimulationSharingModal.svelte +++ b/src/lib/components/TestCaseSimulationSharingModal.svelte @@ -1,24 +1,22 @@ <script lang="ts"> import { Dialog } from "bits-ui" - import { page } from "$app/stores" import CopyClipboard from "$lib/components/CopyClipboard.svelte" + import publicConfig from "$lib/public_config" import { mount, unmount } from "svelte" interface Props { config: { open: boolean; token?: string } } + const { baseUrl } = publicConfig let { config = $bindable() }: Props = $props() let clipboardElement: HTMLElement = $state() let hasClickedCopy = $state(false) let url = $derived( - new URL( - `/test_cases/simulations/${config.token}`, - $page.data.baseUrl, - ).toString(), + new URL(`/test_cases/simulations/${config.token}`, baseUrl).toString(), ) let shareButtons = $derived([ diff --git a/src/lib/components/WaterfallCompareView.svelte b/src/lib/components/WaterfallCompareView.svelte index c3fa5fde4..4802d5f44 100644 --- a/src/lib/components/WaterfallCompareView.svelte +++ b/src/lib/components/WaterfallCompareView.svelte @@ -15,6 +15,7 @@ import { buildVisibleDecompositionsForComparison } from "$lib/decompositions" import type { DisplayMode } from "$lib/displays" import { entityByKey } from "$lib/entities" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import type { CalculationByName, Situation } from "$lib/situations" import { newSimulationUrl } from "$lib/urls" @@ -31,6 +32,7 @@ year: number } + const { revaluationName } = publicConfig let { decompositionByName = $bindable(), displayMode, @@ -63,9 +65,7 @@ const vectorLength = getContext("vectorLength") as Writable<number> const waterfall = getContext("waterfall") as Writable<Waterfall> - let useRevaluationInsteadOfLaw = $derived( - $page.data.revaluationName !== undefined, - ) + let useRevaluationInsteadOfLaw = revaluationName !== undefined let firstCalculationName = $derived( useRevaluationInsteadOfLaw ? "revaluation" : "law", diff --git a/src/lib/components/WaterfallPlainView.svelte b/src/lib/components/WaterfallPlainView.svelte index dff5b11c3..b1a91d3f6 100644 --- a/src/lib/components/WaterfallPlainView.svelte +++ b/src/lib/components/WaterfallPlainView.svelte @@ -12,6 +12,7 @@ decompositionCoreByNameByReformName, waterfalls, } from "$lib/decompositions" + import publicConfig from "$lib/public_config" import { variableSummaryByName, variableSummaryByNameByReformName, @@ -21,18 +22,18 @@ compact?: boolean } + const { reformName } = publicConfig let { compact = false }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> const dispatch = createEventDispatcher() let tab = $state("brut_to_disponible") const year = getContext("year") as Writable<number> let decompositionByName = $derived( buildDecompositionByNameFromCore( - $billName === undefined + reformName === undefined ? decompositionCoreByName - : (decompositionCoreByNameByReformName[$billName] ?? + : (decompositionCoreByNameByReformName[reformName] ?? decompositionCoreByName), ) as DecompositionByName, ) @@ -40,7 +41,7 @@ // Note: A reform variable is always more complete than a variable before reform. // But it may contain different formulas, with different parameters & variables. let billVariableSummaryByName = $derived( - variableSummaryByNameByReformName[$billName] ?? variableSummaryByName, + variableSummaryByNameByReformName[reformName] ?? variableSummaryByName, ) let waterfallsDecompositions = $derived( diff --git a/src/lib/components/WaterfallView.svelte b/src/lib/components/WaterfallView.svelte index 16df414c6..69d918b7a 100644 --- a/src/lib/components/WaterfallView.svelte +++ b/src/lib/components/WaterfallView.svelte @@ -4,7 +4,6 @@ import type { Writable } from "svelte/store" import { goto } from "$app/navigation" - import { page } from "$app/stores" import TestCaseGraph from "$lib/components/test_cases/TestCaseGraph.svelte" import Tooltip from "$lib/components/Tooltip.svelte" import ValueChange from "$lib/components/ValueChange.svelte" @@ -16,6 +15,7 @@ import type { DisplayMode } from "$lib/displays" import { entityByKey, personEntityKey } from "$lib/entities" import { trackTestCaseGraph } from "$lib/matomo" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import { type ActiveSlider, @@ -45,6 +45,7 @@ year: number } + const { householdEntityKey, revaluationName } = publicConfig let { decompositionByName = $bindable(), displayMode, @@ -82,7 +83,7 @@ minimumFractionDigits: 0, style: "currency", }).format(removeNegativeZero(value)) - const householdEntity = entityByKey[$page.data.householdEntityKey] + const householdEntity = entityByKey[householdEntityKey] const parametricReform = getContext( "parametricReform", ) as Writable<ParametricReform> @@ -91,9 +92,7 @@ const vectorLength = getContext("vectorLength") as Writable<number> const waterfall = getContext("waterfall") as Writable<Waterfall> - let useRevaluationInsteadOfLaw = $derived( - $page.data.revaluationName !== undefined, - ) + let useRevaluationInsteadOfLaw = revaluationName !== undefined let firstCalculationName = $derived( useRevaluationInsteadOfLaw ? "revaluation" : "law", diff --git a/src/lib/components/legifrance/LienView.svelte b/src/lib/components/legifrance/LienView.svelte index 4145b4215..25f78daa8 100644 --- a/src/lib/components/legifrance/LienView.svelte +++ b/src/lib/components/legifrance/LienView.svelte @@ -10,14 +10,15 @@ rootTypeFromLegalId, } from "@tricoteuses/legal-explorer" - import { page } from "$app/stores" import ArticleView from "$lib/components/legifrance/ArticleView.svelte" + import publicConfig from "$lib/public_config" interface Props { level?: number lien: Lien } + const { legalUrl } = publicConfig let { level = 1, lien }: Props = $props() let open = $state(false) @@ -51,10 +52,7 @@ id: string, ): Promise<Article | undefined> { const response = await fetch( - new URL( - `api/articles/${encodeURIComponent(id)}?latest=true`, - $page.data.legalUrl, - ), + new URL(`api/articles/${encodeURIComponent(id)}?latest=true`, legalUrl), { headers: { Accept: "application/json" } }, ) if (!response.ok) { diff --git a/src/lib/components/parameters/ArticleModal.svelte b/src/lib/components/parameters/ArticleModal.svelte index 9007892e8..f25e8b1ce 100644 --- a/src/lib/components/parameters/ArticleModal.svelte +++ b/src/lib/components/parameters/ArticleModal.svelte @@ -3,14 +3,15 @@ import { Dialog } from "bits-ui" import { createEventDispatcher } from "svelte" - import { page } from "$app/stores" import ArticleView from "$lib/components/legifrance/ArticleView.svelte" + import publicConfig from "$lib/public_config" interface Props { parameter: ValueParameter | ScaleParameter referenceUrl: string | null } + const { legalUrl } = publicConfig let { parameter, referenceUrl = $bindable() }: Props = $props() const dispatch = createEventDispatcher() @@ -19,7 +20,7 @@ const response = await fetch( new URL( `api/recherche?latest=true&q=${encodeURIComponent(url)}`, - $page.data.legalUrl, + legalUrl, ), { headers: { Accept: "application/json" } }, ) diff --git a/src/lib/components/parameters/ParameterView.svelte b/src/lib/components/parameters/ParameterView.svelte index 89a979b0e..5870e069f 100644 --- a/src/lib/components/parameters/ParameterView.svelte +++ b/src/lib/components/parameters/ParameterView.svelte @@ -11,7 +11,6 @@ import type { Writable } from "svelte/store" import { goto } from "$app/navigation" - import { page } from "$app/stores" import ScaleView from "$lib/components/parameters/ScaleView.svelte" import type { DisplayMode } from "$lib/displays" import { metadata } from "$lib/metadata" @@ -22,6 +21,7 @@ labelFromScaleType, labelFromValueType, } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { getUnitByName, getUnitShortLabel } from "$lib/units" import { type SelfTargetAProps, newSimulationUrl } from "$lib/urls" @@ -30,6 +30,7 @@ parameter: Parameter } + const { openfiscaRepository } = publicConfig let { date, parameter }: Props = $props() const dateFormatter = new Intl.DateTimeFormat("fr-FR", { dateStyle: "full" }) @@ -43,8 +44,6 @@ let lastReviewOrChange = $derived(parameterLastReviewOrChange(parameter)) - let { openfiscaRepository } = $derived($page.data) - let parameterRepositoryUrl = $derived( newParameterRepositoryUrl(metadata, parameter), ) diff --git a/src/lib/components/test_cases/OilSpendingBill.svelte b/src/lib/components/test_cases/OilSpendingBill.svelte index a636f839e..1a6bb4869 100644 --- a/src/lib/components/test_cases/OilSpendingBill.svelte +++ b/src/lib/components/test_cases/OilSpendingBill.svelte @@ -9,6 +9,7 @@ } from "$lib/calculations.svelte" import ValueChange from "$lib/components/ValueChange.svelte" import { entityByKey } from "$lib/entities" + import publicConfig from "$lib/public_config" import { getSituationVariableValue, type Situation } from "$lib/situations" import { removeNegativeZero } from "$lib/values" import { @@ -29,6 +30,7 @@ year: number } + const { householdEntityKey } = publicConfig let { depenseTtcVariableName, nombreLitresVariableName, @@ -42,7 +44,7 @@ }: Props = $props() const dispatch = createEventDispatcher() - const householdEntity = entityByKey[$page.data.householdEntityKey] + const householdEntity = entityByKey[householdEntityKey] const oilPriceFormatter = (value: number): string => new Intl.NumberFormat("fr-FR", { currency: "EUR", diff --git a/src/lib/components/test_cases/TestCaseCompareView.svelte b/src/lib/components/test_cases/TestCaseCompareView.svelte index 6ed824161..14087cb30 100644 --- a/src/lib/components/test_cases/TestCaseCompareView.svelte +++ b/src/lib/components/test_cases/TestCaseCompareView.svelte @@ -13,6 +13,7 @@ waterfalls, } from "$lib/decompositions" import type { DisplayMode } from "$lib/displays" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import type { Situation } from "$lib/situations" import { newSimulationUrl } from "$lib/urls" @@ -28,6 +29,7 @@ year: number } + const { reformName, revaluationName } = publicConfig let { decompositionByName, displayMode, @@ -35,17 +37,12 @@ year, }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> - const dispatch = createEventDispatcher() const evaluationByNameArray = getContext("evaluationByNameArray") as Writable< EvaluationByName[] > const parametricReform = getContext( "parametricReform", ) as Writable<ParametricReform> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > const testCases = getContext("testCases") as Writable<Situation[]> const testCasesIndex = getContext("testCasesIndex") as Writable<number[]> const valuesByCalculationNameByVariableNameArray = getContext( @@ -181,7 +178,7 @@ $waterfall.total, ), bill: - $billName === undefined + reformName === undefined ? undefined : calculateTotal( $evaluationByNameArray[situationsToCompareIndex[0]], @@ -196,7 +193,7 @@ $waterfall.total, ), revaluation: - $revaluationName === undefined + revaluationName === undefined ? undefined : calculateTotal( $evaluationByNameArray[situationsToCompareIndex[0]], @@ -216,7 +213,7 @@ $waterfall.total, ), bill: - $billName === undefined + reformName === undefined ? undefined : calculateTotal( $evaluationByNameArray[situationsToCompareIndex[1]], @@ -231,7 +228,7 @@ $waterfall.total, ), revaluation: - $revaluationName === undefined + revaluationName === undefined ? undefined : calculateTotal( $evaluationByNameArray[situationsToCompareIndex[1]], @@ -275,7 +272,7 @@ ?.calculationEvaluationByName["amendment"] ?.deltaAtVectorIndex ?? 0), bill: - $billName === undefined + reformName === undefined ? undefined : ($evaluationByNameArray[ situationsToCompareIndex[0] @@ -288,7 +285,7 @@ ]?.calculationEvaluationByName["law"] ?.deltaAtVectorIndex ?? 0, revaluation: - $revaluationName === undefined + revaluationName === undefined ? undefined : ($evaluationByNameArray[ situationsToCompareIndex[0] @@ -306,7 +303,7 @@ ?.calculationEvaluationByName["amendment"] ?.deltaAtVectorIndex ?? 0), bill: - $billName === undefined + reformName === undefined ? undefined : ($evaluationByNameArray[ situationsToCompareIndex[1] @@ -319,7 +316,7 @@ ]?.calculationEvaluationByName["law"] ?.deltaAtVectorIndex ?? 0, revaluation: - $revaluationName === undefined + revaluationName === undefined ? undefined : ($evaluationByNameArray[ situationsToCompareIndex[1] diff --git a/src/lib/components/test_cases/TestCaseEdit.svelte b/src/lib/components/test_cases/TestCaseEdit.svelte index f7e568b2e..22ce81030 100644 --- a/src/lib/components/test_cases/TestCaseEdit.svelte +++ b/src/lib/components/test_cases/TestCaseEdit.svelte @@ -27,15 +27,18 @@ import VariableReferredInputsPane from "$lib/components/variables/VariableReferredInputsPane.svelte" import { decompositionCoreByName } from "$lib/decompositions" import { entityByKey, personEntityKey } from "$lib/entities" + import publicConfig from "$lib/public_config" import { type Axis, getSituationVariableValue, + iterSituationVariablesName, type Situation, } from "$lib/situations" - import { iterSituationVariablesName } from "$lib/situations" import { valueFormatter } from "$lib/values" - import type { ValuesByCalculationNameByVariableName } from "$lib/variables" - import { variableSummaryByName } from "$lib/variables" + import { + type ValuesByCalculationNameByVariableName, + variableSummaryByName, + } from "$lib/variables" interface Props { date: string @@ -49,6 +52,7 @@ year: number } + const { hiddenEntitiesKeyPlural } = publicConfig let { date, inputInstantsByVariableName = $bindable(), @@ -62,8 +66,6 @@ let currentInputInstantsByVariableName = inputInstantsByVariableName let currentSituation = situation const dispatch = createEventDispatcher() - const hiddenEntitiesKeyPlural = ($page.data.hiddenEntitiesKeyPlural ?? - []) as string[] let openMoreAggregatKids = $state(false) const personEntity = entityByKey[personEntityKey] as PersonEntity let showAdultsAlert = $state(false) diff --git a/src/lib/components/test_cases/TestCaseEditVariablesSearch.svelte b/src/lib/components/test_cases/TestCaseEditVariablesSearch.svelte index 282f61a51..7232cf65d 100644 --- a/src/lib/components/test_cases/TestCaseEditVariablesSearch.svelte +++ b/src/lib/components/test_cases/TestCaseEditVariablesSearch.svelte @@ -4,6 +4,7 @@ import type { Writable } from "svelte/store" import VariableInput from "$lib/components/variables/VariableInput.svelte" + import publicConfig from "$lib/public_config" import { parseSearch } from "$lib/search/regexp_search" import type { Situation } from "$lib/situations" import { @@ -23,6 +24,7 @@ year: number } + const { reformName } = publicConfig let { date, inputInstantsByVariableName = $bindable(), @@ -32,8 +34,6 @@ year, }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> - let query = $state("") function filter(variables: Variable[], terms: string[] | undefined) { @@ -52,7 +52,7 @@ // Note: A reform variable is always more complete than a variable before reform. // But it may contain different formulas, with different parameters & variables. let billVariableSummaryByName = $derived( - variableSummaryByNameByReformName[$billName] ?? variableSummaryByName, + variableSummaryByNameByReformName[reformName] ?? variableSummaryByName, ) let inputVariables = $derived( (Object.values(billVariableSummaryByName) as Variable[]).filter( diff --git a/src/lib/components/test_cases/TestCaseFilters.svelte b/src/lib/components/test_cases/TestCaseFilters.svelte index bdd824ab2..d813a1934 100644 --- a/src/lib/components/test_cases/TestCaseFilters.svelte +++ b/src/lib/components/test_cases/TestCaseFilters.svelte @@ -27,6 +27,7 @@ rootParameter, rootParameterByReformName, } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { getSituationVariableValue, type Situation } from "$lib/situations" import { valueFormatter } from "$lib/values" import { @@ -44,6 +45,8 @@ year: number } + const { childrenKey, familyEntityKey, householdEntityKey, reformName } = + publicConfig let { displayMode, showOnlyDeciles = $bindable(false), @@ -52,16 +55,14 @@ year, }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> - const childrenKey = $page.data.childrenKey let descriptionsOpen = $state(false) const dispatch = createEventDispatcher() const evaluationByNameArray = getContext("evaluationByNameArray") as Writable< EvaluationByName[] > const personEntity = entityByKey[personEntityKey] - const familyEntity = entityByKey[$page.data.familyEntityKey] - const householdEntity = entityByKey[$page.data.householdEntityKey] + const familyEntity = entityByKey[familyEntityKey] + const householdEntity = entityByKey[householdEntityKey] const formatCurrency = valueFormatter(0, "currency-EUR", false) const formatLongOrdinalSup = (n: number) => { const rule = ordinalPluralRules.select(n) @@ -371,7 +372,7 @@ // before reform. // → Non reform decomposition is not needed. let latestDecompositionCoreByName = $derived( - decompositionCoreByNameByReformName[$billName] ?? decompositionCoreByName, + decompositionCoreByNameByReformName[reformName] ?? decompositionCoreByName, ) let latestDecompositionCore = $derived( latestDecompositionCoreByName[variableName], @@ -387,7 +388,7 @@ // Note: A reform variable is always more complete than a variable before reform. // But it may contain different formulas, with different parameters & variables. let latestVariableSummaryByName = $derived( - variableSummaryByNameByReformName[$billName] ?? variableSummaryByName, + variableSummaryByNameByReformName[reformName] ?? variableSummaryByName, ) let variable = $derived(latestVariableSummaryByName[variableName]) run(() => { @@ -403,7 +404,7 @@ // And the children of a reform node parameter always contain the children of the node parameter // before reform (albeit with some different value parameters). let billRootParameter = $derived( - rootParameterByReformName[$billName] ?? rootParameter, + rootParameterByReformName[reformName] ?? rootParameter, ) let decilesNiveauDeVieParameter = $derived( asScaleParameter(getParameter(billRootParameter, "deciles_niveau_de_vie")), @@ -427,9 +428,9 @@ ) let variableSummary = $derived( variableName !== undefined - ? $billName === undefined + ? reformName === undefined ? variableSummaryByName[variableName] - : variableSummaryByNameByReformName[$billName][variableName] + : variableSummaryByNameByReformName[reformName][variableName] : undefined, ) let filteredTestCases = $derived( diff --git a/src/lib/components/test_cases/TestCaseGraph.svelte b/src/lib/components/test_cases/TestCaseGraph.svelte index 74a02c76c..5ded260df 100644 --- a/src/lib/components/test_cases/TestCaseGraph.svelte +++ b/src/lib/components/test_cases/TestCaseGraph.svelte @@ -58,6 +58,7 @@ rootParameter, rootParameterByReformName, } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { type ActiveSlider, type CalculationByName, @@ -86,6 +87,7 @@ year: number } + const { childrenKey, familyEntityKey, reformName } = publicConfig let { decompositionByName, displayMode, @@ -102,13 +104,11 @@ }: Props = $props() const billActive = getContext("billActive") as Writable<boolean> - const billName = getContext("billName") as Writable<string | undefined> const calculationByName = getContext( "calculationByName", ) as Writable<CalculationByName> - const childrenKey = $page.data.childrenKey const dispatch = createEventDispatcher() - const familyEntity = entityByKey[$page.data.familyEntityKey] + const familyEntity = entityByKey[familyEntityKey] const formatCurrency = valueFormatter(0, "currency-EUR", false) const formatLongOrdinalSup = (n: number) => { const rule = ordinalPluralRules.select(n) @@ -811,7 +811,7 @@ // And the children of a reform node parameter always contain the children of the node parameter // before reform (albeit with some different value parameters). let billRootParameter = $derived( - rootParameterByReformName[$billName] ?? rootParameter, + rootParameterByReformName[reformName] ?? rootParameter, ) let decilesNiveauDeVieParameter = $derived( asScaleParameter(getParameter(billRootParameter, "deciles_niveau_de_vie")), diff --git a/src/lib/components/test_cases/TestCaseGraphXlsxExport.svelte b/src/lib/components/test_cases/TestCaseGraphXlsxExport.svelte index 1694466d0..07a0e70da 100644 --- a/src/lib/components/test_cases/TestCaseGraphXlsxExport.svelte +++ b/src/lib/components/test_cases/TestCaseGraphXlsxExport.svelte @@ -30,6 +30,7 @@ rootParameter, rootParameterByReformName, } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { ParameterReformChangeType, type ParametricReform, @@ -58,6 +59,7 @@ year: number } + const { baseUrl, reformName } = publicConfig let { displayMode, domain, @@ -70,7 +72,6 @@ }: Props = $props() const billActive = getContext("billActive") as Writable<boolean> - const billName = getContext("billName") as Writable<string | undefined> const budgetDate = getContext("budgetDate") as Writable<string> const dateFormatter = new Intl.DateTimeFormat("fr-FR", { day: "2-digit", @@ -105,7 +106,7 @@ // And the children of a reform node parameter always contain the children of the node parameter // before reform (albeit with some different value parameters). let billRootParameter = $derived( - rootParameterByReformName[$billName] ?? rootParameter, + rootParameterByReformName[reformName] ?? rootParameter, ) async function xlsxExport() { @@ -158,10 +159,7 @@ [ undefined, "Lien du cas type et de la réforme :", - new URL( - `/test_cases/simulations/${token}`, - $page.data.baseUrl, - ).toString(), + new URL(`/test_cases/simulations/${token}`, baseUrl).toString(), ], [ undefined, diff --git a/src/lib/components/test_cases/TestCasePictos.svelte b/src/lib/components/test_cases/TestCasePictos.svelte index 0f71fd736..ed9f1ba8f 100644 --- a/src/lib/components/test_cases/TestCasePictos.svelte +++ b/src/lib/components/test_cases/TestCasePictos.svelte @@ -9,6 +9,7 @@ import PictoGardeAlternee from "$lib/components/pictos/PictoGardeAlternee.svelte" import PictoHandicap from "$lib/components/pictos/PictoHandicap.svelte" import { entityByKey, personEntityKey } from "$lib/entities" + import publicConfig from "$lib/public_config" import { getSituationVariableValue, type Situation } from "$lib/situations" import { variableSummaryByName, type VariableValue } from "$lib/variables" @@ -18,10 +19,10 @@ year: number } + const { childrenKey, familyEntityKey } = publicConfig let { classes, situation, year }: Props = $props() - const childrenKey = $page.data.childrenKey - const familyEntity = entityByKey[$page.data.familyEntityKey] + const familyEntity = entityByKey[familyEntityKey] const personEntity = entityByKey[personEntityKey] function getVariableValue( diff --git a/src/lib/components/test_cases/TestCaseSummary.svelte b/src/lib/components/test_cases/TestCaseSummary.svelte index 40d546404..2bbc50e39 100644 --- a/src/lib/components/test_cases/TestCaseSummary.svelte +++ b/src/lib/components/test_cases/TestCaseSummary.svelte @@ -26,6 +26,7 @@ import type { DisplayMode } from "$lib/displays" import { entityByKey, personEntityKey } from "$lib/entities" import { getParameter, rootParameter } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { getCalculatedVariableValueByCalculationName, getSituationVariableValue, @@ -53,6 +54,13 @@ year: number } + const { + childrenKey, + familyEntityKey, + householdEntityKey, + reformName, + taxableHouseholdEntityKey, + } = publicConfig let { displayMode, mode, @@ -62,8 +70,6 @@ year, }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> - const childrenKey = $page.data.childrenKey const dispatch = createEventDispatcher() const euroAmountFormatter = (value: number): string => new Intl.NumberFormat("fr-FR", { @@ -72,13 +78,12 @@ minimumFractionDigits: 0, style: "currency", }).format(removeNegativeZero(value)) - const familyEntity = entityByKey[$page.data.familyEntityKey] - const householdEntity = entityByKey[$page.data.householdEntityKey] + const familyEntity = entityByKey[familyEntityKey] + const householdEntity = entityByKey[householdEntityKey] let isTestCaseCompareModalOpen = $state(false) const personEntity = entityByKey[personEntityKey] let slider: Slider | undefined = $state(undefined) - const taxableHouseholdEntity = - entityByKey[$page.data.taxableHouseholdEntityKey] + const taxableHouseholdEntity = entityByKey[taxableHouseholdEntityKey] let familySituation = $derived(situation[familyEntity.key_plural]) @@ -125,9 +130,9 @@ // Note: A reform variable is always more complete than a variable before reform. let variableSummary = $derived( - $billName === undefined + reformName === undefined ? variableSummaryByName[displayMode.parametersVariableName] - : variableSummaryByNameByReformName[$billName][ + : variableSummaryByNameByReformName[reformName][ displayMode.parametersVariableName ], ) diff --git a/src/lib/components/test_cases/TestCaseView.svelte b/src/lib/components/test_cases/TestCaseView.svelte index 03f169ac1..d4145d229 100644 --- a/src/lib/components/test_cases/TestCaseView.svelte +++ b/src/lib/components/test_cases/TestCaseView.svelte @@ -21,6 +21,7 @@ } from "$lib/decompositions" import { waterfalls } from "$lib/decompositions" import type { DisplayMode } from "$lib/displays" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import type { CalculationByName, Situation } from "$lib/situations" import type { TabsConfig } from "$lib/tabs" @@ -43,6 +44,7 @@ year: number } + const { reformName, revaluationName } = publicConfig let { decompositionByName, displayMode, @@ -63,7 +65,6 @@ tvaVariableName: `tva_sur_${name}`, })) - const billName = getContext("billName") as Writable<string | undefined> const calculationByName = getContext( "calculationByName", ) as Writable<CalculationByName> @@ -73,9 +74,6 @@ const parametricReform = getContext( "parametricReform", ) as Writable<ParametricReform> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > const showNulls = getContext("showNulls") as Writable<boolean> const waterfall = getContext("waterfall") as Writable<Waterfall> @@ -139,11 +137,11 @@ {#if displayMode.parametersVariableName !== undefined} <!-- Note: A reform variable is always more complete than a variable before reform. --> {@const variableSummary = - $billName === undefined + reformName === undefined ? variableSummaryByName[ displayMode.parametersVariableName ] - : variableSummaryByNameByReformName[$billName][ + : variableSummaryByNameByReformName[reformName][ displayMode.parametersVariableName ]} {#if variableSummary !== undefined} @@ -172,11 +170,11 @@ {#if displayMode.parametersVariableName !== undefined} <!-- Note: A reform variable is always more complete than a variable before reform. --> {@const variableSummary = - $billName === undefined + reformName === undefined ? variableSummaryByName[ displayMode.parametersVariableName ] - : variableSummaryByNameByReformName[$billName][ + : variableSummaryByNameByReformName[reformName][ displayMode.parametersVariableName ]} {#if variableSummary !== undefined} @@ -185,8 +183,8 @@ variableSummary.linked_added_variables.map((name) => variableValueByCalculationNameFromEvaluation( evaluationByName[name], - $revaluationName, - $billName, + revaluationName, + reformName, $parametricReform, ), )} @@ -197,10 +195,10 @@ linkedVariablesValueByCalculationName[index]} {#if $showNulls || !isNullVariableValueByCalculationName(linkedVariableValueByCalculationName)} {@const linkedVariableSummary = - $billName === undefined + reformName === undefined ? variableSummaryByName[linkedVariableName] : variableSummaryByNameByReformName[ - $billName + reformName ][linkedVariableName]} <li> <a @@ -237,9 +235,9 @@ {#if displayMode.parametersVariableName !== undefined} <!-- Note: A reform variable is always more complete than a variable before reform. --> {@const variableSummary = - $billName === undefined + reformName === undefined ? variableSummaryByName[displayMode.parametersVariableName] - : variableSummaryByNameByReformName[$billName][ + : variableSummaryByNameByReformName[reformName][ displayMode.parametersVariableName ]} {#if variableSummary !== undefined} @@ -268,8 +266,8 @@ linkedVariables.map((name) => variableValueByCalculationNameFromEvaluation( evaluationByName[name], - $revaluationName, - $billName, + revaluationName, + reformName, $parametricReform, ), )} @@ -284,10 +282,10 @@ linkedVariablesValueByCalculationName[index]} {#if $showNulls || !isNullVariableValueByCalculationName(linkedVariableValueByCalculationName)} {@const linkedVariableSummary = - $billName === undefined + reformName === undefined ? variableSummaryByName[linkedVariableName] : variableSummaryByNameByReformName[ - $billName + reformName ][linkedVariableName]} <li class="flex"> <a @@ -378,9 +376,9 @@ <div class="bg-white"> {#if variableSummaryByName !== undefined} {@const completeVariableSummaryByName = - $billName === undefined + reformName === undefined ? variableSummaryByName - : variableSummaryByNameByReformName[$billName]} + : variableSummaryByNameByReformName[reformName]} <div class="flex w-full justify-between bg-gray-100"> <!--Impacts et waterfall--> <div diff --git a/src/lib/components/transverse_pages/OpenGraph.svelte b/src/lib/components/transverse_pages/OpenGraph.svelte index 2df0082e9..48b53b1d3 100644 --- a/src/lib/components/transverse_pages/OpenGraph.svelte +++ b/src/lib/components/transverse_pages/OpenGraph.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { page } from "$app/stores" + import publicConfig from "$lib/public_config" interface Props { description?: string @@ -10,6 +10,7 @@ url?: string | null } + const { baseUrl } = publicConfig let { description = "LexImpact est un service de l'Assemblée nationale depuis 2020. Il a pour objectif de faciliter l'accès au chiffrage des politiques publiques passées ou à imaginer.", image = "open-graph-image.png", @@ -19,8 +20,6 @@ url = null, }: Props = $props() - let { data } = $derived($page) - let { baseUrl } = $derived(data) let fullTitle = $derived([title, titleSuffix].filter(Boolean).join(" - ")) </script> diff --git a/src/lib/components/variables/FormulaView.svelte b/src/lib/components/variables/FormulaView.svelte index e3fbe4d98..c865d903c 100644 --- a/src/lib/components/variables/FormulaView.svelte +++ b/src/lib/components/variables/FormulaView.svelte @@ -10,6 +10,7 @@ import VariableInput from "$lib/components/variables/VariableInput.svelte" import { entityByKey } from "$lib/entities" import { leafParametersName } from "$lib/parameters" + import publicConfig from "$lib/public_config" import type { Situation } from "$lib/situations" import { variableSummaryByName, @@ -38,6 +39,7 @@ year, }: Props = $props() + const { openfiscaRepository } = publicConfig const requestedVariablesNameToCalculate = getContext( "requestedVariablesNameToCalculate", ) as Writable<Set<string> | undefined> @@ -50,8 +52,6 @@ ), ) - let { openfiscaRepository } = $derived($page.data) - run(() => { $requestedVariablesNameToCalculate = extraction.openFiscaVariablesName }) diff --git a/src/lib/components/variables/InflationLawButton.svelte b/src/lib/components/variables/InflationLawButton.svelte index 9d0af152b..a72f212e4 100644 --- a/src/lib/components/variables/InflationLawButton.svelte +++ b/src/lib/components/variables/InflationLawButton.svelte @@ -6,6 +6,7 @@ import { getContext } from "svelte" import type { Writable } from "svelte/store" + import publicConfig from "$lib/public_config" import { formatValue } from "$lib/values" interface Props { @@ -13,9 +14,9 @@ parameterName: string | undefined } + const { reformName } = publicConfig let { inflatorByReformName, parameterName }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> const yearPLF = getContext("yearPLF") as Writable<number> let inflatorWithLatestByReformName = $derived( @@ -46,9 +47,9 @@ // Latest inflator let billInflator = $derived( - $billName === undefined + reformName === undefined ? undefined - : inflatorWithLatestByReformName?.[$billName], + : inflatorWithLatestByReformName?.[reformName], ) let billInflatorValueFormatted = $derived( billInflator?.values !== undefined diff --git a/src/lib/components/variables/InflationLawDetails.svelte b/src/lib/components/variables/InflationLawDetails.svelte index 951c4b2fc..250b89ed5 100644 --- a/src/lib/components/variables/InflationLawDetails.svelte +++ b/src/lib/components/variables/InflationLawDetails.svelte @@ -7,6 +7,7 @@ import { getContext } from "svelte" import type { Writable } from "svelte/store" + import publicConfig from "$lib/public_config" import { getUnitAtDate } from "$lib/units" import { formatValue, removeNegativeZero } from "$lib/values" @@ -17,6 +18,7 @@ revaluationParameter: ScaleParameter | ValueParameter } + const { revaluationName } = publicConfig let { billParameter, inflatorByReformName, @@ -24,11 +26,6 @@ revaluationParameter, }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > - const numberFormatter = (value: number): string => new Intl.NumberFormat("fr-FR", { style: "decimal", @@ -147,7 +144,7 @@ ) let revaluationInflator = $derived( - inflatorWithLatestByReformName?.[$revaluationName], + inflatorWithLatestByReformName?.[revaluationName], ) let revaluationInflatorValueFormatted = $derived( revaluationInflator !== undefined @@ -158,7 +155,7 @@ : undefined, ) - let billInflator = $derived(inflatorWithLatestByReformName?.[$billName]) + let billInflator = $derived(inflatorWithLatestByReformName?.[reformName]) let billInflatorValueFormatted = $derived( billInflator !== undefined ? formatValue(billInflator.values["latest"].value, billInflator.unit) diff --git a/src/lib/components/variables/InflationLawInfoModal.svelte b/src/lib/components/variables/InflationLawInfoModal.svelte index 5813e85eb..c17d7fc00 100644 --- a/src/lib/components/variables/InflationLawInfoModal.svelte +++ b/src/lib/components/variables/InflationLawInfoModal.svelte @@ -10,6 +10,7 @@ import ArticleModal from "$lib/components/parameters/ArticleModal.svelte" import InflationLawDetails from "$lib/components/variables/InflationLawDetails.svelte" + import publicConfig from "$lib/public_config" interface Props { isOpen?: boolean @@ -19,6 +20,7 @@ revaluationParameter: ScaleParameter | ValueParameter } + const { reformName } = publicConfig let { isOpen = $bindable(false), billParameter, @@ -27,13 +29,12 @@ revaluationParameter, }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> let openReferenceUrl: string | undefined | null = $state(null) const yearPLF = getContext("yearPLF") as Writable<number> // Latest inflator, contains all references. let billInflator = $derived( - $billName === undefined ? undefined : inflatorByReformName?.[$billName], + reformName === undefined ? undefined : inflatorByReformName?.[reformName], ) let references = $derived( diff --git a/src/lib/components/variables/VariableDetail.svelte b/src/lib/components/variables/VariableDetail.svelte index 57d260df0..6483910fa 100644 --- a/src/lib/components/variables/VariableDetail.svelte +++ b/src/lib/components/variables/VariableDetail.svelte @@ -28,6 +28,7 @@ } from "$lib/decompositions" import type { DisplayMode } from "$lib/displays" import { memoUrlByName } from "$lib/memos" + import publicConfig from "$lib/public_config" import type { Situation } from "$lib/situations" import { newSimulationUrl } from "$lib/urls" import { @@ -41,9 +42,9 @@ name: string } + const { reformName } = publicConfig let { displayMode, name }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> const budgetSimulation = getContext("budgetSimulation") as Writable< BudgetSimulation | undefined > @@ -69,7 +70,7 @@ // before reform. // → Non reform decomposition is not needed. let latestDecompositionCoreByName = $derived( - decompositionCoreByNameByReformName[$billName] ?? decompositionCoreByName, + decompositionCoreByNameByReformName[reformName] ?? decompositionCoreByName, ) let latestDecompositionCore = $derived(latestDecompositionCoreByName[name]) let decomposition = $derived( @@ -83,7 +84,7 @@ // Note: A reform variable is always more complete than a variable before reform. // But it may contain different formulas, with different parameters & variables. let latestVariableSummaryByName = $derived( - variableSummaryByNameByReformName[$billName] ?? variableSummaryByName, + variableSummaryByNameByReformName[reformName] ?? variableSummaryByName, ) let variable = $derived(latestVariableSummaryByName[name]) run(() => { diff --git a/src/lib/components/variables/VariableInput.svelte b/src/lib/components/variables/VariableInput.svelte index 91edbb193..ff05e9d7c 100644 --- a/src/lib/components/variables/VariableInput.svelte +++ b/src/lib/components/variables/VariableInput.svelte @@ -6,19 +6,17 @@ import type { Writable } from "svelte/store" import { page } from "$app/stores" - import { - requestAllTestCasesCalculations, - type RequestedCalculations, - } from "$lib/calculations.svelte" + import { requestAllTestCasesCalculations } from "$lib/calculations.svelte" import Autocomplete from "$lib/components/Autocomplete.svelte" import Tooltip from "$lib/components/Tooltip.svelte" import ValueChange from "$lib/components/ValueChange.svelte" import { entityByKey } from "$lib/entities" - import type { Situation } from "$lib/situations" + import publicConfig from "$lib/public_config" import { getCalculatedVariableValueByCalculationName, getSituationVariableValue, setSituationVariableValue, + type Situation, } from "$lib/situations" import { getUnitShortLabel } from "$lib/units" import type { @@ -39,6 +37,7 @@ year: number } + const { territoiresUrl } = publicConfig let { date, highlight = undefined, @@ -122,7 +121,7 @@ `/communes/autocomplete?field=commune&q=${encodeURIComponent( communeTerm, )}`, - $page.data.territoiresUrl, + territoiresUrl, ).toString(), { headers: { Accept: "application/json" } }, ) @@ -299,7 +298,7 @@ const response = await fetch( new URL( `/communes/${encodeURIComponent(code || "00000")}?field=distributions_postales`, - $page.data.territoiresUrl, + territoiresUrl, ).toString(), { headers: { Accept: "application/json" } }, ) diff --git a/src/lib/components/variables/VariableReferredParameters.svelte b/src/lib/components/variables/VariableReferredParameters.svelte index 39099fda0..88dc01c1b 100644 --- a/src/lib/components/variables/VariableReferredParameters.svelte +++ b/src/lib/components/variables/VariableReferredParameters.svelte @@ -29,6 +29,7 @@ rootParameter, rootParameterByReformName, } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { newSimulationUrl } from "$lib/urls" import { iterVariableParametersName, @@ -42,54 +43,17 @@ name: string } + const { reformName, revaluationName } = publicConfig let { date, displayMode, name }: Props = $props() const billActive = getContext("billActive") as Writable<boolean> - const billName = getContext("billName") as Writable<string | undefined> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > let openDirectParameters = $state(true) - - function* iterVariableRootParameters( - bothRootParameterById: { [id: string]: Parameter }, - lawRootParameter: NodeParameter, - revaluationRootParameter: NodeParameter, - billRootParameter: NodeParameter, - ): Generator< - [Parameter, Parameter | undefined, Parameter, Parameter], - void, - unknown - > { - for (const bothChild of Object.values(bothRootParameterById).sort( - (bothChild1, bothChild2) => - bothChild1.class === bothChild2.class || - (bothChild1.class !== ParameterClass.Node && - bothChild2.class !== ParameterClass.Node) - ? bothChild1.title.localeCompare(bothChild2.title) - : bothChild1.class === ParameterClass.Node - ? 1 - : -1, - )) { - if (bothChild.id === undefined) { - // TODO: This is a mistake that shoudn't occur. - continue - } - // Notes: - // A reform (bill) parameter is always more complete than a parameter before reform. - // A reform never changes the class of a parameter - const lawChild = lawRootParameter.children[bothChild.id] // Sometimes undefined - const revaluationChild = revaluationRootParameter.children[bothChild.id] - const billChild = billRootParameter.children[bothChild.id] // Never undefined - yield [bothChild, lawChild, revaluationChild, billChild] - } - } // Note: A reform decomposition is always more complete than a decomposition before reform. // And the children of a reform decomposition always contain the children of the decomposition // before reform. // => Non reform decomposition is not needed. let billDecompositionCoreByName = $derived( - decompositionCoreByNameByReformName[$billName] ?? decompositionCoreByName, + decompositionCoreByNameByReformName[reformName] ?? decompositionCoreByName, ) let billDecompositionCore = $derived(billDecompositionCoreByName[name]) let billDecomposition = $derived( @@ -103,7 +67,7 @@ // Note: A reform variable is always more complete than a variable before reform. // But it may contain different formulas, with different parameters & variables. let billVariableSummaryByName = $derived( - variableSummaryByNameByReformName[$billName] ?? variableSummaryByName, + variableSummaryByNameByReformName[reformName] ?? variableSummaryByName, ) let billVariable = $derived(billVariableSummaryByName[name]) let lawVariable = $derived(variableSummaryByName[name]) @@ -113,13 +77,13 @@ } }) let revaluationRootParameter = $derived( - rootParameterByReformName[$revaluationName] ?? rootParameter, + rootParameterByReformName[revaluationName] ?? rootParameter, ) // Note: A reform parameters tree is always more complete than a parameters tree before reform. // And the children of a reform node parameter always contain the children of the node parameter // before reform (albeit with some different value parameters). let billRootParameter = $derived( - rootParameterByReformName[$billName] ?? revaluationRootParameter, + rootParameterByReformName[reformName] ?? revaluationRootParameter, ) let bothParametersName = $derived( new Set([ @@ -128,7 +92,7 @@ : iterVariableParametersName(lawVariable, date)), ...(billVariable === undefined ? [] - : iterVariableParametersName(billVariable, date, $billName)), + : iterVariableParametersName(billVariable, date, reformName)), ]), ) let bothDirectParametersName = $derived( @@ -156,6 +120,40 @@ ), ) let openAllParameters = $state(false) + + function* iterVariableRootParameters( + bothRootParameterById: { [id: string]: Parameter }, + lawRootParameter: NodeParameter, + revaluationRootParameter: NodeParameter, + billRootParameter: NodeParameter, + ): Generator< + [Parameter, Parameter | undefined, Parameter, Parameter], + void, + unknown + > { + for (const bothChild of Object.values(bothRootParameterById).sort( + (bothChild1, bothChild2) => + bothChild1.class === bothChild2.class || + (bothChild1.class !== ParameterClass.Node && + bothChild2.class !== ParameterClass.Node) + ? bothChild1.title.localeCompare(bothChild2.title) + : bothChild1.class === ParameterClass.Node + ? 1 + : -1, + )) { + if (bothChild.id === undefined) { + // TODO: This is a mistake that shoudn't occur. + continue + } + // Notes: + // A reform (bill) parameter is always more complete than a parameter before reform. + // A reform never changes the class of a parameter + const lawChild = lawRootParameter.children[bothChild.id] // Sometimes undefined + const revaluationChild = revaluationRootParameter.children[bothChild.id] + const billChild = billRootParameter.children[bothChild.id] // Never undefined + yield [bothChild, lawChild, revaluationChild, billChild] + } + } </script> {#if billDecomposition !== undefined || billVariable !== undefined} diff --git a/src/lib/components/variables/VariableReferredScaleParameter.svelte b/src/lib/components/variables/VariableReferredScaleParameter.svelte index 7064b12e6..3b5647488 100644 --- a/src/lib/components/variables/VariableReferredScaleParameter.svelte +++ b/src/lib/components/variables/VariableReferredScaleParameter.svelte @@ -30,6 +30,7 @@ trackLawEditParameterStatus, } from "$lib/matomo" import { rootParameterByReformName } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { ParameterReformChangeType, type ParametricReform, @@ -51,6 +52,7 @@ revaluationParameter: ScaleParameter } + const { reformName, revaluationName } = publicConfig let { billParameter, budget, @@ -63,7 +65,6 @@ }: Props = $props() const billActive = getContext("billActive") as Writable<boolean> - const billName = getContext("billName") as Writable<string | undefined> const dateFormatter = new Intl.DateTimeFormat("fr-FR", { dateStyle: "full" }) .format let isInflationLawInfoModalOpen = $state(false) @@ -71,9 +72,6 @@ const parametricReform = getContext( "parametricReform", ) as Writable<ParametricReform> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > const yearPLF = getContext("yearPLF") as Writable<number> function changeScale({ detail: scale }: { detail: ScaleAtInstant }) { @@ -222,9 +220,9 @@ inflatorType![1] ], ...{ - inflator_reference: (reformName === $billName + inflator_reference: (reformName === reformName ? billParameter - : reformName === $revaluationName + : reformName === revaluationName ? revaluationParameter : undefined )?.inflator_reference, diff --git a/src/lib/components/variables/VariableReferredValueParameter.svelte b/src/lib/components/variables/VariableReferredValueParameter.svelte index 1a2b1135b..e1318d4e7 100644 --- a/src/lib/components/variables/VariableReferredValueParameter.svelte +++ b/src/lib/components/variables/VariableReferredValueParameter.svelte @@ -39,6 +39,7 @@ trackLawEditParameterStatus, } from "$lib/matomo" import { rootParameterByReformName } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { ParameterReformChangeType, type ParametricReform, @@ -62,6 +63,7 @@ revaluationParameter: ValueParameter } + const { reformName, revaluationName } = publicConfig let { billParameter, budget, @@ -82,7 +84,6 @@ ) const dateFormatter = new Intl.DateTimeFormat("fr-FR", { dateStyle: "full" }) .format - const billName = getContext("billName") as Writable<string | undefined> let isLawInfoModalOpen = $state(false) let lawInstantValueCouplesArray: [string, ValueAtInstant][] = $derived( Object.entries(lawParameter?.values ?? []).sort(([instant1], [instant2]) => @@ -99,9 +100,6 @@ ([instant1], [instant2]) => instant2.localeCompare(instant1), ), ) - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > let validValue = undefined let valueError: string | null = $state(null) const yearPLF = getContext("yearPLF") as Writable<number> @@ -224,9 +222,9 @@ inflatorType![1] ], ...{ - inflator_reference: (reformName === $billName + inflator_reference: (reformName === reformName ? billParameter - : reformName === $revaluationName + : reformName === revaluationName ? revaluationParameter : undefined )?.inflator_reference, diff --git a/src/lib/components/variables/VariableValueChange.svelte b/src/lib/components/variables/VariableValueChange.svelte index 4d809b4fc..e383c1798 100644 --- a/src/lib/components/variables/VariableValueChange.svelte +++ b/src/lib/components/variables/VariableValueChange.svelte @@ -4,6 +4,7 @@ import ValueChange from "$lib/components/ValueChange.svelte" import type { EvaluationByName } from "$lib/decompositions" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import { getUnitAtDate } from "$lib/units" import { @@ -23,6 +24,7 @@ bold?: boolean } + const { reformName, revaluationName } = publicConfig let { compact = false, evaluationByName, @@ -33,21 +35,17 @@ bold = false, }: Props = $props() - const billName = getContext("billName") as Writable<string | undefined> const date = getContext("date") as Writable<string> const parametricReform = getContext( "parametricReform", ) as Writable<ParametricReform> - const revaluationName = getContext("revaluationName") as Writable< - string | undefined - > let evaluation = $derived(evaluationByName[name]) let variableSummary = $derived( - $billName === undefined + reformName === undefined ? variableSummaryByName[name] - : variableSummaryByNameByReformName[$billName][name], + : variableSummaryByNameByReformName[reformName][name], ) </script> @@ -66,7 +64,7 @@ ?.deltaAtVectorIndex ?? 0, ), bill: - $billName === undefined + reformName === undefined ? undefined : Math.abs( evaluation?.calculationEvaluationByName["bill"] @@ -76,7 +74,7 @@ evaluation?.calculationEvaluationByName["law"]?.deltaAtVectorIndex ?? 0, ), revaluation: - $revaluationName === undefined + revaluationName === undefined ? undefined : Math.abs( evaluation?.calculationEvaluationByName["revaluation"] diff --git a/src/lib/components/variables/VariableView.svelte b/src/lib/components/variables/VariableView.svelte index 312c0d44e..6f5ab636b 100644 --- a/src/lib/components/variables/VariableView.svelte +++ b/src/lib/components/variables/VariableView.svelte @@ -6,6 +6,7 @@ import FormulaView from "$lib/components/variables/FormulaView.svelte" import VariableInput from "$lib/components/variables/VariableInput.svelte" import { decompositionCoreByName } from "$lib/decompositions" + import publicConfig from "$lib/public_config" import type { Situation } from "$lib/situations" import type { SelfTargetAProps } from "$lib/urls" import type { ValuesByCalculationNameByVariableName } from "$lib/variables" @@ -24,6 +25,7 @@ year: number } + const { openfiscaRepository } = publicConfig let { date, editable, @@ -50,8 +52,6 @@ variable?.last_value_still_valid_on, ) - let { openfiscaRepository } = $derived($page.data) - let possiblyObsolete = $derived( obsolete || lastReview === undefined || diff --git a/src/lib/public_config.ts b/src/lib/public_config.ts new file mode 100644 index 000000000..e1dd4244c --- /dev/null +++ b/src/lib/public_config.ts @@ -0,0 +1,100 @@ +import { + PUBLIC_ADVANCED, + PUBLIC_API_BASE_URLS, + PUBLIC_TITLE, + PUBLIC_BASE_URL, + PUBLIC_CHILDREN_KEY, + PUBLIC_FAMILY_KEY, + PUBLIC_HIDDEN_ENTITIES, + PUBLIC_HOUSEHOLD_KEY, + PUBLIC_LEGAL_URL, + PUBLIC_MATOMO_PREPEND_DOMAIN, + PUBLIC_MATOMO_SUBDOMAINS, + PUBLIC_MATOMO_SITE_ID, + PUBLIC_MATOMO_URL, + PUBLIC_OPENFISCA_BRANCH, + PUBLIC_OPENFISCA_GROUP, + PUBLIC_OPENFISCA_PROJECT, + PUBLIC_OPENFISCA_REPOSITORY_RAW_URL_TEMPLATE, + PUBLIC_OPENFISCA_REPOSITORY_URL_TEMPLATE, + PUBLIC_PORTAL_URL, + PUBLIC_REFORM, + PUBLIC_REFORM_REVALUATION, + PUBLIC_SHOW_TUTORIAL, + PUBLIC_TAXABLE_HOUSEHOLD_KEY, + PUBLIC_TERRITOIRES_URL, +} from "$env/static/public" +import { validatePublicConfig } from "$lib/auditors/public_config" +import type { RepositoryConfig } from "$lib/repositories" + +export interface PublicConfig { + advanced: boolean + apiBaseUrls: string[] + appTitle: string + baseUrl: string + childrenKey: string + familyEntityKey: string + hiddenEntitiesKeyPlural?: string[] + householdEntityKey: string + legalUrl: string + matomo?: { + prependDomain?: boolean + siteId: number + subdomains?: string + url: string + } + openfiscaRepository: RepositoryConfig + portalUrl: string + reformName?: string + revaluationName?: string + showTutorial?: boolean + taxableHouseholdEntityKey: string + territoiresUrl: string +} + +const [validConfig, error] = validatePublicConfig({ + advanced: PUBLIC_ADVANCED, + apiBaseUrls: PUBLIC_API_BASE_URLS, + appTitle: PUBLIC_TITLE, + baseUrl: PUBLIC_BASE_URL, + childrenKey: PUBLIC_CHILDREN_KEY, + familyEntityKey: PUBLIC_FAMILY_KEY, + hiddenEntitiesKeyPlural: PUBLIC_HIDDEN_ENTITIES, + householdEntityKey: PUBLIC_HOUSEHOLD_KEY, + legalUrl: PUBLIC_LEGAL_URL, + matomo: + PUBLIC_MATOMO_SITE_ID && PUBLIC_MATOMO_URL + ? { + prependDomain: PUBLIC_MATOMO_PREPEND_DOMAIN, + siteId: PUBLIC_MATOMO_SITE_ID, + subdomains: PUBLIC_MATOMO_SUBDOMAINS, + url: PUBLIC_MATOMO_URL, + } + : null, + openfiscaRepository: { + branch: PUBLIC_OPENFISCA_BRANCH, + group: PUBLIC_OPENFISCA_GROUP, + project: PUBLIC_OPENFISCA_PROJECT, + rawUrlTemplate: PUBLIC_OPENFISCA_REPOSITORY_RAW_URL_TEMPLATE, + urlTemplate: PUBLIC_OPENFISCA_REPOSITORY_URL_TEMPLATE, + }, + portalUrl: PUBLIC_PORTAL_URL, + reformName: PUBLIC_REFORM, + revaluationName: PUBLIC_REFORM_REVALUATION, + showTutorial: PUBLIC_SHOW_TUTORIAL, + taxableHouseholdEntityKey: PUBLIC_TAXABLE_HOUSEHOLD_KEY, + territoiresUrl: PUBLIC_TERRITOIRES_URL, +}) as [PublicConfig, unknown] +if (error !== null) { + console.error( + `Error in configuration:\n${JSON.stringify( + validConfig, + null, + 2, + )}\nError:\n${JSON.stringify(error, null, 2)}`, + ) + process.exit(-1) +} +const publicConfig = validConfig + +export default publicConfig diff --git a/src/lib/server/auditors/server_config.ts b/src/lib/server/auditors/server_config.ts new file mode 100644 index 000000000..543d07431 --- /dev/null +++ b/src/lib/server/auditors/server_config.ts @@ -0,0 +1,131 @@ +import { + auditBoolean, + auditCleanArray, + auditFunction, + auditHttpUrl, + auditInteger, + auditRequire, + auditSetNullish, + auditString, + auditStringToBoolean, + auditStringToNumber, + auditSwitch, + auditTrimString, + auditUnique, + cleanAudit, + type Audit, +} from "@auditors/core" + +export function auditServerConfig( + audit: Audit, + dataUnknown: unknown, +): [unknown, unknown] { + if (dataUnknown == null) { + return [dataUnknown, null] + } + if (typeof dataUnknown !== "object") { + return audit.unexpectedType(dataUnknown, "object") + } + + const data = { ...dataUnknown } + const errors: { [key: string]: unknown } = {} + const remainingKeys = new Set(Object.keys(data)) + + audit.attribute( + data, + "allowRobots", + true, + errors, + remainingKeys, + auditSwitch([auditTrimString, auditStringToBoolean], auditBoolean), + auditSetNullish(false), + ) + for (const key of ["budgetApiUrl", "budgetDemandPipelineUrl"]) { + audit.attribute(data, key, true, errors, remainingKeys, auditHttpUrl) + } + for (const key of [ + "jwtSecret", + "simulationsBudgetDir", + "simulationsTestCasesDir", + ]) { + audit.attribute( + data, + key, + true, + errors, + remainingKeys, + auditTrimString, + auditRequire, + ) + } + for (const key of [ + "budgetDemandPipelineToken", + "budgetJwtSecret", + "githubPersonalAccessToken", + ]) { + audit.attribute(data, key, true, errors, remainingKeys, auditTrimString) + } + audit.attribute( + data, + "openIdConnect", + true, + errors, + remainingKeys, + auditOpenIdConnect, + ) + + return audit.reduceRemaining(data, errors, remainingKeys) +} + +function auditOpenIdConnect( + audit: Audit, + dataUnknown: unknown, +): [unknown, unknown] { + if (dataUnknown == null) { + return [dataUnknown, null] + } + if (typeof dataUnknown !== "object") { + return audit.unexpectedType(dataUnknown, "object") + } + + const data = { ...dataUnknown } + const errors: { [key: string]: unknown } = {} + const remainingKeys = new Set(Object.keys(data)) + + // for (const key of [ + // "cert", + // "decryptionCertificatePath", + // "decryptionPrivateKeyPath", + // "identifierFormat", + // "signatureCertificatePath", + // "signaturePrivateKeyPath", + // ]) { + // audit.attribute(data, key, true, errors, remainingKeys, auditTrimString) + // } + for (const key of ["clientId", "clientSecret"]) { + audit.attribute( + data, + key, + true, + errors, + remainingKeys, + auditTrimString, + auditRequire, + ) + } + audit.attribute( + data, + "issuerUrl", + true, + errors, + remainingKeys, + auditHttpUrl, + auditRequire, + ) + + return audit.reduceRemaining(data, errors, remainingKeys) +} + +export function validateServerConfig(data: unknown): [unknown, unknown] { + return auditServerConfig(cleanAudit, data) +} diff --git a/src/lib/server/budgets.ts b/src/lib/server/budgets.ts index 7936c98bf..819b2c02a 100644 --- a/src/lib/server/budgets.ts +++ b/src/lib/server/budgets.ts @@ -1,10 +1,10 @@ import path from "path" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" export function getBudgetRequestsDirPath(digest: string) { return path.join( - config.simulationsBudgetDir, + serverConfig.simulationsBudgetDir, "requests", digest.substring(0, 2), ) @@ -15,7 +15,7 @@ export function getBudgetRequestsFilePath(digest: string) { export function getBudgetCacheDirPath(digest: string) { return path.join( - config.simulationsBudgetDir, + serverConfig.simulationsBudgetDir, "responses", digest.substring(0, 2), ) diff --git a/src/lib/server/config.ts b/src/lib/server/config.ts deleted file mode 100644 index c586df34a..000000000 --- a/src/lib/server/config.ts +++ /dev/null @@ -1,108 +0,0 @@ -import "dotenv/config" - -import type { RepositoryConfig } from "$lib/repositories" -import { validateConfig } from "$lib/server/auditors/config" - -export interface Config { - advanced: boolean - allowRobots: boolean - apiBaseUrls: string[] - baseUrl: string - budgetApiUrl?: string - budgetDemandPipelineUrl?: string - budgetDemandPipelineToken?: string - budgetJwtSecret?: string - childrenKey: string - familyEntityKey: string - githubPersonalAccessToken?: string - hiddenEntitiesKeyPlural?: string[] - householdEntityKey: string - jwtSecret: string - legalUrl: string - matomo?: { - prependDomain?: boolean - siteId: number - subdomains?: string - url: string - } - openfiscaRepository: RepositoryConfig - openIdConnect?: { - clientId: string - clientSecret: string - issuerUrl: string - } - portalUrl: string - proxy: boolean - reformName?: string - revaluationName?: string - showTutorial?: boolean - simulationsBudgetDir: string - simulationsTestCasesDir: string - taxableHouseholdEntityKey: string - territoiresUrl: string - title: string -} - -const [validConfig, error] = validateConfig({ - advanced: process.env["ADVANCED"], - allowRobots: process.env["ALLOW_ROBOTS"], - apiBaseUrls: process.env["API_BASE_URLS"], - baseUrl: process.env["BASE_URL"], - budgetApiUrl: process.env["BUDGET_API_URL"], - budgetDemandPipelineUrl: process.env["BUDGET_DEMAND_PIPELINE_URL"], - budgetDemandPipelineToken: process.env["BUDGET_DEMAND_PIPELINE_TOKEN"], - budgetJwtSecret: process.env["BUDGET_JWT_SECRET"], - childrenKey: process.env["CHILDREN_KEY"], - familyEntityKey: process.env["FAMILY_KEY"], - githubPersonalAccessToken: process.env["GITHUB_PERSONAL_ACCESS_TOKEN"], - hiddenEntitiesKeyPlural: process.env["HIDDEN_ENTITIES"], - householdEntityKey: process.env["HOUSEHOLD_KEY"], - jwtSecret: process.env["JWT_SECRET"], - legalUrl: process.env["LEGAL_URL"], - matomo: - process.env["MATOMO_SITE_ID"] && process.env["MATOMO_URL"] - ? { - prependDomain: process.env["MATOMO_PREPEND_DOMAIN"], - siteId: process.env["MATOMO_SITE_ID"], - subdomains: process.env["MATOMO_SUBDOMAINS"], - url: process.env["MATOMO_URL"], - } - : null, - openfiscaRepository: { - branch: process.env["OPENFISCA_BRANCH"], - group: process.env["OPENFISCA_GROUP"], - project: process.env["OPENFISCA_PROJECT"], - rawUrlTemplate: process.env["OPENFISCA_REPOSITORY_RAW_URL_TEMPLATE"], - urlTemplate: process.env["OPENFISCA_REPOSITORY_URL_TEMPLATE"], - }, - openIdConnect: process.env["OPENID_CONNECT_CLIENT_ID"] - ? { - clientId: process.env["OPENID_CONNECT_CLIENT_ID"], - clientSecret: process.env["OPENID_CONNECT_CLIENT_SECRET"], - issuerUrl: process.env["OPENID_CONNECT_ISSUER_URL"], - } - : null, - portalUrl: process.env["PORTAL_URL"], - proxy: process.env["PROXY"], - reformName: process.env["REFORM"], - revaluationName: process.env["REFORM_REVALUATION"], - showTutorial: process.env["SHOW_TUTORIAL"], - simulationsBudgetDir: process.env["SIMULATIONS_BUDGET_DIR"], - simulationsTestCasesDir: process.env["SIMULATIONS_TEST_CASES_DIR"], - taxableHouseholdEntityKey: process.env["TAXABLE_HOUSEHOLD_KEY"], - territoiresUrl: process.env["TERRITOIRES_URL"], - title: process.env["TITLE"], -}) as [Config, unknown] -if (error !== null) { - console.error( - `Error in configuration:\n${JSON.stringify( - validConfig, - null, - 2, - )}\nError:\n${JSON.stringify(error, null, 2)}`, - ) - process.exit(-1) -} -const config = validConfig - -export default config diff --git a/src/lib/server/openid_connect_handler.ts b/src/lib/server/openid_connect_handler.ts index 8435c2207..6d6170eed 100644 --- a/src/lib/server/openid_connect_handler.ts +++ b/src/lib/server/openid_connect_handler.ts @@ -5,13 +5,15 @@ import { type Client as OpenIdConnectClient, } from "openid-client" -import config from "$lib/server/config" +import publicConfig from "$lib/public_config" +import serverConfig from "$lib/server/server_config" export interface OpenIdConnectLocals { openIdConnectClient?: OpenIdConnectClient } -const { baseUrl, openIdConnect } = config +const { baseUrl } = publicConfig +const { openIdConnect } = serverConfig let openIdConnectClient: OpenIdConnectClient | undefined = undefined openIdConnectCustom.setHttpOptionsDefaults({ diff --git a/src/lib/server/server_config.ts b/src/lib/server/server_config.ts new file mode 100644 index 000000000..f01c9e557 --- /dev/null +++ b/src/lib/server/server_config.ts @@ -0,0 +1,64 @@ +import { + ALLOW_ROBOTS, + BUDGET_API_URL, + BUDGET_DEMAND_PIPELINE_URL, + BUDGET_DEMAND_PIPELINE_TOKEN, + BUDGET_JWT_SECRET, + GITHUB_PERSONAL_ACCESS_TOKEN, + JWT_SECRET, + OPENID_CONNECT_CLIENT_ID, + OPENID_CONNECT_CLIENT_SECRET, + OPENID_CONNECT_ISSUER_URL, + SIMULATIONS_BUDGET_DIR, + SIMULATIONS_TEST_CASES_DIR, +} from "$env/static/private" +import { validateServerConfig } from "$lib/server/auditors/server_config" + +export interface ServerConfig { + allowRobots: boolean + budgetApiUrl?: string + budgetDemandPipelineUrl?: string + budgetDemandPipelineToken?: string + budgetJwtSecret?: string + githubPersonalAccessToken?: string + jwtSecret: string + openIdConnect?: { + clientId: string + clientSecret: string + issuerUrl: string + } + simulationsBudgetDir: string + simulationsTestCasesDir: string +} + +const [validConfig, error] = validateServerConfig({ + allowRobots: ALLOW_ROBOTS, + budgetApiUrl: BUDGET_API_URL, + budgetDemandPipelineUrl: BUDGET_DEMAND_PIPELINE_URL, + budgetDemandPipelineToken: BUDGET_DEMAND_PIPELINE_TOKEN, + budgetJwtSecret: BUDGET_JWT_SECRET, + githubPersonalAccessToken: GITHUB_PERSONAL_ACCESS_TOKEN, + jwtSecret: JWT_SECRET, + openIdConnect: OPENID_CONNECT_CLIENT_ID + ? { + clientId: OPENID_CONNECT_CLIENT_ID, + clientSecret: OPENID_CONNECT_CLIENT_SECRET, + issuerUrl: OPENID_CONNECT_ISSUER_URL, + } + : null, + simulationsBudgetDir: SIMULATIONS_BUDGET_DIR, + simulationsTestCasesDir: SIMULATIONS_TEST_CASES_DIR, +}) as [ServerConfig, unknown] +if (error !== null) { + console.error( + `Error in configuration:\n${JSON.stringify( + validConfig, + null, + 2, + )}\nError:\n${JSON.stringify(error, null, 2)}`, + ) + process.exit(-1) +} +const serverConfig = validConfig + +export default serverConfig diff --git a/src/lib/server/test_cases.ts b/src/lib/server/test_cases.ts index 1b10fbe81..8d837119a 100644 --- a/src/lib/server/test_cases.ts +++ b/src/lib/server/test_cases.ts @@ -1,10 +1,10 @@ import path from "path" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" export function getTestCasesRequestsDirPath(digest: string) { return path.join( - config.simulationsTestCasesDir, + serverConfig.simulationsTestCasesDir, "requests", digest.substring(0, 2), ) @@ -15,7 +15,7 @@ export function getTestCasesRequestsFilePath(digest: string) { export function getTestCasesCacheDirPath(digest: string) { return path.join( - config.simulationsTestCasesDir, + serverConfig.simulationsTestCasesDir, "responses", digest.substring(0, 2), ) @@ -26,7 +26,7 @@ export function getTestCasesCacheFilePath(digest: string) { export function getTestCasesOpenGraphsDirPath(digest: string) { return path.join( - config.simulationsTestCasesDir, + serverConfig.simulationsTestCasesDir, "opengraphs", digest.substring(0, 2), ) diff --git a/src/lib/server/user_handler.ts b/src/lib/server/user_handler.ts index b66c35d1e..13360f1fa 100644 --- a/src/lib/server/user_handler.ts +++ b/src/lib/server/user_handler.ts @@ -1,7 +1,7 @@ import type { Handle } from "@sveltejs/kit" import jwt from "jsonwebtoken" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" import type { User } from "$lib/users" export interface UserLocals { @@ -15,7 +15,7 @@ export const userHandler: Handle = async ({ event, resolve }) => { if (idTokenJwt !== undefined) { try { locals.id_token = ( - jwt.verify(idTokenJwt, config.jwtSecret) as { id_token: string } + jwt.verify(idTokenJwt, serverConfig.jwtSecret) as { id_token: string } ).id_token } catch (e) { console.warn(`Invalid JSON Web Token for id_token: ${idTokenJwt}. ${e}`) @@ -26,7 +26,7 @@ export const userHandler: Handle = async ({ event, resolve }) => { const userJwt = cookies.get("user") if (userJwt !== undefined) { try { - locals.user = jwt.verify(userJwt, config.jwtSecret) as User + locals.user = jwt.verify(userJwt, serverConfig.jwtSecret) as User } catch (e) { console.warn(`Invalid JSON Web Token for user: ${userJwt}. ${e}`) cookies.delete("user", { path: "/" }) diff --git a/src/routes/+error.svelte b/src/routes/+error.svelte index f2872de7d..bc0d9f4b6 100644 --- a/src/routes/+error.svelte +++ b/src/routes/+error.svelte @@ -1,10 +1,13 @@ <script lang="ts"> import { page } from "$app/stores" + // import publicConfig from "$lib/public_config" + + // const {appTitle} = publicConfig let title = $derived(`${$page.status}: ${$page.error.message}`) </script> -<!-- <title>Erreur | {$page.data.title}</title> --> +<!-- <title>Erreur | {appTitle}</title> --> <svelte:head> <title>Erreur</title> </svelte:head> diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 9d94316fd..f22a3d385 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -1,73 +1,25 @@ import type { LayoutServerLoad } from "./$types" -import type { RepositoryConfig } from "$lib/repositories" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" import type { User } from "$lib/users" -const { openfiscaRepository } = config - export const load: LayoutServerLoad = async ( event, ): Promise<{ - advanced: boolean - apiBaseUrls: string[] - baseUrl: string authenticationEnabled: boolean canDemandBudgetSimulation: boolean - childrenKey: string - familyEntityKey: string hasGithubPersonalAccessToken: boolean - hiddenEntitiesKeyPlural?: string[] - householdEntityKey: string - legalUrl: string - matomo?: { - prependDomain?: boolean - siteId: number - subdomains?: string - url: string - } - openfiscaRepository: RepositoryConfig - portalUrl: string - reformName?: string - revaluationName?: string - showTutorial?: boolean - taxableHouseholdEntityKey: string - territoiresUrl: string - title: string user?: User }> => { const { locals } = event const { user } = locals return { - advanced: config.advanced, - apiBaseUrls: config.apiBaseUrls, - authenticationEnabled: config.openIdConnect !== undefined, - baseUrl: config.baseUrl, + authenticationEnabled: serverConfig.openIdConnect !== undefined, canDemandBudgetSimulation: - config.budgetDemandPipelineUrl !== undefined && - config.budgetDemandPipelineToken !== undefined, - childrenKey: config.childrenKey, - familyEntityKey: config.familyEntityKey, + serverConfig.budgetDemandPipelineUrl !== undefined && + serverConfig.budgetDemandPipelineToken !== undefined, hasGithubPersonalAccessToken: - config.githubPersonalAccessToken !== undefined, - hiddenEntitiesKeyPlural: config.hiddenEntitiesKeyPlural, - householdEntityKey: config.householdEntityKey, - legalUrl: config.legalUrl, - matomo: config.matomo, - openfiscaRepository: { - branch: openfiscaRepository.branch, - group: openfiscaRepository.group, - project: openfiscaRepository.project, - rawUrlTemplate: openfiscaRepository.rawUrlTemplate, - urlTemplate: openfiscaRepository.urlTemplate, - }, - portalUrl: config.portalUrl, - reformName: config.reformName, - revaluationName: config.revaluationName, - showTutorial: config.showTutorial, - taxableHouseholdEntityKey: config.taxableHouseholdEntityKey, - territoiresUrl: config.territoiresUrl, - title: config.title, + serverConfig.githubPersonalAccessToken !== undefined, user, } } diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 6c89852bb..8bb9855a2 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -51,6 +51,7 @@ } from "$lib/matomo" import { metadata } from "$lib/metadata" import { getNavbarConfig, type NavbarConfig } from "$lib/navbar" + import publicConfig from "$lib/public_config" import { reformMetadataByName, type ParametricReform } from "$lib/reforms" import { extractInputInstantsFromTestCases, @@ -84,6 +85,12 @@ children?: import("svelte").Snippet } + const { + baseUrl, + matomo: matomoConfig, + reformName, + revaluationName, + } = publicConfig let { data, children }: Props = $props() let axisBySituationIndex: { [situationIndex: string]: Axis } = {} @@ -101,26 +108,20 @@ */ let currentBillName: string | undefined = - data.reformName === undefined + reformName === undefined ? undefined - : reformMetadataByName[data.reformName] === undefined + : reformMetadataByName[reformName] === undefined ? undefined - : data.reformName - const billName: Writable<string | undefined> = writable(currentBillName) - setContext("billName", billName) + : reformName const billActive: Writable<boolean> = writable(currentBillName !== undefined) setContext("billActive", billActive) let currentRevaluationName: string | undefined = - data.revaluationName === undefined + revaluationName === undefined ? undefined - : reformMetadataByName[data.revaluationName] === undefined + : reformMetadataByName[revaluationName] === undefined ? undefined - : data.revaluationName - const revaluationName: Writable<string | undefined> = writable( - currentRevaluationName, - ) - setContext("revaluationName", revaluationName) + : revaluationName const customOpenGraphRoutes = [ /\/fonctionnement/, @@ -173,8 +174,6 @@ inputInstantsByVariableNameArray, ) - const matomoConfig = data.matomo - const navbarConfig: Writable<NavbarConfig> = writable( getNavbarConfig($page.route.id ?? "/"), ) @@ -225,7 +224,7 @@ const showNulls = writable(false) setContext("showNulls", showNulls) - const showTutorial = writable(false) + const showTutorial = writable(publicConfig.showTutorial) setContext("showTutorial", showTutorial) const testCasesValue: Situation[] = structuredClone(testCasesCore) @@ -305,7 +304,7 @@ quantile_compare_variables: quantileCompareVariables, winners_loosers_variable: variableName, quantile_nb: 10, - plf: $billName === undefined ? undefined : $yearPLF, + plf: reformName === undefined ? undefined : $yearPLF, } } @@ -522,9 +521,9 @@ }: TestCasesCalculationInput, ) { const completeVariableSummaryByName = - $billName === undefined + reformName === undefined ? variableSummaryByName - : variableSummaryByNameByReformName[$billName] + : variableSummaryByNameByReformName[reformName] try { // Note: crypto.randomUUID() is not supported by Safari before version 15.4. // const token = crypto.randomUUID() @@ -663,7 +662,7 @@ const calculationNonVirtualVariablesName = calculationName === "law" ? nonVirtualVariablesName - : (nonVirtualVariablesNameByReformName[$billName as string] ?? + : (nonVirtualVariablesNameByReformName[reformName as string] ?? nonVirtualVariablesName) if (calculationNonVirtualVariablesName.includes(variableName)) { if (calculation.situationIndex === undefined) { @@ -955,7 +954,7 @@ let { fetch } = $derived(data) let { url } = $derived($page) run(() => { - updateBillName($billName) + updateBillName(reformName) }) run(() => { updateOnSliderChange($testCases) @@ -1063,14 +1062,14 @@ /> <meta property="og:image" - content={new URL("open-graph-image.png", data.baseUrl).toString()} + content={new URL("open-graph-image.png", baseUrl).toString()} /> <meta property="og:title" content="Simulateur cotisations & prestations sociales - LexImpact - Assemblée nationale" /> <meta property="og:type" content="website" /> - <meta property="og:url" content={data.baseUrl} /> + <meta property="og:url" content={baseUrl} /> {/if} </svelte:head> diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 88bab23f2..7d677202f 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -70,6 +70,7 @@ trackTestCaseShare, trackTestCaseEdit, } from "$lib/matomo" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import { publishTestCaseSimulation } from "$lib/simulations" import { getPopulationReservedKeys, type Situation } from "$lib/situations" @@ -90,11 +91,11 @@ data: PageData } + const { appTitle, baseUrl, reformName } = publicConfig let { data }: Props = $props() let animationEndedTimeoutId = undefined const billActive = getContext("billActive") as Writable<boolean> - const billName = getContext("billName") as Writable<string | undefined> const budgetSimulation = getContext("budgetSimulation") as Writable< BudgetSimulation | undefined > @@ -468,7 +469,7 @@ // function changeBillName({ target }: Event) { // const { value } = target as HTMLSelectElement - // $billName = value === "undefined" ? undefined : value + // reformName = value === "undefined" ? undefined : value // $requestedCalculations = requestTestCasesCalculation( // $requestedCalculations, // "bill", @@ -730,10 +731,7 @@ return } const { token } = await response.json() - const url = new URL( - `/test_cases/simulations/${token}`, - $page.data.baseUrl, - ).toString() + const url = new URL(`/test_cases/simulations/${token}`, baseUrl).toString() const copyClipboard = mount(CopyClipboard, { target: clipboardElement, props: { value: url }, @@ -983,7 +981,7 @@ <svelte:window bind:innerWidth={windowInnerWidth} onkeydown={onKeyDown} /> <svelte:head> - <title>Assemblée nationale - LexImpact | {data.title}</title> + <title>Assemblée nationale - LexImpact | {appTitle}</title> <meta name="description" content="Le simulateur LexImpact de l'Assemblée nationale permet de chiffrer les effets de la modification des lois socio-fiscales françaises sur des ménages types et sur le budget de l'État et de la Sécurité sociale. L'outil concerne de nombreux dispositifs, tels que les impôts, les cotisations et les prestations sociales." @@ -1306,7 +1304,7 @@ class="rounded border-1 text-xs" on:blur={changeBillName} on:change={changeBillName} - value={$billName} + value={reformName} > <option value={undefined}>Pas de projet/proposition de loi</option> {#each metadata.reforms as { label, name }} @@ -1611,11 +1609,11 @@ </h2> {:else} {@const variableSummary = - $billName === undefined + reformName === undefined ? variableSummaryByName[ displayMode.parametersVariableName ] - : variableSummaryByNameByReformName[$billName][ + : variableSummaryByNameByReformName[reformName][ displayMode.parametersVariableName ]} {#if variableSummary !== undefined} @@ -1889,11 +1887,11 @@ > {#if displayMode.parametersVariableName !== undefined} {@const variableSummary = - $billName === undefined + reformName === undefined ? variableSummaryByName[ displayMode.parametersVariableName ] - : variableSummaryByNameByReformName[$billName][ + : variableSummaryByNameByReformName[reformName][ displayMode.parametersVariableName ]} {#if displayMode.testCasesIndex.length > 0} diff --git a/src/routes/accueil/+page.svelte b/src/routes/accueil/+page.svelte index ec797c890..b74ae8ddc 100644 --- a/src/routes/accueil/+page.svelte +++ b/src/routes/accueil/+page.svelte @@ -29,13 +29,10 @@ import type { DisplayMode } from "$lib/displays" import { trackSearchVariable } from "$lib/matomo" import type { NavbarConfig } from "$lib/navbar" + import publicConfig from "$lib/public_config" import { newSimulationUrl } from "$lib/urls" - interface Props { - data: PageData - } - - let { data }: Props = $props() + const { appTitle } = publicConfig let displayMode: DisplayMode = $state({ testCasesIndex: [], @@ -220,7 +217,7 @@ </script> <svelte:head> - <title>Assemblée nationale - LexImpact | {data.title}</title> + <title>Assemblée nationale - LexImpact | {appTitle}</title> <meta name="description" content="Le simulateur LexImpact de l'Assemblée nationale permet de chiffrer les effets de la modification des lois socio-fiscales françaises sur des ménages types et sur le budget de l'État et de la Sécurité sociale. L'outil concerne de nombreux dispositifs, tels que les impôts, les cotisations et les prestations sociales." diff --git a/src/routes/auth/login/+server.ts b/src/routes/auth/login/+server.ts index 821873042..198507e4b 100644 --- a/src/routes/auth/login/+server.ts +++ b/src/routes/auth/login/+server.ts @@ -5,7 +5,7 @@ import { generators } from "openid-client" import type { RequestHandler } from "./$types" import { validateLoginLogoutQuery } from "$lib/server/auditors/queries" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" export const GET: RequestHandler = async ({ cookies, locals, url }) => { const [query, queryError] = validateLoginLogoutQuery(url.searchParams) as [ @@ -41,7 +41,7 @@ export const GET: RequestHandler = async ({ cookies, locals, url }) => { }) cookies.set( "signin", - jwt.sign({ nonce, token }, config.jwtSecret, { + jwt.sign({ nonce, token }, serverConfig.jwtSecret, { expiresIn: "1h", }), { diff --git a/src/routes/auth/login_callback/+server.ts b/src/routes/auth/login_callback/+server.ts index 04da6aeb7..0612ee0b2 100644 --- a/src/routes/auth/login_callback/+server.ts +++ b/src/routes/auth/login_callback/+server.ts @@ -2,7 +2,8 @@ import { error, type RequestHandler } from "@sveltejs/kit" import jwt from "jsonwebtoken" import type { Client as OpenIdConnectClient } from "openid-client" -import config from "$lib/server/config" +import publicConfig from "$lib/public_config" +import serverConfig from "$lib/server/server_config" import type { SigninPayload } from "$lib/users" export const POST: RequestHandler = async ({ @@ -28,7 +29,10 @@ export const POST: RequestHandler = async ({ } let signinPayload: SigninPayload try { - signinPayload = jwt.verify(signinJwt, config.jwtSecret) as SigninPayload + signinPayload = jwt.verify( + signinJwt, + serverConfig.jwtSecret, + ) as SigninPayload } catch (e) { console.error(`Invalid JSON Web Token: ${signinJwt}. ${e}`) error(401, `Invalid JSON Web Token`) @@ -54,7 +58,7 @@ export const POST: RequestHandler = async ({ if (tokenSet.id_token !== undefined) { cookies.set( "id_token", - jwt.sign({ id_token: tokenSet.id_token }, config.jwtSecret, { + jwt.sign({ id_token: tokenSet.id_token }, serverConfig.jwtSecret, { expiresIn: "1w", }), { @@ -64,16 +68,20 @@ export const POST: RequestHandler = async ({ }, ) } - cookies.set("user", jwt.sign(user, config.jwtSecret, { expiresIn: "1w" }), { - httpOnly: true, - path: "/", - secure: true, - }) + cookies.set( + "user", + jwt.sign(user, serverConfig.jwtSecret, { expiresIn: "1w" }), + { + httpOnly: true, + path: "/", + secure: true, + }, + ) return new Response(undefined, { status: 302, headers: { - location: new URL(`/auth/restore_state`, config.baseUrl).toString(), + location: new URL(`/auth/restore_state`, publicConfig.baseUrl).toString(), }, }) } diff --git a/src/routes/auth/logout/+server.ts b/src/routes/auth/logout/+server.ts index 48ab7fee6..1e6caa1b4 100644 --- a/src/routes/auth/logout/+server.ts +++ b/src/routes/auth/logout/+server.ts @@ -3,7 +3,7 @@ import { error } from "@sveltejs/kit" import type { RequestHandler } from "./$types" import { validateLoginLogoutQuery } from "$lib/server/auditors/queries" -import config from "$lib/server/config" +import publicConfig from "$lib/public_config" export const GET: RequestHandler = ({ cookies, locals, url }) => { const [query, queryError] = validateLoginLogoutQuery(url.searchParams) as [ @@ -37,7 +37,7 @@ export const GET: RequestHandler = ({ cookies, locals, url }) => { if (idToken === undefined) { return new Response(undefined, { status: 302, - headers: { location: config.baseUrl }, + headers: { location: publicConfig.baseUrl }, }) } if (locals.openIdConnectClient !== undefined) { diff --git a/src/routes/auth/logout_callback/+server.ts b/src/routes/auth/logout_callback/+server.ts index 473b59582..f8f353532 100644 --- a/src/routes/auth/logout_callback/+server.ts +++ b/src/routes/auth/logout_callback/+server.ts @@ -1,12 +1,12 @@ import type { RequestHandler } from "@sveltejs/kit" -import config from "$lib/server/config" +import publicConfig from "$lib/public_config" export const GET: RequestHandler = async () => { return new Response(undefined, { status: 302, headers: { - location: new URL(`/auth/restore_state`, config.baseUrl).toString(), + location: new URL(`/auth/restore_state`, publicConfig.baseUrl).toString(), }, }) } diff --git a/src/routes/budgets/+server.ts b/src/routes/budgets/+server.ts index 7313aeec4..413963b54 100644 --- a/src/routes/budgets/+server.ts +++ b/src/routes/budgets/+server.ts @@ -13,7 +13,7 @@ import { getBudgetCacheDirPath, getBudgetCacheFilePath, } from "$lib/server/budgets" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" import type { CachedSimulation } from "$lib/simulations" import type { User } from "$lib/users" import { budgetEditableParametersName } from "$lib/variables" @@ -23,7 +23,7 @@ interface PayloadUser extends User { iat?: number } -const { simulationsBudgetDir } = config +const { simulationsBudgetDir } = serverConfig function hashBudgetSimulationCache( parametricReform: ParametricReform, @@ -46,8 +46,8 @@ function hashBudgetSimulationCache( export const POST: RequestHandler = async ({ fetch, locals, request }) => { if ( - config.budgetApiUrl === undefined || - config.budgetJwtSecret === undefined + serverConfig.budgetApiUrl === undefined || + serverConfig.budgetJwtSecret === undefined ) { error( 404, @@ -61,7 +61,7 @@ export const POST: RequestHandler = async ({ fetch, locals, request }) => { const requestJwtToken = request.headers.get("jwt-token") if (requestJwtToken !== null) { try { - user = jwt.verify(requestJwtToken, config.jwtSecret) as User + user = jwt.verify(requestJwtToken, serverConfig.jwtSecret) as User } catch (e) { console.warn( `Invalid JSON Web Token for id_token: ${requestJwtToken}. ${e}`, @@ -168,12 +168,12 @@ export const POST: RequestHandler = async ({ fetch, locals, request }) => { delete payload.user.iat // Request calculation of the current reform - const response = await fetch(config.budgetApiUrl, { + const response = await fetch(serverConfig.budgetApiUrl, { body: await request.arrayBuffer(), headers: { Accept: "application/json", "Content-Type": "application/json; charset=utf-8", - "jwt-token": jwt.sign(payload, config.budgetJwtSecret), + "jwt-token": jwt.sign(payload, serverConfig.budgetJwtSecret), }, method: "POST", }) @@ -182,7 +182,7 @@ export const POST: RequestHandler = async ({ fetch, locals, request }) => { // Gateway timeout, etc. // Budget API never returns a JSON when a status other than 200 occurs. console.error( - `An error occurred while calling budget API at ${config.budgetApiUrl}`, + `An error occurred while calling budget API at ${serverConfig.budgetApiUrl}`, ) console.error(`${response.status} ${response.statusText}`) console.error(await response.text()) @@ -260,7 +260,7 @@ export const POST: RequestHandler = async ({ fetch, locals, request }) => { headers: { Accept: "application/json", "Content-Type": "application/json; charset=utf-8", - "jwt-token": jwt.sign(user, config.jwtSecret), + "jwt-token": jwt.sign(user, serverConfig.jwtSecret), }, method: "POST", }) diff --git a/src/routes/budgets/demands/+server.ts b/src/routes/budgets/demands/+server.ts index dee54d3ad..ce6dd5914 100644 --- a/src/routes/budgets/demands/+server.ts +++ b/src/routes/budgets/demands/+server.ts @@ -9,8 +9,9 @@ import { error, json } from "@sveltejs/kit" import type { RequestHandler } from "./$types" import type { DisplayMode } from "$lib/displays" +import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" function auditBody(audit: Audit, dataUnknown: unknown): [unknown, unknown] { if (dataUnknown == null) { @@ -93,7 +94,7 @@ export const POST: RequestHandler = async ({ fetch, request, url }) => { simulation: unknown } - const response = await fetch(config.budgetDemandPipelineUrl!, { + const response = await fetch(serverConfig.budgetDemandPipelineUrl!, { body: JSON.stringify({ variables: [ { key: "DISPLAY_MODE", value: JSON.stringify(displayMode) }, @@ -103,14 +104,14 @@ export const POST: RequestHandler = async ({ fetch, request, url }) => { { key: "USE_PROD", value: JSON.stringify( - config.baseUrl.includes("socio-fiscal.leximpact.an.fr"), + publicConfig.baseUrl.includes("socio-fiscal.leximpact.an.fr"), ), }, ], }), headers: { "Content-Type": "application/json; charset=utf-8", - "PRIVATE-TOKEN": config.budgetDemandPipelineToken!, + "PRIVATE-TOKEN": serverConfig.budgetDemandPipelineToken!, }, method: "POST", }) diff --git a/src/routes/budgets/simulations/+server.ts b/src/routes/budgets/simulations/+server.ts index f646c5ee9..e03a3a5cc 100644 --- a/src/routes/budgets/simulations/+server.ts +++ b/src/routes/budgets/simulations/+server.ts @@ -13,11 +13,11 @@ import { getBudgetRequestsDirPath, getBudgetRequestsFilePath, } from "$lib/server/budgets" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" import type { CachedSimulation } from "$lib/simulations" import type { User } from "$lib/users" -const { simulationsBudgetDir } = config +const { simulationsBudgetDir } = serverConfig function auditBody(audit: Audit, dataUnknown: unknown): [unknown, unknown] { if (dataUnknown == null) { @@ -70,7 +70,7 @@ export const POST: RequestHandler = async ({ locals, request, url }) => { const requestJwtToken = request.headers.get("jwt-token") if (requestJwtToken !== null) { try { - user = jwt.verify(requestJwtToken, config.jwtSecret) as User + user = jwt.verify(requestJwtToken, serverConfig.jwtSecret) as User } catch (e) { console.warn( `Invalid JSON Web Token for id_token: ${requestJwtToken}. ${e}`, diff --git a/src/routes/budgets/simulations/[simulation]/+page.server.ts b/src/routes/budgets/simulations/[simulation]/+page.server.ts index 64b32773b..1d574da79 100644 --- a/src/routes/budgets/simulations/[simulation]/+page.server.ts +++ b/src/routes/budgets/simulations/[simulation]/+page.server.ts @@ -15,10 +15,10 @@ import type { PageServerLoad } from "./$types" import type { DisplayMode } from "$lib/displays" import type { ParametricReform } from "$lib/reforms" import { getBudgetRequestsFilePath } from "$lib/server/budgets" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" import type { CachedSimulation } from "$lib/simulations" -const { simulationsBudgetDir } = config +const { simulationsBudgetDir } = serverConfig function auditParams(audit: Audit, dataUnknown: unknown): [unknown, unknown] { if (dataUnknown == null) { diff --git a/src/routes/budgets/simulations/index/+server.ts b/src/routes/budgets/simulations/index/+server.ts index d7384a698..a58d96fd8 100644 --- a/src/routes/budgets/simulations/index/+server.ts +++ b/src/routes/budgets/simulations/index/+server.ts @@ -5,10 +5,10 @@ import fs from "fs-extra" import type { RequestHandler } from "./$types" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" import type { CachedSimulation } from "$lib/simulations" -const { simulationsBudgetDir } = config +const { simulationsBudgetDir } = serverConfig export const POST: RequestHandler = async () => { const indexDir = path.join(simulationsBudgetDir, "index.json") diff --git a/src/routes/contribuer/+page.svelte b/src/routes/contribuer/+page.svelte index 8ab8e7ea7..5cf6fb7e9 100644 --- a/src/routes/contribuer/+page.svelte +++ b/src/routes/contribuer/+page.svelte @@ -2,16 +2,13 @@ import type { PageData } from "./$types" import { goto } from "$app/navigation" + import publicConfig from "$lib/public_config" - interface Props { - data: PageData - } - - let { data }: Props = $props() + const { appTitle } = publicConfig </script> <svelte:head> - <title>Contribuer| {data.title}</title> + <title>Contribuer| {appTitle}</title> </svelte:head> <main class="flex items-center justify-center bg-graph-paper"> diff --git a/src/routes/entities/+page.svelte b/src/routes/entities/+page.svelte index fc0b68ebc..04e84edfe 100644 --- a/src/routes/entities/+page.svelte +++ b/src/routes/entities/+page.svelte @@ -1,17 +1,12 @@ <script lang="ts"> - import type { PageData } from "./$types" - import { entityByKey } from "$lib/entities" + import publicConfig from "$lib/public_config" - interface Props { - data: PageData - } - - let { data }: Props = $props() + const { appTitle } = publicConfig </script> <svelte:head> - <title>Entités | {data.title}</title> + <title>Entités | {appTitle}</title> </svelte:head> <main> diff --git a/src/routes/fonctionnement/+page.svelte b/src/routes/fonctionnement/+page.svelte index 8caa84819..4d937ce3a 100644 --- a/src/routes/fonctionnement/+page.svelte +++ b/src/routes/fonctionnement/+page.svelte @@ -12,12 +12,9 @@ import Footer from "$lib/components/transverse_pages/Footer.svelte" import OpenGraph from "$lib/components/transverse_pages/OpenGraph.svelte" import { withLinkedVariableNames } from "$lib/decompositions" + import publicConfig from "$lib/public_config" - interface Props { - data: PageData - } - - let { data }: Props = $props() + const { appTitle } = publicConfig let testCaseSelectModalOpen = $state(false) const year = getContext("year") as Writable<number> @@ -25,7 +22,7 @@ <svelte:head> <title> - Fonctionnement du simulateurs | {data.title} + Fonctionnement du simulateurs | {appTitle} </title> </svelte:head> <OpenGraph diff --git a/src/routes/parameters/+page.svelte b/src/routes/parameters/+page.svelte index ddcd329f4..4106b5fe1 100644 --- a/src/routes/parameters/+page.svelte +++ b/src/routes/parameters/+page.svelte @@ -4,22 +4,15 @@ import type { Parameter } from "@openfisca/json-model" import { onMount } from "svelte" - import type { PageData } from "./$types" - import { browser } from "$app/environment" import { goto } from "$app/navigation" import { page } from "$app/stores" import Search from "$lib/components/search/Search.svelte" + import publicConfig from "$lib/public_config" import { SearchMode } from "$lib/search/search_mode" - interface Props { - data: PageData - } - - let { data }: Props = $props() - + const { appTitle } = publicConfig let searchInputValue = $state("") - let url = $derived($page.url) onMount(() => { @@ -50,7 +43,7 @@ <svelte:head> <title - >Paramètres{searchInputValue ? ` « ${searchInputValue} »` : " "} | {data.title}</title + >Paramètres{searchInputValue ? ` « ${searchInputValue} »` : " "} | {appTitle}</title > </svelte:head> diff --git a/src/routes/parameters/[parameter]/+page.svelte b/src/routes/parameters/[parameter]/+page.svelte index 8859a036b..b7af1a547 100644 --- a/src/routes/parameters/[parameter]/+page.svelte +++ b/src/routes/parameters/[parameter]/+page.svelte @@ -5,12 +5,14 @@ import type { PageData } from "./$types" import ParameterView from "$lib/components/parameters/ParameterView.svelte" + import publicConfig from "$lib/public_config" import { newSelfTargetAProps } from "$lib/urls" interface Props { data: PageData } + const { appTitle } = publicConfig let { data }: Props = $props() const date = getContext("date") as Writable<string> @@ -21,7 +23,7 @@ </script> <svelte:head> - <title>{parameter.name} | Paramètres | {data.title}</title> + <title>{parameter.name} | Paramètres | {appTitle}</title> </svelte:head> <ParameterView date={$date} {parameter} /> diff --git a/src/routes/parameters/[parameter]/+server.ts b/src/routes/parameters/[parameter]/+server.ts index 3f7879c5c..ed8df1ce9 100644 --- a/src/routes/parameters/[parameter]/+server.ts +++ b/src/routes/parameters/[parameter]/+server.ts @@ -13,10 +13,12 @@ import { error } from "@sveltejs/kit" import type { RequestHandler } from "./$types" import { getParameter, rootParameter } from "$lib/parameters" -import config from "$lib/server/config" +import publicConfig from "$lib/public_config" +import serverConfig from "$lib/server/server_config" import { units } from "$lib/units" -const { githubPersonalAccessToken, openfiscaRepository } = config +const { openfiscaRepository } = publicConfig +const { githubPersonalAccessToken } = serverConfig export const PUT: RequestHandler = async ({ request, params }) => { if (githubPersonalAccessToken === undefined) { diff --git a/src/routes/parameters/[parameter]/edit/+page.svelte b/src/routes/parameters/[parameter]/edit/+page.svelte index 611e5a5c6..8b8554b24 100644 --- a/src/routes/parameters/[parameter]/edit/+page.svelte +++ b/src/routes/parameters/[parameter]/edit/+page.svelte @@ -22,6 +22,7 @@ import ScaleEdit from "$lib/components/parameters/ScaleEdit.svelte" import ValueEdit from "$lib/components/parameters/ValueEdit.svelte" import { labelFromParameterClass } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { units } from "$lib/units" import { newSelfTargetAProps } from "$lib/urls" @@ -29,6 +30,7 @@ data: PageData } + const { appTitle } = publicConfig let { data }: Props = $props() const date = getContext("date") as Writable<string> @@ -114,7 +116,7 @@ </script> <svelte:head> - <title>Édition | {processedParameter.name} | Paramètres | {data.title}</title> + <title>Édition | {processedParameter.name} | Paramètres | {appTitle}</title> </svelte:head> {#if showErrors && Object.keys(errors).length > 0} diff --git a/src/routes/parameters/[parameter]/edit/+page.ts b/src/routes/parameters/[parameter]/edit/+page.ts index ca7189220..dd323309c 100644 --- a/src/routes/parameters/[parameter]/edit/+page.ts +++ b/src/routes/parameters/[parameter]/edit/+page.ts @@ -10,9 +10,12 @@ import { error } from "@sveltejs/kit" import type { PageLoad } from "./$types" import { getParameter, rootParameter } from "$lib/parameters" +import publicConfig from "$lib/public_config" import { newParameterRepositoryRawUrl } from "$lib/repositories" import { units } from "$lib/units" +const { openfiscaRepository } = publicConfig + export const load: PageLoad = async function ({ fetch, params, parent }) { const data = await parent() const { parameter: name } = params @@ -22,7 +25,7 @@ export const load: PageLoad = async function ({ fetch, params, parent }) { } let unprocessedParameterUrl = newParameterRepositoryRawUrl( - data.openfiscaRepository, + openfiscaRepository, processedParameter, ) if (unprocessedParameterUrl === undefined) { diff --git a/src/routes/robots.txt/+server.ts b/src/routes/robots.txt/+server.ts index 7dcedc65f..3db667d61 100644 --- a/src/routes/robots.txt/+server.ts +++ b/src/routes/robots.txt/+server.ts @@ -1,9 +1,9 @@ import type { RequestHandler } from "@sveltejs/kit" import dedent from "dedent-js" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" -const { allowRobots } = config +const { allowRobots } = serverConfig export const GET: RequestHandler = async () => { return new Response( diff --git a/src/routes/test_cases/+server.ts b/src/routes/test_cases/+server.ts index 4ff5b2980..b8d631ec3 100644 --- a/src/routes/test_cases/+server.ts +++ b/src/routes/test_cases/+server.ts @@ -4,13 +4,13 @@ import fs from "fs-extra" import type { RequestHandler } from "./$types" import { hashObject } from "$lib/hash" -import config from "$lib/server/config" +import publicConfig from "$lib/public_config" import { getTestCasesCacheDirPath, getTestCasesCacheFilePath, } from "$lib/server/test_cases" -const { apiBaseUrls } = config +const { apiBaseUrls } = publicConfig export const POST: RequestHandler = async ({ fetch, request }) => { const input = await request.clone().json() diff --git a/src/routes/test_cases/simulations/[simulation]/+page.svelte b/src/routes/test_cases/simulations/[simulation]/+page.svelte index 88e714ef4..9b532594c 100644 --- a/src/routes/test_cases/simulations/[simulation]/+page.svelte +++ b/src/routes/test_cases/simulations/[simulation]/+page.svelte @@ -15,6 +15,7 @@ EvaluationByName, DecompositionByName, } from "$lib/decompositions" + import publicConfig from "$lib/public_config" import type { ParametricReform } from "$lib/reforms" import type { Situation } from "$lib/situations" import { newSimulationUrl } from "$lib/urls" @@ -25,6 +26,7 @@ data: PageData } + const { baseUrl } = publicConfig let { data }: Props = $props() const decompositionByName = getContext( @@ -96,7 +98,7 @@ ?.label}» sur ce cas type ! Le simulateur permet aussi de connaître les impôts, cotisations et prestations sociales de ce foyer." image={new URL( `test_cases/og_image/${$page.params.simulation}`, - data.baseUrl, + baseUrl, ).toString()} title="Voici les impacts calculés par LexImpact sur mon cas type" titleSuffix={null} @@ -107,7 +109,7 @@ description="➡️ Ce simulateur permet de connaître le montants des impôts, cotisations et prestations sociales d'un foyer. Il permet aussi de modifier la loi et de voir les impacts !" image={new URL( `test_cases/og_image/${$page.params.simulation}`, - data.baseUrl, + baseUrl, ).toString()} title="Mon cas type configuré sur LexImpact" titleSuffix={null} diff --git a/src/routes/variables/+page.svelte b/src/routes/variables/+page.svelte index 0604b6086..4b38af7fc 100644 --- a/src/routes/variables/+page.svelte +++ b/src/routes/variables/+page.svelte @@ -1,17 +1,12 @@ <script lang="ts"> - import type { PageData } from "./$types" - + import publicConfig from "$lib/public_config" import { variableSummaryByName } from "$lib/variables" - interface Props { - data: PageData - } - - let { data }: Props = $props() + const { appTitle } = publicConfig </script> <svelte:head> - <title>Variables | {data.title}</title> + <title>Variables | {appTitle}</title> </svelte:head> <main> diff --git a/src/routes/variables/[variable]/+page.svelte b/src/routes/variables/[variable]/+page.svelte index b411611a3..01152a977 100644 --- a/src/routes/variables/[variable]/+page.svelte +++ b/src/routes/variables/[variable]/+page.svelte @@ -9,6 +9,7 @@ import { goto } from "$app/navigation" import VariableView from "$lib/components/variables/VariableView.svelte" import type { DisplayMode } from "$lib/displays" + import publicConfig from "$lib/public_config" import type { Situation } from "$lib/situations" import { newSelfTargetAProps, newSimulationUrl } from "$lib/urls" import type { ValuesByCalculationNameByVariableName } from "$lib/variables" @@ -17,6 +18,7 @@ data: PageData } + const { appTitle } = publicConfig let { data }: Props = $props() const date = getContext("date") as Writable<string> @@ -112,7 +114,7 @@ </script> <svelte:head> - <title>{variable.name} | Variables | {data.title}</title> + <title>{variable.name} | Variables | {appTitle}</title> </svelte:head> <main class="flex items-center justify-center bg-polka-dots"> diff --git a/src/routes/variables/[variable]/inputs/[date]/+page.svelte b/src/routes/variables/[variable]/inputs/[date]/+page.svelte index d49fd873b..531801b71 100644 --- a/src/routes/variables/[variable]/inputs/[date]/+page.svelte +++ b/src/routes/variables/[variable]/inputs/[date]/+page.svelte @@ -11,11 +11,13 @@ import type { Situation } from "$lib/situations" import { newSelfTargetAProps } from "$lib/urls" import type { ValuesByCalculationNameByVariableName } from "$lib/variables" + import publicConfig from "$lib/public_config" interface Props { data: PageData } + const { appTitle } = publicConfig let { data }: Props = $props() const inputInstantsByVariableNameArray = getContext( @@ -87,8 +89,7 @@ </script> <svelte:head> - <title>Variables d'entrée au {date} | {name} | Variables | {data.title}</title - > + <title>Variables d'entrée au {date} | {name} | Variables | {appTitle}</title> </svelte:head> <main> diff --git a/src/routes/variables/[variable]/parameters/[date]/+page.svelte b/src/routes/variables/[variable]/parameters/[date]/+page.svelte index f28883155..0e2112646 100644 --- a/src/routes/variables/[variable]/parameters/[date]/+page.svelte +++ b/src/routes/variables/[variable]/parameters/[date]/+page.svelte @@ -2,20 +2,14 @@ import { getContext, setContext } from "svelte" import type { Writable } from "svelte/store" - import type { PageData } from "./$types" - import { page } from "$app/stores" import VariableReferredParameters from "$lib/components/variables/VariableReferredParameters.svelte" import { waterfalls } from "$lib/decompositions" import type { DisplayMode } from "$lib/displays" + import publicConfig from "$lib/public_config" import { newSelfTargetAProps } from "$lib/urls" - interface Props { - data: PageData - } - - let { data }: Props = $props() - + const { appTitle } = publicConfig let displayMode: DisplayMode = $derived({ testCasesIndex: $testCasesIndex ?? [0], variableName: name, @@ -33,9 +27,7 @@ </script> <svelte:head> - <title - >Paramètres influant au {date} | {name} | Variables | {data.title}</title - > + <title>Paramètres influant au {date} | {name} | Variables | {appTitle}</title> </svelte:head> <main> diff --git a/src/routes/variables/[variable]/xlsx/+page.svelte b/src/routes/variables/[variable]/xlsx/+page.svelte index 01d997f29..ce22a6925 100644 --- a/src/routes/variables/[variable]/xlsx/+page.svelte +++ b/src/routes/variables/[variable]/xlsx/+page.svelte @@ -25,6 +25,7 @@ import { page } from "$app/stores" import { entityByKey, personEntityKey } from "$lib/entities" import { rootParameter } from "$lib/parameters" + import publicConfig from "$lib/public_config" import { getPopulationReservedKeys, // type Axis, @@ -42,6 +43,7 @@ data: PageData } + const { apiBaseUrls } = publicConfig let { data }: Props = $props() type ValuesByCalculationNameByPeriodByVariableName = { @@ -618,7 +620,7 @@ ) } let { variable: requestedVariableName } = $derived($page.params) - let { apiBaseUrls, variables } = $derived(data) + let { variables } = $derived(data) run(() => { if (browser) { calculate(variables) diff --git a/src/scripts/clear_simulations_cache.ts b/src/scripts/clear_simulations_cache.ts index 4a0e7e031..81e55d596 100644 --- a/src/scripts/clear_simulations_cache.ts +++ b/src/scripts/clear_simulations_cache.ts @@ -2,9 +2,9 @@ import path from "path" import fs from "fs-extra" -import config from "$lib/server/config" +import serverConfig from "$lib/server/server_config" -const { simulationsBudgetDir, simulationsTestCasesDir } = config +const { simulationsBudgetDir, simulationsTestCasesDir } = serverConfig // Remove private budget simulations from index. const indexFilePath = path.join(simulationsBudgetDir, "index.json") -- GitLab