Skip to content

Commit

Permalink
Merge pull request #30 from FGA0138-MDS-Ajax/server
Browse files Browse the repository at this point in the history
Server
  • Loading branch information
Jose1277 authored Jul 1, 2024
2 parents 51ada8c + 0ddeb44 commit 4d98ffc
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 63 deletions.
25 changes: 25 additions & 0 deletions projeto/client/actions/editar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import * as z from "zod";
import { SettingsSchema } from "@/schemas";

export const editar = async (values: z.infer<typeof SettingsSchema>) => {
const validatedFields = SettingsSchema.safeParse(values);
console.log(validatedFields);
if (!validatedFields.success) {
return { error: validatedFields.error };
}

try {
const response = await fetch('http://localhost:8000/auth/editar', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(validatedFields.data)
});
return response.json();
}
catch (error) {
console.error('Erro durante a edição:', error);
return { error: error || 'Erro ao conectar com o servidor' };
}
};
1 change: 0 additions & 1 deletion projeto/client/components/auth/card-register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export const CardWrapper = ({
</CardContent>
{showSocial && (
<CardFooter>
<Social />
</CardFooter>
)}
<CardFooter>
Expand Down
5 changes: 0 additions & 5 deletions projeto/client/components/auth/card-wrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,6 @@ export const CardWrapper = ({
<CardContent>
{children}
</CardContent>
{showSocial && (
<CardFooter>
<Social />
</CardFooter>
)}
<CardFooter>
<BackButton
label={backButtonLabel}
Expand Down
122 changes: 68 additions & 54 deletions projeto/client/components/auth/settings-form.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
'use client';

import * as z from "zod";

import { useForm } from "react-hook-form";
import { useState, useTransition } from "react";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

import { SettingsSchema } from "@/schemas";
import { Input } from "@/components/ui/input";
import {
Form,
FormControl,
Expand All @@ -15,13 +13,13 @@ import {
FormLabel,
FormMessage,
} from "@/components/ui/form";
import React from "react";
import Select from "react-select";
import { CardWrapper } from "./card-register"
import { CardWrapper } from "./card-register";
import { Button } from "@/components/ui/button";
import { FormError } from "@/components/form-error";
import { FormSuccess } from "@/components/form-sucess";
import { Label } from "../ui/label";
import { useSession } from "next-auth/react";
import { editar } from "@/actions/editar";

const TimeSelect = [
{ value: "America_Mineiro", label: "America Mineiro" },
Expand All @@ -44,77 +42,93 @@ const TimeSelect = [
{ value: "Palmeiras", label: "Palmeiras" },
{ value: "Sao_Paulo", label: "Sao Paulo" },
{ value: "Vasco", label: "Vasco" },
{ value: "Vitoria", label: "Vitoria" }
]

{ value: "Vitoria", label: "Vitoria" },
];

export const SettingsForm = () => {
const [error, setError] = useState<string | undefined>("");
const [success, setSuccess] = useState<string | undefined>("");
const [isPending, startTransition] = useTransition();
const { data: session } = useSession();
const id = session?.user?.id;

const form = useForm<z.infer<typeof SettingsSchema>>({
resolver: zodResolver(SettingsSchema),
defaultValues: {
time:"",
usuario: "",
time: "",
},
});

const onSubmit = (values: z.infer<typeof SettingsSchema>) => {
console.log(values);
}
const onSubmit = async (values: z.infer<typeof SettingsSchema>) => {
console.log('onSubmit called with values:', values);
if (id === undefined) {
setError("ID do usuário não encontrado");
return;
}
const payload = {
id: id,
time: values.time,
};
console.log('Payload:', payload);
setError("");
setSuccess("");

startTransition(async () => {
try {
const data = await editar(payload);
console.log('Response from editar:', data);
if (data.error) {
setError(data.error.message || 'Erro desconhecido');
} else {
setSuccess("Mudança de time realizada com sucesso!");
form.reset();
window.location.href = '/home';
}
} catch (error) {
setError('Erro ao editar: ' + error);
}
});
};

return (
<CardWrapper
headerLabel="Altere seu perfil"
>
<CardWrapper headerLabel="Altere seu perfil">
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-6"
>
<div className="sapace-y-4">
<FormField
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormItem>
<input type="hidden" name="id" value={id} />
</FormItem>
<div className="space-y-4">
<Controller
control={form.control}
name="time"
render={({field}) => (
render={({ field }) => (
<FormItem>
<FormLabel>Time</FormLabel>
<FormControl>
<Select
options={TimeSelect}
>
</Select>
</FormControl>
</FormItem>
)}
></FormField>
<br/>
<FormField
control={form.control}
name="usuario"
render={({ field}) => (
<FormItem>
<FormLabel>Usuário</FormLabel>
<FormControl>
<Input
{...field}
placeholder="usuário"
type="text"
<Select
{...field}
options={TimeSelect}
value={TimeSelect.find(option => option.value === field.value)}
onChange={(option) => {
field.onChange(option ? option.value : '');
console.log('Selected time:', option?.value);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
></FormField>
/>

</div>
<FormError message=""/>
<FormSuccess message=""/>
<Button
type="submit"
className="bg-[#005B14] w-full"
>

<FormError message={error} />
<FormSuccess message={success} />
<Button type="submit" className="bg-[#005B14] w-full">
Salvar
</Button>
</form>
</Form>
</CardWrapper>
);
};
};
Binary file modified projeto/client/public/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 1 addition & 3 deletions projeto/client/schemas/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,5 @@ export const CadastroSchema = z.object({

export const SettingsSchema = z.object({
time: z.string(),
usuario: z.string().min(2, {
message: "Usuário inválido"
}),
id: z.number().int().positive()
});
9 changes: 9 additions & 0 deletions projeto/server/src/repositories/auth.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,15 @@ class AuthRepository {
throw error;
}
}

async editar(time_favorito:string , id:number){
const conn = await mysqlConn.getConnection();
const [result] = await conn.query(
'UPDATE USUARIO SET TIME_FAVORITO = ? WHERE IDUSUARIO = ?',
[time_favorito, id]
);
return result;
}
}

export default new AuthRepository();
12 changes: 12 additions & 0 deletions projeto/server/src/routes/auth.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,17 @@ router.post('/login', async (req, res) => {
}
});

router.post('/editar', async (req, res) => {
const time = req.body.time;
const id = req.body.id;
console.log(time, id);
try{
const result = await AuthRepository.editar(time, id);
res.send(result);
}
catch(err) {
res.status(400).send(err);
}
});

export default router;

0 comments on commit 4d98ffc

Please sign in to comment.