Merge branch 'master' into initial-frontend

This commit is contained in:
lemeow125 2023-09-30 17:40:16 +08:00 committed by GitHub
commit fab7491a8d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 2331 additions and 524 deletions

60
App.tsx
View file

@ -1,4 +1,5 @@
import "react-native-gesture-handler"; import "react-native-gesture-handler";
import styles from "./src/styles";
import { NavigationContainer } from "@react-navigation/native"; import { NavigationContainer } from "@react-navigation/native";
import { createDrawerNavigator } from "@react-navigation/drawer"; import { createDrawerNavigator } from "@react-navigation/drawer";
import { Provider } from "react-redux"; import { Provider } from "react-redux";
@ -22,6 +23,11 @@ import { StatusBar } from "expo-status-bar";
import UserInfoPage from "./src/routes/UserInfoPage/UserInfoPage"; import UserInfoPage from "./src/routes/UserInfoPage/UserInfoPage";
import SubjectsPage from "./src/routes/SubjectsPage/SubjectsPage"; import SubjectsPage from "./src/routes/SubjectsPage/SubjectsPage";
import ConversationPage from "./src/routes/ConversationPage/ConversationPage"; import ConversationPage from "./src/routes/ConversationPage/ConversationPage";
import Loading from "./src/routes/Loading/Loading";
import StartStudying from "./src/routes/StartStudying/StartStudying";
import { ToastProvider } from "react-native-toast-notifications";
import InfoIcon from "./src/icons/InfoIcon/InfoIcon";
import CreateGroup from "./src/routes/CreateGroup/CreateGroup";
const Drawer = createDrawerNavigator(); const Drawer = createDrawerNavigator();
@ -29,7 +35,7 @@ const linking = {
prefixes: [Linking.makeUrl("/")], prefixes: [Linking.makeUrl("/")],
config: { config: {
screens: { screens: {
Home: "home", Home: "",
Login: "login", Login: "login",
Register: "register", Register: "register",
Onboarding: "onboarding", Onboarding: "onboarding",
@ -56,28 +62,36 @@ export default function App() {
} }
}, [initialRoute]); }, [initialRoute]);
return ( return (
<QueryClientProvider client={queryClient}> <ToastProvider
<Provider store={store}> icon={<InfoIcon size={32} />}
<StatusBar style="light" /> textStyle={{ ...styles.text_white_tiny_bold }}
>
<QueryClientProvider client={queryClient}>
<Provider store={store}>
<StatusBar style="light" />
<NavigationContainer linking={linking}>
<Drawer.Navigator <NavigationContainer linking={linking} fallback={<Loading />}>
initialRouteName="Revalidation" <Drawer.Navigator
drawerContent={CustomDrawerContent} initialRouteName="Revalidation"
screenOptions={DrawerScreenSettings} drawerContent={CustomDrawerContent}
> screenOptions={DrawerScreenSettings}
<Drawer.Screen name="Home" component={Home} /> >
<Drawer.Screen name="Login" component={Login} /> <Drawer.Screen name="Login" component={Login} />
<Drawer.Screen name="Register" component={Register} /> <Drawer.Screen name="Register" component={Register} />
<Drawer.Screen name="Onboarding" component={Onboarding} /> <Drawer.Screen name="Home" component={Home} />
<Drawer.Screen name="Revalidation" component={Revalidation} /> <Drawer.Screen name="Onboarding" component={Onboarding} />
<Drawer.Screen name="Activation" component={Activation} /> <Drawer.Screen name="Revalidation" component={Revalidation} />
<Drawer.Screen name="User Info" component={UserInfoPage} /> <Drawer.Screen name="Activation" component={Activation} />
<Drawer.Screen name="Subjects" component={SubjectsPage} /> <Drawer.Screen name="User Info" component={UserInfoPage} />
<Drawer.Screen name="Conversation" component={ConversationPage} /> <Drawer.Screen name="Subjects" component={SubjectsPage} />
</Drawer.Navigator> <Drawer.Screen name="Start Studying" component={StartStudying} />
</NavigationContainer> <Drawer.Screen name="Create Group" component={CreateGroup} />
</Provider> <Drawer.Screen name="Conversation" component={ConversationPage} />
</QueryClientProvider> </Drawer.Navigator>
</NavigationContainer>
</Provider>
</QueryClientProvider>
</ToastProvider>
); );
} }

View file

