Skip to content

Commit

Permalink
Working on removing duplication in code
Browse files Browse the repository at this point in the history
Pair-Programmed With @avichaljadeja2002
  • Loading branch information
rhit-villencr committed Jan 15, 2025
1 parent ab45dfe commit a227da9
Show file tree
Hide file tree
Showing 26 changed files with 328 additions and 404 deletions.
4 changes: 2 additions & 2 deletions app/addCalendarEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import axios from 'axios';
import { IPAddr, repeatingData } from './constants';
import GenericAddPageForm from './addEventPage';
import { IPAddr, repeatingData } from '../constants/constants';
import GenericAddPageForm from './genericAddEventPage';
import { cLog } from './log'

export default function AddCalendarEvents() {
Expand Down
4 changes: 2 additions & 2 deletions app/addFinanceEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import axios from 'axios';
import { IPAddr, repeatingData } from './constants';
import GenericAddPageForm from './addEventPage';
import { IPAddr, repeatingData } from '../constants/constants';
import GenericAddPageForm from './genericAddEventPage';
import { cLog } from './log'

export default function AddFinanceEvents() {
Expand Down
4 changes: 2 additions & 2 deletions app/addHealthEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import axios from 'axios';
import { IPAddr, repeatingData } from './constants';
import GenericAddPageForm from './addEventPage';
import { IPAddr, repeatingData } from '../constants/constants';
import GenericAddPageForm from './genericAddEventPage';
import { cLog } from './log'

export default function AddHealthEvents() {
Expand Down
4 changes: 2 additions & 2 deletions app/addMeals.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react'
import axios from 'axios';
import { IPAddr, repeatingData } from './constants';
import GenericAddPageForm from './addEventPage';
import { IPAddr, repeatingData } from '../constants/constants';
import GenericAddPageForm from './genericAddEventPage';
import { cLog } from './log'
import AsyncStorage from '@react-native-async-storage/async-storage';

Expand Down
2 changes: 1 addition & 1 deletion app/another.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import { View, Text } from 'react-native';
import { styles } from './styles';
import { styles } from '../assets/styles/styles';

export default function AnotherScreen() {
return (
Expand Down
86 changes: 18 additions & 68 deletions app/calendarEvents.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import React, { useState, useCallback } from 'react';
import { View, Text, TouchableOpacity, Alert } from 'react-native';
import React, { useState } from 'react';
import GenericMainPageForm from './genericMainPage';
import { Alert } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as Linking from 'expo-linking';
import axios from 'axios';
import { IPAddr, formatTime } from './constants';
import { styles } from './styles';
import GenericMainPageForm from './mainPageTemplate';
import { Task } from '@/components/Types';
import { useFocusEffect } from '@react-navigation/native';
import { IPAddr } from '../constants/constants';
import { cLog } from './log'
import AsyncStorage from '@react-native-async-storage/async-storage';

const CLIENT_ID = process.env.EXPO_PUBLIC_CLIENT_ID || '';
const CLIENT_SECRET = process.env.EXPO_PUBLIC_CLIENT_SECRET || '';
Expand All @@ -20,22 +16,17 @@ const AUTH_URI = 'https://accounts.google.com/o/oauth2/v2/auth';
WebBrowser.maybeCompleteAuthSession();

export default function CalendarTracker() {
const [tasks, setTasks] = useState<Task[]>([]);
const [isGoogleCalendarLinked, setIsGoogleCalendarLinked] = useState<boolean>(false);
const [isGoogleCalendarLinked, setIsGoogleCalendarLinked] = useState(false);

const handlePress = async () => {
try {
cLog("Initiating OAuth login...");

const authUrl = `${AUTH_URI}?response_type=code&client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=https://www.googleapis.com/auth/calendar&access_type=offline&prompt=consent`;

const result = await WebBrowser.openAuthSessionAsync(authUrl, REDIRECT_URI);
cLog("WebBrowser result:" + result);

if (result.type === 'success' && result.url) {
const authCodeMatch = result.url.match(/code=([^&]*)/);
const authCode = authCodeMatch ? authCodeMatch[1] : null;

if (authCode) {
cLog("Received authorization code:" + authCode);
getAccessToken(authCode);
Expand All @@ -61,13 +52,11 @@ export default function CalendarTracker() {
params.append('client_secret', CLIENT_SECRET);
params.append('redirect_uri', REDIRECT_URI);
params.append('grant_type', 'authorization_code');

const response = await axios.post(TOKEN_URI, params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});

if (response.data.access_token) {
cLog("Received access token:" + response.data.access_token);
linkGoogleCalendar(1, response.data.access_token);
Expand All @@ -90,12 +79,11 @@ export default function CalendarTracker() {
userId: userId,
accessToken: token,
});

if (response.status === 200 && response.data.includes("successfully")) {
cLog('Google Calendar linked successfully:' + response.data);
Alert.alert('Google Calendar linked successfully!');
setIsGoogleCalendarLinked(true);
fetchEvents();
// fetchEvents();
} else {
console.error("Failed to link Google Calendar");
Alert.alert('Failed to link Google Calendar');
Expand All @@ -106,56 +94,18 @@ export default function CalendarTracker() {
}
};

const fetchEvents = async () => {
try {
const hit = `${IPAddr}/get_calendar_events/` + (await AsyncStorage.getItem('userId'));
cLog('Fetching calendar events from:' + hit);
const response = await axios.get(hit);

if (response.status === 200 && response.data) {
const { events, googleCalendarLinked } = response.data;

setIsGoogleCalendarLinked(googleCalendarLinked);
const formattedEvents = events.map((event: any) => ({
id: `${event.id}-${event.event_date}-${event.event_time}`,
title: `${event.title} at ${event.event_date}, ${formatTime(event.event_time)}`,
done: false,
icon: 'calendar-outline',
event: event
})).slice(0, 20);;

setTasks(formattedEvents);
} else {
console.error('Failed to fetch events');
}
} catch (error) {
console.error('Error fetching events:', error);
}
};


useFocusEffect(
useCallback(() => {
fetchEvents();
}, [])
);

return (
<View style={styles.bigContainer}>
<GenericMainPageForm
title='Calendar Tracker'
header='Upcoming Events'
nextPage='addCalendarEvents'
thisPage='calendarEvents'
tasks={tasks}
/>
{!isGoogleCalendarLinked && (
<View style={{ alignItems: 'center', marginBottom: 25 }}>
<TouchableOpacity style={styles.linkButton} onPress={handlePress}>
<Text style={styles.linkButtonText}>Link to Google Calendar</Text>
</TouchableOpacity>
</View>)
}
</View>
<GenericMainPageForm
title='Calendar Tracker'
nextPage='addCalendarEvents'
thisPage='calendarEvents'
hitAddress={`/get_calendar_events/`}
googleCalendar={true}
eventIdFunc={(event: any) => `${event.id}-${event.event_date}-${event.event_time}`}
eventIconFunc={() => 'calendar-outline'}
handlePress={handlePress}
isGoogleCalendarLinked={isGoogleCalendarLinked}
setIsGoogleCalendarLinked={setIsGoogleCalendarLinked}
/>
);
}
44 changes: 7 additions & 37 deletions app/finance.tsx
Original file line number Diff line number Diff line change
@@ -1,44 +1,14 @@
import { IPAddr, formatTime } from './constants';
import { Task } from '../components/Types';
import axios from 'axios';
import GenericMainPageForm from './mainPageTemplate';
import React, { useState, useCallback } from 'react';
import { useFocusEffect } from '@react-navigation/native';
import { cLog } from './log'
import AsyncStorage from '@react-native-async-storage/async-storage';
import React from 'react';
import GenericMainPageForm from './genericMainPage';

export default function FinanceTracker() {
const [tasks, setTasks] = useState<Task[]>([]);

const fetchEvents = async () => {
const hit = IPAddr + '/get_finance_events/' + (await AsyncStorage.getItem('userId'));
cLog('Fetching finance events from:' + hit);
axios.get(hit)
.then(response => {
const events = response.data.map((event: any) => ({
id: event.id.toString(),
title: `${event.title} at ${event.event_date}, ${formatTime(event.event_time)}`,
done: false,
icon: 'wallet-outline',
event: event
})).slice(0, 10);;
setTasks(events);
})
.catch(error => console.error('Error fetching events:', error));
}

useFocusEffect(
useCallback(() => {
fetchEvents();
}, [])
);

return (
<GenericMainPageForm
title='Finance Tracker'
header='Upcoming Events'
nextPage='addFinanceEvents'
thisPage='finance'
tasks={tasks}
/>);
}
hitAddress={`/get_finance_events/`}
eventIconFunc={() => 'wallet-outline'}
/>
);
}
4 changes: 2 additions & 2 deletions app/addEventPage.tsx → app/genericAddEventPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import React, { useCallback, useState } from 'react';
import { View, TextInput, Text, TouchableOpacity, ScrollView } from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import { Dropdown } from 'react-native-element-dropdown';
import { styles } from './styles';
import { styles } from '../assets/styles/styles';
import { RootStackParamList } from '@/components/Types';
import { StackNavigationProp } from '@react-navigation/stack';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import MultiSelect from 'react-native-multiple-select';
import { cLog } from './log';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { verifyToken } from './constants';
import { verifyToken } from '../constants/constants';

interface FormProps {
title: string;
Expand Down
Loading

0 comments on commit a227da9

Please sign in to comment.