Skip to content

Commit

Permalink
fix: correct date parsing for other english dates
Browse files Browse the repository at this point in the history
also move utils a bit around
  • Loading branch information
thraizz committed Sep 1, 2024
1 parent 276e492 commit 8e56032
Show file tree
Hide file tree
Showing 11 changed files with 87 additions and 41 deletions.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/components/panels/AllDataCombinedTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { AgGridReact } from "ag-grid-react";
import { useContext, useEffect, useState } from "react";
import { SessionContext } from "../../provider/SessionContext";
import { GolfSwingData } from "../../types/GolfSwingData";
import { sortGolfSwingKeysForHeader } from "../../utils";
import { translateHeader } from "../../utils/csvLocalization";
import { getAllDataFromSession } from "../../utils/getAllDataFromSession";
import { sortGolfSwingKeysForHeader } from "../../utils/utils";
import { BaseDisclosure } from "../base/BaseDisclosure";

export const AllDataCombinedTable = () => {
Expand Down
4 changes: 1 addition & 3 deletions src/components/panels/AveragesPerSession.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { useClubsPerSession } from "../../hooks/useClubsPerSesssion";
import { SessionContext } from "../../provider/SessionContext";
import { GolfSwingData } from "../../types/GolfSwingData";
import { useAveragePerSession } from "../../utils/calculateAverages";
import { getPairsForYfield, parseDate } from "../../utils/utils";
import { BaseLabel } from "../base/BaseLabel";
import { BaseListbox } from "../base/BaseListbox";
import type { ClubDataForTable } from "./AveragesPerSessionGraph";
import { AveragesPerSessionGraph } from "./AveragesPerSessionGraph";
import { parseDate, getPairsForYfield } from "../../utils";
dayjs.extend(customParseFormat);

export const AveragesPerSession = () => {
Expand Down Expand Up @@ -47,8 +47,6 @@ export const AveragesPerSession = () => {
return [];
}, [sessions, clubSelected, clubDataByDate, averages, yField, club]);

console.log(averagesByDate);

return (
<div className="flex h-auto w-full flex-col gap-3 rounded-xl bg-white p-4">
<h4 className="mb-4 text-xl font-bold text-gray-800">
Expand Down
2 changes: 1 addition & 1 deletion src/components/panels/AveragesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { ColDef } from "ag-grid-community";
import { AgGridReact } from "ag-grid-react";
import { useContext, useEffect, useState } from "react";
import { SessionContext } from "../../provider/SessionContext";
import { sortGolfSwingKeysForHeader } from "../../utils";
import {
AveragedSwing,
useAveragedSwings,
} from "../../utils/calculateAverages";
import { translateHeader } from "../../utils/csvLocalization";
import { sortGolfSwingKeysForHeader } from "../../utils/utils";
import { BaseDisclosure } from "../base/BaseDisclosure";
import { BaseLabel } from "../base/BaseLabel";
const defaultColumns: ColDef<AveragedSwing>[] = [
Expand Down
7 changes: 4 additions & 3 deletions src/components/panels/ShotScatterPlot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import {
golfSwingDataKeysInMeters,
} from "../../types/GolfSwingData";
import { Sessions } from "../../types/Sessions";
import { getDayFromRow } from "../../utils/date.utils";
import { getAllDataFromSession } from "../../utils/getAllDataFromSession";
import { parseDate } from "../../utils/utils";
import { BaseLabel } from "../base/BaseLabel";
import { BaseListbox } from "../base/BaseListbox";
import { parseDate } from "../../utils";

export const ShotScatterPlot = () => {
const { sessions } = useContext(SessionContext);
Expand Down Expand Up @@ -134,7 +135,7 @@ export const ShotScatterPlot = () => {
table: clubs[club].map((row) => ({
x: row[xField as keyof GolfSwingData],
y: row[yField as keyof GolfSwingData],
date: parseDate((row["Date"] || row["Datum"])?.split(" ")[0] ?? ""),
date: parseDate(getDayFromRow(row)),
})),
};
}
Expand All @@ -143,7 +144,7 @@ export const ShotScatterPlot = () => {
table: swings.map((row) => ({
x: row[xField as keyof GolfSwingData],
y: row[yField as keyof GolfSwingData],
date: parseDate((row["Date"] || row["Datum"])?.split(" ")[0] ?? ""),
date: parseDate(getDayFromRow(row)),
})),
};
}
Expand Down
2 changes: 2 additions & 0 deletions src/firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ if (import.meta.env.DEV && import.meta.env.VITE_USE_EMULATORS === "true") {
connectAuthEmulator(auth, "http://localhost:9099");
connectFirestoreEmulator(db, "localhost", 8080);
}

export const ANONYMOUS_USER_UID = "6U4S2ruwXMPrULj50b9uLpsaRk53";
56 changes: 30 additions & 26 deletions src/provider/SessionContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import React, {
useMemo,
useState,
} from "react";
import { db } from "../firebase";
import { ANONYMOUS_USER_UID, db } from "../firebase";
import { Session, Sessions } from "../types/Sessions";
import { reduceSessionToDefinedValues } from "../utils";
import { translateSessionsToEnglish } from "../utils/csvLocalization";
import { getDateFromResults } from "../utils/date.utils";
import { filterResultsWithMissingCells } from "../utils/filterResultsWithMissingCells";
import { reduceSessionToDefinedValues } from "../utils/utils";
import { UserContext } from "./UserContext";

export interface SessionContextInterface {
Expand All @@ -21,27 +22,29 @@ export interface SessionContextInterface {
setSessions: (sessions: Sessions) => void;
fetchSnapshot: () => Promise<Sessions | undefined>;
deleteSession: (id: string) => Promise<void>;
exportSessionsToJson: (sessions: Sessions) => void;
}

const SessionContext = createContext<SessionContextInterface>({
initialized: false,
isLoading: false,
sessions: {},
setSessions: () => {},
setSessions: () => { },
fetchSnapshot: () => Promise.resolve(undefined),
deleteSession: () => Promise.resolve(),
exportSessionsToJson: () => { },
});

const SessionProvider: React.FC<PropsWithChildren> = ({ children }) => {
const [sessions, _setSessions] = useState<Sessions>({});
const setSessions = useCallback((sessions: Sessions) => {
_setSessions(filterResultsWithMissingCells(sessions));
const [sessions, setSessions] = useState<Sessions>({});
const setSessionsCallback = useCallback((sessions: Sessions) => {
setSessions(filterResultsWithMissingCells(sessions));
}, []);
const [initialized, setInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(false);

const { user } = useContext(UserContext);
const uuid = user?.isAnonymous ? "6U4S2ruwXMPrULj50b9uLpsaRk53" : user?.uid;
const uuid = user?.isAnonymous ? ANONYMOUS_USER_UID : user?.uid;

const fetchSnapshot = useCallback(async () => {
setIsLoading(true);
Expand All @@ -58,13 +61,25 @@ const SessionProvider: React.FC<PropsWithChildren> = ({ children }) => {
};
return acc;
}, {} as Sessions);
setSessions(sessionResult);
setSessionsCallback(sessionResult);
setInitialized(true);
setIsLoading(false);
return sessionResult;
}
setIsLoading(false);
}, [uuid, setSessions]);
}, [uuid, setSessionsCallback]);

// Export current sessions as JSON file
const exportSessionsToJson = useCallback((sessions: Sessions) => {
const element = document.createElement("a");
const file = new Blob([JSON.stringify(sessions)], {
type: "application/json",
});
element.href = URL.createObjectURL(file);
element.download = "sessions.json";
document.body.appendChild(element);
element.click();
}, []);

const deleteSession = useCallback(
async (id: string) => {
Expand All @@ -73,31 +88,33 @@ const SessionProvider: React.FC<PropsWithChildren> = ({ children }) => {
}
const document = doc(db, "r10data", uuid, "data", id);
await deleteDoc(document);
_setSessions((prev: Sessions) => {
setSessions((prev: Sessions) => {
const newSessions = { ...prev };
delete newSessions[id];
return newSessions;
});
},
[uuid, _setSessions],
[uuid, setSessions],
);

const memoizedValue = useMemo(
() => ({
initialized,
isLoading,
sessions: translateSessionsToEnglish(sessions),
setSessions,
setSessions: setSessionsCallback,
fetchSnapshot,
deleteSession,
exportSessionsToJson,
}),
[
initialized,
isLoading,
sessions,
setSessions,
setSessionsCallback,
fetchSnapshot,
deleteSession,
exportSessionsToJson,
],
);

Expand All @@ -109,16 +126,3 @@ const SessionProvider: React.FC<PropsWithChildren> = ({ children }) => {
};

export { SessionContext, SessionProvider };

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getDateFromResults = (results: any[]) => {
if (results.length > 0) {
const date: string =
results[0].Date ||
results[0].Datum ||
"No date found. Contact me please.";

return date.split(" ")[0];
}
return "";
};
4 changes: 2 additions & 2 deletions src/router.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Navigate, Outlet, createBrowserRouter } from "react-router-dom";
import { routes } from "./routes";
import {
RedirectIfNotLoggedIn,
RedirectIfSignedIn,
} from "./utils/AuthRedirects";
} from "./components/AuthRedirects";
import { routes } from "./routes";
import { Authentication } from "./views/Authentication";
import { Dashboard } from "./views/Dashboard";
import { Goals } from "./views/Goals";
Expand Down
17 changes: 17 additions & 0 deletions src/utils/date.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const getDateFromResults = (results: any[]) => {
if (results.length > 0) {
const date: string =
results[0].Date ||
results[0].Datum ||
"No date found. Contact me please.";

return date.split(" ")[0];
}
return "";
};

export const getDayFromRow = (row: any) => {
const date = row["Date"] || row["Datum"] || "";
const dayPart = date.split(" ")[0] ?? "";
return dayPart;
};
File renamed without changes.
34 changes: 29 additions & 5 deletions src/utils.ts → src/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import dayjs from "dayjs";
import { ClubDataForTable } from "./components/panels/AveragesPerSessionGraph";
import { GolfSwingData } from "./types/GolfSwingData";
import { Session } from "./types/Sessions";
import { AveragedSwing, AveragedSwingRecord } from "./utils/calculateAverages";
import { ClubDataForTable } from "../components/panels/AveragesPerSessionGraph";
import { GolfSwingData } from "../types/GolfSwingData";
import { Session } from "../types/Sessions";
import { AveragedSwing, AveragedSwingRecord } from "./calculateAverages";

export const sortGolfSwingKeysForHeader = (a: string, b: string) => {
// We want to prioritize Carry Distance, Total Distance, Club Name, Ball Spped, and Date
Expand Down Expand Up @@ -144,7 +144,31 @@ export const getPairsForYfield: (
// might be english or german format
export const parseDate = (input: string) => {
if (input.includes("/")) {
return dayjs(input, "MM/DD/YY").format("YYYY-MM-DD");
const possibleDatFormats = [
"MM/DD/YYYY",
"MM/DD/YY",
"M/DD/YYYY",
"M/DD/YY",
"MM/D/YYYY",
"MM/D/YY",
"M/D/YYYY",
"M/D/YY",
];

let date = "";

const isDateParsed = possibleDatFormats.some((format) => {
const parsedDate = dayjs(input, format, "en");
if (parsedDate.isValid()) {
date = parsedDate.format("YYYY-MM-DD");
return true; // Stop iteration once a valid date is found
}
return false;
});

if (!isDateParsed) console.error("Could not parse date", input);

return date;
} else if (input.includes(".")) {
return dayjs(input, "DD.MM.YY", "de").format("YYYY-MM-DD");
} else {
Expand Down

0 comments on commit 8e56032

Please sign in to comment.