From e8209762c0bbffa9320b234e9ffd8490b4011bbf Mon Sep 17 00:00:00 2001 From: Hugo Falcao Date: Tue, 6 Sep 2022 20:49:00 -0300 Subject: [PATCH] wip --- package.json | 4 +- src/App.tsx | 28 +- src/LocalStorage.ts | 37 +- .../UserSearchInfos/UserSearchInfos.tsx | 10 +- .../BuscarPassageiro/BuscarPassageiro.tsx | 205 +++--- .../CadastrarItinerario.tsx | 679 +++++++++++++++++- src/pages/Cadastro/Cadastro.tsx | 338 +++++---- .../CadastroCompletar/CadastroCompletar.tsx | 99 +-- src/pages/CadastroVan.tsx | 301 ++++---- src/pages/MinhasVans.tsx | 161 +++-- src/pages/Perfil.tsx | 28 +- src/pages/Transportes/Transportes.tsx | 92 ++- src/services/api/transports.ts | 36 +- src/services/api/users.ts | 87 ++- src/services/functions/carsService.ts | 12 +- src/services/functions/sessionsService.ts | 12 +- src/services/functions/transportsService.ts | 28 +- src/services/functions/usersService.ts | 59 +- yarn.lock | 4 +- 19 files changed, 1500 insertions(+), 720 deletions(-) diff --git a/package.json b/package.json index 2127989..ba6fd45 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ "@craco/craco": "^6.4.5", "@hookform/error-message": "^2.0.0", "@ionic-selectable/core": "^5.0.0-alpha.13", - "@ionic/react": "^6.0.0", - "@ionic/react-router": "^6.0.0", + "@ionic/react": "^6.2.5", + "@ionic/react-router": "^6.2.5", "@testing-library/jest-dom": "^5.11.9", "@testing-library/react": "^11.2.5", "@testing-library/user-event": "^12.6.3", diff --git a/src/App.tsx b/src/App.tsx index 61182f6..82cef17 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -11,20 +11,6 @@ import { import { IonReactRouter } from "@ionic/react-router"; import { Redirect, Route } from "react-router-dom"; -// importação das páginas -import BuscarPassageiro from "./pages/BuscarPassageiro/BuscarPassageiro"; -import BuscarTransporte from "./pages/BuscarTransporte/BuscarTransporte"; -import Cadastro from "./pages/Cadastro/Cadastro"; -import CadastroCompletar from "./pages/CadastroCompletar/CadastroCompletar"; -import CompletarDocumento from "./pages/CadastroCompletar/CompletarDocumento"; -import CompletarTelefone from "./pages/CadastroCompletar/CompletarTelefone"; -import CadastroVan from "./pages/CadastroVan"; -import Home from "./pages/Home"; -import Login from "./pages/Login"; -import Perfil from "./pages/Perfil"; -import PerfilEditar from "./pages/PerfilEditar"; -import Transportes from "./pages/Transportes/Transportes"; - /* Core CSS required for Ionic components to work properly */ import "@ionic/react/css/core.css"; @@ -49,9 +35,23 @@ import "./theme/tailwind.css"; import { home, person, search } from "ionicons/icons"; import React, { useContext, useState } from "react"; + +/* Importação das páginas */ +import BuscarPassageiro from "./pages/BuscarPassageiro/BuscarPassageiro"; +import BuscarTransporte from "./pages/BuscarTransporte/BuscarTransporte"; import CadastrarItinerario from "./pages/CadastrarItinerario/CadastrarItinerario"; +import Cadastro from "./pages/Cadastro/Cadastro"; +import CadastroCompletar from "./pages/CadastroCompletar/CadastroCompletar"; +import CompletarDocumento from "./pages/CadastroCompletar/CompletarDocumento"; +import CompletarTelefone from "./pages/CadastroCompletar/CompletarTelefone"; +import CadastroVan from "./pages/CadastroVan"; +import Home from "./pages/Home"; +import Login from "./pages/Login"; import MeusItinerarios from "./pages/MeusItinerarios/MeusItinerarios"; import MinhasVans from "./pages/MinhasVans"; +import Perfil from "./pages/Perfil"; +import PerfilEditar from "./pages/PerfilEditar"; +import Transportes from "./pages/Transportes/Transportes"; setupIonicReact(); diff --git a/src/LocalStorage.ts b/src/LocalStorage.ts index 3596bbc..9442f53 100644 --- a/src/LocalStorage.ts +++ b/src/LocalStorage.ts @@ -1,24 +1,21 @@ -const tokenId = 'token'; -const productDetails = '@productDetails'; - const LocalStorage = { - getToken: (): string => { - const tokenId = localStorage.getItem('tokenId') + getToken: (): string => { + const tokenId = localStorage.getItem("tokenId"); - if (!tokenId) { - return '' - } - - return tokenId - }, - - setToken: (token: string) => { - localStorage.setItem('tokenId', token) - }, - - clearToken: () => { - localStorage.removeItem('tokenId') + if (!tokenId) { + return ""; } -} -export default LocalStorage \ No newline at end of file + return tokenId; + }, + + setToken: (token: string) => { + localStorage.setItem("tokenId", token); + }, + + clearToken: () => { + localStorage.removeItem("tokenId"); + }, +}; + +export default LocalStorage; diff --git a/src/components/UserSearchInfos/UserSearchInfos.tsx b/src/components/UserSearchInfos/UserSearchInfos.tsx index f9fae2e..607340c 100644 --- a/src/components/UserSearchInfos/UserSearchInfos.tsx +++ b/src/components/UserSearchInfos/UserSearchInfos.tsx @@ -4,15 +4,9 @@ import { IonCardSubtitle, IonCol, IonIcon, - IonNote, IonRow, } from "@ionic/react"; -import { - arrowForward, - call, - callOutline, - navigateOutline, -} from "ionicons/icons"; +import { call, callOutline, navigateOutline } from "ionicons/icons"; import "./UserSearchInfos.css"; export const UserSearchInfos = (record: any) => { @@ -28,7 +22,7 @@ export const UserSearchInfos = (record: any) => {

- +  {record.record.address_to}

diff --git a/src/pages/BuscarPassageiro/BuscarPassageiro.tsx b/src/pages/BuscarPassageiro/BuscarPassageiro.tsx index b03819d..4923608 100644 --- a/src/pages/BuscarPassageiro/BuscarPassageiro.tsx +++ b/src/pages/BuscarPassageiro/BuscarPassageiro.tsx @@ -1,127 +1,158 @@ -import { IonContent, IonPage, IonFab, IonFabButton, IonIcon } from '@ionic/react'; -import { search } from 'ionicons/icons'; -import './BuscarPassageiro.css'; +import { + IonContent, + IonFab, + IonFabButton, + IonIcon, + IonPage, +} from "@ionic/react"; +import { search } from "ionicons/icons"; +import "./BuscarPassageiro.css"; import { Map, Marker, Overlay } from "pigeon-maps"; -import { maptiler } from 'pigeon-maps/providers'; -import { useEffect, useState } from 'react'; +import { maptiler } from "pigeon-maps/providers"; +import { useEffect, useState } from "react"; -import RecordsStore from '../../store/RecordsStore'; -import { fetchRecords } from '../../store/Selectors'; -import { getUsersSearching } from '../../services/api/users'; -import { UserSearchInfos } from '../../components/UserSearchInfos/UserSearchInfos'; +import { UserSearchInfos } from "../../components/UserSearchInfos/UserSearchInfos"; +import { getUsersSearching } from "../../services/api/users"; +import RecordsStore from "../../store/RecordsStore"; +import { fetchRecords } from "../../store/Selectors"; -const maptilerProvider = maptiler('d5JQJPLLuap8TkJJlTdJ', 'streets'); +const maptilerProvider = maptiler("d5JQJPLLuap8TkJJlTdJ", "streets"); const BuscarPassageiro: React.FC = () => { + // UNCOMMENT THESE TO USE CURRENT LOCATION. - // UNCOMMENT THESE TO USE CURRENT LOCATION. + // const [ currentPoint, setCurrentPoint ] = useState(false); - // const [ currentPoint, setCurrentPoint ] = useState(false); + // useEffect(() => { - // useEffect(() => { + // const getCurrentLocation = async () => { - // const getCurrentLocation = async () => { + // const fetchedLocation = await getLocation(); + // setCurrentPoint(fetchedLocation.currentLocation); + // } - // const fetchedLocation = await getLocation(); - // setCurrentPoint(fetchedLocation.currentLocation); - // } + // getCurrentLocation(); + // }, []); - // getCurrentLocation(); - // }, []); + // useIonViewWillEnter(() => { - // useIonViewWillEnter(() => { + // getUsersSearching(currentPoint); + // }); - // getUsersSearching(currentPoint); - // }); + const [currentPoint, setCurrentPoint] = useState({ + latitude: -22.907829, + longitude: -47.062943, + }); - const [ currentPoint, setCurrentPoint ] = useState({ latitude: -22.907829, longitude: -47.062943 }); + const records = RecordsStore.useState(fetchRecords); + const center = { latitude: -22.907829, longitude: -47.062943 }; - const records = RecordsStore.useState(fetchRecords); - const center = { latitude: -22.907829, longitude: -47.062943 }; + const [results, setResults] = useState([]); + const [zoom, setZoom] = useState(14); - const [ results, setResults ] = useState([]); - const [ zoom, setZoom ] = useState(14); + // const [ moveMode, setMoveMode ] = useState(false); - const [ moveMode, setMoveMode ] = useState(false); + // useEffect(() => { - // useEffect(() => { + // const getData = async () => { - // const getData = async () => { + // await getUsersSearching(currentPoint); + // } - // await getUsersSearching(currentPoint); - // } + // getData(); + // }, [ currentPoint ]); - // getData(); - // }, [ currentPoint ]); + useEffect(() => { + setResults(records); + }, [records]); - useEffect(() => { + const hideMarkers = () => { + console.log("entrou"); + const tempRecords = JSON.parse(JSON.stringify(results)); + tempRecords.forEach((tempRecord: any) => (tempRecord.showInfo = false)); + console.log(tempRecords); + setResults(tempRecords); + }; - setResults(records); - }, [ records ]); - - const hideMarkers = () => { - console.log('entrou') - const tempRecords = JSON.parse(JSON.stringify(results)); - tempRecords.forEach((tempRecord:any) => tempRecord.showInfo = false); - console.log(tempRecords) - setResults(tempRecords); - } - - const handleMap = (e:any) => { + const handleMap = (e: any) => { setCurrentPoint({ latitude: e.center[0], longitude: e.center[1] }); - } + }; const searchResults = async () => { await getUsersSearching(currentPoint); - } + }; - const showMarkerInfo = (e:any, index:any) => { + const showMarkerInfo = (e: any, index: any) => { + const tempRecords = JSON.parse(JSON.stringify(results)); - const tempRecords = JSON.parse(JSON.stringify(results)); + // Hide all current marker infos + !tempRecords[index].showInfo && + tempRecords.forEach((tempRecord: any) => (tempRecord.showInfo = false)); + tempRecords[index].showInfo = !tempRecords[index].showInfo; - // Hide all current marker infos - !tempRecords[index].showInfo && tempRecords.forEach((tempRecord:any) => tempRecord.showInfo = false); - tempRecords[index].showInfo = !tempRecords[index].showInfo; - - console.log(tempRecords) - setResults(tempRecords); - } + console.log(tempRecords); + setResults(tempRecords); + }; return ( - - {/* { results && + + {/* { results && <> */} - handleMap(e)} defaultCenter={ [center.latitude, center.longitude] } defaultZoom={ zoom } provider={ maptilerProvider } touchEvents={ true }> + handleMap(e)} + defaultCenter={[center.latitude, center.longitude]} + defaultZoom={zoom} + provider={maptilerProvider} + touchEvents={true} + > + {results && + results.map( + (record: { latitude_from: any; longitude_from: any }, index) => { + return ( + showMarkerInfo(e, index)} + key={index} + color="#3578e5" + width={50} + anchor={[ + parseFloat(record.latitude_from), + parseFloat(record.longitude_from), + ]} + /> + ); + } + )} - {results && results.map((record:{latitude_from:any, longitude_from:any}, index) => { - return showMarkerInfo(e, index) } key={ index } color="#3578e5" width={ 50 } anchor={ [ parseFloat(record.latitude_from), parseFloat(record.longitude_from) ] } /> - })} + {results.map((record: any, index) => { + if (record.showInfo) { + return ( + + + + ); + } + })} + - { results.map((record:any, index) => { - - if (record.showInfo) { - - return ( - - - - ) - } - })} - - - - - - - - {/* */} - {/* } */} - - + + + + + + {/* */} + {/* } */} + + ); }; -export default BuscarPassageiro; \ No newline at end of file +export default BuscarPassageiro; diff --git a/src/pages/CadastrarItinerario/CadastrarItinerario.tsx b/src/pages/CadastrarItinerario/CadastrarItinerario.tsx index f83f844..863d7a0 100644 --- a/src/pages/CadastrarItinerario/CadastrarItinerario.tsx +++ b/src/pages/CadastrarItinerario/CadastrarItinerario.tsx @@ -1,18 +1,185 @@ +import { Color } from "@ionic/core"; import { IonBackButton, IonButton, IonButtons, + IonCheckbox, IonContent, + IonDatetime, IonHeader, IonIcon, + IonInput, + IonItem, + IonLabel, + IonList, IonPage, + IonRange, + IonSelect, + IonSelectOption, + IonSlide, + IonSlides, IonTitle, + IonToast, IonToolbar, } from "@ionic/react"; -import { close, locateOutline, locationOutline } from "ionicons/icons"; -import GooglePlacesAutocomplete from "react-google-places-autocomplete"; +import { + add, + addCircleOutline, + arrowBack, + arrowForward, + checkmark, + close, + informationCircle, + locateOutline, + locationOutline, + removeCircleOutline, +} from "ionicons/icons"; +import { useEffect, useRef, useState } from "react"; +import GooglePlacesAutocomplete, { + geocodeByAddress, + getLatLng, +} from "react-google-places-autocomplete"; +import { useHistory } from "react-router"; +import * as vansRoutes from "../../services/api/vans"; +import sessionsService from "../../services/functions/sessionsService"; + +const slideOpts = { + initialSlide: 0, + allowTouchMove: false, +}; + +interface VanInfo { + plate: string; + brand: string; + model: string; + seats_number: string; + document_status: boolean; + locator_name: string; + locator_address: string; + locator_complement: string; + locator_city: string; + locator_state: string; +} + +interface Coords { + lat: number; + lng: number; +} export default function CadastrarItinerario() { + const minDate = new Date(); + + const history = useHistory(); + + const mySlides = useRef(null); + const nextButton1 = useRef(null); + const nextButton2 = useRef(null); + + const [specificDate, setSpecificDate] = useState(false); + const [singleVacancy, setSingleVacancy] = useState(false); + const [vans, setVans] = useState(); + const [showToast, setShowToast] = useState(false); + const [toastMessage, setToastMessage] = useState(""); + const [toastColor, setToastColor] = useState("primary"); + //Infos + const [initialAddress, setInitialAddress] = useState(""); + const [initialCoords, setInitialCoords] = useState(); + const [neighborhoods, setNeighborhoods] = useState>([]); + const [finalAddress, setFinalAddress] = useState(""); + const [destinations, setDestinations] = useState>([]); + const [daysOfWeek, setDaysOfWeek] = useState(); + const [specificDay, setSpecificDay] = useState(); + const [departureTime, setDepartureTime] = useState(); + const [arrivalTime, setArrivalTime] = useState(); + const [monthlyPrice, setMonthlyPrice] = useState(0); + const [dailyPrice, setDailyPrice] = useState(0); + const [van, setVan] = useState(""); + const [nickname, setNickname] = useState(""); + + const redirectUserToLogin = () => { + history.push({ pathname: "/login" }); + }; + + const onBtnClicked = async (direction: string) => { + const swiper = await mySlides.current.getSwiper(); + if (direction === "next") { + swiper.slideNext(); + } else if (direction === "prev") { + swiper.slidePrev(); + } + }; + + function formatRange(rangeValue: number) { + switch (rangeValue) { + case 1: + return "Segunda"; + case 2: + return "Terça"; + case 3: + return "Quarta"; + case 4: + return "Quinta"; + case 5: + return "Sexta"; + case 6: + return "Sabádo"; + case 7: + return "Domingo"; + + default: + return ""; + } + } + + useEffect(() => { + const getUserVans = async () => { + let userId = ""; + + const refreshSessionRes = await sessionsService.refreshSession(); + + if (refreshSessionRes.error) { + redirectUserToLogin(); + return; + } + + if (refreshSessionRes.userId) { + userId = refreshSessionRes.userId; + } + + vansRoutes + .getByUserId(userId) + .then((response) => { + if (response.status === "error") { + setToastColor("danger"); + setToastMessage(response.message); + setShowToast(true); + + return; + } + + setVans(response.data); + }) + .catch((err) => { + setToastColor("danger"); + setToastMessage(err); + setShowToast(true); + }); + }; + + getUserVans(); + }, []); + + useEffect(() => { + console.log(initialAddress); + if (initialAddress.label && initialAddress.label.length > 0) { + geocodeByAddress(initialAddress.label) + .then((results) => getLatLng(results[0])) + .then(({ lat, lng }) => setInitialCoords({ lat, lng })); + } + }, [initialAddress]); + + function addNeighborhoodToList() {} + return ( @@ -24,34 +191,486 @@ export default function CadastrarItinerario() { -
-

Digite o endereço de onde você iniciará a rota do itinerário

-
- - -
-
- - -
-
- Cadastrar -
-
+ + +
+

+ Digite o endereço de onde você iniciará a rota do itinerário +

+
+ + {/* */} + +
+
+ onBtnClicked("next")} + color="primary" + > + + +
+
+ + + Essa informação é importante para que possamos informar aos + passageiros um horário aproximado que você passará para + pegá-lo. + +
+
+
+ +
+

+ Adicione os bairros que você atenderá +

+
+ + { + addNeighborhoodToList(); + }, + }} + /> +
+
+ + + +
+
+ + + + Taquaral + + + + Barão Geraldo + + +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} color="primary"> + + +
+
+ + + Não se preocupe, você poderá adicionar ou remover bairros + posteriormente caso precise editando o itinerário. + +
+
+
+ +
+

