tokenRefresh, crear y editar productos con img funcionando
This commit is contained in:
@@ -10,8 +10,7 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@repo/shadcn/card';
|
||||
import { Edit } from 'lucide-react';
|
||||
|
||||
import {ProductList} from '@/feactures/inventory/components/products/see-product'
|
||||
|
||||
export default async function SurveyResponsePage({
|
||||
params,
|
||||
@@ -39,56 +38,57 @@ export default async function SurveyResponsePage({
|
||||
// console.log(data.data);
|
||||
|
||||
return (
|
||||
<ProductList product={product} />
|
||||
// <PageContainer>
|
||||
<main className='px-4 lg:px-6 flex flex-col md:flex-row gap-3 lg:gap-4 md:relative'>
|
||||
<div className='w-full flex justify-between flex-col'>
|
||||
// <main className='px-4 lg:px-6 flex flex-col md:flex-row gap-3 lg:gap-4 md:relative'>
|
||||
// <div className='w-full flex justify-between flex-col'>
|
||||
|
||||
<img
|
||||
className="border-2 object-contain w-full f-full min-h-[400px] md:h-[70vh] aspect-square rounded-2xl"
|
||||
src={`http://localhost:3000/uploads/inventory/${product.userId}/${product.urlImg}`}
|
||||
alt=""
|
||||
/>
|
||||
// <img
|
||||
// className="border-2 object-contain w-full f-full min-h-[400px] md:h-[70vh] aspect-square rounded-2xl"
|
||||
// src={`http://localhost:3000/uploads/inventory/${product.userId}/${product.urlImg}`}
|
||||
// alt=""
|
||||
// />
|
||||
|
||||
<section className=''>
|
||||
<img
|
||||
className="border-2 object-cover w-[64px] h-[64px] md:w-[96px] md:h-[96px] aspect-square rounded-2xl"
|
||||
src={`http://localhost:3000/uploads/inventory/${product.userId}/${product.urlImg}`}
|
||||
alt=""
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
<Card className="flex flex-col md:w-[400px] lg:w-[500px] min-h-[400px] md:h-[85vh] md:overflow-auto md:sticky top-0 right-0">
|
||||
<CardHeader className='py-2 px-2 md:px-4 lg:px-6'>
|
||||
<CardTitle className="font-bold text-2xl">
|
||||
{product.title.charAt(0).toUpperCase() + product.title.slice(1)}
|
||||
</CardTitle>
|
||||
<p className='font-semibold'>$ {product.price} </p>
|
||||
{product.status === 'AGOTADO' ? (
|
||||
<p className="font-semibold text-lg text-red-900">AGOTADO</p>
|
||||
) : ('')}
|
||||
</CardHeader>
|
||||
<CardContent className="py-0 px-2 md:px-4 lg:px-6 flex-col justify-between flex-grow md:overflow-auto">
|
||||
<div>
|
||||
<p className='font-semibold text-lg border-t border-b'> Descripción</p>
|
||||
<p className='p-1'>{product.description}</p>
|
||||
{/* <p className='p-1'>{lorem+lorem+lorem+lorem}</p> */}
|
||||
</div>
|
||||
// <section className=''>
|
||||
// <img
|
||||
// className="border-2 object-cover w-[64px] h-[64px] md:w-[96px] md:h-[96px] aspect-square rounded-2xl"
|
||||
// src={`http://localhost:3000/uploads/inventory/${product.userId}/${product.urlImg}`}
|
||||
// alt=""
|
||||
// />
|
||||
// </section>
|
||||
// </div>
|
||||
// <Card className="flex flex-col md:w-[400px] lg:w-[500px] min-h-[400px] md:h-[85vh] md:overflow-auto md:sticky top-0 right-0">
|
||||
// <CardHeader className='py-2 px-2 md:px-4 lg:px-6'>
|
||||
// <CardTitle className="font-bold text-2xl">
|
||||
// {product.title.charAt(0).toUpperCase() + product.title.slice(1)}
|
||||
// </CardTitle>
|
||||
// <p className='font-semibold'>$ {product.price} </p>
|
||||
// {product.status === 'AGOTADO' ? (
|
||||
// <p className="font-semibold text-lg text-red-900">AGOTADO</p>
|
||||
// ) : ('')}
|
||||
// </CardHeader>
|
||||
// <CardContent className="py-0 px-2 md:px-4 lg:px-6 flex-col justify-between flex-grow md:overflow-auto">
|
||||
// <div>
|
||||
// <p className='font-semibold text-lg border-t border-b'> Descripción</p>
|
||||
// <p className='p-1'>{product.description}</p>
|
||||
// {/* <p className='p-1'>{lorem+lorem+lorem+lorem}</p> */}
|
||||
// </div>
|
||||
|
||||
<div className='mt-2'>
|
||||
<p className='font-semibold text-lg border-t border-b'> Dirección</p>
|
||||
<p className='p-1'>{product.address}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
// <div className='mt-2'>
|
||||
// <p className='font-semibold text-lg border-t border-b'> Dirección</p>
|
||||
// <p className='p-1'>{product.address}</p>
|
||||
// </div>
|
||||
// </CardContent>
|
||||
|
||||
<CardFooter className="px-2 md:px-4 lg:px-6">
|
||||
<div>
|
||||
<p className='font-semibold text-lg border-t border-b mt-4'>Información del vendedor</p>
|
||||
<p>{product.fullname}</p>
|
||||
<p>{product.phone}</p>
|
||||
<p>{product.email}</p>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</main>
|
||||
// <CardFooter className="px-2 md:px-4 lg:px-6">
|
||||
// <div>
|
||||
// <p className='font-semibold text-lg border-t border-b mt-4'>Información del vendedor</p>
|
||||
// <p>{product.fullname}</p>
|
||||
// <p>{product.phone}</p>
|
||||
// <p>{product.email}</p>
|
||||
// </div>
|
||||
// </CardFooter>
|
||||
// </Card>
|
||||
// </main>
|
||||
);
|
||||
}
|
||||
@@ -7,14 +7,9 @@ import {
|
||||
|
||||
export const resfreshTokenAction = async (refreshToken: RefreshTokenValue) => {
|
||||
try {
|
||||
const body = {
|
||||
token: refreshToken.token,
|
||||
}
|
||||
const response = await refreshApi.patch('/auth/refresh', {refresh_token: refreshToken.token});
|
||||
|
||||
// Usa la nueva instancia `refreshApi`
|
||||
const response = await refreshApi.patch('/auth/refresh', body);
|
||||
|
||||
const parsed = RefreshTokenResponseSchema.safeParse(response.data);
|
||||
const parsed = RefreshTokenResponseSchema.safeParse(response.data);
|
||||
|
||||
if (!parsed.success) {
|
||||
console.error('Error de validación en la respuesta de refresh token:', {
|
||||
|
||||
@@ -118,15 +118,15 @@ export const getProductById = async (id: number) => {
|
||||
};
|
||||
|
||||
export const createProductAction = async (payload: FormData) => {
|
||||
const session = await auth()
|
||||
const userId = session?.user?.id
|
||||
// const session = await auth()
|
||||
// const userId = session?.user?.id
|
||||
|
||||
if (userId) {
|
||||
payload.append('userId', String(userId));
|
||||
}
|
||||
// if (userId) {
|
||||
// payload.append('userId', String(userId));
|
||||
// }
|
||||
|
||||
const [error, data] = await safeFetchApi(
|
||||
productMutate,
|
||||
test,
|
||||
'/products',
|
||||
'POST',
|
||||
payload,
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from '@repo/shadcn/select';
|
||||
import { Input } from '@repo/shadcn/input';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useCreateUser } from "@/feactures/inventory/hooks/use-mutation";
|
||||
import { useCreateProduct } from "@/feactures/inventory/hooks/use-mutation";
|
||||
import { editInventory, EditInventory } from '@/feactures/inventory/schemas/inventory';
|
||||
import { Textarea } from '@repo/shadcn/textarea';
|
||||
import { STATUS } from '@/constants/status'
|
||||
@@ -37,7 +37,7 @@ export function CreateForm({
|
||||
const {
|
||||
mutate: saveProduct,
|
||||
isPending: isSaving,
|
||||
} = useCreateUser();
|
||||
} = useCreateProduct();
|
||||
|
||||
const [sizeFile, setSizeFile] = useState('0 bytes');
|
||||
const [previewUrls, setPreviewUrls] = useState<string[]>([]);
|
||||
|
||||
@@ -14,7 +14,7 @@ export const columns: ColumnDef<InventoryTable>[] = [
|
||||
header: 'img',
|
||||
cell: ({ row }) => {
|
||||
return (
|
||||
<img src={`http://localhost:3000/uploads/inventory/${row.original.userId}/${row.original.urlImg}`} alt="" width={64} height={64} className="rounded"/>
|
||||
<img src={`http://localhost:3000/uploads/inventory/${row.original.userId}/${row.original.id}/${row.original.urlImg}`} alt="" width={64} height={64} className="rounded"/>
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from '@repo/shadcn/select';
|
||||
import { Input } from '@repo/shadcn/input';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useUpdateUser } from "@/feactures/inventory/hooks/use-mutation";
|
||||
import { useUpdateProduct } from "@/feactures/inventory/hooks/use-mutation";
|
||||
import { editInventory, EditInventory } from '@/feactures/inventory/schemas/inventory'; // Renombrado EditInventory para claridad
|
||||
import { Textarea } from '@repo/shadcn/components/ui/textarea';
|
||||
import {STATUS} from '@/constants/status'
|
||||
@@ -55,7 +55,7 @@ export function UpdateForm({
|
||||
mutate: saveAccountingAccounts,
|
||||
isPending: isSaving,
|
||||
isError,
|
||||
} = useUpdateUser();
|
||||
} = useUpdateProduct();
|
||||
|
||||
const [sizeFile, setSizeFile] = useState('0 bytes');
|
||||
const [previewUrls, setPreviewUrls] = useState<string[]>([]);
|
||||
@@ -106,10 +106,10 @@ export function UpdateForm({
|
||||
}
|
||||
}
|
||||
|
||||
// --- IMPORTANTE: Tu hook `useUpdateUser` DEBE ser capaz de aceptar FormData ---
|
||||
// Si `useUpdateUser` llama a `safeFetchApi`, entonces `safeFetchApi` ya está preparado
|
||||
// --- IMPORTANTE: Tu hook `useUpdateProduct` DEBE ser capaz de aceptar FormData ---
|
||||
// Si `useUpdateProduct` llama a `safeFetchApi`, entonces `safeFetchApi` ya está preparado
|
||||
// para recibir `FormData`.
|
||||
saveAccountingAccounts(formData as any, { // Forzamos el tipo a 'any' si `useUpdateUser` no espera FormData en su tipo
|
||||
saveAccountingAccounts(formData as any, { // Forzamos el tipo a 'any' si `useUpdateProduct` no espera FormData en su tipo
|
||||
onSuccess: () => {
|
||||
form.reset();
|
||||
onSuccess?.();
|
||||
|
||||
@@ -44,7 +44,7 @@ export function ProductList() {
|
||||
<CardContent className="p-0 flex-grow">
|
||||
<img
|
||||
className="object-cover w-full h-full aspect-square border"
|
||||
src={`http://localhost:3000/uploads/inventory/${data.userId}/${data.urlImg}`}
|
||||
src={`http://localhost:3000/uploads/inventory/${data.userId}/${data.id}/${data.urlImg}`}
|
||||
alt=""
|
||||
/>
|
||||
</CardContent>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { allProducts, } from "../../schemas/inventory";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@repo/shadcn/card';
|
||||
|
||||
export function ProductList({product}: {product: allProducts}) {
|
||||
return (
|
||||
// <PageContainer>
|
||||
<main className='px-4 lg:px-6 flex flex-col md:flex-row gap-3 lg:gap-4 md:relative'>
|
||||
<div className='w-full flex justify-between flex-col'>
|
||||
|
||||
<img
|
||||
className="border-2 object-contain w-full f-full min-h-[400px] md:h-[70vh] aspect-square rounded-2xl"
|
||||
src={`http://localhost:3000/uploads/inventory/${product.userId}/${product.id}/${product.urlImg}`}
|
||||
alt=""
|
||||
/>
|
||||
|
||||
<section className=''>
|
||||
<img
|
||||
className="border-2 object-cover w-[64px] h-[64px] md:w-[96px] md:h-[96px] aspect-square rounded-2xl"
|
||||
src={`http://localhost:3000/uploads/inventory/${product.userId}/${product.id}/${product.urlImg}`}
|
||||
alt=""
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
<Card className="flex flex-col md:w-[400px] lg:w-[500px] min-h-[400px] md:h-[85vh] md:overflow-auto md:sticky top-0 right-0">
|
||||
<CardHeader className='py-2 px-2 md:px-4 lg:px-6'>
|
||||
<CardTitle className="font-bold text-2xl">
|
||||
{product.title.charAt(0).toUpperCase() + product.title.slice(1)}
|
||||
</CardTitle>
|
||||
<p className='font-semibold'>$ {product.price} </p>
|
||||
{product.status === 'AGOTADO' ? (
|
||||
<p className="font-semibold text-lg text-red-900">AGOTADO</p>
|
||||
) : ('')}
|
||||
</CardHeader>
|
||||
<CardContent className="py-0 px-2 md:px-4 lg:px-6 flex-col justify-between flex-grow md:overflow-auto">
|
||||
<div>
|
||||
<p className='font-semibold text-lg border-t border-b'> Descripción</p>
|
||||
<p className='p-1'>{product.description}</p>
|
||||
{/* <p className='p-1'>{lorem+lorem+lorem+lorem}</p> */}
|
||||
</div>
|
||||
|
||||
<div className='mt-2'>
|
||||
<p className='font-semibold text-lg border-t border-b'> Dirección</p>
|
||||
<p className='p-1'>{product.address}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="px-2 md:px-4 lg:px-6">
|
||||
<div>
|
||||
<p className='font-semibold text-lg border-t border-b mt-4'>Información del vendedor</p>
|
||||
<p>{product.fullname}</p>
|
||||
<p>{product.phone}</p>
|
||||
<p>{product.email}</p>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { EditInventory } from "../schemas/inventory";
|
||||
import { updateUserAction, createProductAction, updateUserAction2 } from "../actions/actions";
|
||||
|
||||
// Create mutation
|
||||
export function useCreateUser() {
|
||||
export function useCreateProduct() {
|
||||
const queryClient = useQueryClient();
|
||||
const mutation = useMutation({
|
||||
mutationFn: (data: any) => createProductAction(data),
|
||||
@@ -13,7 +13,7 @@ export function useCreateUser() {
|
||||
}
|
||||
|
||||
// Update mutation
|
||||
export function useUpdateUser() {
|
||||
export function useUpdateProduct() {
|
||||
const queryClient = useQueryClient();
|
||||
const mutation = useMutation({
|
||||
// mutationFn: (data: EditInventory) => updateUserAction(data),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// import { user } from '@/feactures/auth/schemas/register';
|
||||
// import { all } from 'axios';
|
||||
import { url } from 'inspector';
|
||||
import { z } from 'zod';
|
||||
|
||||
export type InventoryTable = z.infer<typeof product>;
|
||||
@@ -26,7 +27,11 @@ export const product = z.object({
|
||||
userId: z.number().optional()
|
||||
})
|
||||
|
||||
export const productDetails = product.extend({
|
||||
export const seeProduct = product.extend({
|
||||
urlImg: z.string(),
|
||||
})
|
||||
|
||||
export const productDetails = seeProduct.extend({
|
||||
fullname: z.string(),
|
||||
phone: z.string().nullable(),
|
||||
email: z.string().email().nullable()
|
||||
|
||||
@@ -100,65 +100,77 @@ const authConfig: NextAuthConfig = {
|
||||
signIn: '/', //sigin page
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({
|
||||
token,
|
||||
user,
|
||||
}: {
|
||||
token: any;
|
||||
user: User;
|
||||
async jwt({ token, user }:{
|
||||
user: User
|
||||
token: any
|
||||
|
||||
}) {
|
||||
// 1. Manejar el inicio de sesión inicial
|
||||
// El `user` solo se proporciona en el primer inicio de sesión.
|
||||
if (user) {
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
fullname: user.fullname,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
access_token: user.access_token,
|
||||
access_expire_in: user.access_expire_in,
|
||||
refresh_token: user.refresh_token,
|
||||
refresh_expire_in: user.refresh_expire_in
|
||||
}
|
||||
// return token;
|
||||
}
|
||||
|
||||
// 2. Si no es un nuevo login, verificar la expiración del token
|
||||
const now = Math.floor(Date.now() / 1000); // Usar Math.floor para un número entero
|
||||
|
||||
// Verificar si el token de acceso aún es válido
|
||||
if (now < (token.access_expire_in as number)) {
|
||||
return token; // Si no ha expirado, no hacer nada y devolver el token actual
|
||||
}
|
||||
|
||||
console.log("Now Access Expire:",token.access_expire_in);
|
||||
|
||||
|
||||
// 3. Si el token de acceso ha expirado, verificar el refresh token
|
||||
console.log("Access token ha expirado. Verificando refresh token...");
|
||||
if (now > (token.refresh_expire_in as number)) {
|
||||
console.log("Refresh token ha expirado. Forzando logout.");
|
||||
return null; // Forzar el logout al devolver null
|
||||
}
|
||||
|
||||
console.log("token:", token.refresh_token);
|
||||
|
||||
|
||||
// 4. Si el token de acceso ha expirado pero el refresh token es válido, renovar
|
||||
console.log("Renovando token de acceso...");
|
||||
try {
|
||||
// Si es un nuevo login, asignamos los datos
|
||||
if (user) {
|
||||
token.id = user.id;
|
||||
token.username = user.username;
|
||||
token.fullname = user.fullname;
|
||||
token.email = user.email;
|
||||
token.role = user.role;
|
||||
token.access_token = user.access_token;
|
||||
token.access_expire_in = user.access_expire_in;
|
||||
token.refresh_token = user.refresh_token;
|
||||
token.refresh_expire_in = user.refresh_expire_in;
|
||||
return token; // IMPORTANTE: retornamos el token aquí para evitar que entre en el siguiente 'if'
|
||||
const res = await resfreshTokenAction({ token: token.refresh_token as string });
|
||||
|
||||
if (!res || !res.tokens) {
|
||||
throw new Error('Fallo en la respuesta de la API de refresco.');
|
||||
}
|
||||
|
||||
// Verificar si el access_token ha expirado
|
||||
const now = Date.now() / 1000;
|
||||
if (now < (token.access_expire_in as number)) {
|
||||
return token; // Si el token no ha expirado, lo retornamos sin cambios
|
||||
}
|
||||
console.log("Old Access Expire:", token.access_expire_in);
|
||||
console.log("New Access Expire:", res.tokens.access_expire_in);
|
||||
|
||||
// Si el access_token ha expirado, verificar el refresh_token
|
||||
if (now > (token.refresh_expire_in as number)) {
|
||||
console.log("Refresh token ha expirado. Forzando logout.");
|
||||
return null; // Forzar logout
|
||||
}
|
||||
|
||||
// Si el access_token ha expirado pero el refresh_token es válido, renovar
|
||||
console.log("Renovando token de acceso...");
|
||||
const res = await resfreshTokenAction({
|
||||
token: token.refresh_token as string,
|
||||
});
|
||||
|
||||
console.log("Pepe");
|
||||
console.log("token:", token.refresh_token);
|
||||
|
||||
|
||||
if (!res) throw new Error('Fallo al renovar el token');
|
||||
// Actualizar el token directamente con los nuevos valores
|
||||
token.access_token = res.tokens.access_token;
|
||||
token.access_expire_in = res.tokens.access_expire_in;
|
||||
token.refresh_token = res.tokens.refresh_token;
|
||||
token.refresh_expire_in = res.tokens.refresh_expire_in;
|
||||
return token;
|
||||
|
||||
// Actualizar el token con la nueva información
|
||||
return {
|
||||
...token,
|
||||
access_token: res.tokens.access_token,
|
||||
access_expire_in: res.tokens.access_expire_in,
|
||||
refresh_token: res.tokens.refresh_token,
|
||||
refresh_expire_in: res.tokens.refresh_expire_in,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error al renovar el token: ", error);
|
||||
return null; // Fallo al renovar, forzar logout
|
||||
}
|
||||
},
|
||||
async session({ session, token }: { session: Session; token: DefaultJWT }) {
|
||||
async session({ session, token }: { session: Session; token: any }) {
|
||||
session.access_token = token.access_token as string;
|
||||
session.access_expire_in = token.access_expire_in as number;
|
||||
session.refresh_token = token.refresh_token as string;
|
||||
|
||||
@@ -12,6 +12,8 @@ const fetchApi = axios.create({
|
||||
// ESTE INTERCEPTOR ESTÁ BIEN PARA EL RESTO DE LAS PETICIONES AUTENTICADAS
|
||||
fetchApi.interceptors.request.use(async (config: any) => {
|
||||
try {
|
||||
console.log("Solicitando autenticación...");
|
||||
|
||||
const { auth } = await import('@/lib/auth'); // Importación dinámica
|
||||
const session = await auth();
|
||||
const token = session?.access_token;
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 786 KiB |
BIN
apps/web/public/uploads/inventory/1/1/1-17102590731691.jpg
Normal file
BIN
apps/web/public/uploads/inventory/1/1/1-17102590731691.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
BIN
apps/web/public/uploads/inventory/1/1/2-MANZNA-ROJA.jpg
Normal file
BIN
apps/web/public/uploads/inventory/1/1/2-MANZNA-ROJA.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 9.9 KiB |
Reference in New Issue
Block a user