From 1ac4d1a9e0ffded07c1fec0e1498aa16ae166c90 Mon Sep 17 00:00:00 2001
From: Toufic Batache <taffou2a@gmail.com>
Date: Fri, 1 Sep 2023 15:14:28 +0200
Subject: [PATCH] =?UTF-8?q?Rendre=20l'impact=20budg=C3=A9taire=20public=20?=
 =?UTF-8?q?avec=20les=20donn=C3=A9es=20de=20l'API?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 example.env                       |   1 +
 src/lib/server/auditors/config.ts |  11 +-
 src/lib/server/config.ts          |   2 +
 src/routes/+layout.svelte         |   4 +-
 src/routes/+page.svelte           | 188 +++---------------------------
 src/routes/budget/+server.ts      |  13 ++-
 6 files changed, 33 insertions(+), 186 deletions(-)

diff --git a/example.env b/example.env
index b092162f3..af1b81a04 100644
--- a/example.env
+++ b/example.env
@@ -16,6 +16,7 @@ BASE_URL="http://localhost:5173"
 
 # Public HTTP(S) URL of LexImpact Socio-Fiscal Budget server
 # BUDGET_API_URL="https://SECRET.DOMAIN.NAME/state_simulation"
+# BUDGET_PUBLIC_API_URL="https://SECRET.DOMAIN.NAME/default_state_simulation"
 
 # Secret key used to sign JSON web tokens sent to Budget API
 # BUDGET_JWT_SECRET="SECRET"
diff --git a/src/lib/server/auditors/config.ts b/src/lib/server/auditors/config.ts
index 4603fec64..253e63cdc 100644
--- a/src/lib/server/auditors/config.ts
+++ b/src/lib/server/auditors/config.ts
@@ -65,14 +65,9 @@ export function auditConfig(
       auditRequire,
     )
   }
