From 5fa57845052655883120ba4d19a85d8756fb8d8c Mon Sep 17 00:00:00 2001
From: Zach Berwaldt <zberwaldt@tutamail.com>
Date: Wed, 6 Mar 2024 21:53:07 -0500
Subject: [FEAT] Refactor API main file and models

This commit refactors the `main.go` file in the API directory, as well as the related models in the `models.go` file. The changes include:

- Reordering imports and removing unnecessary imports
- Fixing error messages to be more descriptive
- Handling database connections more efficiently with deferred closures
- Handling errors and returning appropriate error responses
- Adding proper JSON bindings for POST requests
- Adding new views in the database scripts for aggregated statistics and daily user statistics

No changes were made to imports and requires.
---
 fe/src/lib/DataView.svelte | 130 ++++++++++++++++++++++++---------------------
 1 file changed, 69 insertions(+), 61 deletions(-)

(limited to 'fe/src/lib/DataView.svelte')

diff --git a/fe/src/lib/DataView.svelte b/fe/src/lib/DataView.svelte
index 2b1b8b9..7d62a43 100644
--- a/fe/src/lib/DataView.svelte
+++ b/fe/src/lib/DataView.svelte
@@ -9,8 +9,6 @@
     import AddForm from "./forms/AddForm.svelte";
 
     let json: Promise<any>;
-    let totals: Promise<any>;
-    let userStats: Promise<any>;
 
     let barCanvasRef: HTMLCanvasElement;
     let lineCanvasRef: HTMLCanvasElement;
@@ -18,6 +16,10 @@
     let lineChart: any;
 
     let lastSevenDays: string[];
+    let lastSevenDaysData: number[];
+
+    let userTotalsLabels: string[];
+    let userTotalsData: number[];
 
     async function fetchData() {
         const res = await fetch("http://localhost:8080/api/v1/stats/", {
@@ -33,24 +35,27 @@
         }
     }
 
-    async function fetchTotals() {
+    async function fetchDailyUserStatistics() {
         const res = await fetch("http://localhost:8080/api/v1/stats/totals/", {
-            method: 'GET',
-            mode: 'no-cors',
+            method: "GET",
             headers: {
                 Authorization: `Bearer ${$token}`
             }
         });
 
         if (res.ok) {
-            totals = res.json();
+            const json = await res.json();
+            let labels = json.map(d => d.name);
+            let data = json.map(d => d.total);
+            return [labels, data];
         } else {
             throw new Error("There was a problem with your request");
         }
+
     }
 
-    async function fetchStatsForUser() {
-        const res = await fetch("http://localhost:8080/api/v1/stats/user/1aa668f3-7527-4a67-9c24-fdf307542eeb", {
+    async function fetchWeeklyTotals() {
+        const res = await fetch("http://localhost:8080/api/v1/stats/weekly/", {
             method: "GET",
             headers: {
                 Authorization: `Bearer ${$token}`
@@ -58,22 +63,15 @@
         });
 
         if (res.ok) {
-            userStats = res.json();
+            const json = await res.json();
+            let labels = json.map(d => d.date);
+            let data = json.map(d => d.total);
+            return [labels, data];
         } else {
             throw new Error("There was a problem with your request");
         }
     }
 
-    function getLastSevenDays() {
-        const result = [];
-        for (let i = 0; i < 7; i++) {
-            let d = new Date();
-            d.setDate(d.getDate() - i);
-            result.push(d.toISOString().substring(0, 10));
-        }
-        return result;
-    }
-
     function closeDialog() {
         addFormOpen.set(false);
     }
@@ -81,61 +79,79 @@
     function onStatisticAdd() {
         closeDialog();
         fetchData();
+        fetchWeeklyTotals().then(updateWeeklyTotalsChart).catch(err => console.error(err));
+        fetchDailyUserStatistics().then(updateDailyUserTotalsChart).catch(err => console.error(err));
     }
 
-    onMount(() => {
-        fetchData();
-//        fetchTotals();
-        fetchStatsForUser();
-        lastSevenDays = getLastSevenDays();
-        barChart = new Chart(barCanvasRef, {
-            type: "bar",
+    function setupWeeklyTotalsChart(result) {
+        [lastSevenDays, lastSevenDaysData] = result;
+        lineChart = new Chart(lineCanvasRef, {
+            type: "line",
             data: {
                 labels: lastSevenDays,
                 datasets: [
                     {
-                        label: "Zach",
-                        data: [1, 2, 8, 2, 5, 5, 1],
-                        backgroundColor: "rgba(255, 192, 192, 0.2)",
-                        borderColor: "rgba(75, 192, 192, 1)",
-                        borderWidth: 1
-                    }, {
-                        label: "Parker",
-                        data: [6, 1, 1, 4, 3, 5, 1],
-                        backgroundColor: "rgba(75, 192, 192, 0.2)",
-                        borderColor: "rgba(75, 192, 192, 1)",
-                        borderWidth: 1
+                        label: "Totals",
+                        data: lastSevenDaysData,
+                        backgroundColor: "rgba(255, 192, 192, 0.2)"
                     }
                 ]
             },
             options: {
-                responsive: true
+                responsive: true,
+                plugins: {
+                    legend: {
+                        display: false
+                    }
+                }
             }
         });
-        lineChart = new Chart(lineCanvasRef, {
-            type: "line",
+    }
+
+    function setupDailyUserTotalsChart(result) {
+        [userTotalsLabels, userTotalsData] = result;
+
+        barChart = new Chart(barCanvasRef, {
+            type: "bar",
             data: {
-                labels: lastSevenDays,
+                labels: userTotalsLabels,
                 datasets: [
                     {
-                        label: "Zach",
-                        data: [1, 2, 8, 2, 5, 5, 1],
-                        backgroundColor: "rgba(255, 192, 192, 0.2)",
-                        borderColor: "rgba(75, 192, 192, 1)",
-                        borderWidth: 1
-                    }, {
-                        label: "Parker",
-                        data: [6, 1, 1, 4, 3, 5, 1],
-                        backgroundColor: "rgba(75, 192, 192, 0.2)",
-                        borderColor: "rgba(75, 192, 192, 1)",
-                        borderWidth: 1
+                        data: userTotalsData,
+                        backgroundColor: [
+                            "#330000",
+                            "rgba(100, 200, 192, 0.2)"
+                        ]
                     }
                 ]
             },
             options: {
-                responsive: true
+                responsive: true,
+                plugins: {
+                    legend: {
+                        display: false
+                    }
+                }
             }
         });
+    }
+
+    function updateWeeklyTotalsChart(result) {
+        [,lastSevenDaysData] = result;
+        lineChart.data.datasets[0].data = lastSevenDaysData;
+        lineChart.update();
+    }
+
+    function updateDailyUserTotalsChart(result) {
+        [,userTotalsData] = result;
+        barChart.data.datasets[0].data = userTotalsData;
+        barChart.update();
+    }
+
+    onMount(() => {
+        fetchData();
+        fetchWeeklyTotals().then(setupWeeklyTotalsChart);
+        fetchDailyUserStatistics().then(setupDailyUserTotalsChart);
     });
 
     onDestroy(() => {
@@ -164,14 +180,6 @@
             <p>{error}</p>
         {/await}
     </Card>
-    <Card>
-        <button on:click={() => fetchTotals()}>Get totals</button>
-        {#await totals then data}
-            {JSON.stringify(data)}
-        {:catch error}
-            <p>{error}</p>
-        {/await}
-    </Card>
 </Column>
 <!-- <Chart /> -->
 
-- 
cgit v1.1