@ -42,9 +42,15 @@
[ [
"expo-location", "expo-location",
{ {
"locationAlwaysAndWhenInUsePermission": "Allow Stud-E to use your location." "locationAlwaysAndWhenInUsePermission": "Allow StudE to use your location."
} }
] ],
[
"expo-image-picker",
{
"photosPermission": "Allow StudE to take and send photos for sharing in-app"
}
]
], ],
"extra": { "extra": {
"eas": { "eas": {

38
package-lock.json generated
View file

@ -16,6 +16,8 @@
"@tanstack/react-query": "^4.29.25", "@tanstack/react-query": "^4.29.25",
"axios": "^1.4.0", "axios": "^1.4.0",
"expo": "~48.0.18", "expo": "~48.0.18",
"expo-file-system": "~15.2.2",
"expo-image-picker": "~14.1.1",
"expo-intent-launcher": "~10.5.2", "expo-intent-launcher": "~10.5.2",
"expo-linking": "~4.0.1", "expo-linking": "~4.0.1",
"expo-location": "~15.1.1", "expo-location": "~15.1.1",
@ -34,6 +36,7 @@
"react-native-screens": "~3.20.0", "react-native-screens": "~3.20.0",
"react-native-select-dropdown": "^3.3.4", "react-native-select-dropdown": "^3.3.4",
"react-native-svg": "13.4.0", "react-native-svg": "13.4.0",
"react-native-toast-notifications": "^3.3.1",
"react-query": "^3.39.3", "react-query": "^3.39.3",
"react-redux": "^8.1.1", "react-redux": "^8.1.1",
"redux": "^4.2.1" "redux": "^4.2.1"
@ -41,6 +44,7 @@
"devDependencies": { "devDependencies": {
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",
"@types/react": "~18.0.14", "@types/react": "~18.0.14",
"@types/react-native-fetch-blob": "^0.10.7",
"typescript": "^4.9.4" "typescript": "^4.9.4"
} }
}, },
@ -5311,6 +5315,12 @@
"csstype": "^3.0.2" "csstype": "^3.0.2"
} }
}, },
"node_modules/@types/react-native-fetch-blob": {
"version": "0.10.7",
"resolved": "https://registry.npmjs.org/@types/react-native-fetch-blob/-/react-native-fetch-blob-0.10.7.tgz",
"integrity": "sha512-9UTvmUvArimShiENeR3xnRO71NcZjpTi7AcFAIbhdTIfqQOO2OK/I/DpUPXcZF/erffLxOoRkoXrZOxyBBWKRQ==",
"dev": true
},
"node_modules/@types/scheduler": { "node_modules/@types/scheduler": {
"version": "0.16.3", "version": "0.16.3",
"resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.3.tgz", "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.3.tgz",
@ -7458,6 +7468,25 @@
"expo": "*" "expo": "*"
} }
}, },
"node_modules/expo-image-loader": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/expo-image-loader/-/expo-image-loader-4.1.1.tgz",
"integrity": "sha512-ciEHVokU0f6w0eTxdRxLCio6tskMsjxWIoV92+/ZD37qePUJYMfEphPhu1sruyvMBNR8/j5iyOvPFVGTfO8oxA==",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-image-picker": {
"version": "14.1.1",
"resolved": "https://registry.npmjs.org/expo-image-picker/-/expo-image-picker-14.1.1.tgz",
"integrity": "sha512-SvWtnkLW7jp5Ntvk3lVcRQmhFYja8psmiR7O6P/+7S6f4llt3vaFwb4I3+pUXqJxxpi7BHc2+95qOLf0SFOIag==",
"dependencies": {
"expo-image-loader": "~4.1.0"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-intent-launcher": { "node_modules/expo-intent-launcher": {
"version": "10.5.2", "version": "10.5.2",
"resolved": "https://registry.npmjs.org/expo-intent-launcher/-/expo-intent-launcher-10.5.2.tgz", "resolved": "https://registry.npmjs.org/expo-intent-launcher/-/expo-intent-launcher-10.5.2.tgz",
@ -12425,6 +12454,15 @@
"react-native": "*" "react-native": "*"
} }
}, },
"node_modules/react-native-toast-notifications": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/react-native-toast-notifications/-/react-native-toast-notifications-3.3.1.tgz",
"integrity": "sha512-yc1Q2nOdIYvAf0GAIlmg8q42hiwpEHnLxkxJ6P+tN6jpcKZ1qzMXlgnmNdyF9cm9VOyHQexEP8952IKNAv1Olw==",
"peerDependencies": {
"react": "*",
"react-native": "*"
}
},
"node_modules/react-native/node_modules/promise": { "node_modules/react-native/node_modules/promise": {
"version": "8.3.0", "version": "8.3.0",
"resolved": "https://registry.npmjs.org/promise/-/promise-8.3.0.tgz", "resolved": "https://registry.npmjs.org/promise/-/promise-8.3.0.tgz",

View file

@ -17,6 +17,8 @@
"@tanstack/react-query": "^4.29.25", "@tanstack/react-query": "^4.29.25",
"axios": "^1.4.0", "axios": "^1.4.0",
"expo": "~48.0.18", "expo": "~48.0.18",
"expo-file-system": "~15.2.2",
"expo-image-picker": "~14.1.1",
"expo-intent-launcher": "~10.5.2", "expo-intent-launcher": "~10.5.2",
"expo-linking": "~4.0.1", "expo-linking": "~4.0.1",
"expo-location": "~15.1.1", "expo-location": "~15.1.1",
@ -35,6 +37,7 @@
"react-native-screens": "~3.20.0", "react-native-screens": "~3.20.0",
"react-native-select-dropdown": "^3.3.4", "react-native-select-dropdown": "^3.3.4",
"react-native-svg": "13.4.0", "react-native-svg": "13.4.0",
"react-native-toast-notifications": "^3.3.1",
"react-query": "^3.39.3", "react-query": "^3.39.3",
"react-redux": "^8.1.1", "react-redux": "^8.1.1",
"redux": "^4.2.1" "redux": "^4.2.1"
@ -42,6 +45,7 @@
"devDependencies": { "devDependencies": {
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",
"@types/react": "~18.0.14", "@types/react": "~18.0.14",
"@types/react-native-fetch-blob": "^0.10.7",
"typescript": "^4.9.4" "typescript": "^4.9.4"
}, },
"private": true "private": true

View file

@ -1,21 +1,28 @@
import axios from "axios"; import axios from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import { import {
ActivationParams, ActivationType,
LoginParams, LocationType,
OnboardingParams, LoginType,
PatchStudentData, OnboardingType,
RegistrationParams, PatchUserInfoType,
StudentData, RegistrationType,
StudentStatusPatchType,
StudentStatusType,
StudyGroupCreateType,
StudyGroupType,
} from "../../interfaces/Interfaces"; } from "../../interfaces/Interfaces";
export let backendURL = ""; export let backendURL = "https://stude.keannu1.duckdns.org";
export let backendURLWebsocket = ""; export let backendURLWebsocket = "ws://stude.keannu1.duckdns.org";
let use_production = true; if (__DEV__) {
if (__DEV__ || !use_production) { backendURL = "http://10.0.10.8:8083";
backendURL = "http://10.0.10.8:8000"; backendURLWebsocket = "ws://10.0.10.8:8083";
backendURLWebsocket = "ws://10.0.10.8:8000"; }
} else {
// Switch this on if you wanna run production URLs while in development
let use_production = false;
if (__DEV__ && use_production) {
backendURL = "https://stude.keannu1.duckdns.org"; backendURL = "https://stude.keannu1.duckdns.org";
backendURLWebsocket = "ws://stude.keannu1.duckdns.org"; backendURLWebsocket = "ws://stude.keannu1.duckdns.org";
} }
@ -25,8 +32,29 @@ const instance = axios.create({
timeout: 1000, timeout: 1000,
}); });
console.log("Using backend API:", backendURL);
// 3rd Party APIs
export const urlProvider =
"https://openstreetmap.keannu1.duckdns.org/tile/{z}/{x}/{y}.png?";
// App APIs // App APIs
// Error Handling
export function ParseError(error: any) {
if (error.response && error.response.data) {
return JSON.stringify(error.response.data)
.replaceAll(/[{}()"]/g, " ")
.replaceAll(/,/g, "\n")
.replaceAll("[", "")
.replaceAll("]", "")
.replaceAll(".", "")
.replaceAll(/"/g, "")
.replaceAll("non_field_errors", "")
.trim();
}
return "Unable to reach server";
}
// Token Handling // Token Handling
export async function getAccessToken() { export async function getAccessToken() {
const accessToken = await AsyncStorage.getItem("access_token"); const accessToken = await AsyncStorage.getItem("access_token");
@ -59,40 +87,28 @@ export async function GetConfig() {
} }
// User APIs // User APIs
export function UserRegister(register: RegistrationParams) { export function UserRegister(register: RegistrationType) {
console.log(JSON.stringify(register));
return instance return instance
.post("/api/v1/accounts/users/", register) .post("/api/v1/accounts/users/", register)
.then(async (response) => { .then(async (response) => {
return [true, response.status]; return [true, response.status];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
return [false, error_message]; return [false, error_message];
}); });
} }
export function UserLogin(user: LoginParams) { export function UserLogin(user: LoginType) {
return instance return instance
.post("/api/v1/accounts/jwt/create/", user) .post("/api/v1/accounts/jwt/create/", user)
.then(async (response) => { .then(async (response) => {
/*console.log(
"Access Token:",
response.data.access,
"\nRefresh Token:",
response.data.refresh
);*/
setAccessToken(response.data.access); setAccessToken(response.data.access);
setRefreshToken(response.data.refresh); setRefreshToken(response.data.refresh);
return [true]; return [true];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
// console.log(error_message);
return [false, error_message]; return [false, error_message];
}); });
} }
@ -106,21 +122,14 @@ export async function TokenRefresh() {
}) })
.then(async (response) => { .then(async (response) => {
setAccessToken(response.data.access); setAccessToken(response.data.access);
/*console.log(
"Token refresh success! New Access Token",
response.data.access
);*/
return true; return true;
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
console.log("Token Refresh error:", error_message);
return false; return false;
}); });
} }
export async function UserInfo() { export async function GetUserInfo() {
const config = await GetConfig(); const config = await GetConfig();
return instance return instance
.get("/api/v1/accounts/users/me/", config) .get("/api/v1/accounts/users/me/", config)
@ -129,37 +138,31 @@ export async function UserInfo() {
return [true, response.data]; return [true, response.data];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
return [false, error_message]; return [false, error_message];
}); });
} }
export async function PatchUserInfo(info: PatchStudentData) { export async function PatchUserInfo(info: PatchUserInfoType) {
const config = await GetConfig(); const config = await GetConfig();
return instance return instance
.patch("/api/v1/accounts/users/me/", info, config) .patch("/api/v1/accounts/users/me/", info, config)
.then((response) => { .then((response) => {
console.log(JSON.stringify(response.data));
return [true, response.data]; return [true, response.data];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
// console.log(error_message);
return [false, error_message]; return [false, error_message];
}); });
} }
export function UserActivate(activation: ActivationParams) { export function UserActivate(activation: ActivationType) {
return instance return instance
.post("/api/v1/accounts/users/activation/", activation) .post("/api/v1/accounts/users/activation/", activation)
.then(async (response) => { .then(() => {
return true; return true;
}) })
.catch((error) => { .catch(() => {
return false; return false;
}); });
} }
@ -179,9 +182,7 @@ export async function GetCourses() {
return [true, response.data]; return [true, response.data];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
return [false, error_message]; return [false, error_message];
}); });
} }
@ -199,9 +200,7 @@ export async function GetSemesters() {
return [true, response.data]; return [true, response.data];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
return [false, error_message]; return [false, error_message];
}); });
} }
@ -215,69 +214,135 @@ export async function GetYearLevels() {
return [true, response.data]; return [true, response.data];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
return [false, error_message]; return [false, error_message];
}); });
} }
export async function GetSubjects( export async function GetSubjects() {
byCourseOnly: boolean,
course: string,
year_level?: string,
semester?: string
) {
const config = await GetConfig();
console.log("by course only?", byCourseOnly);
// If year level and semester specified,
if (!byCourseOnly && year_level && semester) {
return instance
.get(
"/api/v1/subjects/" + course + "/" + year_level + "/" + semester,
config
)
.then((response) => {
// console.log(JSON.stringify(response.data));
return [true, response.data];
})
.catch((error) => {
let error_message = "";
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
return [false, error_message];
});
}
// If only course is specified
else {
return instance
.get("/api/v1/subjects/" + course, config)
.then((response) => {
// console.log(JSON.stringify(response.data));
return [true, response.data];
})
.catch((error) => {
let error_message = "";
if (error.response) error_message = error.response.data;
else error_message = "Unable to reach servers";
return [false, error_message];
});
}
}
export async function OnboardingUpdateStudentInfo(info: OnboardingParams) {
const config = await GetConfig(); const config = await GetConfig();
return instance return instance
.patch("/api/v1/accounts/users/me/", info, config) .get("/api/v1/subjects/", config)
.then((response) => { .then((response) => {
console.log(JSON.stringify(response.data));
return [true, response.data]; return [true, response.data];
}) })
.catch((error) => { .catch((error) => {
let error_message = ""; let error_message = ParseError(error);
if (error.response) error_message = error.response.data; return [false, error_message];
else error_message = "Unable to reach servers"; });
console.log("Error updating onboarding info", error_message); }
export async function GetStudentStatus() {
const config = await GetConfig();
return instance
.get("/api/v1/student_status/self/", config)
.then((response) => {
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message];
});
}
export async function PatchStudentStatus(info: StudentStatusPatchType) {
const config = await GetConfig();
return instance
.patch("/api/v1/student_status/self/", info, config)
.then((response) => {
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message];
});
}
export async function GetStudentStatusList() {
const config = await GetConfig();
return instance
.get("/api/v1/student_status/list/", config)
.then((response) => {
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message];
});
}
export async function GetStudentStatusListNear() {
const config = await GetConfig();
return instance
.get("/api/v1/student_status/near/", config)
.then((response) => {
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message];
});
}
// To-do
export async function GetStudentStatusListFilteredCurrentLocation(
location: LocationType
) {
const config = await GetConfig();
return instance
.post(
"/api/v1/student_status/near_current_location/",
{
location: location,
},
config
)
.then((response) => {
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message];
});
}
export async function GetStudyGroupListFiltered() {
const config = await GetConfig();
return instance
.get("/api/v1/study_groups/near/", config)
.then((response) => {
console.log("DEBUGGG", response.data);
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message];
});
}
export async function GetStudyGroupList() {
const config = await GetConfig();
return instance
.get("/api/v1/study_groups/", config)
.then((response) => {
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message];
});
}
export async function CreateStudyGroup(info: StudyGroupCreateType) {
const config = await GetConfig();
// console.log("Creating study group:", info);
return instance
.post("/api/v1/study_groups/create/", info, config)
.then((response) => {
return [true, response.data];
})
.catch((error) => {
let error_message = ParseError(error);
return [false, error_message]; return [false, error_message];
}); });
} }

View file