+ Digite o endereço de destino final do itinerário +

+
+ + { + nextButton2.current!.disabled = false; + }, + }} + /> +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} + color="primary" + > + + +
+
+ + + Não se preocupe, você poderá adicionar paradas. + +
+
+
+ +
+

+ Adicione paradas durante o trajeto do itinerário para encontrar + mais passageiros +

+
+ + +
+
+ + + +
+
+ + + + Unicamp + + + + CPFL + + +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} color="primary"> + + +
+
+ + + Não se preocupe, você poderá adicionar ou remover paradas + posteriormente caso precise editando o itinerário. + +
+
+
+ +
+

+ Escolha o(s) dia(s) da semana ou um dia específico que o + itinerário será realizado +

+ +
+ + Dia Específico ? + + event.detail.checked + ? setSpecificDate(true) + : setSpecificDate(false) + } + > + + +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} color="primary"> + + +
+
+
+ +
+

+ Qual o horário estimado de ínicio do itinerário ? +

+
+ +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} + color="primary" + > + + +
+
+ + + Não se preocupe, é apenas um horário estimado. + +
+
+
+ +
+

+ Qual o horário estimado de chegado no último destino do + itinerário ? +

+
+ +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} + color="primary" + > + + +
+
+ + + Não se preocupe, é apenas um horário estimado. + +
+
+
+ +
+

