Skip to content

Commit e2b5dbb

Browse files
committed
feat: ✨ Refatora lógica de autenticação e gerenciamento de pedidos - Atualiza o hook useCheckRotas para redirecionar usuários não autenticados. - Altera a função de adição de pedidos para usar createOrder. - Implementa a função getOrder para buscar pedidos do localStorage. - Adiciona idUser ao tipo IPedido para associar pedidos ao usuário.
1 parent 42f2cd2 commit e2b5dbb

9 files changed

Lines changed: 129 additions & 50 deletions

File tree

src/hooks/useCheckRotas.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,24 +12,21 @@ const useCheckRotas = () => {
1212
const navigate = useNavigate();
1313
const location = useLocation();
1414

15-
useEffect(() => {
16-
if (!isLogado) {
17-
navigate("/login");
18-
}
19-
}, [dispatch, isLogado , navigate]);
20-
2115
useEffect(() => {
2216
const privatePrefixes = [
2317
`/${CheckoutSteps.CHECKOUT}`,
24-
`/${CheckoutSteps.PEDIDOS}`,
25-
`/${CheckoutSteps.FAVORITOS}`,
18+
`/${CheckoutSteps.PEDIDOS}`,
19+
`/${CheckoutSteps.FAVORITOS}`,
2620
];
2721
if (
2822
privatePrefixes.some((prefix) => location.pathname.startsWith(prefix))
2923
) {
3024
dispatch(checkAuthenticatedUser());
25+
if (!isLogado) {
26+
navigate("/login");
27+
}
3128
}
32-
}, [isLogado, navigate, location.pathname , dispatch]);
29+
}, [isLogado, navigate, location.pathname, dispatch]);
3330
};
3431

35-
export default useCheckRotas;
32+
export default useCheckRotas;

