Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Onboard Sync #50

Merged
merged 2 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 12 additions & 14 deletions backend/course.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,13 @@ def to_dict(self):

def distill_dacourses(data):
dacourses = {}
for table in data["coursestable"]:
for raw in table["courses"]:
season, year = raw["term"].split()
season_map = { "Spring": "01", "Fall": "03" }
raw["term"] = f"{year}{season_map.get(season)}"
dacourses[raw["id"]] = raw
season_map = {"Spring": "01", "Fall": "03"}

for c in data["courses"]:
season, year = c["term"].split()
c["term"] = f"{year}{season_map.get(season)}"
dacourses[c["code"]] = c # Assuming course code is unique

dacourses = list(dacourses.values())

grouped_dacourses = defaultdict(list)
Expand All @@ -55,12 +56,12 @@ def distill_dacourses(data):

consolidate = []
for group in grouped_dacourses:
result = coursify(group)
result = coursify(group) # Assuming coursify is a function you defined
if result:
consolidate.extend(result)

all = [studentCourse.to_dict() for studentCourse in consolidate]
return all
all_courses = [studentCourse.to_dict() for studentCourse in consolidate]
return all_courses


def coursify(dacourses):
Expand All @@ -78,23 +79,20 @@ def coursify(dacourses):
student_courses = []
for dacourse in dacourses:
# Course Portion
offering = next((c for c in response.json() if c["course_code"] == dacourse["id"]), None)
offering = next((c for c in response.json() if c["course_code"] == dacourse["code"]), None)
if not offering:
continue

codes = [l["course_code"] for l in offering["course"]["listings"]]
title = offering["course"]["title"]
credit = int(dacourse["credit"].strip("()"))
credit = int(dacourse["credits"])
areas = offering["course"]["areas"]
skills = offering["course"]["skills"]
seasons = ["Fall", "Spring"]
course = Course(codes, title, credit, areas, skills, seasons)

# StudentCourse Portion
status = dacourse["status"]
if status not in {"IP", "PROSPECTIVE", "W"}:
status = "COMPLETE"

student_courses.append(StudentCourse(course, status, key))

return student_courses
Expand Down
54 changes: 44 additions & 10 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,24 @@
from flask_cors import cross_origin

# Ryan
from year import *
from course import *

cred = credentials.Certificate(r'secrets/majoraudit-firebase-adminsdk-bc6kc-6e9544580c.json')
app = firebase_admin.initialize_app(cred)

db = firestore.client()

allowed_CORS_origins=['http://127.0.0.1:3000', 'http://127.0.0.1:3000/graduation', 'http://127.0.0.1:5000', 'majoraudit.web.app']
allowed_CORS_origins=['http://127.0.0.1:3000', 'http://127.0.0.1:3000/graduation', 'http://127.0.0.1:3000/courses', 'http://127.0.0.1:3000/onboard', 'http://127.0.0.1:5000']

class User:
def __init__(self, netID, onboard, name, degrees, studentCourses, yearTree):
def __init__(self, netID, onboard, name, degrees, studentCourses, language):
self.netID = netID
self.onboard = onboard
self.name = name
self.degrees = degrees
self.studentCourses = studentCourses
self.yearTree = yearTree
self.language = language


app = Flask(__name__, template_folder='templates')
CORS(app, supports_credentials=True, origins=allowed_CORS_origins)
Expand Down Expand Up @@ -91,8 +91,8 @@ def login():
onboard=False,
name="",
degrees=[],
studentCourses=[],
yearTree=[]
studentCourses=[],
language=""
)
db.collection("Users").document(netID).set(new_user.__dict__)

Expand Down Expand Up @@ -123,6 +123,30 @@ def logout():
@app.get('/sync')
def sync():
True






@app.get("/CT_Courses")
def get_ct_courses():
key = request.args.get('key')
if not key:
return jsonify({"error": "Missing Param"}), 400

cookies = {
'session': 'enter_session_here',
'session.sig': 'enter_session_sig_here'
}
url = f"https://api.coursetable.com/api/catalog/public/{key}"

try:
response = requests.get(url, cookies=cookies)
response.raise_for_status()
return jsonify(response.json())
except requests.exceptions.RequestException as e:
return jsonify({"Error": str(e)}), 500


@app.get('/check_login')
Expand Down Expand Up @@ -192,19 +216,26 @@ def sync_data():

# Check
data = request.json
required_fields = ["name", "degree", "major", "coursestable"]
required_fields = ["name", "degrees", "courses", "language"]
if not data or not all(field in data for field in required_fields):
return make_response(jsonify({"Error": "Invalid Data"}), 400)

# Process
courses = distill_dacourses(data)
year_tree = year_treeify(courses)
studentCourses = distill_dacourses(data)

