Fix more bugs

This commit is contained in:
Santiago Lo Coco 2023-12-06 18:29:00 -03:00
parent 67376fe98b
commit 2df601ddce
8 changed files with 70 additions and 35 deletions

View File

@ -1,11 +1,11 @@
{ {
"name": "sample-client-users", "name": "browser-client",
"version": "0.1.0", "version": "0.1.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "sample-client-users", "name": "browser-client",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"antd": "^5.3.3", "antd": "^5.3.3",

View File

@ -48,6 +48,16 @@ export interface FlightCreate {
gate: string; gate: string;
} }
export interface FlightCreateFull {
flight_code: string;
status: string;
origin: string;
destination: string;
departure_time: Date;
arrival_time: Date;
gate: string;
}
export interface FlightEditNotNull { export interface FlightEditNotNull {
departure_time: string, departure_time: string,
arrival_time: string, arrival_time: string,

View File

@ -1,5 +1,5 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { FlightCreate, Flight } from "../../Types"; import { FlightCreate, FlightCreateFull, Flight } from "../../Types";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import "./FlightForm.css"; import "./FlightForm.css";
import { createFlight } from "../../Api"; import { createFlight } from "../../Api";
@ -14,15 +14,18 @@ export const CreateFlight = () => {
status: "Scheduled", status: "Scheduled",
origin: "Frankfurt", origin: "Frankfurt",
destination: "Rome", destination: "Rome",
departure_time: "2023-10-09 10:00 AM", departure_time: new Date().toISOString().slice(0, 16),
arrival_time: "2023-10-09 12:00 PM", arrival_time: new Date(new Date().getTime() + 2 * 60 * 60 * 1000).toISOString().slice(0, 16),
gate: "A1", gate: "A1",
}); });
const handleSubmit = async (event: React.FormEvent) => { const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault(); event.preventDefault();
setError(null); if (flightData.departure_time >= flightData.arrival_time) {
setError("Departure time must be before the arrival time")
return;
}
const token = localStorage.getItem("token"); const token = localStorage.getItem("token");
if (!token) { if (!token) {
@ -30,7 +33,17 @@ export const CreateFlight = () => {
return; return;
} }
createFlight(flightData, token) let newFlightData: FlightCreate = {
flight_code: flightData.flight_code,
status: flightData.status,
origin: flightData.origin,
destination: flightData.destination,
departure_time: formatDate(flightData.departure_time),
arrival_time: formatDate(flightData.arrival_time),
gate: flightData.gate,
}
createFlight(newFlightData, token)
.then((data) => { .then((data) => {
setFlight(data); setFlight(data);
navigate("/home") navigate("/home")
@ -42,6 +55,20 @@ export const CreateFlight = () => {
}); });
}; };
function formatDate(isoString: string) {
let date = new Date(isoString)
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
let hours = date.getHours();
const minutes = date.getMinutes().toString().padStart(2, '0');
const amOrPm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12 || 12;
return `${year}-${month}-${day} ${hours.toString().padStart(2, '0')}:${minutes} ${amOrPm}`;
}
return ( return (
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
{error && {error &&
@ -96,7 +123,7 @@ export const CreateFlight = () => {
<label> <label>
Departure Time: Departure Time:
<input <input
type="text" type="datetime-local"
name="DepartureTime" name="DepartureTime"
value={flightData.departure_time} value={flightData.departure_time}
onChange={(e) => onChange={(e) =>
@ -107,7 +134,7 @@ export const CreateFlight = () => {
<label> <label>
Arrival Time: Arrival Time:
<input <input
type="text" type="datetime-local"
name="ArrivalTime" name="ArrivalTime"
value={flightData.arrival_time} value={flightData.arrival_time}
onChange={(e) => onChange={(e) =>

View File

@ -20,7 +20,7 @@ export const Home: React.FC<Props> = (props) => {
const [currentPage, setCurrentPage] = useState(initialPage); const [currentPage, setCurrentPage] = useState(initialPage);
const { loading, isAirline, user, token, isAdmin } = useAuth(); const { loading, isAirline, user, token, isAdmin } = useAuth();
const { subscriptions, loading: subsLoading, fetchData } = useFetchSubscriptions(user, token); const { subscriptions, loading: subsLoading, fetchData } = useFetchSubscriptions(user, token, !isAirline && !isAdmin);
useEffect(() => { useEffect(() => {
const newParams = new URLSearchParams(window.location.search); const newParams = new URLSearchParams(window.location.search);
@ -52,7 +52,7 @@ export const Home: React.FC<Props> = (props) => {
return currentPage > 1 ? true : false return currentPage > 1 ? true : false
} }
if (loading || isLoading || subsLoading) { if (loading || isLoading) {
return <div>Loading...</div>; return <div>Loading...</div>;
} }

View File

@ -2,6 +2,7 @@ import React, { useEffect } from "react";
import { useState } from "react"; import { useState } from "react";
import { User, Flight, FlightCreate } from "../Types"; import { User, Flight, FlightCreate } from "../Types";
import { createFlight } from "../Api"; import { createFlight } from "../Api";
import useAuth from "../useAuth";
export const useCreateFlight = (flight_data: FlightCreate) => { export const useCreateFlight = (flight_data: FlightCreate) => {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);

View File

@ -3,7 +3,7 @@ import { useState } from "react";
import { User, Flight, SubscriptionsCreate } from "../Types"; import { User, Flight, SubscriptionsCreate } from "../Types";
import { fetchSubscriptions } from "../Api"; import { fetchSubscriptions } from "../Api";
export const useFetchSubscriptions = (user: User | undefined, token: string | undefined) => { export const useFetchSubscriptions = (user: User | undefined, token: string | undefined, isUser: boolean) => {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [subscriptions, setSubscriptions] = useState<SubscriptionsCreate[]>([]); const [subscriptions, setSubscriptions] = useState<SubscriptionsCreate[]>([]);
const [loading, setLoading] = useState<boolean>(true); const [loading, setLoading] = useState<boolean>(true);
@ -11,7 +11,7 @@ export const useFetchSubscriptions = (user: User | undefined, token: string | u
const fetchData = useCallback(async () => { const fetchData = useCallback(async () => {
setError(null); setError(null);
if (!user || !token || !loading) { if (!user || !token || !loading || !isUser) {
return; return;
} }
@ -21,7 +21,7 @@ export const useFetchSubscriptions = (user: User | undefined, token: string | u
setLoading(false) setLoading(false)
}) })
.catch((error) => { }); .catch((error) => { });
}, [user, token]); }, [user, token, isUser]);
useEffect(() => { useEffect(() => {
fetchData() fetchData()

View File

@ -1,15 +1,8 @@
from datetime import datetime
from typing import Annotated, Optional from typing import Annotated, Optional
from asyncreq import request from asyncreq import request
from fastapi import ( from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Response
APIRouter,
BackgroundTasks,
Depends,
Header,
HTTPException,
Request,
Response,
)
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.api.config import API_MESSAGES from src.api.config import API_MESSAGES
@ -30,6 +23,15 @@ def get_flight_by_id(id: int, db: Session = Depends(get_db)):
@router.post("", response_model=Flight) @router.post("", response_model=Flight)
def create_flight(flight: FlightCreate, db: Session = Depends(get_db)): def create_flight(flight: FlightCreate, db: Session = Depends(get_db)):
try:
if not (
datetime.strptime(flight.departure_time, "%Y-%m-%d %I:%M %p")
and datetime.strptime(flight.arrival_time, "%Y-%m-%d %I:%M %p")
):
raise HTTPException(status_code=400, detail="Invalid date")
except (ValueError, TypeError):
raise HTTPException(status_code=400, detail="Invalid date")
try: try:
return flight_crud.create_flight(db=db, flight=flight) return flight_crud.create_flight(db=db, flight=flight)
except ValueError as e: except ValueError as e:
@ -45,7 +47,6 @@ async def update_flight(
id: int, id: int,
update: FlightUpdate, update: FlightUpdate,
background_tasks: BackgroundTasks, background_tasks: BackgroundTasks,
req: Request,
db: Session = Depends(get_db), db: Session = Depends(get_db),
x_api_request_id: Annotated[str | None, Header()] = None, x_api_request_id: Annotated[str | None, Header()] = None,
): ):

View File

@ -39,7 +39,7 @@ async function validLogin() {
const ArrivalTime = await driver.findElement(By.name('ArrivalTime')) const ArrivalTime = await driver.findElement(By.name('ArrivalTime'))
const DepartureTime = await driver.findElement(By.name('DepartureTime')) const DepartureTime = await driver.findElement(By.name('DepartureTime'))
const Gate = await driver.findElement(By.name('Gate')) const Gate = await driver.findElement(By.name('Gate'))
await Code.click(); await Code.click();
await Code.clear(); await Code.clear();
await Code.sendKeys(process.env.code); await Code.sendKeys(process.env.code);
@ -48,7 +48,7 @@ async function validLogin() {
await Status.clear(); await Status.clear();
await Status.sendKeys('Scheduled'); await Status.sendKeys('Scheduled');
await Origin.click() await Origin.click();
await Origin.clear(); await Origin.clear();
await Origin.sendKeys('Salta'); await Origin.sendKeys('Salta');
@ -56,16 +56,12 @@ async function validLogin() {
await Destination.clear(); await Destination.clear();
await Destination.sendKeys('Buenos aires'); await Destination.sendKeys('Buenos aires');
await ArrivalTime.click(); await ArrivalTime.sendKeys('03170020241155AM');
await ArrivalTime.clear();
await ArrivalTime.sendKeys('2023-11-04 05:16 AM'); await DepartureTime.sendKeys('03170020240850AM');
await DepartureTime.click(); await Gate.click();
await DepartureTime.clear(); await Gate.clear();
await DepartureTime.sendKeys('2023-11-04 03:11 AM');
await Gate.click();
await Gate.clear();
await Gate.sendKeys('A5'); await Gate.sendKeys('A5');
await driver.wait(until.elementLocated(By.name('CreateFlightButton'), 5000)) await driver.wait(until.elementLocated(By.name('CreateFlightButton'), 5000))