src/pages/checkout/Summary/index.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import usePaymentConfirmed from "@/hooks/usePaymentConfirmed";
1010
import Botao from "@/components/Botao";
1111
import { useDispatch } from "react-redux";
1212
import { AppDispatch } from "@/store";
13-
import { addPedido } from "@/store/reducers/pedidos";
13+
import { addPedidoFetch } from "@/store/reducers/pedidos";
1414
import { useNavigate } from "react-router-dom";
1515
import useCleanStatus from "@/hooks/useCleanStatus";
1616
const Summary = () => {
@@ -27,7 +27,7 @@ const Summary = () => {
2727
const clearStatus = useCleanStatus();
2828
const handlefinalizePurchase = () => {
2929
dispatch(
30-
addPedido({
30+
addPedidoFetch({
3131
status: "concluido",
3232
date: cart.data,
3333
totValue: cart.totValue + frete.price,

src/pages/login/FormLogin/index.tsx

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ import { useDispatch } from "react-redux";
1010
import { loginUser } from "@/store/reducers/usuario";
1111
import { useSelector } from "react-redux";
1212
import { RootState } from "@/types/store";
13-
import { useNavigate } from "react-router-dom";
13+
import { useLocation, useNavigate } from "react-router-dom";
1414
import { AppDispatch } from "@/store";
1515

1616
const FormLogin = () => {
1717
const dispatch = useDispatch<AppDispatch>();
1818
const navigate = useNavigate();
19+
const location = useLocation();
1920
const user = useSelector((state: RootState) => state.usuario);
2021
const cart = useSelector((state: RootState) => state.carrinho);
2122
const {
@@ -32,16 +33,11 @@ const FormLogin = () => {
3233
});
3334

3435
useEffect(() => {
35-
if (isSubmitSuccessful && user.isLogado) {
36-
if (cart.data.length) {
37-
navigate("/carrinho");
38-
reset();
39-
return;
40-
}
41-
navigate("/");
36+
if (isSubmitSuccessful || user.isLogado) {
4237
reset();
38+
navigate(-1);
4339
}
44-
}, [isSubmitSuccessful, reset, user, cart, navigate]);
40+
}, [isSubmitSuccessful, reset, user, cart, navigate, location]);
4541
const submit = (data: ILogin) => {
4642
dispatch(loginUser(data));
4743
};

src/pages/login/index.tsx

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,13 @@ import Section from "@/components/Section";
22
import Typography from "@/components/Typography";
33
import { thema } from "@/styles/thema";
44
import FormLogin from "./FormLogin";
5-
import { Link, useNavigate } from "react-router-dom";
5+
import { Link } from "react-router-dom";
66
import useWriteSlowly from "@/hooks/useWriteSlowly";
77
import { DivFadeInForm } from "@/styles/forms";
8-
import { useSelector } from "react-redux";
9-
import { RootState } from "@/types/store";
10-
import { useEffect } from "react";
118
const title = "Entre com sua conta!";
129
const Login = () => {
1310
const writeTitle = useWriteSlowly(title);
14-
const { isLogado } = useSelector((state: RootState) => state.usuario);
15-
const navigate = useNavigate();
1611

17-
useEffect(() => {
18-
if (isLogado) {
19-
navigate("/");
20-
}
21-
}, [isLogado, navigate]);
22-
2312
return (
2413
<Section classNameSection="secao login">
2514
<Typography

src/pages/pedidos/PedidosCard.tsx

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -43,21 +43,22 @@ const PedidosCard = ({ product, pedido }: PedidosCardProps) => {
4343
</Typography>
4444
<CardPedidoDetails>
4545
{pedido.date.map((date) =>
46-
date.details.map((detail) => (
46+
date.details.map((detail) =>
4747
product.id === date.id ? (
4848
<Typography
49-
classNameTypograph="basicParagraphSmall"
50-
elementoHtml="p"
51-
isColor={thema.colorsPrimary.cinzaChumbo}
52-
>
53-
<strong>Cor: </strong>
54-
{detail.cor} - <strong>Tamanho: </strong>
55-
{detail.tamanho}.
56-
</Typography>
49+
key={detail.id}
50+
classNameTypograph="basicParagraphSmall"
51+
elementoHtml="p"
52+
isColor={thema.colorsPrimary.cinzaChumbo}
53+
>
54+
<strong>Cor: </strong>
55+
{detail.cor} - <strong>Tamanho: </strong>
56+
{detail.tamanho}.
57+
</Typography>
5758
) : null
58-
)))}
59+
)
60+
)}
5961
</CardPedidoDetails>
60-
6162
</CardPedidoContent>
6263
</CardPedido>
6364
);

src/pages/pedidos/index.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,18 @@ import { RootState } from "@/types/store";
77
import CartIsEmpty from "@/components/CartIsEmpty";
88
import NewsLetter from "@/components/NewsLetter";
99
import Facilidades from "@/components/Facilidades";
10+
import { useEffect } from "react";
11+
import { useDispatch } from "react-redux";
12+
import { AppDispatch } from "@/store";
13+
import { fetchGetPedidos } from "@/store/reducers/pedidos";
1014
const Pedidos = () => {
1115
const pedidos = useSelector((state: RootState) => state.pedidos);
16+
const dispatch = useDispatch<AppDispatch>();
17+
18+
useEffect(() => {
19+
dispatch(fetchGetPedidos());
20+
}, [dispatch]);
21+
1222
return (
1323
<>
1424
<Section classNameSection="secao produtos">

src/service/index.ts

Lines changed: 71 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import apiCep from "@/api";
22
import { v4 as uuidv4 } from "uuid";
33
import { IData } from "@/types/checkout";
4-
import { IFrete } from "@/types/store";
4+
import { IFrete, IPedido } from "@/types/store";
55
import {
66
DateUsuario,
77
ILogin,
@@ -159,12 +159,17 @@ export const authenticateUserFetch = async (
159159
try {
160160
const usuarios = getStorage("user") as UsuarioLocalStorage[];
161161
/* verifica se o email existe */
162-
if (!Array.isArray(usuarios) || !usuarios.some((u) => u.email === data.email)) {
162+
if (
163+
!Array.isArray(usuarios) ||
164+
!usuarios.some((u) => u.email === data.email)
165+
) {
163166
reject(new Error("Email não cadastrado"));
164167
return;
165168
}
166169

167-
const user = usuarios.find((user) => user.email === data.email) as UsuarioLocalStorage;
170+
const user = usuarios.find(
171+
(user) => user.email === data.email
172+
) as UsuarioLocalStorage;
168173
const isValid = await verifyPassword(
169174
data.password,
170175
user.salt,
@@ -202,13 +207,13 @@ export const authenticateUserFetch = async (
202207
});
203208
};
204209
/* Função para verificar se o usuário está logado */
205-
export const checkAuthenticated = (): Promise<UsuarioState> => {
210+
export const checkAuthenticated = async (): Promise<UsuarioState> => {
206211
return new Promise((resolve, reject) => {
207212
try {
208213
const validToken = getAccessToken();
209214
const dataUser = getSessionStorage("dataUser") as UsuarioState;
210215

211-
if (!validToken || validToken !== dataUser.accessToken){
216+
if (!validToken || validToken !== dataUser.accessToken) {
212217
console.warn("Token inválido ou expirado");
213218
resolve({ isLogado: false } as UsuarioState);
214219
return;
@@ -227,3 +232,64 @@ export const checkAuthenticated = (): Promise<UsuarioState> => {
227232
}
228233
});
229234
};
235+
236+
/* Api simular pedido */
237+
238+
export const getOrder = async (): Promise<IPedido[]> => {
239+
return new Promise((resolve, reject) => {
240+
try {
241+
/* Verifica se o usuário está logado */
242+
const user = getSessionStorage("dataUser") as UsuarioState;
243+
if (!user) {
244+
console.warn("Usuário nao autenticado", user);
245+
reject(new Error("Usuário não autenticado"));
246+
return;
247+
}
248+
/* Pegando os pedidos do localStorage */
249+
const pedidos = getStorage("pedidos") as IPedido[];
250+
if (Array.isArray(pedidos)) {
251+
resolve(pedidos.filter((p) => p.idUser === user.id));
252+
return;
253+
}
254+
resolve([]);
255+
} catch (error) {
256+
console.error("Erro ao buscar pedidos:", error);
257+
reject(error);
258+
}
259+
});
260+
}
261+
export const createOrder = async (newPedidos: IPedido): Promise<IPedido[]> => {
262+
return new Promise((resolve, reject) => {
263+
try {
264+
console.log("Criando pedido:", newPedidos);
265+
/* Verifica se o usuário está logado */
266+
const user = getSessionStorage("dataUser") as UsuarioState;
267+
if (!user) {
268+
console.warn("Usuário nao autenticado", user);
269+
reject(new Error("Usuário não autenticado"));
270+
return;
271+
}
272+
273+
/* Adicionando o id do usuário */
274+
const addUserPedido = {
275+
...newPedidos,
276+
idUser: user.id,
277+
id: uuidv4(),
278+
};
279+
280+
/* Adicionando o pedido */
281+
const pedidos = getStorage("pedidos") as IPedido[];
282+
if (Array.isArray(pedidos)) {
283+
pedidos.push(addUserPedido);
284+
setStorage("pedidos", pedidos);
285+
resolve(pedidos.filter((p) => p.idUser === user.id));
286+
return;
287+
}
288+
setStorage("pedidos", [addUserPedido]);
289+
resolve([addUserPedido]);
290+
} catch (error) {
291+
console.error("Erro ao adicionar pedido:", error);
292+
reject(error);
293+
}
294+
});
295+
};

src/store/reducers/pedidos.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
1+
import { createOrder, getOrder } from "@/service";
12
import { IPedido } from "@/types/store";
23
import { showSuccessNotification } from "@/utils/showSuccessNotification";
3-
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
4+
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
45
import { v4 as uuidv4 } from "uuid";
56

67
const initialState: IPedido[] = [];
78

9+
export const fetchGetPedidos = createAsyncThunk<IPedido[]>(
10+
"pedidos/fetchGetPedidos",
11+
getOrder
12+
)
13+
14+
export const addPedidoFetch = createAsyncThunk<IPedido[], IPedido>(
15+
"pedidos/addPedidoFetch",
16+
createOrder
17+
);
18+
819
const pedidosSlice = createSlice({
920
name: "pedidos",
1021
initialState,
@@ -25,6 +36,14 @@ const pedidosSlice = createSlice({
2536
];
2637
},
2738
},
39+
extraReducers: (builder) => {
40+
builder.addCase(addPedidoFetch.pending, (state) => state);
41+
builder.addCase(addPedidoFetch.rejected, (state) => state);
42+
builder.addCase(addPedidoFetch.fulfilled, (_, { payload }) => payload);
43+
builder.addCase(fetchGetPedidos.pending, (state) => state);
44+
builder.addCase(fetchGetPedidos.rejected, (state) => state);
45+
builder.addCase(fetchGetPedidos.fulfilled, (_, { payload }) => payload);
46+
},
2847
});
2948

3049
export const { addPedido } = pedidosSlice.actions;

src/types/store.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export enum CheckoutSteps {
8484

8585
export interface IPedido {
8686
id?: string;
87+
idUser?: string;
8788
status: "pendente" | "concluido" | "cancelado";
8889
date: ICart[];
8990
totValue: number;

0 commit comments

Comments
 (0)