@ -5,7 +5,10 @@ import { Text, View } from "react-native";
import { colors } from "../../styles"; import { colors } from "../../styles";
import styles from "../../styles"; import styles from "../../styles";
import { RootDrawerParamList } from "../../interfaces/Interfaces"; import {
RootDrawerParamList,
StudentStatusPatchType,
} from "../../interfaces/Interfaces";
import AppIcon from "../../icons/AppIcon/AppIcon"; import AppIcon from "../../icons/AppIcon/AppIcon";
import HomeIcon from "../../icons/HomeIcon/HomeIcon"; import HomeIcon from "../../icons/HomeIcon/HomeIcon";
import LoginIcon from "../../icons/LoginIcon/LoginIcon"; import LoginIcon from "../../icons/LoginIcon/LoginIcon";
@ -18,11 +21,48 @@ import { logout } from "../../features/redux/slices/StatusSlice/StatusSlice";
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import UserIcon from "../../icons/UserIcon/UserIcon"; import UserIcon from "../../icons/UserIcon/UserIcon";
import SubjectIcon from "../../icons/SubjectIcon/SubjectIcon"; import SubjectIcon from "../../icons/SubjectIcon/SubjectIcon";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import toast from "react-native-toast-notifications/lib/typescript/toast";
import { PatchStudentStatus } from "../Api/Api";
import { useToast } from "react-native-toast-notifications";
export default function CustomDrawerContent(props: {}) { export default function CustomDrawerContent(props: {}) {
const navigation = useNavigation<RootDrawerParamList>(); const navigation = useNavigation<RootDrawerParamList>();
const status = useSelector((state: RootState) => state.status); const status = useSelector((state: RootState) => state.status);
const dispatch = useDispatch(); const dispatch = useDispatch();
const queryClient = useQueryClient();
const toast = useToast();
const debug_disable_clear_on_logout = true;
const stop_studying_logout = useMutation({
mutationFn: async (info: StudentStatusPatchType) => {
const data = await PatchStudentStatus(info);
if (data[0] != true) {
return Promise.reject(new Error());
}
console.log("DEBUG", data);
return data;
},
onSuccess: async () => {
toast.show("Logged out. Stopped studying", {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
queryClient.clear();
dispatch(logout());
await AsyncStorage.clear();
navigation.navigate("Login");
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
});
if (status.logged_in && status.onboarding) { if (status.logged_in && status.onboarding) {
return ( return (
<DrawerContentScrollView {...props}> <DrawerContentScrollView {...props}>
@ -38,9 +78,16 @@ export default function CustomDrawerContent(props: {}) {
<DrawerButton <DrawerButton
onPress={async () => { onPress={async () => {
dispatch(logout()); if (debug_disable_clear_on_logout) {
await AsyncStorage.clear(); queryClient.clear();
navigation.navigate("Login"); dispatch(logout());
await AsyncStorage.clear();
navigation.navigate("Login");
} else {
stop_studying_logout.mutate({
active: false,
});
}
}} }}
> >
<LogoutIcon size={32} /> <LogoutIcon size={32} />
@ -86,9 +133,16 @@ export default function CustomDrawerContent(props: {}) {
</DrawerButton> </DrawerButton>
<DrawerButton <DrawerButton
onPress={async () => { onPress={async () => {
dispatch(logout()); if (debug_disable_clear_on_logout) {
await AsyncStorage.clear(); queryClient.clear();
navigation.navigate("Login"); dispatch(logout());
await AsyncStorage.clear();
navigation.navigate("Login");
} else {
stop_studying_logout.mutate({
active: false,
});
}
}} }}
> >
<LogoutIcon size={32} /> <LogoutIcon size={32} />

View file

@ -0,0 +1,20 @@
import { LocationType } from "../../interfaces/Interfaces";
import GetDistance from "./GetDistance";
export default function GetDistanceFromUSTP(location: LocationType) {
const ustpCoords = {
latitude: 8.4857,
longitude: 124.6565,
latitudeDelta: 0.000235,
longitudeDelta: 0.000067,
};
let dist = GetDistance(
location.latitude,
location.longitude,
ustpCoords.latitude,
ustpCoords.longitude
);
dist = Math.round(dist);
return dist;
}

View file

@ -0,0 +1,79 @@
import * as React from "react";
import { View, Text } from "react-native";
import MapView, { UrlTile, Callout, Marker } from "react-native-maps";
import styles, { Viewport, colors } from "../../styles";
import { urlProvider } from "../Api/Api";
import { LocationType, RawLocationType } from "../../interfaces/Interfaces";
import GetDistance from "../../components/GetDistance/GetDistance";
type props = {
location: LocationType;
dist: any;
};
export default function MapRendererFar(props: props) {
return (
<>
<Text style={styles.text_white_medium}>
You are too far from USTP {"\n"}
Get closer to use Stud-E
</Text>
<MapView
style={{
height: Viewport.height * 0.5,
width: Viewport.width * 0.8,
alignSelf: "center",
}}
customMapStyle={[
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
]}
mapType="none"
scrollEnabled={false}
zoomEnabled={false}
toolbarEnabled={false}
rotateEnabled={false}
minZoomLevel={18}
initialRegion={{
latitude: props.location.latitude,
longitude: props.location.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
loadingBackgroundColor={colors.secondary_2}
>
<UrlTile
urlTemplate={urlProvider}
shouldReplaceMapContent={true}
maximumZ={19}
flipY={false}
zIndex={1}
/>
<Marker
coordinate={{
latitude: props.location.latitude,
longitude: props.location.longitude,
}}
pinColor={colors.primary_1}
>
<Callout>
<Text style={styles.text_black_tiny}>
You are here {"\n"}
X: {Math.round(props.location.longitude) + "\n"}
Z: {Math.round(props.location.latitude)}
</Text>
</Callout>
</Marker>
</MapView>
<Text style={styles.text_white_small}>
{props.dist}km away from USTP {"\n"}
</Text>
</>
);
}

View file

@ -1,24 +0,0 @@
export default function ParseError(text: string) {
if (text) {
return text
.replaceAll(/[{}()"]/g, " ")
.replaceAll(/,/g, "\n")
.replaceAll("[", "")
.replaceAll("]", "")
.replaceAll(".", "");
}
return "";
}
export function ParseLoginError(text: string) {
if (text) {
return text
.replaceAll(/[{}()"]/g, " ")
.replaceAll(/,/g, "\n")
.replaceAll("[", "")
.replaceAll("]", "")
.replaceAll(".", "")
.replaceAll("non_field_errors", "");
}
return "";
}

View file

@ -3,7 +3,7 @@ import { IconProps } from "../../interfaces/Interfaces";
import { Svg, Path } from "react-native-svg"; import { Svg, Path } from "react-native-svg";
import { colors } from "../../styles"; import { colors } from "../../styles";
export default function DropdownIcon(props: IconProps) { export default function CaretDownIcon(props: IconProps) {
return ( return (
<> <>
<Svg <Svg

View file

@ -0,0 +1,24 @@
import * as React from "react";
import { IconProps } from "../../interfaces/Interfaces";
import { Svg, Path } from "react-native-svg";
import { colors } from "../../styles";
export default function CaretUpIcon(props: IconProps) {
return (
<>
<Svg
height={props.size + "px"}
width={props.size + "px"}
viewBox="0 0 24 24"
stroke-width="2"
stroke={colors.icon_color}
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
>
<Path stroke="none" d="M0 0h24v24H0z" fill="none"></Path>
<Path d="M18 14l-6 -6l-6 6h12"></Path>
</Svg>
</>
);
}

View file

@ -0,0 +1,27 @@
import * as React from "react";
import { IconProps } from "../../interfaces/Interfaces";
import { Svg, Path } from "react-native-svg";
import { colors } from "../../styles";
export default function InfoIcon(props: IconProps) {
return (
<>
<Svg
width={props.size}
height={props.size}
viewBox="0 0 24 24"
strokeWidth="2"
stroke={colors.icon_color}
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
>
<Path stroke="none" d="M0 0h24v24H0z" fill="none"></Path>
<Path d="M12 9h.01"></Path>
<Path d="M11 12h1v4h1"></Path>
<Path d="M12 3c7.2 0 9 1.8 9 9s-1.8 9 -9 9s-9 -1.8 -9 -9s1.8 -9 9 -9z"></Path>
</Svg>
</>
);
}

View file

@ -1,3 +1,7 @@
import * as Location from "expo-location";
import { GetStudentStatus } from "../components/Api/Api";
import { Float } from "react-native/Libraries/Types/CodegenTypes";
export interface IconProps { export interface IconProps {
size: number; size: number;
} }
@ -9,6 +13,7 @@ export interface ResponsiveIconProps {
export interface RootDrawerParamList { export interface RootDrawerParamList {
navigate: any; navigate: any;
replace: any;
} }
// Redux Interfaces // Redux Interfaces
@ -28,7 +33,7 @@ export interface LoggedInUserState {
// API Interfaces // API Interfaces
export interface RegistrationParams { export interface RegistrationType {
email: string; email: string;
username: string; username: string;
password: string; password: string;
@ -37,12 +42,12 @@ export interface RegistrationParams {
student_id_number: string; student_id_number: string;
} }
export interface LoginParams { export interface LoginType {
username: string; username: string;
password: string; password: string;
} }
export interface ActivationParams { export interface ActivationType {
uid: string; uid: string;
token: string; token: string;
} }
@ -53,80 +58,165 @@ export interface OptionType {
} }
// Semester // Semester
export interface Semester { export interface SemesterType {
id: string; id: string;
name: string; name: string;
shortname: string; shortname: string;
} }
export type Semesters = Array<Semester>; export type SemestersType = Array<SemesterType>;
export type SemesterParams = [boolean, Semesters]; export type SemesterReturnType = [boolean, SemestersType];
// Year Level // Year Level
export interface YearLevel { export interface YearLevelType {
id: string; id: string;
name: string; name: string;
shortname: string; shortname: string;
} }
export type YearLevels = Array<YearLevel>; export type YearLevelsType = Array<YearLevelType>;
export type YearLevelParams = [boolean, YearLevels]; export type YearLevelReturnType = [boolean, YearLevelsType];
// Course // Course
export interface Course { export interface CourseType {
id: string; id: string;
name: string; name: string;
shortname: string; shortname: string;
} }
export type Courses = Array<Course>; export type CoursesType = Array<CourseType>;
export type CourseParams = [boolean, Courses]; export type CourseReturnType = [boolean, CoursesType];
// Subject // Subject
export interface Subject { export interface SubjectType {
id: number;
name: string; name: string;
code: string; code: string;
// courses: any[]; // To-do course: string;
// year_levels: any[]; // To-do year_level: string;
// semesters: any[]; // To-do semester: string;
} }
export type Subjects = Array<Subject>; export type SubjectsType = Array<SubjectType>;
export type SubjectParams = [boolean, Subjects]; export type SubjectsReturnType = [boolean, SubjectsType];
export type AvatarType = {
uri: string;
type: string;
name: string;
};
// For dropdown menu // For dropdown menu
export interface OnboardingParams { export interface OnboardingType {
year_level: string; year_level: string;
course: string; course: string;
semester: string; semester: string;
} }
export interface PatchStudentData { export interface PatchUserInfoType {
course?: string | null; course?: string;
first_name?: string | null; first_name?: string;
last_name?: string | null; last_name?: string;
semester?: string | null; semester?: string;
subjects?: any[] | null; // To-do, replace 'any' with your actual type subjects?: string[];
year_level?: string | null; year_level?: string;
irregular?: boolean;
avatar?: string;
} }
export interface StudentData { export interface LocationType {
latitude: Float;
longitude: Float;
}
export interface StudentStatusType {
subject: string;
location: LocationType;
landmark: string | null;
active: boolean;
study_group: string;
}
export interface StudentStatusPatchType {
subject?: string;
location?: LocationType;
landmark?: string | null;
active?: boolean;
study_group?: string;
}
export interface StudentStatusFilterType {
active: boolean;
distance: number;
landmark: string | null;
location: LocationType;
study_group?: string;
subject: string;
user: string;
weight?: number;
}
export interface StudentStatusFilterTypeFlattened {
active: boolean;
distance: number;
landmark: string | null;
latitude: Float;
longitude: Float;
study_group?: string;
subject: string;
user: string;
weight?: number;
}
export interface StudyGroupType {
name: string;
students: string[];
distance: number;
landmark: string | null;
location: LocationType;
subject: string;
radius: number;
}
export interface StudyGroupCreateType {
name: string;
location: LocationType;
subject: string;
}
export type StudyGroupReturnType = [boolean, StudyGroupType[]];
export type StudentStatusReturnType = [boolean, StudentStatusType];
export type StudentStatusListType = Array<StudentStatusFilterType>;
export type StudentStatusListReturnType = [boolean, StudentStatusListType];
export type RawLocationType = Location.LocationObject;
export interface UserInfoType {
first_name: string; first_name: string;
last_name: string; last_name: string;
email: string; email: string;
avatar: string; avatar: string;
student_id_number: string; student_id_number: string;
is_banned: boolean; irregular: boolean;
semester: string; semester: string;
semester_shortname: string; semester_shortname: string;
course: string; course: string;
course_shortname: string; course_shortname: string;
year_level: string; year_level: string;
yearlevel_shortname: string; yearlevel_shortname: string;
subjects: any[]; // To-do subjects: string[];
username: string; username: string;
} }
export type UserInfoParams = [boolean, StudentData]; export type UserInfoReturnType = [boolean, UserInfoType];
export type subjectUserMapType = {
subject: string;
users: string[];
latitude: Float;
longitude: Float;
radius: Float;
};

View file

@ -6,6 +6,7 @@ import { useNavigation, useRoute } from "@react-navigation/native";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { UserActivate } from "../../components/Api/Api"; import { UserActivate } from "../../components/Api/Api";
import { RootDrawerParamList } from "../../interfaces/Interfaces"; import { RootDrawerParamList } from "../../interfaces/Interfaces";
import { useToast } from "react-native-toast-notifications";
interface ActivationRouteParams { interface ActivationRouteParams {
uid?: string; uid?: string;
@ -16,9 +17,7 @@ export default function Activation() {
const route = useRoute(); const route = useRoute();
const { uid, token } = (route.params as ActivationRouteParams) || ""; const { uid, token } = (route.params as ActivationRouteParams) || "";
const navigation = useNavigation<RootDrawerParamList>(); const navigation = useNavigation<RootDrawerParamList>();
const [state, setState] = useState( const toast = useToast();
"Activating with UID " + uid + " and Token " + token
);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
useEffect(() => { useEffect(() => {
@ -28,16 +27,22 @@ export default function Activation() {
token: String(token), token: String(token),
}); });
if (result) { if (result) {
setTimeout(() => { toast.show("Activation successful", {
setState("Activation successful!"); type: "success",
}, 1000); placement: "top",
duration: 4000,
animationType: "slide-in",
});
setTimeout(() => { setTimeout(() => {
navigation.navigate("Login"); navigation.navigate("Login");
}, 2000); }, 2000);
} else { } else {
setTimeout(() => { toast.show("Activation unsuccessful. Please contact support", {
setState("Activation unsuccessful\nPlease contact support"); type: "warning",
}, 1000); placement: "top",
duration: 4000,
animationType: "slide-in",
});
} }
setLoading(false); setLoading(false);
} }
@ -63,8 +68,9 @@ export default function Activation() {
size={96} size={96}
color={colors.secondary_1} color={colors.secondary_1}
/> />
<Text style={styles.text_white_medium}>{state}</Text> <Text style={styles.text_white_medium}>
<Text style={styles.text_white_tiny}>{uid + "\n" + token}</Text> {"Activating with UID: " + uid + "\nToken: " + token}
</Text>
</AnimatedContainer> </AnimatedContainer>
</View> </View>
); );

View file

@ -0,0 +1,177 @@
import * as React from "react";
import styles, { Viewport } from "../../styles";
import {
View,
Text,
TextInput,
NativeSyntheticEvent,
TextInputChangeEventData,
} from "react-native";
import { useState } from "react";
import {
RootDrawerParamList,
StudentStatusPatchType,
StudyGroupCreateType,
} from "../../interfaces/Interfaces";
import Button from "../../components/Button/Button";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { PatchStudentStatus, CreateStudyGroup } from "../../components/Api/Api";
import { colors } from "../../styles";
import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll";
import { urlProvider } from "../../components/Api/Api";
import MapView, { UrlTile, Marker } from "react-native-maps";
import { useNavigation } from "@react-navigation/native";
import { useToast } from "react-native-toast-notifications";
export default function CreateGroup({ route }: any) {
const { location, subject } = route.params;
const queryClient = useQueryClient();
const navigation = useNavigation<RootDrawerParamList>();
const toast = useToast();
const [name, setName] = useState("");
const study_group_create = useMutation({
mutationFn: async (info: StudyGroupCreateType) => {
const data = await CreateStudyGroup(info);
if (data[0] != true) {
return Promise.reject(new Error());
}
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: ["user_status"] });
queryClient.invalidateQueries({ queryKey: ["study_group_list"] });
student_status_patch.mutate({
study_group: name,
});
toast.show("Created successfully", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
});
const student_status_patch = useMutation({
mutationFn: async (info: StudentStatusPatchType) => {
const data = await PatchStudentStatus(info);
if (data[0] != true) {
return Promise.reject(new Error());
}
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: ["user_status"] });
toast.show(`Joined group ${name} successfully`, {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
navigation.navigate("Home");
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
});
if (location) {
return (
<View style={styles.background}>
<AnimatedContainerNoScroll>
<View style={{ zIndex: -1 }}>
<View style={styles.padding} />
<MapView
style={{
height: Viewport.height * 0.4,
width: Viewport.width * 0.8,
alignSelf: "center",
}}
customMapStyle={[
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
]}
mapType="none"
scrollEnabled={false}
zoomEnabled={false}
toolbarEnabled={false}
rotateEnabled={false}
minZoomLevel={18}
initialRegion={{
latitude: location.latitude,
longitude: location.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
loadingBackgroundColor={colors.secondary_2}
>
<UrlTile
urlTemplate={urlProvider}
shouldReplaceMapContent={true}
maximumZ={19}
flipY={false}
zIndex={1}
/>
<Marker
coordinate={{
latitude: location.latitude,
longitude: location.longitude,
}}
pinColor={colors.primary_1}
/>
</MapView>
<View style={styles.padding} />
</View>
<TextInput
style={styles.text_input}
placeholder="Group Name"
placeholderTextColor="white"
autoCapitalize="none"
value={name}
onChange={(
e: NativeSyntheticEvent<TextInputChangeEventData>
): void => {
setName(e.nativeEvent.text);
}}
/>
<View style={styles.padding} />
<Button
onPress={() => {
study_group_create.mutate({
name: name,
location: location,
subject: subject,
});
}}
>
<Text style={styles.text_white_small}>Start Studying</Text>
</Button>
<View style={styles.padding} />
</AnimatedContainerNoScroll>
</View>
);
}
return <View />;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,17 @@
import * as React from "react";
import styles from "../../styles";
import { View, Text, ActivityIndicator } from "react-native";
import { colors } from "../../styles";
import AnimatedContainer from "../../components/AnimatedContainer/AnimatedContainer";
export default function Loading() {
return (
<View style={styles.background}>
<AnimatedContainer>
<View style={{ paddingVertical: 8 }} />
<ActivityIndicator size={128} color={colors.secondary_1} />
<Text style={styles.text_white_medium}>Loading StudE...</Text>
</AnimatedContainer>
</View>
);
}

View file

@ -8,14 +8,12 @@ import {
TextInputChangeEventData, TextInputChangeEventData,
} from "react-native"; } from "react-native";
import { useDispatch } from "react-redux"; import { useDispatch } from "react-redux";
import { colors } from "../../styles";
import { useState } from "react"; import { useState } from "react";
import LoginIcon from "../../icons/LoginIcon/LoginIcon"; import LoginIcon from "../../icons/LoginIcon/LoginIcon";
import Button from "../../components/Button/Button"; import Button from "../../components/Button/Button";
import { useNavigation } from "@react-navigation/native"; import { useNavigation } from "@react-navigation/native";
import { RootDrawerParamList } from "../../interfaces/Interfaces"; import { RootDrawerParamList } from "../../interfaces/Interfaces";
import { UserInfo, UserLogin } from "../../components/Api/Api"; import { GetUserInfo, UserLogin } from "../../components/Api/Api";
import { ParseLoginError } from "../../components/ParseError/ParseError";
import AnimatedContainer from "../../components/AnimatedContainer/AnimatedContainer"; import AnimatedContainer from "../../components/AnimatedContainer/AnimatedContainer";
import { setUser } from "../../features/redux/slices/UserSlice/UserSlice"; import { setUser } from "../../features/redux/slices/UserSlice/UserSlice";
import { import {
@ -23,6 +21,7 @@ import {
setOnboarding, setOnboarding,
unsetOnboarding, unsetOnboarding,
} from "../../features/redux/slices/StatusSlice/StatusSlice"; } from "../../features/redux/slices/StatusSlice/StatusSlice";
import { useToast } from "react-native-toast-notifications";
export default function Login() { export default function Login() {
const navigation = useNavigation<RootDrawerParamList>(); const navigation = useNavigation<RootDrawerParamList>();
@ -31,7 +30,7 @@ export default function Login() {
username: "", username: "",
password: "", password: "",
}); });
const [error, setError] = useState(""); const toast = useToast();
return ( return (
<View style={styles.background}> <View style={styles.background}>
<AnimatedContainer> <AnimatedContainer>
@ -60,14 +59,13 @@ export default function Login() {
placeholderTextColor="white" placeholderTextColor="white"
secureTextEntry={true} secureTextEntry={true}
value={creds.password} value={creds.password}
autoCapitalize={"none"}
onChange={( onChange={(
e: NativeSyntheticEvent<TextInputChangeEventData> e: NativeSyntheticEvent<TextInputChangeEventData>
): void => { ): void => {
setCreds({ ...creds, password: e.nativeEvent.text }); setCreds({ ...creds, password: e.nativeEvent.text });
}} }}
/> />
<View style={{ paddingVertical: 2 }} />
<Text style={styles.text_white_small}>{error}</Text>
<View style={{ paddingVertical: 4 }} /> <View style={{ paddingVertical: 4 }} />
<Button <Button
onPress={async () => { onPress={async () => {
@ -77,7 +75,7 @@ export default function Login() {
}).then(async (result) => { }).then(async (result) => {
if (result[0]) { if (result[0]) {
setUser({ ...creds, username: "", password: "", error: "" }); setUser({ ...creds, username: "", password: "", error: "" });
let user_info = await UserInfo(); let user_info = await GetUserInfo();
dispatch(login()); dispatch(login());
dispatch(setUser(user_info[1])); dispatch(setUser(user_info[1]));
// Redirect to onboarding if no year level, course, or semester specified // Redirect to onboarding if no year level, course, or semester specified
@ -88,14 +86,30 @@ export default function Login() {
) { ) {
dispatch(setOnboarding()); dispatch(setOnboarding());
navigation.navigate("Onboarding"); navigation.navigate("Onboarding");
toast.show("Successfully logged in", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
} else { } else {
dispatch(unsetOnboarding()); dispatch(unsetOnboarding());
toast.show("Successfully logged in", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
navigation.navigate("Home"); navigation.navigate("Home");
} }
console.log(JSON.stringify(user_info)); console.log(JSON.stringify(user_info));
} else { } else {
console.log("heh", ParseLoginError(JSON.stringify(result[1]))); toast.show(JSON.stringify(result[1]), {
setError(ParseLoginError(JSON.stringify(result[1]))); type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
} }
}); });
}} }}

View file

@ -3,10 +3,10 @@ import styles from "../../styles";
import { View, Text } from "react-native"; import { View, Text } from "react-native";
import { useNavigation } from "@react-navigation/native"; import { useNavigation } from "@react-navigation/native";
import { import {
Course,
RootDrawerParamList, RootDrawerParamList,
Semester, CourseType,
YearLevel, SemesterType,
YearLevelType,
} from "../../interfaces/Interfaces"; } from "../../interfaces/Interfaces";
import { colors } from "../../styles"; import { colors } from "../../styles";
import { MotiView } from "moti"; import { MotiView } from "moti";
@ -18,18 +18,18 @@ import {
GetCourses, GetCourses,
GetSemesters, GetSemesters,
GetYearLevels, GetYearLevels,
OnboardingUpdateStudentInfo, PatchUserInfo,
} from "../../components/Api/Api"; } from "../../components/Api/Api";
import { useDispatch } from "react-redux"; import { useDispatch } from "react-redux";
import { unsetOnboarding } from "../../features/redux/slices/StatusSlice/StatusSlice"; import { unsetOnboarding } from "../../features/redux/slices/StatusSlice/StatusSlice";
import { setUser } from "../../features/redux/slices/UserSlice/UserSlice"; import { setUser } from "../../features/redux/slices/UserSlice/UserSlice";
import AnimatedContainer from "../../components/AnimatedContainer/AnimatedContainer";
import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll"; import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll";
import { useToast } from "react-native-toast-notifications";
export default function Onboarding() { export default function Onboarding() {
const navigation = useNavigation<RootDrawerParamList>(); const navigation = useNavigation<RootDrawerParamList>();
const dispatch = useDispatch(); const dispatch = useDispatch();
// const creds = useSelector((state: RootState) => state.auth.creds); // const creds = useSelector((state: RootState) => state.auth.creds);
const [error, setError] = useState(""); const toast = useToast();
// Semesters // Semesters
const [selected_semester, setSelectedSemester] = useState(""); const [selected_semester, setSelectedSemester] = useState("");
const [semesterOpen, setSemesterOpen] = useState(false); const [semesterOpen, setSemesterOpen] = useState(false);
@ -39,14 +39,28 @@ export default function Onboarding() {
]); ]);
const semester_query = useQuery({ const semester_query = useQuery({
queryKey: ["semesters"], queryKey: ["semesters"],
queryFn: GetSemesters, queryFn: async () => {
const data = await GetSemesters();
if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data) => { onSuccess: (data) => {
let semesters = data[1].map((item: Semester) => ({ let semesters = data[1].map((item: SemesterType) => ({
label: item.name, label: item.name,
value: item.name, value: item.name,
})); }));
setSemesters(semesters); setSemesters(semesters);
}, },
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
}); });
// Year Level // Year Level
const [selected_yearlevel, setSelectedYearLevel] = useState(""); const [selected_yearlevel, setSelectedYearLevel] = useState("");
@ -57,14 +71,28 @@ export default function Onboarding() {
]); ]);
const yearlevel_query = useQuery({ const yearlevel_query = useQuery({
queryKey: ["year_levels"], queryKey: ["year_levels"],
queryFn: GetYearLevels, queryFn: async () => {
const data = await GetYearLevels();
if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data) => { onSuccess: (data) => {
let year_levels = data[1].map((item: YearLevel) => ({ let year_levels = data[1].map((item: YearLevelType) => ({
label: item.name, label: item.name,
value: item.name, value: item.name,
})); }));
setYearLevels(year_levels); setYearLevels(year_levels);
}, },
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
}); });
// Course // Course
const [selected_course, setSelectedCourse] = useState(""); const [selected_course, setSelectedCourse] = useState("");
@ -78,14 +106,28 @@ export default function Onboarding() {
]); ]);
const course_query = useQuery({ const course_query = useQuery({
queryKey: ["courses"], queryKey: ["courses"],
queryFn: GetCourses, queryFn: async () => {
const data = await GetCourses();
if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data) => { onSuccess: (data) => {
let courses = data[1].map((item: Course) => ({ let courses = data[1].map((item: CourseType) => ({
label: item.name, label: item.name,
value: item.name, value: item.name,
})); }));
setCourses(courses); setCourses(courses);
}, },
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
}); });
if (yearlevel_query.error || semester_query.error || course_query.error) { if (yearlevel_query.error || semester_query.error || course_query.error) {
return ( return (
@ -196,7 +238,6 @@ export default function Onboarding() {
dropDownContainerStyle={{ backgroundColor: colors.primary_2 }} dropDownContainerStyle={{ backgroundColor: colors.primary_2 }}
/> />
</MotiView> </MotiView>
<Text style={styles.text_white_small}>{error}</Text>
<MotiView <MotiView
from={{ from={{
opacity: 0, opacity: 0,
@ -217,7 +258,7 @@ export default function Onboarding() {
!selected_yearlevel || !selected_course || !selected_semester !selected_yearlevel || !selected_course || !selected_semester
} }
onPress={async () => { onPress={async () => {
let result = await OnboardingUpdateStudentInfo({ let result = await PatchUserInfo({
semester: selected_semester, semester: selected_semester,
course: selected_course, course: selected_course,
year_level: selected_yearlevel, year_level: selected_yearlevel,
@ -227,11 +268,25 @@ export default function Onboarding() {
setSelectedCourse(""); setSelectedCourse("");
setSelectedYearLevel(""); setSelectedYearLevel("");
setSelectedSemester(""); setSelectedSemester("");
setError("Success!");
dispatch(setUser(result[1])); dispatch(setUser(result[1]));
toast.show("Changes applied successfully", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
navigation.navigate("Home"); navigation.navigate("Home");
} else { } else {
setError(result[1]); dispatch(setUser(result[1]));
toast.show(
"An error has occured\nChanges have not been saved",
{
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
}
);
} }
}} }}
> >

View file

@ -15,11 +15,12 @@ import { RootDrawerParamList } from "../../interfaces/Interfaces";
import SignupIcon from "../../icons/SignupIcon/SignupIcon"; import SignupIcon from "../../icons/SignupIcon/SignupIcon";
import { UserRegister } from "../../components/Api/Api"; import { UserRegister } from "../../components/Api/Api";
import IsNumber from "../../components/IsNumber/IsNumber"; import IsNumber from "../../components/IsNumber/IsNumber";
import ParseError from "../../components/ParseError/ParseError";
import AnimatedContainer from "../../components/AnimatedContainer/AnimatedContainer"; import AnimatedContainer from "../../components/AnimatedContainer/AnimatedContainer";
import { useToast } from "react-native-toast-notifications";
export default function Register() { export default function Register() {
const navigation = useNavigation<RootDrawerParamList>(); const navigation = useNavigation<RootDrawerParamList>();
const toast = useToast();
// const dispatch = useDispatch(); // const dispatch = useDispatch();
// const creds = useSelector((state: RootState) => state.auth.creds); // const creds = useSelector((state: RootState) => state.auth.creds);
const [user, setUser] = useState({ const [user, setUser] = useState({
@ -29,7 +30,6 @@ export default function Register() {
username: "", username: "",
email: "", email: "",
password: "", password: "",
feedback: "",
}); });
return ( return (
<View style={styles.background}> <View style={styles.background}>
@ -113,6 +113,7 @@ export default function Register() {
placeholderTextColor={colors.text_default} placeholderTextColor={colors.text_default}
secureTextEntry={true} secureTextEntry={true}
value={user.password} value={user.password}
autoCapitalize={"none"}
onChange={( onChange={(
e: NativeSyntheticEvent<TextInputChangeEventData> e: NativeSyntheticEvent<TextInputChangeEventData>
): void => { ): void => {
@ -120,8 +121,6 @@ export default function Register() {
}} }}
/> />
<View style={{ paddingVertical: 4 }} /> <View style={{ paddingVertical: 4 }} />
<Text style={styles.text_white_small}>{user.feedback}</Text>
<View style={{ paddingVertical: 4 }} />
<Button <Button
onPress={async () => { onPress={async () => {
await UserRegister({ await UserRegister({
@ -142,16 +141,25 @@ export default function Register() {
username: "", username: "",
email: "", email: "",
password: "", password: "",
feedback:
"Success! An email has been sent to activate your account",
}); });
toast.show(
"Success! An email has been sent to activate your account",
{
type: "success",
placement: "top",
duration: 6000,
animationType: "slide-in",
}
);
setTimeout(() => { setTimeout(() => {
navigation.navigate("Login"); navigation.navigate("Login");
}, 10000); }, 10000);
} else { } else {
setUser({ toast.show(JSON.stringify(result[1]), {
...user, type: "warning",
feedback: ParseError(JSON.stringify(result[1])), placement: "top",
duration: 6000,
animationType: "slide-in",
}); });
} }
}); });

View file

@ -1,7 +1,7 @@
import * as React from "react"; import * as React from "react";
import styles from "../../styles"; import styles from "../../styles";
import { View, Text, ActivityIndicator } from "react-native"; import { View, Text, ActivityIndicator } from "react-native";
import { TokenRefresh, UserInfo } from "../../components/Api/Api"; import { TokenRefresh, GetUserInfo } from "../../components/Api/Api";
import { useDispatch } from "react-redux"; import { useDispatch } from "react-redux";
import { colors } from "../../styles"; import { colors } from "../../styles";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
@ -15,37 +15,55 @@ import AnimatedContainer from "../../components/AnimatedContainer/AnimatedContai
import { setUser } from "../../features/redux/slices/UserSlice/UserSlice"; import { setUser } from "../../features/redux/slices/UserSlice/UserSlice";
import { setOnboarding } from "../../features/redux/slices/StatusSlice/StatusSlice"; import { setOnboarding } from "../../features/redux/slices/StatusSlice/StatusSlice";
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import { useToast } from "react-native-toast-notifications";
export default function Revalidation() { export default function Revalidation() {
const dispatch = useDispatch(); const dispatch = useDispatch();
const navigation = useNavigation<RootDrawerParamList>(); const navigation = useNavigation<RootDrawerParamList>();
const [state, setState] = useState("Checking for existing session"); const [state, setState] = useState("Checking for existing session");
const toast = useToast();
useEffect(() => { useEffect(() => {
setState("Previous session found"); setState("Previous session found");
TokenRefresh().then(async (response) => { TokenRefresh().then(async (response) => {
let user_info = await UserInfo(); let user_info = await GetUserInfo();
if (response && user_info[0]) { if (response && user_info[0]) {
dispatch(login()); dispatch(login());
dispatch(setUser(user_info[1])); dispatch(setUser(user_info[1]));
if ( if (
!( !user_info[1].year_level ||
user_info[1].year_level || !user_info[1].course ||
user_info[1].course || !user_info[1].semester
user_info[1].semester
)
) { ) {
dispatch(setOnboarding()); dispatch(setOnboarding());
toast.show("Previous session restored", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
await setTimeout(() => { await setTimeout(() => {
navigation.navigate("Onboarding"); navigation.navigate("Onboarding");
}, 700); }, 700);
} else { } else {
dispatch(unsetOnboarding()); dispatch(unsetOnboarding());
toast.show("Previous session restored", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
await setTimeout(() => { await setTimeout(() => {
navigation.navigate("Home"); navigation.navigate("Home");
}, 700); }, 700);
} }
} else { } else {
await setState("Session expired"); await setState("Session expired");
toast.show("Session expired. Please login again", {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
await setTimeout(() => { await setTimeout(() => {
AsyncStorage.clear(); AsyncStorage.clear();
navigation.navigate("Login"); navigation.navigate("Login");

View file

@ -0,0 +1,204 @@
import * as React from "react";
import styles, { Viewport } from "../../styles";
import { View, Text, ToastAndroid } from "react-native";
import { useState } from "react";
import {
UserInfoReturnType,
OptionType,
RootDrawerParamList,
StudentStatusType,
StudentStatusReturnType,
StudentStatusPatchType,
} from "../../interfaces/Interfaces";
import Button from "../../components/Button/Button";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
PatchStudentStatus,
GetUserInfo,
ParseError,
} from "../../components/Api/Api";
import { colors } from "../../styles";
import DropDownPicker from "react-native-dropdown-picker";
import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll";
import { urlProvider } from "../../components/Api/Api";
import MapView, { UrlTile, Marker } from "react-native-maps";
import { useNavigation } from "@react-navigation/native";
import { useToast } from "react-native-toast-notifications";
export default function StartStudying({ route }: any) {
const { location } = route.params;
const queryClient = useQueryClient();
const navigation = useNavigation<RootDrawerParamList>();
const toast = useToast();
// Subject choices
const [selected_subject, setSelectedSubject] = useState("");
const [subjectsOpen, setSubjectsOpen] = useState(false);
const [subjects, setSubjects] = useState<OptionType[]>([]);
const StudentInfo = useQuery({
queryKey: ["user"],
queryFn: async () => {
const data = await GetUserInfo();
if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data: UserInfoReturnType) => {
let subjects = data[1].subjects.map((subject: string) => ({
label: subject,
value: subject,
}));
setSubjects(subjects);
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
});
const mutation = useMutation({
mutationFn: async (info: StudentStatusPatchType) => {
const data = await PatchStudentStatus(info);
if (data[0] == false) {
return Promise.reject(new Error(JSON.stringify(data[1])));
}
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: ["user_status"] });
toast.show("You are now studying \n" + selected_subject, {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
navigation.navigate("Home");
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
});
if (location && location.coords) {
return (
<View style={styles.background}>
<AnimatedContainerNoScroll>
<View style={{ zIndex: -1 }}>
<View style={styles.padding} />
<MapView
style={{
height: Viewport.height * 0.4,
width: Viewport.width * 0.8,
alignSelf: "center",
}}
customMapStyle={[
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
]}
mapType="none"
scrollEnabled={false}
zoomEnabled={false}
toolbarEnabled={false}
rotateEnabled={false}
minZoomLevel={18}
initialRegion={{
latitude: location.coords.latitude,
longitude: location.coords.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
loadingBackgroundColor={colors.secondary_2}
>
<UrlTile
urlTemplate={urlProvider}
shouldReplaceMapContent={true}
maximumZ={19}
flipY={false}
zIndex={1}
/>
<Marker
coordinate={{
latitude: location.coords.latitude,
longitude: location.coords.longitude,
}}
pinColor={colors.primary_1}
/>
</MapView>
<View style={styles.padding} />
</View>
<DropDownPicker
zIndex={1000}
max={16}
open={subjectsOpen}
value={selected_subject}
items={subjects}
setOpen={(open) => {
setSubjectsOpen(open);
}}
setValue={setSelectedSubject}
placeholderStyle={{
...styles.text_white_tiny_bold,
...{ textAlign: "left" },
}}
placeholder="Select subject"
multipleText="Select subject"
style={styles.input}
textStyle={{
...styles.text_white_tiny_bold,
...{ textAlign: "left" },
}}
modalContentContainerStyle={{
backgroundColor: colors.primary_2,
borderWidth: 0,
zIndex: 1000,
}}
autoScroll
dropDownDirection="BOTTOM"
listMode="MODAL"
/>
<View style={styles.padding} />
<Button
onPress={() => {
console.log({
subject: selected_subject,
location: {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
},
});
mutation.mutate({
active: true,
subject: selected_subject,
location: {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
},
});
}}
>
<Text style={styles.text_white_small}>Start Studying</Text>
</Button>
<View style={styles.padding} />
</AnimatedContainerNoScroll>
</View>
);
}
return <View />;
}

View file

@ -1,42 +1,60 @@
import * as React from "react"; import * as React from "react";
import styles from "../../styles"; import styles from "../../styles";
import { View, Text } from "react-native";
import { useState } from "react";
import { import {
View, UserInfoReturnType,
Text, SubjectsReturnType,
TextInput, SubjectType,
NativeSyntheticEvent,
TextInputChangeEventData,
} from "react-native";
import { useEffect, useState } from "react";
import {
SemesterParams,
UserInfoParams,
Semester,
SubjectParams,
Subject,
YearLevel,
Course,
OptionType, OptionType,
Subjects, StudentStatusType,
PatchUserInfoType,
StudentStatusPatchType,
} from "../../interfaces/Interfaces"; } from "../../interfaces/Interfaces";
import Button from "../../components/Button/Button"; import Button from "../../components/Button/Button";
import { Image } from "react-native"; import { Image } from "react-native";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { import {
GetCourses,
GetSemesters,
GetSubjects, GetSubjects,
GetYearLevels,
PatchUserInfo, PatchUserInfo,
UserInfo, GetUserInfo,
PatchStudentStatus,
} from "../../components/Api/Api"; } from "../../components/Api/Api";
import { colors } from "../../styles"; import { colors } from "../../styles";
import DropDownPicker from "react-native-dropdown-picker"; import DropDownPicker from "react-native-dropdown-picker";
import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll"; import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll";
import BouncyCheckbox from "react-native-bouncy-checkbox"; import { useSelector } from "react-redux";
import { RootState } from "../../features/redux/Store/Store";
import { useToast } from "react-native-toast-notifications";
export default function SubjectsPage() { export default function SubjectsPage() {
const logged_in_user = useSelector((state: RootState) => state.user.user);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const toast = useToast();
// Student Status
const studentstatus_mutation = useMutation({
mutationFn: async (info: StudentStatusPatchType) => {
const data = await PatchStudentStatus(info);
if (data[0] != true) {
return Promise.reject(new Error());
}
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: ["user_status"] });
},
onError: () => {
toast.show("An error has occured\nChanges have not been saved", {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
});
// User Info // User Info
const [user, setUser] = useState({ const [user, setUser] = useState({
first_name: "", first_name: "",
@ -49,17 +67,18 @@ export default function SubjectsPage() {
course_shortname: "", course_shortname: "",
avatar: "", avatar: "",
student_id_number: "", student_id_number: "",
subjects: [] as Subjects, subjects: [] as string[],
});
const [displayName, setDisplayName] = useState({
first_name: "",
last_name: "",
}); });
const StudentInfo = useQuery({ const StudentInfo = useQuery({
queryKey: ["user"], queryKey: ["user"],
queryFn: UserInfo, queryFn: async () => {
onSuccess: (data: UserInfoParams) => { const data = await GetUserInfo();
// console.log(data[1]); if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data: UserInfoReturnType) => {
setUser({ setUser({
...user, ...user,
first_name: data[1].first_name, first_name: data[1].first_name,
@ -71,31 +90,50 @@ export default function SubjectsPage() {
student_id_number: data[1].student_id_number, student_id_number: data[1].student_id_number,
subjects: data[1].subjects, subjects: data[1].subjects,
}); });
setDisplayName({ setSelectedSubjects(data[1].subjects);
first_name: data[1].first_name, },
last_name: data[1].last_name, onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
}); });
setSelectedSubjects(user.subjects);
}, },
}); });
const mutation = useMutation({ const mutation = useMutation({
mutationFn: PatchUserInfo, mutationFn: async (info: PatchUserInfoType) => {
const data = await PatchUserInfo(info);
if (data[0] != true) {
return Promise.reject(new Error());
}
return data;
},
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user"] }); queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: ["subjects", viewAll] }); queryClient.invalidateQueries({ queryKey: ["subjects"] });
setSelectedSubjects([]); setSelectedSubjects([]);
// Reset student status when changing user info to prevent bugs
studentstatus_mutation.mutate({
active: false,
});
toast.show("Changes applied successfully.\nStudent status reset", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
}, },
}); });
// View all Subjects or only view those under current course, year level, and semester
// This is for irregular students
const [viewAll, setViewAll] = useState(false);
// If viewing all subjects, refresh the choices
useEffect(() => {
queryClient.invalidateQueries({ queryKey: ["subjects", viewAll] });
}, [viewAll]);
// Subjects // Subjects
const [selected_subjects, setSelectedSubjects] = useState<any>([]); const [selected_subjects, setSelectedSubjects] = useState<any>([]);
@ -104,42 +142,31 @@ export default function SubjectsPage() {
const Subjects = useQuery({ const Subjects = useQuery({
enabled: StudentInfo.isFetched, enabled: StudentInfo.isFetched,
queryKey: ["subjects", viewAll], queryKey: ["subjects"],
queryFn: async () => { queryFn: async () => {
let data; const data = await GetSubjects();
if ( if (data[0] == false) {
StudentInfo.data && return Promise.reject(new Error(JSON.stringify(data[1])));
StudentInfo.data[1].course_shortname &&
StudentInfo.data[1].yearlevel_shortname &&
StudentInfo.data[1].semester_shortname
) {
data = await GetSubjects(
viewAll,
StudentInfo.data[1].course_shortname,
StudentInfo.data[1].yearlevel_shortname,
StudentInfo.data[1].semester_shortname
);
console.log(JSON.stringify(data));
}
if (data) {
if (!data[0]) {
throw new Error("Error with query" + data[1]);
}
if (!data[1]) {
throw new Error("User has no course, year level, or semester!");
}
// console.log("Subjects available:", data[1]);
} }
return data; return data;
}, },
onSuccess: (data: SubjectParams) => { onSuccess: (data: SubjectsReturnType) => {
let subjectsData = data[1].map((subject: Subject) => ({ if (data[1]) {
label: subject.name, let subjects = data[1].map((subject: SubjectType) => ({
value: subject.name, label: subject.name,
})); value: subject.name,
// Update the 'subjects' state }));
setSelectedSubjects(user.subjects);
setSubjects(subjectsData); setSubjects(subjects);
}
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
}, },
}); });
@ -163,9 +190,9 @@ export default function SubjectsPage() {
<View style={styles.flex_row}> <View style={styles.flex_row}>
<Avatar /> <Avatar />
<Text style={{ ...styles.text_white_small, ...{ marginLeft: 16 } }}> <Text style={{ ...styles.text_white_small, ...{ marginLeft: 16 } }}>
{(displayName.first_name || "Undefined") + {(logged_in_user.first_name || "Undefined") +
" " + " " +
(displayName.last_name || "User") + (logged_in_user.last_name || "User") +
"\n" + "\n" +
user.student_id_number} user.student_id_number}
</Text> </Text>
@ -211,29 +238,17 @@ export default function SubjectsPage() {
</View> </View>
</View> </View>
<View style={{ zIndex: -1 }}> <View style={{ zIndex: -1 }}>
<View style={styles.padding} />
<View style={styles.flex_row}>
<BouncyCheckbox
onPress={() => {
setViewAll(!viewAll);
setSubjectsOpen(false);
}}
fillColor={colors.secondary_3}
/>
<Text style={styles.text_white_small}>Irregular </Text>
</View>
<View style={styles.padding} /> <View style={styles.padding} />
<Button <Button
onPress={() => { onPress={() => {
setSelectedSubjects([]);
setSubjectsOpen(!subjectsOpen);
mutation.mutate({ mutation.mutate({
subjects: selected_subjects, subjects: selected_subjects,
}); });
}} }}
> >
<Text style={styles.text_white_small}>Save Change</Text> <Text style={styles.text_white_small}>Save Changes</Text>
</Button> </Button>
<View style={styles.padding} />
</View> </View>
</AnimatedContainerNoScroll> </AnimatedContainerNoScroll>
</View> </View>

View file

@ -6,18 +6,19 @@ import {
TextInput, TextInput,
NativeSyntheticEvent, NativeSyntheticEvent,
TextInputChangeEventData, TextInputChangeEventData,
Pressable,
} from "react-native"; } from "react-native";
import { useState } from "react"; import { useState } from "react";
import { import {
SemesterParams, SemesterReturnType,
UserInfoParams, UserInfoReturnType,
Semester, SemesterType,
SubjectParams, YearLevelType,
Subject, CourseType,
YearLevel,
Course,
OptionType, OptionType,
Subjects, StudentStatusType,
PatchUserInfoType,
StudentStatusPatchType,
} from "../../interfaces/Interfaces"; } from "../../interfaces/Interfaces";
import Button from "../../components/Button/Button"; import Button from "../../components/Button/Button";
import { Image } from "react-native"; import { Image } from "react-native";
@ -25,18 +26,52 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { import {
GetCourses, GetCourses,
GetSemesters, GetSemesters,
GetSubjects,
GetYearLevels, GetYearLevels,
PatchStudentStatus,
PatchUserInfo, PatchUserInfo,
UserInfo, GetUserInfo,
} from "../../components/Api/Api"; } from "../../components/Api/Api";
import { colors } from "../../styles"; import { colors } from "../../styles";
import DropDownPicker from "react-native-dropdown-picker"; import DropDownPicker from "react-native-dropdown-picker";
import { ValueType } from "react-native-dropdown-picker";
import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll"; import AnimatedContainerNoScroll from "../../components/AnimatedContainer/AnimatedContainerNoScroll";
import BouncyCheckbox from "react-native-bouncy-checkbox";
import { useSelector } from "react-redux";
import { RootState } from "../../features/redux/Store/Store";
import { useDispatch } from "react-redux";
import { setUser as setUserinState } from "../../features/redux/slices/UserSlice/UserSlice";
import * as ImagePicker from "expo-image-picker";
import * as FileSystem from "expo-file-system";
import { useToast } from "react-native-toast-notifications";
export default function UserInfoPage() { export default function UserInfoPage() {
const logged_in_user = useSelector((state: RootState) => state.user.user);
const dispatch = useDispatch();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const toast = useToast();
// Student Status
const studentstatus_mutation = useMutation({
mutationFn: async (info: StudentStatusPatchType) => {
const data = await PatchStudentStatus(info);
if (data[0] != true) {
return Promise.reject(new Error());
}
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: ["user_status"] });
},
onError: () => {
toast.show("An error has occured\nChanges have not been saved", {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
});
// User Info // User Info
const [user, setUser] = useState({ const [user, setUser] = useState({
first_name: "", first_name: "",
@ -49,15 +84,18 @@ export default function UserInfoPage() {
course_shortname: "", course_shortname: "",
avatar: "", avatar: "",
student_id_number: "", student_id_number: "",
}); irregular: false,
const [displayName, setDisplayName] = useState({
first_name: "",
last_name: "",
}); });
const StudentInfo = useQuery({ const StudentInfo = useQuery({
queryKey: ["user"], queryKey: ["user"],
queryFn: UserInfo, queryFn: async () => {
onSuccess: (data: UserInfoParams) => { const data = await GetUserInfo();
if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data: UserInfoReturnType) => {
// console.log(data[1]); // console.log(data[1]);
setUser({ setUser({
...user, ...user,
@ -66,23 +104,55 @@ export default function UserInfoPage() {
year_level: data[1].year_level, year_level: data[1].year_level,
semester: data[1].semester, semester: data[1].semester,
course: data[1].course, course: data[1].course,
avatar: data[1].avatar,
student_id_number: data[1].student_id_number, student_id_number: data[1].student_id_number,
}); irregular: data[1].irregular,
setDisplayName({ avatar: data[1].avatar,
first_name: data[1].first_name,
last_name: data[1].last_name,
}); });
setSelectedCourse(data[1].course); setSelectedCourse(data[1].course);
setSelectedSemester(data[1].semester); setSelectedSemester(data[1].semester);
setSelectedYearLevel(data[1].year_level); setSelectedYearLevel(data[1].year_level);
dispatch(setUserinState(data[1]));
},
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
}, },
}); });
const mutation = useMutation({ const mutation = useMutation({
mutationFn: PatchUserInfo, mutationFn: async (info: PatchUserInfoType) => {
const data = await PatchUserInfo(info);
if (data[0] == false) {
return Promise.reject(new Error());
}
return data;
},
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user"] }); queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: ["subjects"] }); queryClient.invalidateQueries({ queryKey: ["subjects"] });
// Reset student status when changing user info to prevent bugs
studentstatus_mutation.mutate({
active: false,
});
toast.show("Changes applied successfully.\nStudent status reset", {
type: "success",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
dispatch(setUserinState(user));
},
onError: () => {
toast.show("An error has occured\nChanges have not been saved", {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
}, },
}); });
@ -92,9 +162,15 @@ export default function UserInfoPage() {
const [semesters, setSemesters] = useState<OptionType[]>([]); const [semesters, setSemesters] = useState<OptionType[]>([]);
const Semesters = useQuery({ const Semesters = useQuery({
queryKey: ["semesters"], queryKey: ["semesters"],
queryFn: GetSemesters, queryFn: async () => {
onSuccess: (data: SemesterParams) => { const data = await GetSemesters();
let semestersData = data[1].map((semester: Semester) => ({ if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data: SemesterReturnType) => {
let semestersData = data[1].map((semester: SemesterType) => ({
label: semester.name, label: semester.name,
value: semester.name, value: semester.name,
shortname: semester.shortname, shortname: semester.shortname,
@ -102,6 +178,14 @@ export default function UserInfoPage() {
// Update the 'semesters' state // Update the 'semesters' state
setSemesters(semestersData); setSemesters(semestersData);
}, },
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
}); });
// Year Level // Year Level
@ -110,14 +194,28 @@ export default function UserInfoPage() {
const [year_levels, setYearLevels] = useState<OptionType[]>([]); const [year_levels, setYearLevels] = useState<OptionType[]>([]);
const yearlevel_query = useQuery({ const yearlevel_query = useQuery({
queryKey: ["year_levels"], queryKey: ["year_levels"],
queryFn: GetYearLevels, queryFn: async () => {
const data = await GetYearLevels();
if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data) => { onSuccess: (data) => {
let year_levels = data[1].map((yearlevel: YearLevel) => ({ let year_levels = data[1].map((yearlevel: YearLevelType) => ({
label: yearlevel.name, label: yearlevel.name,
value: yearlevel.name, value: yearlevel.name,
})); }));
setYearLevels(year_levels); setYearLevels(year_levels);
}, },
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
}); });
// Course // Course
@ -126,27 +224,64 @@ export default function UserInfoPage() {
const [courses, setCourses] = useState<OptionType[]>([]); const [courses, setCourses] = useState<OptionType[]>([]);
const course_query = useQuery({ const course_query = useQuery({
queryKey: ["courses"], queryKey: ["courses"],
queryFn: GetCourses, queryFn: async () => {
const data = await GetCourses();
if (data[0] == false) {
return Promise.reject(new Error(data[1]));
}
return data;
},
onSuccess: (data) => { onSuccess: (data) => {
let courses = data[1].map((course: Course) => ({ let courses = data[1].map((course: CourseType) => ({
label: course.name, label: course.name,
value: course.name, value: course.name,
})); }));
setCourses(courses); setCourses(courses);
}, },
onError: (error: Error) => {
toast.show(String(error), {
type: "warning",
placement: "top",
duration: 2000,
animationType: "slide-in",
});
},
}); });
// Toggle editing of profile
const [isEditable, setIsEditable] = useState(false);
// Profile photo // Profile photo
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.canceled) {
const encodedImage = await FileSystem.readAsStringAsync(
result.assets[0].uri,
{ encoding: "base64" }
);
mutation.mutate({
avatar: encodedImage,
});
}
};
function Avatar() { function Avatar() {
if (user.avatar) { if (user.avatar) {
return <Image source={{ uri: user.avatar }} style={styles.profile} />; return (
<Pressable onPress={pickImage}>
<Image source={{ uri: user.avatar }} style={styles.profile} />
</Pressable>
);
} else { } else {
return ( return (
<Image <Pressable onPress={pickImage}>
source={require("../../img/user_profile_placeholder.png")} <Image
style={{ ...styles.profile, ...{ marginRight: 48 } }} source={require("../../img/user_profile_placeholder.png")}
/> style={{ ...styles.profile, ...{ marginRight: 48 } }}
/>
</Pressable>
); );
} }
} }
@ -157,9 +292,9 @@ export default function UserInfoPage() {
<View style={styles.flex_row}> <View style={styles.flex_row}>
<Avatar /> <Avatar />
<Text style={{ ...styles.text_white_small, ...{ marginLeft: 16 } }}> <Text style={{ ...styles.text_white_small, ...{ marginLeft: 16 } }}>
{(displayName.first_name || "Undefined") + {(logged_in_user.first_name || "Undefined") +
" " + " " +
(displayName.last_name || "User") + (logged_in_user.last_name || "User") +
"\n" + "\n" +
user.student_id_number} user.student_id_number}
</Text> </Text>
@ -173,7 +308,6 @@ export default function UserInfoPage() {
<View style={{ flex: 3 }}> <View style={{ flex: 3 }}>
<TextInput <TextInput
style={styles.input} style={styles.input}
editable={isEditable}
onChange={( onChange={(
e: NativeSyntheticEvent<TextInputChangeEventData> e: NativeSyntheticEvent<TextInputChangeEventData>
): void => { ): void => {
@ -190,7 +324,6 @@ export default function UserInfoPage() {
<View style={{ flex: 3 }}> <View style={{ flex: 3 }}>
<TextInput <TextInput
style={styles.input} style={styles.input}
editable={isEditable}
onChange={( onChange={(
e: NativeSyntheticEvent<TextInputChangeEventData> e: NativeSyntheticEvent<TextInputChangeEventData>
): void => { ): void => {
@ -206,7 +339,6 @@ export default function UserInfoPage() {
</View> </View>
<View style={{ flex: 3 }}> <View style={{ flex: 3 }}>
<DropDownPicker <DropDownPicker
disabled={!isEditable}
zIndex={4000} zIndex={4000}
open={yearLevelOpen} open={yearLevelOpen}
value={selected_yearlevel} value={selected_yearlevel}
@ -242,7 +374,6 @@ export default function UserInfoPage() {
</View> </View>
<View style={{ flex: 3 }}> <View style={{ flex: 3 }}>
<DropDownPicker <DropDownPicker
disabled={!isEditable}
zIndex={3000} zIndex={3000}
open={semesterOpen} open={semesterOpen}
value={selected_semester} value={selected_semester}
@ -278,7 +409,6 @@ export default function UserInfoPage() {
</View> </View>
<View style={{ flex: 3 }}> <View style={{ flex: 3 }}>
<DropDownPicker <DropDownPicker
disabled={!isEditable}
zIndex={2000} zIndex={2000}
open={courseOpen} open={courseOpen}
value={selected_course} value={selected_course}
@ -310,27 +440,37 @@ export default function UserInfoPage() {
</View> </View>
<View style={styles.padding} /> <View style={styles.padding} />
<View style={{ zIndex: -1 }}> <View style={{ zIndex: -1 }}>
<View style={{ ...styles.flex_row, ...{ alignSelf: "center" } }}>
<BouncyCheckbox
onPress={() => {
mutation.mutate({
irregular: !user.irregular,
});
setUser({ ...user, irregular: !user.irregular });
}}
isChecked={user.irregular}
disableBuiltInState
fillColor={colors.secondary_3}
/>
<Text style={styles.text_white_small}>Irregular </Text>
</View>
<Button <Button
onPress={() => { onPress={() => {
if (isEditable) { setYearLevelOpen(false);
setYearLevelOpen(false); setSemesterOpen(false);
setSemesterOpen(false); setCourseOpen(false);
setCourseOpen(false); mutation.mutate({
mutation.mutate({ first_name: user.first_name,
first_name: user.first_name, last_name: user.last_name,
last_name: user.last_name, course: selected_course,
course: selected_course, semester: selected_semester,
semester: selected_semester, year_level: selected_yearlevel,
year_level: selected_yearlevel, });
});
}
setIsEditable(!isEditable);
}} }}
> >
<Text style={styles.text_white_small}> <Text style={styles.text_white_small}>Save Changes</Text>
{isEditable && StudentInfo.isSuccess ? "Save" : "Edit Profile"}
</Text>
</Button> </Button>
<View style={styles.padding} />
</View> </View>
</AnimatedContainerNoScroll> </AnimatedContainerNoScroll>
</View> </View>

View file

@ -171,7 +171,8 @@ const styles = StyleSheet.create({
width: "70%", width: "70%",
}, },
map: { map: {
height: Viewport.height * 0.8, marginVertical: 4,
height: Viewport.height * 0.7,
width: Viewport.width * 0.8, width: Viewport.width * 0.8,
alignSelf: "center", alignSelf: "center",
}, },
@ -182,6 +183,8 @@ const styles = StyleSheet.create({
borderRadius: 150 / 2, borderRadius: 150 / 2,
overflow: "hidden", overflow: "hidden",
padding: 0, padding: 0,
borderColor: colors.primary_2,
borderWidth: 3,
}, },
input: { input: {
paddingHorizontal: 8, paddingHorizontal: 8,