Procházet zdrojové kódy

Merge branch 'mostrar-api' into develop

wilitp před 4 roky
rodič
revize
56d4e9cca3

+ 35 - 2
app/src/api/tables.ts

@@ -1,10 +1,43 @@
 import { apiURL } from "../config";
+import { Summary } from "../types/summary";
 import { mockPayloads, mockRequest } from "./mocks";
 // Quizas llamarlos table no hacia falta,
 // pero es preferible antes de que a alguien se le olvide usar un alias cuando importe estas funciones.
 
-export const generalTable = (from: string, to: string, year: string) => {
-  return mockRequest(true, mockPayloads.general, null);
+export const generalTable = (from: string, to: string, token: string) => {
+  const headers = new Headers();
+  headers.append("Access-Control-Allow-Origin", "*");
+  headers.append("Authorization", `Bearer ${token}`);
+
+  const config: RequestInit = {
+    method: "GET",
+    mode: "cors",
+    headers,
+  };
+
+  const qParams = new URLSearchParams();
+  qParams.append("start_datetime", from);
+  qParams.append("end_datetime", to);
+
+  console.log({ from, to });
+
+  return new Promise<Summary[]>(async (resolve, reject) => {
+    const res = await fetch(
+      `${apiURL}summary/all_stations?${qParams.toString()}`,
+      config
+    );
+    if (!res.ok) {
+      const reason = await res.text();
+      reject(reason);
+    }
+
+    try {
+      const body = await res.json();
+      resolve(body);
+    } catch (err) {
+      reject(err);
+    }
+  });
 };
 
 export const seasonsSummariesTable = (

+ 8 - 4
app/src/components/UI/dashboard/cockpit/index.tsx

@@ -56,18 +56,22 @@ const Cockpit: FC = () => {
       <div className="col-6 col-lg-4 mb-2 col-xl-auto mb-xl-0">
         <CalendarInput
           onChange={(e: ChangeEvent<HTMLInputElement>) =>
-            dashboardDispatch(actions.setFromControl(e.target.value))
+            dashboardDispatch(
+              actions.setFromControl(e.target.valueAsDate?.toISOString() ?? "")
+            )
           }
-          value={dashboardState.from}
+          value={dashboardState.from.slice(0, 10)}
           name="Comparación"
         />
       </div>
       <div className="col-6 col-lg-4 mb-2 col-xl-auto mb-xl-0">
         <CalendarInput
           onChange={(e: ChangeEvent<HTMLInputElement>) =>
-            dashboardDispatch(actions.setToControl(e.target.value))
+            dashboardDispatch(
+              actions.setToControl(e.target.valueAsDate?.toISOString() ?? "")
+            )
           }
-          value={dashboardState.to}
+          value={dashboardState.to.slice(0, 10)}
           name="Comparación"
         />
       </div>

+ 19 - 14
app/src/components/data/GeneralPerSector/index.tsx

@@ -1,30 +1,35 @@
-import React, { useState, useEffect, FC } from "react";
+import React, { useState, useEffect, FC, useContext } from "react";
 import { generalTable } from "../../../api/tables";
+import { UserStateContext } from "../../../context/auth/AuthProvider";
+import { StateContext } from "../../../context/dashboard/Provider";
 import { Summary } from "../../../types/summary";
 import { TableHeader as Header, TdGroup } from "../shared";
 import * as classes from "../tables.module.css";
 
-const TemperaturePerSector: FC = () => {
+const GeneralPerSector: FC = () => {
   const [data, setData] = useState<Summary[] | null>(null);
+  const { userToken } = useContext(UserStateContext);
+  const { from, to } = useContext(StateContext);
 
   useEffect(() => {
-    generalTable("", "", "").then((res) => {
-      setData(JSON.parse(res));
+    if (!userToken) return;
+    generalTable(from, to, userToken).then((res) => {
+      setData(res);
     });
-  }, []);
+  }, [from, to, userToken]);
 
   // Formato de los summaries(filas)
   const rows = data?.map((x) => (
-    <tr key={x.station.code}>
-      <th className={classes.cell}>{x.station.name}</th>
+    <tr key={x.station.station_code}>
+      <th className={classes.cell}>{x.station.title}</th>
       <TdGroup>
-        <td>{x.lt10}%</td>
-        <td>{x.gt30}%</td>
-        <td>{x.gt33}%</td>
+        <td>{x.lt10 ?? "-"}%</td>
+        <td>{x.gt30 ?? "-"}%</td>
+        <td>{x.gt33 ?? "-"}%</td>
       </TdGroup>
-      <td className={classes.cell}>{x.grados_acumulados}</td>
-      <td className={classes.cell}>{x.amplitud_termica}</td>
-      <td className={classes.cell}>{x.precip_acumulada}</td>
+      <td className={classes.cell}>{x.grados_acumulados ?? "-"}</td>
+      <td className={classes.cell}>{x.amplitud_termica ?? "-"}</td>
+      <td className={classes.cell}>{x.precip_acumulada ?? "-"}</td>
     </tr>
   ));
 
@@ -47,4 +52,4 @@ const TemperaturePerSector: FC = () => {
     </>
   );
 };
-export default TemperaturePerSector;
+export default GeneralPerSector;

+ 1 - 4
app/src/context/dashboard/reducer.ts

@@ -9,10 +9,7 @@ export const defaultState = {
 
 export const getInitialState = (): State => {
   const now = new Date();
-  const dayNum = now.getDate();
-  const day = `${now.getFullYear()}-${now.getMonth() + 1}-${
-    dayNum < 10 ? `0${dayNum}` : dayNum
-  }`;
+  const day = now.toISOString();
   return {
     sector: null,
     year: now.getFullYear().toString(),

+ 2 - 2
app/src/types/summary.ts

@@ -1,7 +1,7 @@
 export interface Summary {
   station: {
-    name: string;
-    code: string;
+    title: string;
+    station_code: string;
   };
   from: string;
   to: string;