+ Preencha as informações de pagamento +

+ Valor cobrado mensalmente +
+ setMonthlyPrice(monthlyPrice - 1)} + icon={removeCircleOutline} + /> +

R$ {monthlyPrice}

+ setMonthlyPrice(monthlyPrice + 1)} + icon={addCircleOutline} + /> +
+
+ + Aceitar pedidos para vagas avulsa ? + + setSingleVacancy(event.detail.checked) + } + > + + +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} + color="primary" + > + + +
+
+ + + Lembre-se esse valor será cobrado independente do destino do + passageiro. +
+ + Em breve será possível cobrar valores diferentes para cada + destino. + +
+
+
+
+ +
+

+ Escolha o veículo que será utilizado no itinerário +

+
+ + {vans ? ( + vans.map((van, index) => { + return ( + + {van.brand + + " - " + + van.model + + " | Placa: " + + van.plate} + + ); + }) + ) : ( + <> + )} + +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} + color="primary" + > + + +
+
+
+ +
+

+ Escolha um apelido para o itinerário +

+
+ setNickname(event.detail.value!)} + placeholder="Manhã - Centro" + > +
+
+ onBtnClicked("prev")} color="primary"> + + + onBtnClicked("next")} + color="primary" + > + + Cadastrar + +
+
+
+
+ setShowToast(false)} + message={toastMessage} + duration={2500} + />
); diff --git a/src/pages/Cadastro/Cadastro.tsx b/src/pages/Cadastro/Cadastro.tsx index 5c91087..fcd87db 100644 --- a/src/pages/Cadastro/Cadastro.tsx +++ b/src/pages/Cadastro/Cadastro.tsx @@ -1,215 +1,245 @@ -import { IonToast, IonProgressBar, IonItem, IonLabel, IonInput, IonBackButton, IonButton, IonButtons, IonCardTitle, IonCol, IonContent, IonGrid, IonHeader, IonPage, IonRow, IonToolbar } from '@ionic/react'; -import { arrowBack, logoFacebook, mail } from 'ionicons/icons'; -import { Action } from '../../components/Action'; -import { useContext, useEffect, useState } from 'react'; -import { useHistory, useParams } from 'react-router'; -import './Cadastro.css'; -import ModalExample from '../../components/Email'; -import * as UsersService from '../../services/api/users' -import LocalStorage from '../../LocalStorage'; -import { UserContext } from '../../App'; -import { Color } from '@ionic/core'; +import { Color } from "@ionic/core"; +import { + IonBackButton, + IonButton, + IonButtons, + IonCardTitle, + IonCol, + IonContent, + IonGrid, + IonHeader, + IonInput, + IonItem, + IonLabel, + IonPage, + IonRow, + IonToast, + IonToolbar, +} from "@ionic/react"; +import { arrowBack } from "ionicons/icons"; +import { useContext, useState } from "react"; +import { useHistory, useParams } from "react-router"; +import { UserContext } from "../../App"; +import { Action } from "../../components/Action"; +import LocalStorage from "../../LocalStorage"; +import * as UsersService from "../../services/api/users"; +import "./Cadastro.css"; const Cadastro: React.FC = () => { const history = useHistory(); const user = useContext(UserContext); - + const [showToast, setShowToast] = useState(false); - const [messageToast, setMessageToast] = useState(''); + const [messageToast, setMessageToast] = useState(""); const [toastColor, setToastColor] = useState("primary"); - const [email, setEmail] = useState(''); - const [password, setPassword] = useState(''); - const [confirmPassword, setConfirmPassword] = useState(''); - const [firstName, setFirstName] = useState(''); - const [lastName, setLastName] = useState(''); - const [birthDate, setBirthDate] = useState(''); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [firstName, setFirstName] = useState(""); + const [lastName, setLastName] = useState(""); + const [birthDate, setBirthDate] = useState(""); const [lResult, setlResult] = useState({ - error: '', - success: true + error: "", + success: true, }); const emailValidate = () => { var usuario = email.substring(0, email.indexOf("@")); var dominio = email.substring(email.indexOf("@") + 1, email.length); - if ((usuario.length >= 1) && - (dominio.length >= 3) && - (usuario.search("@") == -1) && - (dominio.search("@") == -1) && - (usuario.search(" ") == -1) && - (dominio.search(" ") == -1) && - (dominio.search(".") != -1) && - (dominio.indexOf(".") >= 1) && - (dominio.lastIndexOf(".") < dominio.length - 1)) - { - return true; + if ( + usuario.length >= 1 && + dominio.length >= 3 && + usuario.search("@") === -1 && + dominio.search("@") === -1 && + usuario.search(" ") === -1 && + dominio.search(" ") === -1 && + dominio.search(".") !== -1 && + dominio.indexOf(".") >= 1 && + dominio.lastIndexOf(".") < dominio.length - 1 + ) { + return true; } else { - return false; + return false; } }; const clearResult = () => { - lResult.error = ''; - lResult.success = true; - } + lResult.error = ""; + lResult.success = true; + }; const fieldValidate = async () => { - clearResult(); + clearResult(); - if(!emailValidate()) { - lResult.error = 'E-mail inválido!'; - lResult.success = false; - return lResult; - } else if(password.length < 7 || password.length > 12) { //TODO: validar de acordo com a documentação - lResult.error = 'A senha deve ter de 7 a 12 caracteres!'; - lResult.success = false; - return lResult; - } - + if (!emailValidate()) { + lResult.error = "E-mail inválido!"; + lResult.success = false; return lResult; + } else if (password.length < 7 || password.length > 12) { + //TODO: validar de acordo com a documentação + lResult.error = "A senha deve ter de 7 a 12 caracteres!"; + lResult.success = false; + return lResult; + } + + return lResult; }; const handleSubmit = async () => { - if(name === '' || email === '' || birthDate === '' || password === '' || confirmPassword === '') { - setToastColor("warning") - setMessageToast('Nenhum campo pode estar vazio!'); + if ( + name === "" || + email === "" || + birthDate === "" || + password === "" || + confirmPassword === "" + ) { + setToastColor("warning"); + setMessageToast("Nenhum campo pode estar vazio!"); setShowToast(true); - return + return; } - - if(password !== confirmPassword) { - setToastColor("warning") - setMessageToast('As senhas devem ser iguais!'); + + if (password !== confirmPassword) { + setToastColor("warning"); + setMessageToast("As senhas devem ser iguais!"); setShowToast(true); - return + return; } - + const signUpForm = { name: firstName, lastname: lastName, email: email, birth_date: birthDate, - password: password - } + password: password, + }; let result = fieldValidate(); - if(!(await result).success) { - setToastColor("warning") + if (!(await result).success) { + setToastColor("warning"); setMessageToast(lResult.error); setShowToast(true); - return + return; } let retorno = await UsersService.create(signUpForm); - if(!retorno.token) { - setToastColor('danger') + if (!retorno.token) { + setToastColor("danger"); setMessageToast(retorno.message); setShowToast(true); - return + return; } LocalStorage.setToken(retorno.token.token); user.setIsLoggedIn(true); - history.push({ pathname: '/home', state: { - redirectData: { - showToastMessage: true, - toastColor: "success", - toastMessage: "Usuário cadastrado com sucesso!", - } - }}) + history.push({ + pathname: "/home", + state: { + redirectData: { + showToastMessage: true, + toastColor: "success", + toastMessage: "Usuário cadastrado com sucesso!", + }, + }, + }); }; - const { name } = useParams<{ name: string; }>(); + const { name } = useParams<{ name: string }>(); return ( - - + + - + - - - + + + - - - {/* Como você deseja se cadastrar? */} - Cadastro - - - - -
- - Nome - setFirstName(e.target.value)} - // error={isError} - // onIonChange={(e: any) => setFirstName(e.detail.value)} - > - - - - Sobrenome - setLastName(e.target.value)} - > - - -
- - - E-mail - setEmail(e.target.value)} - > - - + + + {/* Como você deseja se cadastrar? */} + Cadastro + + + + +
+ + Nome + setFirstName(e.target.value)} + // error={isError} + // onIonChange={(e: any) => setFirstName(e.detail.value)} + > + + + Sobrenome + setLastName(e.target.value)} + > + +
- - Data de nascimento - setBirthDate(e.target.value)} - > - - - - - Senha - setPassword(e.target.value)} - > - - - Confirme a senha - setConfirmPassword(e.target.value)} - > - - - Cadastrar-se -
-
- - Ao se cadastrar, você aceita nossos Termos e Condições e nossa Política de Privacidade. - - + + E-mail + setEmail(e.target.value)} + > + + + + Data de nascimento + setBirthDate(e.target.value)} + > + + + + Senha + setPassword(e.target.value)} + > + + + Confirme a senha + setConfirmPassword(e.target.value)} + > + + + + Cadastrar-se + +
+
+ + Ao se cadastrar, você aceita nossos{" "} + Termos e Condições e nossa{" "} + Política de Privacidade. + +
{/*
*/} @@ -220,9 +250,9 @@ const Cadastro: React.FC = () => { message={messageToast} duration={2500} /> -
-
+ + ); }; -export default Cadastro; \ No newline at end of file +export default Cadastro; diff --git a/src/pages/CadastroCompletar/CadastroCompletar.tsx b/src/pages/CadastroCompletar/CadastroCompletar.tsx index 9489c79..0181366 100644 --- a/src/pages/CadastroCompletar/CadastroCompletar.tsx +++ b/src/pages/CadastroCompletar/CadastroCompletar.tsx @@ -1,26 +1,26 @@ import { -IonBackButton, -IonButtons, -IonCard, -IonCardContent, -IonContent, -IonHeader, -IonIcon, -IonItem, -IonLabel, -IonPage, -IonTitle, -IonToast, -IonToolbar + IonBackButton, + IonButtons, + IonCard, + IonCardContent, + IonContent, + IonHeader, + IonIcon, + IonItem, + IonLabel, + IonPage, + IonTitle, + IonToast, + IonToolbar, } from "@ionic/react"; -import React, { useEffect, useReducer, useState } from "react"; +import React, { useEffect, useState } from "react"; -import '../Perfil.css' -import { useHistory, useLocation } from "react-router"; import { callOutline, documentTextOutline } from "ionicons/icons"; +import { useHistory, useLocation } from "react-router"; +import "../Perfil.css"; -import '../Cadastro/Cadastro.css' import { Color } from "@ionic/core"; +import "../Cadastro/Cadastro.css"; interface cardItem { icon: string; @@ -43,64 +43,69 @@ interface userData { interface LocationState { userData: userData; - + redirectData?: { showToastMessage: boolean; toastColor: Color; toastMessage: string; - } + }; } let items: cardItem[] = [ { icon: documentTextOutline, - label: 'Documento', - description: 'Cadastre seu documento para que seu perfil possa ser verificado', - url: '/perfil/completar/documento', - required: false + label: "Documento", + description: + "Cadastre seu documento para que seu perfil possa ser verificado", + url: "/perfil/completar/documento", + required: false, }, { icon: callOutline, - label: 'Informações de contato', - description: 'Cadastre seu número de telefone celular que para possam contatar você', - url: '/perfil/completar/telefone', - required: false - } -] + label: "Informações de contato", + description: + "Cadastre seu número de telefone celular que para possam contatar você", + url: "/perfil/completar/telefone", + required: false, + }, +]; const CadastroCompletar: React.FC = () => { const history = useHistory(); const location = useLocation(); const [showToast, setShowToast] = useState(false); - const [toastMessage, setToastMessage] = useState(''); + const [toastMessage, setToastMessage] = useState(""); const [toastColor, setToastColor] = useState("primary"); const handleCardClick = (item: cardItem) => { - if (!item.required) return + if (!item.required) return; - history.push({ pathname: item.url, state: { userData: location.state.userData } }); - } + history.push({ + pathname: item.url, + state: { userData: location.state.userData }, + }); + }; useEffect(() => { if (!location.state || !location.state.userData) { - history.push({ pathname: '/perfil' }) + history.push({ pathname: "/perfil" }); } if (location.state && location.state.redirectData) { - const redirectData = location.state.redirectData + const redirectData = location.state.redirectData; if (redirectData.showToastMessage) { - setToastColor(redirectData.toastColor) - setToastMessage(redirectData.toastMessage) - setShowToast(true) + setToastColor(redirectData.toastColor); + setToastMessage(redirectData.toastMessage); + setShowToast(true); } } - if (!location.state.userData.document) items[0].required = true - if (!location.state.userData.phone_number) items[1].required = true + if (!location.state.userData.document) items[0].required = true; + if (!location.state.userData.phone_number) items[1].required = true; }, []); - + return ( @@ -113,9 +118,15 @@ const CadastroCompletar: React.FC = () => { - { items.map((item, index) => { + {items.map((item, index) => { return ( - { handleCardClick(item) }}> + { + handleCardClick(item); + }} + > {item.label} @@ -123,7 +134,7 @@ const CadastroCompletar: React.FC = () => { {item.description} - ) + ); })} { const history = useHistory(); - + const [showToast, setShowToast] = useState(false); const [toastMessage, setToastMessage] = useState(""); const [toastColor, setToastColor] = useState("primary"); - const [carModels, setCarModels] = useState([{ - id_model: '', - name: '' - }]); + const [carModels, setCarModels] = useState([ + { + id_model: "", + name: "", + }, + ]); const [inputValues, setInputValues] = useReducer( (state: any, newState: any) => ({ ...state, ...newState }), { - carPlate: '', - carBrand: '', - carModel: '', + carPlate: "", + carBrand: "", + carModel: "", seats_number: 1, isRented: false, - locator_name: '', - locator_address: '', - locator_complement: '', - locator_city: '', - locator_state: '', + locator_name: "", + locator_address: "", + locator_complement: "", + locator_city: "", + locator_state: "", } ); const clearRentalData = () => { setInputValues({ - carRentalName: '', - complement: '', - city: '', - state: '', - }) + carRentalName: "", + complement: "", + city: "", + state: "", + }); }; const validateForm = (): boolean => { @@ -104,7 +106,7 @@ const CadastroVan: React.FC = () => { return false; } - if ((Number)(vanForm.seats_number) < 1) { + if (Number(vanForm.seats_number) < 1) { setToastMessage("Número de passageiros deve ser positivo!"); setShowToast(true); return false; @@ -126,7 +128,7 @@ const CadastroVan: React.FC = () => { locator_complement: inputValues.locator_complement, locator_city: inputValues.locator_city, locator_state: inputValues.locator_state, - } + }; if (!locatorForm.locator_name) { setToastMessage("Nome do Locador é obrigatório"); @@ -157,74 +159,82 @@ const CadastroVan: React.FC = () => { const handleSubmit = async () => { if (!validateForm()) { - return + return; } // cria registro da van - await vansRoutes.create({ - plate: inputValues.carPlate, - brand: inputValues.carBrand, - model: inputValues.carModel, - seats_number: inputValues.seats_number, - locator_name: inputValues.locator_name, - locator_address: inputValues.locator_address, - locator_complement: inputValues.locator_complement, - locator_city: inputValues.locator_city, - locator_state: inputValues.locator_state - }).then(response => { - if (response.status === 'error') { - setToastMessage(response.message); + await vansRoutes + .create({ + plate: inputValues.carPlate, + brand: inputValues.carBrand, + model: inputValues.carModel, + seats_number: inputValues.seats_number, + locator_name: inputValues.locator_name, + locator_address: inputValues.locator_address, + locator_complement: inputValues.locator_complement, + locator_city: inputValues.locator_city, + locator_state: inputValues.locator_state, + }) + .then((response) => { + if (response.status === "error") { + setToastMessage(response.message); + setShowToast(true); + + return; + } + + history.push({ + pathname: "/minhas-vans", + state: { + redirectData: { + showToastMessage: true, + toastColor: "success", + toastMessage: response.message, + }, + }, + }); + }) + .catch((err) => { + setToastColor("danger"); + setToastMessage(err); setShowToast(true); - - return - } - - history.push({ pathname: '/minhas-vans', state: { - redirectData: { - showToastMessage: true, - toastColor: "success", - toastMessage: response.message, - }, - }}) - }).catch((err) => { - setToastColor("danger") - setToastMessage(err); - setShowToast(true); - }) + }); }; useEffect(() => { - let isMounted = true + let isMounted = true; const getCarsModels = async () => { - const carModelsRes = await carsService.getAllCarModels() - + const carModelsRes = await carsService.getAllCarModels(); + if (carModelsRes.error) { - setToastColor("danger") + setToastColor("danger"); setToastMessage(carModelsRes.error.errorMessage); setShowToast(true); - return + return; } - + if (carModelsRes.data) { if (isMounted) { - setCarModels(carModelsRes.data) + setCarModels(carModelsRes.data); } } - } + }; - getCarsModels() + getCarsModels(); - return () => { isMounted = false } - }, []) + return () => { + isMounted = false; + }; + }, []); return ( Cadastro de veículo - - + + @@ -235,46 +245,62 @@ const CadastroVan: React.FC = () => { Informações do veículo - Placa + Placa setInputValues({ carPlate: e.target.value })} + placeholder="Digite a Placa do Veículo" + onIonChange={(e: any) => + setInputValues({ carPlate: e.target.value }) + } /> {/* TODO, problema de setState para valores vindos de um evento sendo triggerado por um ion-select */} Marca - { setInputValues({ carBrand: e.detail.value }) }}> - { carModels ? carModels.map((carModel, index) => { - return ({carModel.name}) - }) : <> } + { + setInputValues({ carBrand: e.detail.value }); + }} + > + {carModels ? ( + carModels.map((carModel, index) => { + return ( + + {carModel.name} + + ); + }) + ) : ( + <> + )} - Modelo + Modelo setInputValues({ carModel: e.target.value })} + placeholder="Digite o Modelo do Veículo" + onIonChange={(e: any) => + setInputValues({ carModel: e.target.value }) + } /> - - Número de assentos - + Número de assentos setInputValues({ seats_number: e.target.value })} + placeholder="podem ser ocupados por passageiros" + onIonChange={(e: any) => + setInputValues({ seats_number: e.target.value }) + } /> @@ -286,52 +312,67 @@ const CadastroVan: React.FC = () => { O veículo é alugado? - setInputValues({ isRented: e.detail.checked })} /> + + setInputValues({ isRented: e.detail.checked }) + } + /> {inputValues.isRented && (
- - - setInputValues({ locator_name: e.target.value })} - /> + + + + setInputValues({ locator_name: e.target.value }) + } + /> - setInputValues({ locator_address: e.target.value })} - /> - setInputValues({ locator_complement: e.target.value })} - /> - setInputValues({ locator_city: e.target.value })} - /> - setInputValues({ locator_state: e.target.value })} - /> - + + setInputValues({ locator_address: e.target.value }) + } + /> + + setInputValues({ locator_complement: e.target.value }) + } + /> + + setInputValues({ locator_city: e.target.value }) + } + /> + + setInputValues({ locator_state: e.target.value }) + } + /> +
)}
Salvar @@ -341,12 +382,12 @@ const CadastroVan: React.FC = () => { setShowToast(false)} message={toastMessage} duration={2500} - /> + /> ); diff --git a/src/pages/MinhasVans.tsx b/src/pages/MinhasVans.tsx index d9129c5..4b0e93f 100644 --- a/src/pages/MinhasVans.tsx +++ b/src/pages/MinhasVans.tsx @@ -1,21 +1,32 @@ -import { IonBackButton, IonButtons, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, IonContent, IonHeader, IonIcon, IonItem, IonLabel, IonPage, IonTitle, IonToast, IonToolbar } from '@ionic/react'; -import { Color } from '@ionic/core'; -import { carOutline } from 'ionicons/icons'; -import { useContext, useEffect, useState } from 'react'; -import { useHistory, useLocation } from 'react-router'; +import { Color } from "@ionic/core"; +import { + IonBackButton, + IonButtons, + IonCard, + IonCardContent, + IonCardHeader, + IonCardSubtitle, + IonCardTitle, + IonContent, + IonHeader, + IonPage, + IonTitle, + IonToast, + IonToolbar, +} from "@ionic/react"; +import { useEffect, useState } from "react"; +import { useHistory } from "react-router"; -import { UserContext } from '../App'; +import * as vansRoutes from "../services/api/vans"; -import * as vansRoutes from '../services/api/vans'; - -import sessionsService from '../services/functions/sessionsService' +import sessionsService from "../services/functions/sessionsService"; interface VanInfo { plate: string; brand: string; model: string; seats_number: string; - document_status: boolean, + document_status: boolean; locator_name: string; locator_address: string; locator_complement: string; @@ -27,90 +38,104 @@ const MinhasVans: React.FC = () => { const history = useHistory(); const [showToast, setShowToast] = useState(false); - const [toastMessage, setToastMessage] = useState(''); + const [toastMessage, setToastMessage] = useState(""); const [toastColor, setToastColor] = useState("primary"); const [userVans, setUserVans] = useState(); const redirectUserToLogin = () => { - history.push({ pathname: '/login' }); - } + history.push({ pathname: "/login" }); + }; useEffect(() => { const getUserVans = async () => { - let userId = '' + let userId = ""; + + const refreshSessionRes = await sessionsService.refreshSession(); - const refreshSessionRes = await sessionsService.refreshSession() - if (refreshSessionRes.error) { - redirectUserToLogin() - return + redirectUserToLogin(); + return; } - + if (refreshSessionRes.userId) { - userId = refreshSessionRes.userId + userId = refreshSessionRes.userId; } - vansRoutes.getByUserId(userId).then(response => { - if (response.status === 'error') { - setToastColor("danger") - setToastMessage(response.message); - setShowToast(true); - - return - } - - setUserVans(response.data) - }).catch((err) => { - setToastColor("danger") - setToastMessage(err); - setShowToast(true); - }) - } + vansRoutes + .getByUserId(userId) + .then((response) => { + if (response.status === "error") { + setToastColor("danger"); + setToastMessage(response.message); + setShowToast(true); + + return; + } + + setUserVans(response.data); + }) + .catch((err) => { + setToastColor("danger"); + setToastMessage(err); + setShowToast(true); + }); + }; + + getUserVans(); + }, []); - getUserVans() - }, []) - return ( Minhas vans - - - - - - - - { userVans ? userVans.map((van, index) => { + + + + + + + + {userVans ? ( + userVans.map((van, index) => { return ( - - {van.plate} - {van.brand} - {van.model} - - { van.locator_name ? + + {van.plate} + + {van.brand} - {van.model} + + + {van.locator_name ? ( <> - {van.seats_number} assentos - Locador: {van.locator_name} - : - <> - {van.seats_number} assentos - Não é alugado + + {van.seats_number} assentos - Locador: {van.locator_name} + - } + ) : ( + <> + + {van.seats_number} assentos - Não é alugado + + + )} - ) - }) : <>} + ); + }) + ) : ( + <> + )} - setShowToast(false)} - message={toastMessage} - duration={2500} - /> - + setShowToast(false)} + message={toastMessage} + duration={2500} + /> + ); }; diff --git a/src/pages/Perfil.tsx b/src/pages/Perfil.tsx index 3249a56..2a184b0 100644 --- a/src/pages/Perfil.tsx +++ b/src/pages/Perfil.tsx @@ -19,8 +19,6 @@ import { IonToast, IonToolbar, } from "@ionic/react"; -import { useHistory, useLocation } from "react-router-dom"; -import React, { useState, useEffect, useReducer, useContext } from "react"; import { callOutline, cardOutline, @@ -32,14 +30,19 @@ import { shieldCheckmarkOutline, starOutline, } from "ionicons/icons"; +import React, { useContext, useEffect, useReducer, useState } from "react"; +import { useHistory, useLocation } from "react-router-dom"; -import "./Perfil.css"; import LocalStorage from "../LocalStorage"; +import "./Perfil.css"; -import sessionsService from "../services/functions/sessionsService"; -import usersService from "../services/functions/usersService"; -import { UserContext } from "../App"; import { Color } from "@ionic/core"; +import { UserContext } from "../App"; +import sessionsService from "../services/functions/sessionsService"; +import { + checkIfUserIsDriver, + getById, +} from "../services/functions/usersService"; interface ScanNewProps { match: { @@ -131,7 +134,7 @@ const Perfil: React.FC = (props) => { } // get user info by ID - const getByIdRes = await usersService.getById(userId); + const getByIdRes = await getById(userId); if (getByIdRes.error) { if (isVisitor && props.match.params.id) { @@ -147,7 +150,7 @@ const Perfil: React.FC = (props) => { } // check if user is driver (if they have vans) - const userIsDriverRes = await usersService.checkIfUserIsDriver(userId); + const userIsDriverRes = await checkIfUserIsDriver(userId); // if (userIsDriverRes.error) { // setToastColor('warning') @@ -358,6 +361,15 @@ const Perfil: React.FC = (props) => { Buscar passageiros + + history.push({ pathname: "/cadastrar-itinerario" }) + } + > + + Cadastrar itinerário + diff --git a/src/pages/Transportes/Transportes.tsx b/src/pages/Transportes/Transportes.tsx index 9853750..aa3ae96 100644 --- a/src/pages/Transportes/Transportes.tsx +++ b/src/pages/Transportes/Transportes.tsx @@ -1,52 +1,34 @@ import { + IonButton, + IonCard, + IonCardContent, + IonCheckbox, IonContent, - IonPage, IonFab, IonFabButton, - IonIcon, - IonCard, - IonInput, - IonRow, - IonCol, - IonCardContent, - IonButton, - IonHeader, - IonToolbar, - IonButtons, - IonBackButton, - IonTabs, - IonTabBar, - IonTabButton, - IonLabel, - IonBadge, - IonRouterOutlet, - IonSlides, - IonSlide, - IonModal, - IonList, - IonRadioGroup, - IonListHeader, - IonItem, - IonRadio, - IonCheckbox, IonFooter, + IonHeader, + IonIcon, + IonItem, + IonLabel, + IonModal, + IonPage, + IonRadio, + IonRadioGroup, + IonSlide, + IonSlides, IonToast, + IonToolbar, } from "@ionic/react"; import { - arrowBack, - arrowBackOutline, arrowForwardOutline, chevronBackOutline, - chevronForwardOutline, closeOutline, - locateOutline, - locationOutline, - timeOutline, } from "ionicons/icons"; import { useEffect, useState } from "react"; import { useHistory, useLocation } from "react-router"; -import { getTransportes } from "../../services/functions/transportsService"; import { createUserSearch } from "../../services/api/users"; +import { getTransportes } from "../../services/functions/transportsService"; import "./Transportes.css"; interface InfoBusca { @@ -63,8 +45,8 @@ const Transportes: React.FC = () => { const [transportes, setTransportes] = useState([]); const [showModalFilters, setShowModalFilters] = useState(false); const [showToast, setShowToast] = useState(false); - const [messageToast, setMessageToast ] = useState(''); - const [toastColor, setToastColor] = useState('success'); + const [messageToast, setMessageToast] = useState(""); + const [toastColor, setToastColor] = useState("success"); useEffect(() => { if (props) { @@ -77,15 +59,21 @@ const Transportes: React.FC = () => { setTransportes(data); } - function criaAlerta(){ - createUserSearch(props.coordinatesFrom.lat, props.coordinatesFrom.lng, props.addressTo.label).then(() => { - setMessageToast('Alerta criado com sucesso!'); - setShowToast(true); - }).catch((err:any) => { - setMessageToast('Não foi possível criar o alerta!'); - setToastColor('danger'); - setShowToast(true); - }) + function criaAlerta() { + createUserSearch( + props.coordinatesFrom.lat, + props.coordinatesFrom.lng, + props.addressTo.label + ) + .then(() => { + setMessageToast("Alerta criado com sucesso!"); + setShowToast(true); + }) + .catch((err: any) => { + setMessageToast("Não foi possível criar o alerta!"); + setToastColor("danger"); + setShowToast(true); + }); } return ( @@ -107,7 +95,7 @@ const Transportes: React.FC = () => {
- {transportes && transportes.length > 0? ( + {transportes && transportes.length > 0 ? (
@@ -124,9 +112,11 @@ const Transportes: React.FC = () => {
- ) - : - (

Não foi encontrado nenhum transporte que atenda essa rota.

)} + ) : ( +

+ Não foi encontrado nenhum transporte que atenda essa rota. +

+ )} {transportes && transportes.map((record: any, index: any) => { return ( @@ -139,7 +129,7 @@ const Transportes: React.FC = () => {
); - })} + })}
criaAlerta()}>Criar Alerta @@ -208,7 +198,7 @@ const Transportes: React.FC = () => { setShowToast(false)} message={messageToast} diff --git a/src/services/api/transports.ts b/src/services/api/transports.ts index c9d2677..b4d64c6 100644 --- a/src/services/api/transports.ts +++ b/src/services/api/transports.ts @@ -1,10 +1,9 @@ -import instance from './api'; +import instance from "./api"; // import LocalStorage from '../LocalStorage'; -import transportsRoutes from '../../constants/routes/transportsRoutes'; -import { AxiosRequestHeaders } from 'axios'; -import LocalStorage from '../../LocalStorage'; -import { setStore } from '../../store/RecordsStore'; +import { AxiosRequestHeaders } from "axios"; +import transportsRoutes from "../../constants/routes/transportsRoutes"; +import LocalStorage from "../../LocalStorage"; let token: string; let header: AxiosRequestHeaders; @@ -13,26 +12,29 @@ function updateHeader() { token = LocalStorage.getToken(); header = { - "Accept": 'application/json', - "Content-Type": 'application/json', - "Authorization": 'Bearer ' + token - } + Accept: "application/json", + "Content-Type": "application/json", + Authorization: "Bearer " + token, + }; } export interface getTransportsRequest { coordinatesFrom: { - lat: number, - lng: number - }, + lat: number; + lng: number; + }; coordinatesTo: { - lat: number, - lng: number - } + lat: number; + lng: number; + }; } export async function get(coordinates: getTransportsRequest) { updateHeader(); - const response = await instance.get(transportsRoutes.get.url + `/${coordinates}`, { headers: header }); + const response = await instance.get( + transportsRoutes.get.url + `/${coordinates}`, + { headers: header } + ); return response.data; -} \ No newline at end of file +} diff --git a/src/services/api/users.ts b/src/services/api/users.ts index 20c1246..8c9a5e2 100644 --- a/src/services/api/users.ts +++ b/src/services/api/users.ts @@ -1,10 +1,10 @@ -import instance from './api'; +import instance from "./api"; // import LocalStorage from '../LocalStorage'; -import userRoutes from '../../constants/routes/usersRoutes'; -import { AxiosRequestHeaders } from 'axios'; -import LocalStorage from '../../LocalStorage'; -import { setStore } from '../../store/RecordsStore'; +import { AxiosRequestHeaders } from "axios"; +import userRoutes from "../../constants/routes/usersRoutes"; +import LocalStorage from "../../LocalStorage"; +import { setStore } from "../../store/RecordsStore"; let token: string; let header: AxiosRequestHeaders; @@ -13,20 +13,20 @@ function updateHeader() { token = LocalStorage.getToken(); header = { - "Accept": 'application/json', - "Content-Type": 'application/json', - "Authorization": 'Bearer ' + token - } + Accept: "application/json", + "Content-Type": "application/json", + Authorization: "Bearer " + token, + }; } export interface CadastroResponse { - message?: string; - - token?: { - token: string; - }; - - error?: string; + message?: string; + + token?: { + token: string; + }; + + error?: string; } export interface CadastroRequest { @@ -63,21 +63,28 @@ export async function create(CadastroRequest: any) { export async function getById(userId: string) { updateHeader(); - const response = await instance.get(userRoutes.get.url + `/${userId}`, { headers: header }); + const response = await instance.get(userRoutes.get.url + `/${userId}`, { + headers: header, + }); return response.data; } export async function update(userData: UpdateUserRequest) { updateHeader(); - const response = await instance.patch(userRoutes.update.url, userData, { headers: header }); + const response = await instance.patch(userRoutes.update.url, userData, { + headers: header, + }); return response.data; } export async function checkIfUserIsDriver(id_user: string) { updateHeader(); - const response = await instance.get(userRoutes.checkIfUserIsDriver.url + `/${id_user}`, { headers: header }); + const response = await instance.get( + userRoutes.checkIfUserIsDriver.url + `/${id_user}`, + { headers: header } + ); return response.data; } @@ -85,25 +92,39 @@ export async function checkIfUserIsDriver(id_user: string) { export async function getSocialInfo(userId: string) { updateHeader(); - const response = await instance.get(userRoutes.getSocialInfo.url + `/${userId}`, { headers: header }); + const response = await instance.get( + userRoutes.getSocialInfo.url + `/${userId}`, + { headers: header } + ); return response.data; } export async function getUsersSearching(currentPoint: any) { // Replace lat/long with values from get current location. - // Allow choosing of radius? - // Offset could = amount loaded in an infinite scroll? - var latitude = currentPoint.latitude, longitude = currentPoint.longitude, radius = 3000, offset = 0; - // const response = await fetch(`http://localhost:4000/get-records?latitude=${ latitude }&longitude=${ longitude }&radius=${ radius }&offset=${ offset }`); - const response = await instance.post(`${userRoutes.getUsersSearching.url}`, currentPoint) - // const data = await response.json(); - console.log(response.data) - setStore(response.data); + // Allow choosing of radius? + // Offset could = amount loaded in an infinite scroll? + // var latitude = currentPoint.latitude, longitude = currentPoint.longitude, radius = 3000, offset = 0; + // const response = await fetch(`http://localhost:4000/get-records?latitude=${ latitude }&longitude=${ longitude }&radius=${ radius }&offset=${ offset }`); + const response = await instance.post( + `${userRoutes.getUsersSearching.url}`, + currentPoint + ); + // const data = await response.json(); + console.log(response.data); + setStore(response.data); } -export async function createUserSearch(latitude_from: any, longitude_from: any, addres_to: any) { - const response = await instance.post(`${userRoutes.createUserSearch.url}`, { latitude_from, longitude_from, addres_to }); +export async function createUserSearch( + latitude_from: any, + longitude_from: any, + addres_to: any +) { + const response = await instance.post(`${userRoutes.createUserSearch.url}`, { + latitude_from, + longitude_from, + addres_to, + }); - console.log(response) - setStore(response); -} \ No newline at end of file + console.log(response); + setStore(response); +} diff --git a/src/services/functions/carsService.ts b/src/services/functions/carsService.ts index e46855e..fe2bfc8 100644 --- a/src/services/functions/carsService.ts +++ b/src/services/functions/carsService.ts @@ -8,20 +8,18 @@ interface getAllCarModelsReturn { error?: { errorMessage: string; - } + }; } interface getAllCarModelsRes { status?: string; - message: string + message: string; data?: { id_model: string; name: string; }[]; - - } const getAllCarModels = async (): Promise => { @@ -48,4 +46,8 @@ const getAllCarModels = async (): Promise => { } }; -export default { getAllCarModels }; +const method = { + getAllCarModels, +}; + +export default method; diff --git a/src/services/functions/sessionsService.ts b/src/services/functions/sessionsService.ts index 5685c19..38dedff 100644 --- a/src/services/functions/sessionsService.ts +++ b/src/services/functions/sessionsService.ts @@ -14,7 +14,7 @@ interface refreshSessionResponse { const refreshSession = async (): Promise => { try { - let res: refreshSessionResponse = await sessionRoutes.refresh() + let res: refreshSessionResponse = await sessionRoutes.refresh(); if (res.status === "error") { return { @@ -26,7 +26,7 @@ const refreshSession = async (): Promise => { return { userId: res.userId, }; - } catch(err) { + } catch (err) { return { error: true, errorMessage: "Por favor, autentique-se.", @@ -40,7 +40,11 @@ const refreshSession = async (): Promise => { // } else { // // Anything else // } -// } + // } }; -export default { refreshSession } \ No newline at end of file +const method = { + refreshSession, +}; + +export default method; diff --git a/src/services/functions/transportsService.ts b/src/services/functions/transportsService.ts index 611196a..015b12c 100644 --- a/src/services/functions/transportsService.ts +++ b/src/services/functions/transportsService.ts @@ -1,20 +1,18 @@ -import * as transportsRoutes from '../api/transports'; - interface CoordinatesRequest { - coordinatesFrom:{ - lat: number, - lng: number - }, - coordinatesTo:{ - lat: number, - lng: number - } + coordinatesFrom: { + lat: number; + lng: number; + }; + coordinatesTo: { + lat: number; + lng: number; + }; } -export async function getTransportes(request: CoordinatesRequest) : Promise { +export async function getTransportes( + request: CoordinatesRequest +): Promise { try { - let res : any = await transportsRoutes.get(request); - } catch (error) { - - } + // let res : any = await transportsRoutes.get(request); + } catch (error) {} } diff --git a/src/services/functions/usersService.ts b/src/services/functions/usersService.ts index 87b4f40..67e8b6a 100644 --- a/src/services/functions/usersService.ts +++ b/src/services/functions/usersService.ts @@ -10,10 +10,10 @@ interface getByIdReturn { bio: string; document_type: string; document: string; - }, + }; error?: { errorMessage: string; - } + }; } interface getByIdRes { @@ -29,65 +29,67 @@ interface getByIdRes { bio: string; document_type: string; document: string; - }, + }; } -const getById = async (userId: string): Promise => { +export const getById = async (userId: string): Promise => { try { - let res: getByIdRes = await usersRoutes.getById(userId) + let res: getByIdRes = await usersRoutes.getById(userId); if (res.status === "error") { return { error: { errorMessage: res.message, - } + }, }; } return { userData: res.data, }; - } catch(err) { + } catch (err) { return { error: { errorMessage: "Por favor, autentique-se.", - } + }, }; } }; interface getByIdReturn { data?: { - phone: '', - whatsapp: '', - facebook: '', - telegram: '', - }, + phone: ""; + whatsapp: ""; + facebook: ""; + telegram: ""; + }; error?: { errorMessage: string; - } + }; } -const getUserSocialInfo = async (userId: string): Promise => { +export const getUserSocialInfo = async ( + userId: string +): Promise => { try { - let res: getByIdRes = await usersRoutes.getSocialInfo(userId) + let res: getByIdRes = await usersRoutes.getSocialInfo(userId); if (res.status === "error") { return { error: { errorMessage: res.message, - } + }, }; } return { userData: res.data, }; - } catch(err) { + } catch (err) { return { error: { errorMessage: "Por favor, autentique-se.", - } + }, }; } }; @@ -96,7 +98,7 @@ interface checkIfUserIsDriverReturn { result?: boolean; error?: { errorMessage: string; - } + }; } interface checkIfUserIsDriverResponse { @@ -105,31 +107,32 @@ interface checkIfUserIsDriverResponse { result?: boolean; error?: { errorMessage: string; - } + }; } -const checkIfUserIsDriver = async (id_user: string): Promise => { +export const checkIfUserIsDriver = async ( + id_user: string +): Promise => { try { - let res: checkIfUserIsDriverResponse = await usersRoutes.checkIfUserIsDriver(id_user) + let res: checkIfUserIsDriverResponse = + await usersRoutes.checkIfUserIsDriver(id_user); if (res.status === "error") { return { error: { errorMessage: res.message, - } + }, }; } return { result: res.result, }; - } catch(err) { + } catch (err) { return { error: { errorMessage: "Por favor, autentique-se.", - } + }, }; } }; - -export default { getById, getUserSocialInfo, checkIfUserIsDriver } \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 3d4782b..9d60e16 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1377,7 +1377,7 @@ ionicons "^6.0.3" tslib "^2.1.0" -"@ionic/react-router@^6.0.0": +"@ionic/react-router@^6.2.5": version "6.2.5" resolved "https://registry.yarnpkg.com/@ionic/react-router/-/react-router-6.2.5.tgz#b10041b0edc7ca67a5e95b2184dcc10cac9a6459" integrity sha512-56KygdYv/KExvZLlCKTJp84l+4/5Y5TY9G8eIENo75Wunr8CA+a1CFFbR75ov4pckJGcVKkpAgJPDQGndrEBzg== @@ -1385,7 +1385,7 @@ "@ionic/react" "^6.2.5" tslib "*" -"@ionic/react@^6.0.0", "@ionic/react@^6.2.5": +"@ionic/react@^6.2.5": version "6.2.5" resolved "https://registry.yarnpkg.com/@ionic/react/-/react-6.2.5.tgz#6a9815c3cdbf8a8d48972bcdb9cf82cdccb9c50c" integrity sha512-dvne9iY97uCb7+Wen0cRAY0nxL+ecKAMVBK6CLWMLec6Eh8NVE3BU2tG/4ZjheNrclWCPAv20us8zLbJVIht0g==