Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Planscreen player #131

Merged
merged 11 commits into from
Apr 9, 2024
37 changes: 37 additions & 0 deletions add_user_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import random
import time
import math
import firebase_admin
from firebase_admin import firestore

app = firebase_admin.initialize_app()
db = firestore.client()

# Define the assigned_data array
assigned_data = [
{"drill": "YtCsaxzscFScnpZYmnKI", "assigned_time": "1710522958", "completed": False},
{"drill": "YtCsaxzscFScnpZYmnKI", "assigned_time": "1710464940", "completed": False},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710464941", "completed": False},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710292142", "completed": True},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710292143", "completed": False},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710292144", "completed": False},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710205745", "completed": True},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710205746", "completed": False},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710032940", "completed": False},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710032941", "completed": False},
{"drill": "SpvYyY94HaulVH2zmVyM", "assigned_time": "1710012940", "completed": False},
]

# Get a reference to the user collection
users_collection = db.collection("teams").document("1").collection("users")


print(users_collection.stream())


# Loop through each document in the collection and update the assigned_data field
for doc in users_collection.stream():
print(doc)
doc_ref = users_collection.document(doc.id)
doc_ref.update({'assigned_data': assigned_data})
print(f"Document {doc.id} updated successfully.")
1 change: 1 addition & 0 deletions app/(auth)/signup.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export default function SignUp() {
// hardcoded "player" role for now, add role selection to profile settings in future PR
role: "player",
uid: userRef,
assigned_data: [],
});

setCurrentUserId(userCredential.user.uid);
Expand Down
4 changes: 4 additions & 0 deletions app/content/drill/[id]/description.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import { useDrillInfo } from "~/hooks/useDrillInfo";

