Skip to content

Commit

Permalink
Code cleanup for linter
Browse files Browse the repository at this point in the history
  • Loading branch information
brok3turtl3 committed Jun 8, 2024
1 parent 59917c9 commit be2cdf8
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 123 deletions.
42 changes: 18 additions & 24 deletions client/src/pages/CreateApplicationPage/CreateApplicationPage.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useAppSelector, useAppDispatch } from "../../app/hooks";
import { createApplication } from "../../features/applications/applicationSlice";
import {
IApplication,
IStatus,
IApplicationFormData,
} from "../../../types/applications";
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useAppSelector, useAppDispatch } from '../../app/hooks';
import { createApplication } from '../../features/applications/applicationSlice';
import { IStatus, IApplicationFormData } from '../../../types/applications';

const CreateApplicationPage = (): JSX.Element => {
const user = useAppSelector((state) => state.user.userData);
const { status } = useAppSelector((state) => state.application);

const [statuses, setStatuses] = useState<IStatus[]>([]);
const [formData, setFormData] = useState<IApplicationFormData>({
title: "",
company: "",
location: "",
description: "",
url: "",
title: '',
company: '',
location: '',
description: '',
url: '',
status_id: 1,
user_id: user?._id || "",
user_id: user?._id || '',
quick_apply: false,
date_applied: new Date().toISOString().split("T")[0],
general_notes: "",
date_applied: new Date().toISOString().split('T')[0],
general_notes: '',
job_id: 0,
});

Expand All @@ -32,10 +28,10 @@ const CreateApplicationPage = (): JSX.Element => {
useEffect(() => {
async function fetchStatuses() {
try {
const response = await axios.get("/api/applications/statuses");
const response = await axios.get('/api/applications/statuses');
setStatuses(response.data);
} catch (error) {
console.error("Error fetching statuses:", error);
console.error('Error fetching statuses:', error);
}
}

Expand All @@ -49,12 +45,10 @@ const CreateApplicationPage = (): JSX.Element => {
};

const handleChange = (
e: React.ChangeEvent<
HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
>
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
) => {
const { name, value, type } = e.target;
if (type === "checkbox") {
if (type === 'checkbox') {
const checked = (e.target as HTMLInputElement).checked;
setFormData((prevFormData) => ({
...prevFormData,
Expand Down Expand Up @@ -185,7 +179,7 @@ const CreateApplicationPage = (): JSX.Element => {
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
type="submit"
>
{status === "creating" ? "Creating..." : "Create Application"}
{status === 'creating' ? 'Creating...' : 'Create Application'}
</button>
</form>
</div>
Expand Down
54 changes: 25 additions & 29 deletions client/src/pages/UpdateApplicationPage/UpdateApplicationPage.tsx
Original file line number Diff line number Diff line change
@@ -1,57 +1,55 @@
import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import axios from "axios";
import { useAppSelector, useAppDispatch } from "../../app/hooks";
import { updateApplication } from "../../features/applications/applicationSlice";
import { IApplicationFormData, IStatus } from "../../../types/applications";
import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import axios from 'axios';
import { useAppSelector, useAppDispatch } from '../../app/hooks';
import { updateApplication } from '../../features/applications/applicationSlice';
import { IApplicationFormData, IStatus } from '../../../types/applications';

const UpdateApplicationPage = (): JSX.Element => {
const { id } = useParams<{ id: string }>();
console.log("id:", id);
console.log('id:', id);
const user = useAppSelector((state) => state.user.userData);
const { application, status, error } = useAppSelector(
(state) => state.application
);
const { status } = useAppSelector((state) => state.application);
const dispatch = useAppDispatch();
const navigate = useNavigate();

const [statuses, setStatuses] = useState<IStatus[]>([]);
const [formData, setFormData] = useState<IApplicationFormData>({
title: "",
company: "",
location: "",
description: "",
url: "",
title: '',
company: '',
location: '',
description: '',
url: '',
status_id: 1,
user_id: user?._id || "",
user_id: user?._id || '',
quick_apply: false,
date_applied: new Date().toISOString().split("T")[0],
general_notes: "",
date_applied: new Date().toISOString().split('T')[0],
general_notes: '',
job_id: 0,
});

useEffect(() => {
async function fetchStatuses() {
try {
const response = await axios.get("/api/applications/statuses");
const response = await axios.get('/api/applications/statuses');
setStatuses(response.data);
} catch (error) {
console.error("Error fetching statuses:", error);
console.error('Error fetching statuses:', error);
}
}

async function fetchApplication() {
try {
console.log("HITTT!!!!!");
console.log('HITTT!!!!!');
const response = await axios.get(`/api/applications/${id}`);
const applicationData = response.data;
applicationData.date_applied = new Date(applicationData.date_applied)
.toISOString()
.split("T")[0];
.split('T')[0];

setFormData(applicationData);
} catch (error) {
console.error("Error fetching application:", error);
console.error('Error fetching application:', error);
}
}

Expand All @@ -62,16 +60,14 @@ const UpdateApplicationPage = (): JSX.Element => {
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
dispatch(updateApplication({ id: Number(id), ...formData }));
navigate("/app/applications");
navigate('/app/applications');
};

const handleChange = (
e: React.ChangeEvent<
HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
>
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
) => {
const { name, value, type } = e.target;
if (type === "checkbox") {
if (type === 'checkbox') {
const checked = (e.target as HTMLInputElement).checked;
setFormData((prevFormData) => ({
...prevFormData,
Expand Down Expand Up @@ -204,7 +200,7 @@ const UpdateApplicationPage = (): JSX.Element => {
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
type="submit"
>
{status === "updating" ? "Updating..." : "Update Application"}
{status === 'updating' ? 'Updating...' : 'Update Application'}
</button>
</form>
</div>
Expand Down
102 changes: 32 additions & 70 deletions server/controllers/applicationsController.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { Request, Response, NextFunction } from "express";
import { CustomRequest } from "../types/customRequest";
import { pool } from "../config/sql-db";
import { Request, Response, NextFunction } from 'express';
import { CustomRequest } from '../types/customRequest';
import { pool } from '../config/sql-db';

interface StatusCount {
status: string;
count: string;
}

const getAllApplications = async (
req: Request,
res: Response,
next: NextFunction
) => {
const getAllApplications = async (req: Request, res: Response) => {
try {
const userId = req.query.user_id;

Expand All @@ -33,26 +29,22 @@ const getAllApplications = async (
const { rows } = await pool.query(query, [userId]);
res.json(rows);
} catch (error) {
console.error("Error fetching job applications:", error);
res.status(500).json({ message: "Internal server error" });
console.error('Error fetching job applications:', error);
res.status(500).json({ message: 'Internal server error' });
}
};

const getStatuses = async (req: Request, res: Response, next: NextFunction) => {
try {
const { rows } = await pool.query("SELECT * FROM statuses");
const { rows } = await pool.query('SELECT * FROM statuses');
res.json(rows);
} catch (error) {
console.error("Error fetching statuses:", error);
res.status(500).json({ message: "Internal server error" });
console.error('Error fetching statuses:', error);
res.status(500).json({ message: 'Internal server error' });
}
};

const createApplication = async (
req: Request,
res: Response,
next: NextFunction
) => {
const createApplication = async (req: Request, res: Response) => {
try {
const {
title,
Expand Down Expand Up @@ -89,23 +81,16 @@ const createApplication = async (
date_applied,
general_notes,
];
const applicationResult = await pool.query(
applicationQuery,
applicationValues
);
const applicationResult = await pool.query(applicationQuery, applicationValues);

res.status(201).json({ id: applicationResult.rows[0].id });
} catch (error) {
console.error("Error creating application:", error);
res.status(500).json({ message: "Internal server error" });
console.error('Error creating application:', error);
res.status(500).json({ message: 'Internal server error' });
}
};

const getApplicationById = async (
req: CustomRequest<{ id: string }>,
res: Response,
next: NextFunction
) => {
const getApplicationById = async (req: CustomRequest<{ id: string }>, res: Response) => {
const { id } = req.params;
try {
const query = `
Expand Down Expand Up @@ -133,42 +118,26 @@ const getApplicationById = async (
const { rows } = await pool.query(query, [id]);

if (rows.length === 0) {
return res.status(404).json({ message: "Application not found" });
return res.status(404).json({ message: 'Application not found' });
}
console.log("user id: ", rows[0].user_id);

if (!req.user || req.user.id !== rows[0].user_id)
return res
.status(401)
.json({ message: "You are not authorized to retrieve those records" });
return res.status(401).json({ message: 'You are not authorized to retrieve those records' });

res.json(rows[0]);
} catch (error) {
console.error("Error fetching application by id:", error);
res.status(500).json({ message: "Internal server error" });
console.error('Error fetching application by id:', error);
res.status(500).json({ message: 'Internal server error' });
}
};

const updateApplication = async (
req: CustomRequest<{ id: string }>,
res: Response,
next: NextFunction
) => {
const updateApplication = async (req: CustomRequest<{ id: string }>, res: Response) => {
const { id } = req.params;
if (!req.user || req.user.id !== id)
return res
.status(401)
.json({ message: "You are not authorized to retrieve those records" });
return res.status(401).json({ message: 'You are not authorized to retrieve those records' });
try {
const { id } = req.params;
const {
job_id,
status_id,
user_id,
quick_apply,
date_applied,
general_notes,
} = req.body;
const { job_id, status_id, user_id, quick_apply, date_applied, general_notes } = req.body;
const query = `
UPDATE applications
SET job_id = $1, status_id = $2, user_id = $3, quick_apply = $4, date_applied = $5, general_notes = $6
Expand All @@ -183,23 +152,17 @@ const updateApplication = async (
general_notes,
id,
]);
res.status(200).json({ message: "Application updated successfully" });
res.status(200).json({ message: 'Application updated successfully' });
} catch (error) {
console.error("Error updating application:", error);
res.status(500).json({ message: "Internal server error" });
console.error('Error updating application:', error);
res.status(500).json({ message: 'Internal server error' });
}
};

const getAggregatedUserStats = async (
req: CustomRequest<{ userId: string }>,
res: Response,
next: NextFunction
) => {
const getAggregatedUserStats = async (req: CustomRequest<{ userId: string }>, res: Response) => {
const { userId } = req.params;
if (!req.user || req.user.id !== userId)
return res
.status(401)
.json({ message: "You are not authorized to retrieve those records" });
return res.status(401).json({ message: 'You are not authorized to retrieve those records' });
try {
const applicationsByStatusQuery = `
SELECT statuses.name AS status, COUNT(*) AS count
Expand All @@ -208,23 +171,22 @@ const getAggregatedUserStats = async (
WHERE applications.user_id = $1
GROUP BY statuses.name
`;
const applicationsByStatusResult = await pool.query<StatusCount>(
applicationsByStatusQuery,
[userId]
);
const applicationsByStatusResult = await pool.query<StatusCount>(applicationsByStatusQuery, [
userId,
]);

const totalApplications = applicationsByStatusResult.rows.reduce(
(sum: number, row: StatusCount) => sum + parseInt(row.count, 10),
0
0,
);

res.json({
totalApplications,
applicationsByStatus: applicationsByStatusResult.rows,
});
} catch (error) {
console.error("Error fetching aggregated data:", error);
res.status(500).send("Internal server error");
console.error('Error fetching aggregated data:', error);
res.status(500).send('Internal server error');
}
};

Expand Down

0 comments on commit be2cdf8

Please sign in to comment.