Skip to content

Commit

Permalink
feat: Trips são filtradas a partir do Service ID (#78)
Browse files Browse the repository at this point in the history
Co-authored-by: Fernanda Scovino <fscovinom@gmail.com>
  • Loading branch information
Gabriel Guimarães and fernandascovino authored Mar 9, 2023
1 parent 2de837d commit 915c355
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 28 deletions.
2 changes: 1 addition & 1 deletion src/components/Header/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export function Header(props) {
}
</div>
<div className="flex-column items-center mb-5">
<h1 className={`text-lg text-center + ${styles.headerText}`}>Busque pelo código da estação</h1>
<h1 className={`text-lg text-center + ${styles.headerText}`}>Saiba quais linhas passam na cidade</h1>
<div className="flex flex-col w-full">
<div className='relative'>
<button className='absolute right-[12px] top-0 bottom-0' onClick={() => clearInfo()}>
Expand Down
7 changes: 3 additions & 4 deletions src/components/InfoCard/InfoCard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function InfoCard() {
const [linha, setLinha ] = useState(false)
const { theme } = useContext(ThemeContext)
const { code } = useContext(CodeContext)
const { routes, isParent, getMultiplePages, plataforms, setRoutes } = useContext(RoutesContext)
const { routes, isParent, getMultiplePages, plataforms, setRoutes, activateLoader } = useContext(RoutesContext)
const {setTracked} = useContext(MovingMarkerContext)
const { setTrip } = useContext(TripContext);
const { activateForm, setSelectedPlatform } = useContext(FormContext)
Expand Down Expand Up @@ -78,7 +78,7 @@ export function InfoCard() {
strokeWidthSecondary={4}

/> : plataforms.map((e) => Object.values(e).map((values) => {
return <li className='flex justify-between border-b py-2.5' onClick={() => { getMultiplePages("/stop_times/?stop_id=" + Object.keys(values)), infoLinha(), setSelectedPlatform(Object.keys(values))}}>
return <li className='flex justify-between border-b py-2.5' onClick={() => { getMultiplePages("/stop_times/?stop_id=" + Object.keys(values)), infoLinha(), setSelectedPlatform(Object.keys(values)), activateLoader()}}>
<div className={styles.routeName}>
<div className={styles.shortName}>
<img src={pin} alt="" />
Expand All @@ -88,8 +88,7 @@ export function InfoCard() {
</li>
}))

}</> :
routes.map((e) => {
}</> : routes.map((e) => {
return <li key={e.id} onClick={() => setTrip(e.trip_id.trip_id)} className="flex justify-between border-b py-2.5">
<div className={styles.routeName}>
<div className={styles.shortName}>
Expand Down
51 changes: 45 additions & 6 deletions src/hooks/getRoutes.jsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { createContext, useContext, useEffect, useState } from "react";
import { CodeContext } from "./getCode";
import { api } from "../services/api";
import { ServiceIdContext } from "./getServiceId";
export const RoutesContext = createContext()




export function RoutesProvider({ children }) {
const { code } = useContext(CodeContext)
const {serviceId} = useContext(ServiceIdContext)
const [stopId, setStopId] = useState()
const [routes, setRoutes] = useState()
const [plataforms, setPlataforms] = useState([])
const [locationType, setLocationType] = useState()
const [stations, setStations] = useState()
const [isParent, setIsParent] = useState()
const [childName, setChildName] = useState()
const [loader, setLoader] = useState()


useEffect(() => {
Expand All @@ -28,24 +31,60 @@ export function RoutesProvider({ children }) {
})
}
}, [code])

function compareTripName(a, b) {
const aShortName = a.trip_id.trip_short_name;
const bShortName = b.trip_id.trip_short_name;

const aStartsWithLECD = aShortName.startsWith("LECD");
const bStartsWithLECD = bShortName.startsWith("LECD");

if (aStartsWithLECD && !bStartsWithLECD) {
return 1;
}
if (!aStartsWithLECD && bStartsWithLECD) {
return -1;
}

if (aStartsWithLECD && bStartsWithLECD) {
const aNumber = parseInt(aShortName.replace(/\D/g, ""));
const bNumber = parseInt(bShortName.replace(/\D/g, ""));
return aNumber - bNumber;
}

const aNumber = parseInt(aShortName.replace(/\D/g, ""));
const bNumber = parseInt(bShortName.replace(/\D/g, ""));
return aNumber - bNumber;
}

function activateLoader(){
setLoader(true)
setPlataforms([])
}

const filteredTrips = [];
async function getMultiplePages(url) {
const filteredTrips = [];
await api
.get(url)
.then(({ data }) => {
data.results.forEach((item) => {
const existingTrip = filteredTrips.find((trip) => trip.trip_id.trip_short_name === item.trip_id.trip_short_name);
if (!existingTrip) {
if (item.trip_id.service_id === serviceId) {
filteredTrips.push(item);
}
});
if (data.next) {
getMultiplePages(data.next);

} else {
if(locationType === 1){
setLoader(false)
getStations("/stop_times/?stop_id=" + stopId)
}
filteredTrips.sort(compareTripName)
setRoutes([...filteredTrips]);
}
})

});
}

let allStations = []
Expand Down Expand Up @@ -86,9 +125,9 @@ export function RoutesProvider({ children }) {
setPlataforms((prevResults) => [...prevResults, result]);
}
}, [stations]);

return (
<RoutesContext.Provider value={{ routes, stopId, setRoutes, getMultiplePages, isParent, plataforms, setPlataforms, stations, locationType, childName}}>
<RoutesContext.Provider value={{ routes, stopId, setRoutes, getMultiplePages, isParent, plataforms, setPlataforms, stations, locationType, childName, loader, activateLoader}}>
{children}
</RoutesContext.Provider>
)
Expand Down
90 changes: 90 additions & 0 deletions src/hooks/getServiceId.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { createContext, useEffect, useState } from "react";
import { api } from "../services/api";


export const ServiceIdContext = createContext()




export function ServiceIdProvider({ children }) {
const [today, setToday] = useState('')
const [calendar, setCalendar] = useState([])
const [serviceId, setServiceId] = useState('')
const [weekDay, setWeekDay] = useState('')

async function getDates(url) {
let allDates = [];
await api
.get(url)
.then(({ data }) => {
data.results.forEach((item) => {
allDates.push(item);
});
if (data.next) {
getDates(data.next);
}
setCalendar((prevCalendar) => [...prevCalendar, ...allDates]);
});
}
async function getDayOfWeek(url) {
let allDay = [];
await api
.get(url)
.then(({ data }) => {
data.results.forEach((item) => {
allDay.push(item);
});

setWeekDay(allDay);
});
}


useEffect(() => {
getDates('calendar_dates/')
getDayOfWeek('calendar/')
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
setToday(formattedDate)
}, [])


function findService(todayDate) {
const service = calendar.find((item) => item.date === todayDate);
if (service) {
setServiceId(service.service_id);
} else if (weekDay) {
const dayOfWeek = new Date(todayDate).toLocaleDateString('en-US', { weekday: 'long' }).toLowerCase();
const serviceWorks = weekDay.filter((service) => service[dayOfWeek] === 1);
const currentDate = new Date(todayDate);
if (serviceWorks.length > 0) {
const todayService = serviceWorks.find((service) => {
const startDate = new Date(service.start_date);
const endDate = new Date(service.end_date);
return currentDate >= startDate && currentDate <= endDate;
});
if (todayService) {
setServiceId(todayService.service_id);
}
}
}
}



useEffect(() => {
findService(today)
}, [calendar])



return (
<ServiceIdContext.Provider value={{ serviceId }}>
{children}
</ServiceIdContext.Provider>
)
}
35 changes: 19 additions & 16 deletions src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { ShapeProvider } from './hooks/getShape'
import { GPSProvider } from './hooks/getGPS'
import { FormProvider } from './hooks/useForm'
import { MovingMarkerProvider } from './hooks/getMovingMarkers'
import { ServiceIdProvider } from './hooks/getServiceId'
import { ToastContainer } from 'react-toastify'
import { BrowserRouter as Router } from 'react-router-dom'

Expand All @@ -22,22 +23,24 @@ ReactDOM.createRoot(document.getElementById('root')).render(
<Router>
<NameProvider>
<CodeProvider>
<RoutesProvider>
<TripProvider>
<ShapeProvider>
<ThemeProvider>
<GPSProvider>
<MovingMarkerProvider>
<FormProvider>
<App />
</FormProvider>
</MovingMarkerProvider>
</GPSProvider>
</ThemeProvider>
<ToastContainer />
</ShapeProvider>
</TripProvider>
</RoutesProvider>
<ServiceIdProvider>
<RoutesProvider>
<TripProvider>
<ShapeProvider>
<ThemeProvider>
<GPSProvider>
<MovingMarkerProvider>
<FormProvider>
<App />
</FormProvider>
</MovingMarkerProvider>
</GPSProvider>
</ThemeProvider>
<ToastContainer />
</ShapeProvider>
</TripProvider>
</RoutesProvider>
</ServiceIdProvider>
</CodeProvider>
</NameProvider>
</Router>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/SearchMain.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function SearchMain() {
<Header />
<div className="px-4 mt-60 relative z-1">
<h1 className='text-xl text-center mb-3 text-white'>
Saiba quais linhas de ônibus passam nos pontos da cidade
Saiba quais linhas passam na cidade
</h1>
{/* Inputs */}
<div className="flex content-center mb-6">
Expand Down

0 comments on commit 915c355

Please sign in to comment.