-  audit.attribute(
-    data,
-    "budgetApiUrl",
-    true,
-    errors,
-    remainingKeys,
-    auditHttpUrl,
-  )
+  for (const key of ["budgetApiUrl", "budgetPublicApiUrl"]) {
+    audit.attribute(data, key, true, errors, remainingKeys, auditHttpUrl)
+  }
   for (const key of [
     "childrenKey",
     "familyEntityKey",
diff --git a/src/lib/server/config.ts b/src/lib/server/config.ts
index 2abbd37ae..3e2a97b96 100644
--- a/src/lib/server/config.ts
+++ b/src/lib/server/config.ts
@@ -10,6 +10,7 @@ export interface Config {
   apiWebSocketBaseUrls: string[]
   baseUrl: string
   budgetApiUrl?: string
+  budgetPublicApiUrl?: string
   budgetJwtSecret?: string
   childrenKey: string
   familyEntityKey: string
@@ -48,6 +49,7 @@ const [validConfig, error] = validateConfig({
   apiBaseUrls: process.env["API_BASE_URLS"],
   baseUrl: process.env["BASE_URL"],
   budgetApiUrl: process.env["BUDGET_API_URL"],
+  budgetPublicApiUrl: process.env["BUDGET_PUBLIC_API_URL"],
   budgetJwtSecret: process.env["BUDGET_JWT_SECRET"],
   childrenKey: process.env["CHILDREN_KEY"],
   familyEntityKey: process.env["FAMILY_KEY"],
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 0181d007a..cdb81a2c1 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -226,7 +226,6 @@
   }
 
   $: if (
-    user !== undefined &&
     $requestedCalculations.budgetVariableName !== undefined &&
     $requestedCalculations.budgetCalculationNames !== undefined
   ) {
@@ -292,6 +291,9 @@
     budgetVariableName: string,
     // budgetCalculationNames: Set<CalculationName>,
   ): Promise<void> {
+    if (user === undefined && $budgetSimulation !== undefined) {
+      return
+    }
     const budgetParametricReform = Object.fromEntries(
       Object.entries($parametricReform).filter(([parameterName]) =>
         budgetEditableParametersName.has(parameterName),
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 6ed64996c..dc26aca96 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -312,172 +312,6 @@
       .start()
   }
 
-  // TODO tgb: fix this when api changes
-  $: if (user === undefined) {
-    if (
-      $budgetSimulationCache !== undefined &&
-      deepEqual($budgetSimulationCache?.parametricReform, $parametricReform)
-    ) {
-      console.log("showing cached budget simulation")
-      $budgetSimulation = $budgetSimulationCache.budgetSimulation
-    } else {
-      console.log("showing fake budget simulation")
-      $budgetSimulation = {
-        result: {
-          base: {
-            state_budget: {
-              rfr: 1141166010364.9878,
-              irpp: -84198987029.96613,
-            },
-            quantiles: [
-              {
-                irpp_max: 1205.9132080078125,
-                irpp_mean: 106.90776079980795,
-                irpp_min: 0,
-                irpp_sum: 357033036.8133356,
-                rfr_max: 4930.01220703125,
-                rfr_mean: 1399.2841849688537,
-                rfr_min: 0,
-                rfr_sum: 4673100233.198416,
-                count: 3339636.2821769714,
-                quantile_num: 1,
-                fraction: 0.1,
-              },
-              {
-                irpp_max: 787.8517456054688,
-                irpp_mean: 132.23992868572972,
-                irpp_min: 0,
-                irpp_sum: 441519184.4162087,
-                rfr_max: 11357.0029296875,
-                rfr_mean: 8376.618875474238,
-                rfr_min: 4930.9990234375,
-                rfr_sum: 27967634063.49228,
-                count: 3338773.612510681,
-                quantile_num: 2,
-                fraction: 0.2,
-              },
-              {
-                irpp_max: 694.7799072265625,
-                irpp_mean: 176.71526607597514,
-                irpp_min: -95,
-                irpp_sum: 590097695.0551947,
-                rfr_max: 16581.705078125,
-                rfr_mean: 13943.609470937565,
-                rfr_min: 11357.2294921875,
-                rfr_sum: 46561295989.06605,
-                count: 3339257.0328445435,
-                quantile_num: 3,
-                fraction: 0.3,
-              },
-              {
-                irpp_max: 646.0764770507812,
-                irpp_mean: -27.312243370198726,
-                irpp_min: -742,
-                irpp_sum: -91165366.36509918,
-                rfr_max: 20640.91796875,
-                rfr_mean: 18600.66068102042,
-                rfr_min: 16582,
-                rfr_sum: 62087028979.40615,
-                count: 3337893.747116089,
-                quantile_num: 4,
-                fraction: 0.4,
-              },
-              {
-                irpp_max: 732.6367797851562,
-                irpp_mean: -346.4191971591506,
-                irpp_min: -1507,
-                irpp_sum: -1156896952.5983489,
-                rfr_max: 25428.14453125,
-                rfr_mean: 22909.216515526234,
-                rfr_min: 20641,
-                rfr_sum: 76507315387.1778,
-                count: 3339586.726387024,
-                quantile_num: 5,
-                fraction: 0.5,
-              },
-              {
-                irpp_max: 705.9767456054688,
-                irpp_mean: -771.3320849231815,
-                irpp_min: -3124,
-                irpp_sum: -2575853166.281143,
-                rfr_max: 31768.51171875,
-                rfr_mean: 28596.52621441492,
-                rfr_min: 25428.701171875,
-                rfr_sum: 95497716267.53784,
-                count: 3339486.605873108,
-                quantile_num: 6,
-                fraction: 0.6,
-              },
-              {
-                irpp_max: 626.471435546875,
-                irpp_mean: -1544.5756883978845,
-                irpp_min: -5407,
-                irpp_sum: -5157190056.149861,
-                rfr_max: 39383.71875,
-                rfr_mean: 35431.90982272599,
-                rfr_min: 31769.994140625,
-                rfr_sum: 118303748000.65468,
-                count: 3338904.072418213,
-                quantile_num: 7,
-                fraction: 0.7,
-              },
-              {
-                irpp_max: 639.8275146484375,
-                irpp_mean: -2696.538456758809,
-                irpp_min: -8422,
-                irpp_sum: -9003908666.682943,
-                rfr_max: 49484.77734375,
-                rfr_mean: 44133.02085030298,
-                rfr_min: 39384.33203125,
-                rfr_sum: 147362885897.26746,
-                count: 3339061.842086792,
-                quantile_num: 8,
-                fraction: 0.8,
-              },
-              {
-                irpp_max: 2021.9317626953125,
-                irpp_mean: -4744.9083619954945,
-                irpp_min: -13666,
-                irpp_sum: -15844180696.774479,
-                rfr_max: 66955.0859375,
-                rfr_mean: 57118.00797096622,
-                rfr_min: 49487,
-                rfr_sum: 190728243896.19965,
-                count: 3339196.3528060913,
-                quantile_num: 9,
-                fraction: 0.9,
-              },
-              {
-                irpp_max: 15176.8203125,
-                irpp_mean: -15500.926367717611,
-                irpp_min: -968522,
-                irpp_sum: -51758442041.398994,
-                rfr_max: 2104588,
-                rfr_mean: 111252.15603135424,
-                rfr_min: 66956.421875,
-                rfr_sum: 371477041650.98755,
-                count: 3339054.764442444,
-                quantile_num: 10,
-                fraction: 1,
-              },
-            ],
-            compare_before_after: {
-              total: 33390851,
-              non_zero_before: 33390851,
-              non_zero_after: 33390851,
-              above_after: 0,
-              lower_after: 33390851,
-              neutral: 0,
-              tolerance_factor_used: 0.1,
-              weight_factor: 1,
-            },
-          },
-        },
-        errors: [],
-      }
-    }
-  }
-
   $: isModificationsOpen = isUserModificationsOpen && modificationsCount > 0
 
   $: loadParameter($searchParameterName)
@@ -1518,8 +1352,16 @@
         >
           {#if displayMode.budget}
             {#if displayMode.parametersVariableName !== undefined}
+              {@const budgetSimulationData =
+                $budgetSimulationCache !== undefined &&
+                deepEqual(
+                  $budgetSimulationCache?.parametricReform,
+                  $parametricReform,
+                )
+                  ? $budgetSimulationCache.budgetSimulation
+                  : $budgetSimulation}
               <div class="mb-6 flex flex-col px-2 lg:px-5 w-screen md:w-full">
-                {#if $budgetSimulation === undefined || $budgetSimulation.errors.length > 0}
+                {#if budgetSimulationData === undefined || budgetSimulationData.errors.length > 0}
                   {#if displayMode.parametersVariableName !== undefined}
                     <div class="z-10 bg-le-jaune bg-opacity-20">
                       <Spinner />
@@ -1542,9 +1384,9 @@
                   <h3 class="mx-4 mb-2 text-2xl font-bold md:mx-0">
                     Impôt sur le revenu
                   </h3>
-                  <IrBudgetView budgetSimulation={$budgetSimulation} />
+                  <IrBudgetView budgetSimulation={budgetSimulationData} />
                   <IrGagnantsPerdantsView
-                    budgetSimulation={$budgetSimulation}
+                    budgetSimulation={budgetSimulationData}
                   />
                 {:else if displayMode.parametersVariableName === "csg_deductible_salaire" || displayMode.parametersVariableName === "csg_imposable_salaire"}
                   <!--     <a
@@ -1566,9 +1408,9 @@
                       >Imposable et déductible</span
                     >
                   </h3>
-                  <CsgBudgetView budgetSimulation={$budgetSimulation} />
+                  <CsgBudgetView budgetSimulation={budgetSimulationData} />
                   <CsgGagnantsPerdantsView
-                    budgetSimulation={$budgetSimulation}
+                    budgetSimulation={budgetSimulationData}
                   />
                 {/if}
               </div>
@@ -1792,7 +1634,7 @@
       class:md:-translate-y-full={!showButton}
       class:md:-translate-y-3={showButton}
       class:delay-500={showButton}
-      class:!top-0={!showButton}
+      class:md:!top-0={!showButton}
     >
       <p>
         Pour voir l'<strong>impact de votre réforme</strong>&nbsp;:
@@ -1824,8 +1666,8 @@
       class:translate-y-3={showButton}
       class:md:-translate-y-full={!showButton}
       class:md:-translate-y-3={showButton}
+      class:md:!top-0={!showButton}
       class:delay-500={showButton}
-      class:!top-0={!showButton}
     >
       <p>
         Vous êtes en train de visualiser une<br />simulation publique, non
diff --git a/src/routes/budget/+server.ts b/src/routes/budget/+server.ts
index fdf05b7f5..f4e4c04ee 100644
--- a/src/routes/budget/+server.ts
+++ b/src/routes/budget/+server.ts
@@ -10,6 +10,7 @@ import type { RequestHandler } from "./$types"
 export const POST: RequestHandler = async ({ fetch, locals, request }) => {
   if (
     config.budgetApiUrl === undefined ||
+    config.budgetPublicApiUrl === undefined ||
     config.budgetJwtSecret === undefined
   ) {
     throw error(
@@ -21,10 +22,14 @@ export const POST: RequestHandler = async ({ fetch, locals, request }) => {
   const user = locals.user as User
 
   if (user === undefined) {
-    throw error(
-      401,
-      "Vous devez être authentifiés pour accéder aux calculs budgétaires",
-    )
+    return await fetch(config.budgetPublicApiUrl, {
+      body: await request.arrayBuffer(),
+      headers: {
+        Accept: "application/json",
+        "Content-Type": "application/json; charset=utf-8",
+      },
+      method: "POST",
+    })
   }
 
   const payload = {
-- 
GitLab