export default function Description() {
const drillId = useLocalSearchParams()["id"];
const assigned_time = useLocalSearchParams()["assigned_time"];
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved

console.log("WAS IT ASSIGNED2", assigned_time)

const [activeIndex, setActiveIndex] = useState(0);
const [modalVisible, setModalVisible] = useState(false);
Expand Down Expand Up @@ -144,6 +147,7 @@ export default function Description() {
<Link
href={{
pathname: `/segments/drill/${drillId}/submission`,
params: { assigned_time: assigned_time },
}}
asChild
>
Expand Down
3 changes: 3 additions & 0 deletions app/content/drill/[id]/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export default function Index() {
const navigation = useNavigation();
const drillId = useLocalSearchParams()["id"];

const assigned_time = useLocalSearchParams()["assigned_time"];
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved

console.log("WAS IT ASSIGNED", assigned_time)
const {
data: drillInfo,
error: drillInfoError,
Expand Down
199 changes: 195 additions & 4 deletions app/content/plan/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,205 @@
import { PaperProvider, Text } from "react-native-paper";
import React, { useState } from 'react';
import { SafeAreaView } from "react-native-safe-area-context";
import { PaperProvider, Text, Avatar, Button, Card, Appbar } from "react-native-paper";
import { TouchableOpacity } from 'react-native';
import { FlatList, StyleSheet, ScrollView, RefreshControl } from 'react-native';
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { View } from 'react-native';
import { useNavigation, router } from 'expo-router';
import { Link } from 'expo-router';
import drillsData from "~/drill_data.json";
import { collection, doc, getDoc, getDocs, query, updateDoc, where } from "firebase/firestore";
import { db } from "~/firebaseConfig";
import { useEffect } from 'react';

import { formatDate, getUnique } from '~/Utility'
import { useDrillInfo } from "~/hooks/useDrillInfo";
import { useUserInfo } from "~/hooks/useUserInfo";
import Loading from "~/components/loading";
import { currentAuthContext } from "~/context/Auth";

import { useQueryClient } from '@tanstack/react-query';


const DrillList = () => {
const queryClient = useQueryClient();
const { currentUserId, currentTeamId } = currentAuthContext();
const userId = currentUserId ?? null;
const teamId = currentTeamId ?? null;
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved

console.log("USER ID IN PLAN", userId)

const {
data: drillInfo,
error: drillInfoError,
isLoading: drillInfoIsLoading,
} = useDrillInfo();

const {
data: userData,
userError: userError,
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
userIsLoading: userIsLoading,
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
} = useUserInfo(userId);

const [assigned_data, setAssignedData] = useState([]);

FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
const [refreshing, setRefreshing] = React.useState(false);

const onRefresh = React.useCallback(() => {
const refresh = async () => {
setRefreshing(true);
await queryClient.invalidateQueries(["user", { teamId, userId }]);
setRefreshing(false);
};

refresh();
}, [teamId, userId, queryClient]);


console.log("USER DATA", userData);

// Set the assigned_data state when the user data is loaded
useEffect(() => {
if (!userIsLoading && userData && userData.assigned_data) {
setAssignedData(userData.assigned_data);
}
}, [userIsLoading, userData]);

// Group the assigned drills by date
const groupedData = assigned_data.reduce((acc, curr) => {
const date = convertTimestampToDate(curr.assigned_time);
if (!acc[date]) {
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
acc[date] = [];
}
acc[date].push(curr);
return acc;
}, {});

// Sort the dates in descending order
const sortedDates = Object.keys(groupedData).sort((a, b) => new Date(b) - new Date(a));
const today = convertTimestampToDate(Date.now() / 1000);

// Update the completed property of the clicked drill


// Render the list of drills
return userIsLoading || drillInfoIsLoading ? (
<Loading />
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
) : (
<FlatList
refreshControl={
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}
data={sortedDates}
keyExtractor={(date) => date}
renderItem={({ item: date }) => (
<View>
<Text style={{ fontSize: 30, fontWeight: 'bold', textAlign: 'center' }}>
{date === today ? 'Today' : date}
</Text>
{groupedData[date].map((drill) => (
<TouchableOpacity
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
disabled={drill.completed}
onPress={() => {

router.push({ pathname: `content/drill/${drill.drill}`, params: { id: `${drill.drill}`, assigned_time: drill.assigned_time } });
}}
>
<View key={drill.assigned_time} style={{ marginLeft: 20, marginRight: 20 }}>
<View
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
style={{
borderWidth: 1,
borderColor: 'rgba(0,0,0,0.2)',
alignItems: 'center',
justifyContent: 'space-between',
width: '100%',
height: 50,
backgroundColor: `${!drill.completed ? '#fff' : 'green'}`,
borderRadius: 50,
marginBottom: 10,
paddingLeft: 30,
paddingRight: 30,
flexDirection: 'row',
}}
>
<Text style={{ fontSize: 20 }}>{drillInfo[drill.drill]["drillType"]}</Text>
<Text style={{ fontSize: 20 }}>{drillInfo[drill.drill]["spec"]}</Text>
</View>
</View>
</TouchableOpacity>
))}
</View>
)}
/>
);
};

const convertTimestampToDate = (timestamp) => {
const date = new Date(timestamp * 1000);
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};






//This is for the list of drills
export default function Index() {
const d = doc(db, "teams", "1", "drills", "SpvYyY94HaulVH2zmVyM")
//getDoc(d).then(value => console.log(value.data()));

const [cardDataTest, setCardDataTest] = React.useState([])
useEffect(() => {
let drillList = [];
let promiseList = [];
/*Object.values(assigned_data).forEach((data) => {
data.drill = getDoc(doc(db, "teams", "1", "drills", data.drill)).then(drillData => (
drillData.data()
))
});
console.log("DRILL LIST", drillList)
Object.values(assigned_data).forEach((data) => {
console.log("DATA", data)
drillList.push(data.drill);
});*/

/* assigned_data.drills.forEach(did => {
promiseList.push(
getDoc(doc(db, "teams", "1", "drills", did)).then(drillData => (
drillData.data()
))
);

});

Promise.all(promiseList).then(values => {
values.forEach((data) => {
console.log("DRILL DATA", data);
drillList.push(data);
});
setCardDataTest(drillList);
});*/
}, []);
console.log("TEST CARD DATA", cardDataTest)
console.log(formatDate(1710292140))


return (
<PaperProvider>
<SafeAreaView
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
style={{ flex: 1 }}
edges={["right", "top", "left"]}
>
<Text>Plan Index</Text>
<Appbar.Header statusBarHeight={0} style={{ backgroundColor: "FFF" }}>

<Appbar.Content title={"Plan"} titleStyle={{ fontWeight: 'bold' }} />
</Appbar.Header>

<DrillList></DrillList>

FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
</SafeAreaView>
</PaperProvider>
);
Expand Down
2 changes: 1 addition & 1 deletion app/segments/drill/[id]/submission/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Result from "./result";
import { useDrillInfo } from "~/hooks/useDrillInfo";

export default function Index() {
const { id } = useLocalSearchParams();
const { id, assigned_time } = useLocalSearchParams();

const [outputData, setOutputData] = useState([]);
const [toggleResult, setToggleResult] = useState(false);
Expand Down
64 changes: 60 additions & 4 deletions app/segments/drill/[id]/submission/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
BottomSheetScrollView,
} from "@gorhom/bottom-sheet";
import { useLocalSearchParams, useNavigation } from "expo-router";
import { collection, doc, setDoc } from "firebase/firestore";
import { collection, doc, setDoc, getDoc, updateDoc } from "firebase/firestore";
import { useEffect, useMemo, useRef, useState } from "react";
import { Pressable, StyleSheet, View } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
Expand All @@ -31,13 +31,58 @@ import Loading from "~/components/loading";
import { currentAuthContext } from "~/context/Auth";
import { db } from "~/firebaseConfig";
import Description from "./modals/description";
import { useQueryClient } from '@tanstack/react-query';

/***************************************
* Firebase Upload
***************************************/

//A function to upload the outputData to the "attempts" collection
async function uploadAttempt(outputData) {

async function completeAssigned(userId, teamId, assigned_time, id, queryClient) {

console.log("WAS IT ASIGNED 5 and ID", assigned_time, userId)

const userRef = doc(db, "teams", "1", "users", userId)

const getDocument = async () => {
const docSnap = await getDoc(userRef);

if (docSnap.exists()) {
console.log("Document data:", docSnap.data());

const assignedData = docSnap.data()["assigned_data"];
const updatedAssignedData = assignedData.map((item, index) => {
if (item.assigned_time === assigned_time && item.drill === id) {
return { ...item, completed: true };
}
return item;
});

console.log("DOCUMENT DATA INSIDE", updatedAssignedData[0].completed);

try {
await updateDoc(userRef, { assigned_data: updatedAssignedData });
console.log("Document updated successfully!");
queryClient.invalidateQueries(["user", { teamId, userId }]);
} catch (error) {
console.error("Error updating document:", error);
}
} else {
console.log("No such document!");
}
};

getDocument();

}


async function uploadAttempt(outputData, userId, teamId, assigned_time, id, queryClient) {

console.log("WAS IT ASIGNED 4 and ID", assigned_time, userId)


try {
//create new document
const newAttemptRef = doc(collection(db, "teams", "1", "attempts"));
Expand All @@ -51,7 +96,13 @@ async function uploadAttempt(outputData) {
//upload the data
await setDoc(newAttemptRef, uploadData).then(() => {
console.log("Document successfully uploaded!");
});
if (assigned_time) {
completeAssigned(userId, teamId, assigned_time, id, queryClient);
}
})
.catch((error) => {
console.error("Error uploading document: ", error);
});
} catch (e) {
alert(e);
console.log(e);
Expand Down Expand Up @@ -283,6 +334,11 @@ function createOutputData(

export default function Input({ drillInfo, setToggleResult, setOutputData }) {
//Helper varibles
const { id, assigned_time } = useLocalSearchParams();


console.log("ID AND THE ASSIGNED TIME", id, assigned_time)
const queryClient = useQueryClient();

const numInputs = drillInfo.inputs.length;

Expand Down Expand Up @@ -349,7 +405,7 @@ export default function Input({ drillInfo, setToggleResult, setOutputData }) {
);

setOutputData(outputData);
uploadAttempt(outputData);
uploadAttempt(outputData, auth["currentUserId"], auth["currentTeamId"], assigned_time, id, queryClient);
FrankreedX marked this conversation as resolved.
Show resolved Hide resolved
setToggleResult(true);
}}
>
Expand Down
Loading