# Store
user = User(loc_netid, data["name"].split(" ")[1], data["degree"], data["major"], courses, year_tree, data["coursestable"])
user = User(
netID=loc_netid,
onboard=True,
name=data["name"],
degrees=data["degrees"],
studentCourses=studentCourses,
language=data["language"],
)
db.collection("Users").document(loc_netid).set(user.__dict__)

# Transfer
# return jsonify({"loggedIn": True, "onboard": True}
return make_response(jsonify(data), 200)


Expand Down Expand Up @@ -254,3 +285,6 @@ def hello_world(req: https_fn.Request) -> https_fn.Response:
response = https_fn.Response('hello world')
return response




67 changes: 0 additions & 67 deletions backend/year.py

This file was deleted.

13 changes: 8 additions & 5 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import Graduation from './pages/Graduation';
import Courses from './pages/Courses';
import Majors from './pages/Majors';

import { ImportSC } from "./commons/mock/MockStudent";
import { StudentCourse } from "./commons/types/TypeCourse";

function App(){

const [auth, setAuth] = useState({ loggedIn: false, onboard: false });
Expand All @@ -24,7 +27,7 @@ function App(){
};

useEffect(() => {
// checkAuth();
checkAuth();
}, []);

const ProtectedRoute = (element: JSX.Element) => {
Expand All @@ -37,17 +40,17 @@ function App(){
return element;
};

const [GlobalSC, setGlobalSC] = useState<StudentCourse[]>(ImportSC);

return(
<div>
<Globals>
<Routes>
<Route path="/onboard" element={<Onboard setAuth={setAuth}/>}/>

<Route path="/" element={<Navigate to="/graduation"/>}/>
<Route path="/login" element={!auth.loggedIn ? <Login setAuth={setAuth}/> : <Navigate to="/onboard"/>}/>
{/* <Route path="/onboard" element={!auth.onboard ? <Onboard setAuth={setAuth}/> : <Navigate to="/graduation"/>}/> */}
<Route path="/onboard" element={!auth.onboard ? <Onboard setAuth={setAuth} checkAuth={checkAuth}/> : <Navigate to="/graduation"/>}/>
<Route path="/graduation" element={ProtectedRoute(<Graduation/>)}/>
<Route path="/courses" element={ProtectedRoute(<Courses/>)}/>
<Route path="/courses" element={ProtectedRoute(<Courses GlobalSC={GlobalSC} setGlobalSC={setGlobalSC}/>)}/>
<Route path="/majors" element={ProtectedRoute(<Majors/>)}/>
</Routes>
<CourseModal/>
Expand Down
54 changes: 30 additions & 24 deletions frontend/src/api/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const checkUser = (): Promise<{ loggedIn: boolean; onboard: boolean }> =>
};

// syncData()
export const syncData = () => {
export const initExtension = () => {
var event = new CustomEvent("scrapeData", {
detail: { action: "openWebsite" }
});
Expand All @@ -53,6 +53,24 @@ export const getData = () => {
});
};

export const syncData = (data: string) => {
return new Promise((resolve, reject) => {
$.ajax({
url: "http://127.0.0.1:5001/majoraudit/us-central1/functions/sync_data",
method: "POST",
contentType: "application/json",
data: JSON.stringify(data),
xhrFields: { withCredentials: true }
}).done((response) => {
resolve(response);
}).fail((error) => {
reject(error);
});
});
};



export const getMajors = () => {
return new Promise((resolve, reject) => {
$.ajax({
Expand All @@ -70,27 +88,15 @@ export const getMajors = () => {
//

export const getCTCourses = (timekey: string): Promise<any> => {
return new Promise((resolve, reject) => {
const url = `https://api.coursetable.com/api/catalog/public/${timekey}`;
// const cookies = {
// 'session': 'enter_session_here',
// 'session.sig': 'enter_session_sig_here'
// };

$.ajax({
url: url,
method: "GET",
// headers: {
// 'Cookie': `session=${cookies.session}; session.sig=${cookies['session.sig']}`
// }
}).done((data) => {
resolve(data);
}).fail((jqXHR, textStatus) => {
if (jqXHR.status !== 200) {
reject(new Error(`${timekey} ${jqXHR.status}`));
} else {
reject(new Error(`Error: ${textStatus}`));
}
});
});
return new Promise((resolve, reject) => {
$.ajax({
url: `http://127.0.0.1:5001/majoraudit/us-central1/functions/CT_Courses?key=${timekey}`,
method: "GET",
xhrFields: { withCredentials: true }
}).done((data: any) => {
resolve(data);
}).fail((error) => {
reject(error);
});
});
};
Loading
Loading