diff --git a/.gitignore b/.gitignore index cae925f..da91704 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,5 @@ yarn-error.log* # Misc .DS_Store *.pem + +apps/web/public/uploads \ No newline at end of file diff --git a/apps/api/src/features/inventory/inventory.controller.ts b/apps/api/src/features/inventory/inventory.controller.ts index 98f7400..0a2dbfb 100644 --- a/apps/api/src/features/inventory/inventory.controller.ts +++ b/apps/api/src/features/inventory/inventory.controller.ts @@ -47,7 +47,8 @@ export class UsersController { @ApiResponse({ status: 200, description: 'Return the product.' }) @ApiResponse({ status: 404, description: 'product not found.' }) async findOne(@Param('id') id: string) { - const data = await this.inventoryService.findOne(id); + const productId = Number(id) + const data = await this.inventoryService.findOne(productId); return { message: 'product fetched successfully', data }; } @@ -60,7 +61,7 @@ export class UsersController { @Req() req: Request, @Body() createUserDto: CreateProductDto, @UploadedFiles() files: Express.Multer.File[], - @Query('roleId') roleId?: string, + // @Query('roleId') roleId?: string, ) { const id = Number(req['user'].id); const data = await this.inventoryService.create(files,createUserDto,id) @@ -79,18 +80,20 @@ export class UsersController { @Body() body: any ) { const id = Number(req['user'].id); - const result = await this.inventoryService.saveImages(files,body,id); + const result = await this.inventoryService.update(files,body,id); return { data: result }; } - // @Delete(':id') + @Delete(':id') // @Roles('admin') - // @ApiOperation({ summary: 'Delete a user' }) - // @ApiResponse({ status: 200, description: 'User deleted successfully.' }) - // @ApiResponse({ status: 404, description: 'User not found.' }) - // async remove(@Param('id') id: string) { - // return await this.inventoryService.remove(id); - // } + @ApiOperation({ summary: 'Delete a Product' }) + @ApiResponse({ status: 200, description: 'Product deleted successfully.' }) + @ApiResponse({ status: 404, description: 'Product not found.' }) + async remove(@Req() req: Request, @Param('id') id: string) { + const productId = Number(id); + const userId = Number(req['user'].id); + return await this.inventoryService.remove(productId,userId); + } } diff --git a/apps/api/src/features/inventory/inventory.service.ts b/apps/api/src/features/inventory/inventory.service.ts index 4d3eac5..75ed217 100644 --- a/apps/api/src/features/inventory/inventory.service.ts +++ b/apps/api/src/features/inventory/inventory.service.ts @@ -159,7 +159,7 @@ export class InventoryService { return { data, meta }; } - async findOne(id: string): Promise { + async findOne(id: number): Promise { const find = await this.drizzle .select({ id: viewProductsStore.id, @@ -168,6 +168,7 @@ export class InventoryService { price: viewProductsStore.price, address: viewProductsStore.address, urlImg: viewProductsStore.urlImg, + gallery: viewProductsStore.gallery, stock: viewProductsStore.stock, status: viewProductsStore.status, userId: viewProductsStore.userId, @@ -176,10 +177,10 @@ export class InventoryService { phone: viewProductsStore.phone }) .from(viewProductsStore) - .where(eq(viewProductsStore.id, parseInt(id))); + .where(eq(viewProductsStore.id, id)); if (find.length === 0) { - throw new HttpException('Product does not exist', HttpStatus.BAD_REQUEST); + throw new HttpException('Product does not exist', HttpStatus.NOT_FOUND); } return find[0]; @@ -200,7 +201,7 @@ export class InventoryService { gallery.push(fileName); })); - console.log(gallery); + // console.log(gallery); // Start a transaction @@ -217,7 +218,7 @@ export class InventoryService { userId: userId, gallery: gallery } - console.log(productValue); + // console.log(productValue); const [newProduct] = await tx @@ -240,63 +241,38 @@ export class InventoryService { }) } - // async update(id: string, updateProductDto: UpdateProductDto): Promise { - // const productId = parseInt(id); - // // console.log(updateProductDto); - - // // Check if exists - // await this.findOne(id); - - // // Prepare update data - // const updateData: any = {}; - // if (updateProductDto.title) updateData.title = updateProductDto.title; - // if (updateProductDto.description) updateData.description = updateProductDto.description; - // if (updateProductDto.price) updateData.price = updateProductDto.price; - // if (updateProductDto.address) updateData.address = updateProductDto.address; - // if (updateProductDto.status) updateData.status = updateProductDto.status; - // if (updateProductDto.stock) updateData.stock = updateProductDto.stock; - // if (updateProductDto.urlImg) updateData.urlImg = updateProductDto.urlImg; - - // const [updatedProduct] = await this.drizzle.update(products).set(updateData).where(eq(products.id, productId)).returning(); - // return updatedProduct - // // Return updated user - // // return this.findOne(id); - // } - - /** - * Guarda una imagen en el directorio de imágenes. - * @param file - El archivo de imagen a guardar. - * @returns La ruta de la imagen guardada. - */ - async saveImages(file: Express.Multer.File[], updateProductDto: UpdateProductDto, userId: number): Promise { + async update(file: Express.Multer.File[], updateProductDto: UpdateProductDto, userId: number): Promise { const productId = parseInt(updateProductDto.id); - // Construye la ruta al directorio de imágenes. - const picturesPath = join(__dirname, '..', '..', '..', '..', 'web', 'public', 'uploads', 'inventory', userId.toString() , productId.toString()); - - // --- NUEVA LÓGICA: Borrar el directorio anterior --- - try { - // Borra el directorio y todos sus contenidos de forma recursiva y forzada. - await rm(picturesPath, { recursive: true, force: true }); - } catch (error) { - // Es buena práctica manejar el error, aunque `force: true` lo hace menos probable. - // Podrías registrar el error, pero no detener la ejecución. - console.error(`No se pudo eliminar el directorio ${picturesPath}:`, error); - } - // --- FIN DE LA NUEVA LÓGICA --- - - // Crea el directorio si no existe (ya que lo acabamos de borrar o no existía). - await mkdir(picturesPath, { recursive: true }); + // Check if exists + await this.findOne(productId); let gallery: string[] = []; - // Usamos `Promise.all` para manejar las operaciones asíncronas de forma correcta. - await Promise.all(file.map(async (f, index) => { - const fileName = `${index + 1}-${f.originalname}`; - gallery.push(fileName); - const filePath = join(picturesPath, fileName); - await writeFile(filePath, f.buffer); - })); + // check if product exist + if (file && file.length > 0) { + // Construye la ruta al directorio de imágenes. + const picturesPath = join(__dirname, '..', '..', '..', '..', 'web', 'public', 'uploads', 'inventory', userId.toString() , productId.toString()); + + try { + // Borra el directorio y todos sus contenidos de forma recursiva y forzada. + await rm(picturesPath, { recursive: true, force: true }); + } catch (error) { + // Es buena práctica manejar el error, aunque `force: true` lo hace menos probable. + // Podrías registrar el error, pero no detener la ejecución. + console.error(`No se pudo eliminar el directorio ${picturesPath}:`, error); + } + // Crea el directorio si no existe (ya que lo acabamos de borrar o no existía). + await mkdir(picturesPath, { recursive: true }); + + // Usamos `Promise.all` para manejar las operaciones asíncronas de forma correcta. + await Promise.all(file.map(async (f, index) => { + const fileName = `${index + 1}-${f.originalname}`; + gallery.push(fileName); + const filePath = join(picturesPath, fileName); + await writeFile(filePath, f.buffer); + })); + } // Prepare update data const updateData: any = {}; @@ -313,17 +289,26 @@ export class InventoryService { return updatedProduct; } - // async remove(id: string): Promise<{ message: string, data: User }> { - // const userId = parseInt(id); + async remove(productId: number, userId: number): Promise<{ message: string }> { + const picturesPath = join(__dirname, '..', '..', '..', '..', 'web', 'public', 'uploads', 'inventory', userId.toString() , productId.toString()); + + try { + // Borra el directorio y todos sus contenidos de forma recursiva y forzada. + await rm(picturesPath, { recursive: true, force: true }); + } catch (error) { + // Es buena práctica manejar el error, aunque `force: true` lo hace menos probable. + // Podrías registrar el error, pero no detener la ejecución. + console.error(`No se pudo eliminar el directorio ${picturesPath}:`, error); + } - // // Check if user exists - // const user = await this.findOne(id); + // Check if exists + await this.findOne(productId); - // // Delete user (this will cascade delete related records due to foreign key constraints) - // // await this.drizzle.delete(users).where(eq(users.id, userId)); - // await this.drizzle.update(users).set({ isActive: false }).where(eq(users.id, userId)); + // Delete user (this will cascade delete related records due to foreign key constraints) + await this.drizzle.delete(products).where(eq(products.id, productId)); + // await this.drizzle.update(products).set({ status: 'ELIMINADO' }).where(eq(products.id, productId)); - // return { message: 'User deleted successfully', data: user }; - // } + return { message: 'Product deleted successfully' }; + } } diff --git a/apps/web/app/dashboard/productos/[id]/page.tsx b/apps/web/app/dashboard/productos/[id]/page.tsx index aa0bcd4..6091bbe 100644 --- a/apps/web/app/dashboard/productos/[id]/page.tsx +++ b/apps/web/app/dashboard/productos/[id]/page.tsx @@ -1,15 +1,4 @@ -// 'use client'; - -// import PageContainer from '@/components/layout/page-container'; import { getProductById } from '@/feactures/inventory/actions/actions'; -// import { SurveyResponse } from '@/feactures/surveys/components/survey-response'; -import { - Card, - CardContent, - CardFooter, - CardHeader, - CardTitle, -} from '@repo/shadcn/card'; import {ProductList} from '@/feactures/inventory/components/products/see-product' export default async function SurveyResponsePage({ @@ -19,16 +8,18 @@ export default async function SurveyResponsePage({ }) { const { id } = await params; // You can still destructure id from params - if (!id || id === '') { - // Handle the case where no id is provided - return null; - } - + if (!id || id === '') return null; + // Call the function passing the dynamic id const data = await getProductById(Number(id)); if (!data?.data) { - return
Encuesta no encontrada
; + return ( +
+

Lo siento...

+

Producto no encontrado

+
+ ) } return ( diff --git a/apps/web/app/dashboard/productos/page.tsx b/apps/web/app/dashboard/productos/page.tsx index 5d96c70..254c9c6 100644 --- a/apps/web/app/dashboard/productos/page.tsx +++ b/apps/web/app/dashboard/productos/page.tsx @@ -1,4 +1,4 @@ -import PageContainer from '@/components/layout/page-container'; +// import PageContainer from '@/components/layout/page-container'; import { ProductList } from '@/feactures/inventory/components/products/product-list'; import { Button } from '@repo/shadcn/components/ui/button'; import { Metadata } from 'next'; @@ -13,7 +13,7 @@ export default function SurveysPage() { //
-

Productos Disponibles

+

Productos disponibles

diff --git a/apps/web/feactures/inventory/actions/actions.ts b/apps/web/feactures/inventory/actions/actions.ts index 914034a..0974bf4 100644 --- a/apps/web/feactures/inventory/actions/actions.ts +++ b/apps/web/feactures/inventory/actions/actions.ts @@ -4,14 +4,11 @@ import { ApiResponseSchema, InventoryTable, productMutate, - test, - // editInventory, productApiResponseSchema, - getProduct + getProduct, + deleteProduct } from '../schemas/inventory'; -import { auth } from '@/lib/auth'; - export const getInventoryAction = async (params: { page?: number; limit?: number; @@ -53,7 +50,7 @@ export const getInventoryAction = async (params: { nextPage: null, previousPage: null, }, - }; + } } export const getAllProducts = async (params: { @@ -100,9 +97,12 @@ export const getAllProducts = async (params: { previousPage: null, }, }; -}; +} export const getProductById = async (id: number) => { + if (!id) { + return null; + } const [error, data] = await safeFetchApi( getProduct, `/products/id/${id}`, @@ -110,12 +110,15 @@ export const getProductById = async (id: number) => { ); if (error) { + if (error.details.status === 404){ + return null + } console.error('❌ Error en la API:', error); throw new Error(error.message); } return data; -}; +} export const createProductAction = async (payload: FormData) => { const [error, data] = await safeFetchApi( @@ -131,7 +134,7 @@ export const createProductAction = async (payload: FormData) => { } return data; -}; +} export const updateProductAction = async (payload: InventoryTable) => { try { @@ -155,13 +158,16 @@ export const updateProductAction = async (payload: InventoryTable) => { } export const deleteProductAction = async (id: Number) => { + if (!id) { + throw new Error('Error al eliminar el producto') + } const [error] = await safeFetchApi( - productMutate, + deleteProduct, `/products/${id}`, 'DELETE' ) console.log(error); - if (error) throw new Error(error.message || 'Error al eliminar el usuario') + if (error) throw new Error(error.message || 'Error al eliminar el producto') return true; } \ No newline at end of file diff --git a/apps/web/feactures/inventory/components/inventory/create-product-form.tsx b/apps/web/feactures/inventory/components/inventory/create-product-form.tsx index a32d05d..953c4b3 100644 --- a/apps/web/feactures/inventory/components/inventory/create-product-form.tsx +++ b/apps/web/feactures/inventory/components/inventory/create-product-form.tsx @@ -19,7 +19,7 @@ import { import { Input } from '@repo/shadcn/input'; import { useForm } from 'react-hook-form'; import { useCreateProduct } from "@/feactures/inventory/hooks/use-mutation"; -import { editInventory, EditInventory } from '@/feactures/inventory/schemas/inventory'; +import { createProduct, EditInventory } from '@/feactures/inventory/schemas/inventory'; import { Textarea } from '@repo/shadcn/textarea'; import { STATUS } from '@/constants/status' import { useState, useEffect } from 'react'; @@ -59,7 +59,7 @@ export function CreateForm({ }; const form = useForm({ - resolver: zodResolver(editInventory), + resolver: zodResolver(createProduct), defaultValues: defaultformValues, mode: 'onChange', }); diff --git a/apps/web/feactures/inventory/components/inventory/inventory-modal.tsx b/apps/web/feactures/inventory/components/inventory/inventory-modal.tsx index 41a36c6..70aabe7 100644 --- a/apps/web/feactures/inventory/components/inventory/inventory-modal.tsx +++ b/apps/web/feactures/inventory/components/inventory/inventory-modal.tsx @@ -8,14 +8,14 @@ import { DialogTitle, } from '@repo/shadcn/dialog'; // import { AccountPlan } from '@/feactures/users/schemas/account-plan.schema'; -import { EditInventory, editInventory } from '../../schemas/inventory'; +import { EditInventory, InventoryTable } from '../../schemas/inventory'; import { CreateForm } from './create-product-form'; import { UpdateForm } from './update-product-form'; interface ModalProps { open: boolean; onOpenChange: (open: boolean) => void; - defaultValues?: Partial; + defaultValues?: Partial; } export function AccountPlanModal({ diff --git a/apps/web/feactures/inventory/components/inventory/product-tables/cell-action.tsx b/apps/web/feactures/inventory/components/inventory/product-tables/cell-action.tsx index 0e682ec..8cd7bb4 100644 --- a/apps/web/feactures/inventory/components/inventory/product-tables/cell-action.tsx +++ b/apps/web/feactures/inventory/components/inventory/product-tables/cell-action.tsx @@ -9,9 +9,10 @@ import { TooltipProvider, TooltipTrigger, } from '@repo/shadcn/tooltip'; -import { Edit, Trash, User } from 'lucide-react'; +import { Edit, Trash, Eye } from 'lucide-react'; import { InventoryTable } from '@/feactures/inventory/schemas/inventory'; -import { useDeleteUser } from '@/feactures/users/hooks/use-mutation-users'; +// import { useDeleteUser } from '@/feactures/users/hooks/use-mutation-users'; +import { useDeleteProduct } from "@/feactures/inventory/hooks/use-mutation"; import { AccountPlanModal } from '../inventory-modal'; interface CellActionProps { @@ -22,7 +23,7 @@ export const CellAction: React.FC = ({ data }) => { const [loading, setLoading] = useState(false); const [open, setOpen] = useState(false); const [edit, setEdit] = useState(false); - const { mutate: deleteUser } = useDeleteUser(); + const { mutate: deleteUser } = useDeleteProduct(); const router = useRouter(); const onConfirm = async () => { @@ -51,6 +52,23 @@ export const CellAction: React.FC = ({ data }) => {
+ + + + + + +

Ver

+
+
+
+ @@ -80,7 +98,7 @@ export const CellAction: React.FC = ({ data }) => { -

Deshabilitar

+

Eliminar

diff --git a/apps/web/feactures/inventory/components/inventory/product-tables/columns.tsx b/apps/web/feactures/inventory/components/inventory/product-tables/columns.tsx index 539fd27..75fdd83 100644 --- a/apps/web/feactures/inventory/components/inventory/product-tables/columns.tsx +++ b/apps/web/feactures/inventory/components/inventory/product-tables/columns.tsx @@ -5,16 +5,12 @@ import { CellAction } from './cell-action'; import { InventoryTable } from '../../../schemas/inventory'; export const columns: ColumnDef[] = [ - { - accessorKey: 'userId', - header: 'ID', - }, { accessorKey: 'urlImg', header: 'img', cell: ({ row }) => { return ( - + ) }, }, diff --git a/apps/web/feactures/inventory/components/inventory/update-product-form.tsx b/apps/web/feactures/inventory/components/inventory/update-product-form.tsx index d8133e8..7d6b4e8 100644 --- a/apps/web/feactures/inventory/components/inventory/update-product-form.tsx +++ b/apps/web/feactures/inventory/components/inventory/update-product-form.tsx @@ -19,7 +19,7 @@ import { import { Input } from '@repo/shadcn/input'; import { useForm } from 'react-hook-form'; import { useUpdateProduct } from "@/feactures/inventory/hooks/use-mutation"; -import { editInventory, EditInventory } from '@/feactures/inventory/schemas/inventory'; // Renombrado EditInventory para claridad +import { updateInventory, EditInventory, InventoryTable } from '@/feactures/inventory/schemas/inventory'; // Renombrado EditInventory para claridad import { Textarea } from '@repo/shadcn/components/ui/textarea'; import {STATUS} from '@/constants/status' import { useState, useEffect } from 'react'; @@ -43,7 +43,7 @@ import { z } from 'zod'; // Asegúrate de importar Zod interface UpdateFormProps { onSuccess?: () => void; onCancel?: () => void; - defaultValues?: Partial; + defaultValues?: Partial; } export function UpdateForm({ @@ -78,7 +78,7 @@ export function UpdateForm({ }; const form = useForm({ // Usamos el nuevo tipo aquí - resolver: zodResolver(editInventory), // Usamos el esquema extendido + resolver: zodResolver(updateInventory), // Usamos el esquema extendido defaultValues: defaultformValues, mode: 'onChange', }); diff --git a/apps/web/feactures/inventory/components/inventory/users-header.tsx b/apps/web/feactures/inventory/components/inventory/users-header.tsx index ad1229b..cb8c83d 100644 --- a/apps/web/feactures/inventory/components/inventory/users-header.tsx +++ b/apps/web/feactures/inventory/components/inventory/users-header.tsx @@ -13,8 +13,8 @@ export function UsersHeader() { <>
- + {product.title.charAt(0).toUpperCase() + product.title.slice(1)} -

$ {product.price}

- {product.status === 'AGOTADO' ? ( -

AGOTADO

- ) : ('')} +

{product.price}$ + {product.status === 'AGOTADO' ? ( + AGOTADO + ) : ('')} +

- -
-

Descripción

+ +
+

• Descripción

{product.description}

- {/*

{lorem+lorem+lorem+lorem}

*/} -
+ -
-

Dirección

+
+

• Dirección

{product.address}

-
+
-

Información del vendedor

+

• Información del vendedor

{product.fullname}

{product.phone}

{product.email}

diff --git a/apps/web/feactures/inventory/hooks/use-mutation.ts b/apps/web/feactures/inventory/hooks/use-mutation.ts index 98e9797..a21cf9e 100644 --- a/apps/web/feactures/inventory/hooks/use-mutation.ts +++ b/apps/web/feactures/inventory/hooks/use-mutation.ts @@ -1,6 +1,6 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; // import { EditInventory } from "../schemas/inventory"; -import { updateProductAction, createProductAction, } from "../actions/actions"; +import { updateProductAction, createProductAction,deleteProductAction } from "../actions/actions"; // Create mutation export function useCreateProduct() { @@ -25,11 +25,11 @@ export function useUpdateProduct() { } // Delete mutation -// export function useDeleteUser() { -// const queryClient = useQueryClient(); -// return useMutation({ -// mutationFn: (id: number) => deleteUserAction(id), -// onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }), -// onError: (e) => console.error('Error:', e) -// }) -// } \ No newline at end of file +export function useDeleteProduct() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (id: number) => deleteProductAction(id), + onSuccess: () => queryClient.invalidateQueries({ queryKey: ['product'] }), + onError: (e) => console.error('Error:', e) + }) +} \ No newline at end of file diff --git a/apps/web/feactures/inventory/schemas/inventory.ts b/apps/web/feactures/inventory/schemas/inventory.ts index 0d02265..d9deee5 100644 --- a/apps/web/feactures/inventory/schemas/inventory.ts +++ b/apps/web/feactures/inventory/schemas/inventory.ts @@ -4,7 +4,8 @@ import { url } from 'inspector'; import { z } from 'zod'; export type InventoryTable = z.infer; -export type EditInventory = z.infer; +export type EditInventory = z.infer; +export type CreateInventory = z.infer; export type ProductApiResponseSchema = z.infer; export type allProducts = z.infer; @@ -35,19 +36,58 @@ export const productDetails = seeProduct.extend({ email: z.string().email().nullable() }) -export const editInventory = z.object({ +const validateProduct = z.object({ id: z.number().optional(), title: z.string().min(5, { message: "Debe de tener 5 o más caracteres" }), description: z.string().min(10, { message: "Debe de tener 10 o más caracteres" }), stock: z.number(), address: z.string().min(5, { message: "Debe de tener 5 o más caracteres" }), - price: z.string(), + price: z.string().min(1, { message: "Debe de tener 1 o más caracteres" }), + urlImg: z.custom(), + status: z.string().min(1, { message: "Debe de seleccionar un valor" }), + userId: z.number().optional(), +}) + +export const updateInventory = validateProduct.extend({ + urlImg: z.custom() + .refine((files) => (files && files.length <= 10) || files === undefined, "Máximo 10 imágenes") + .refine((files) => + // (files && Array.from(files).every(file => file.size <= MAX_FILE_SIZE)) || files === undefined + { + if (files) { + let size = 0; + Array.from(files).map(file => { + size += file.size; + }) + if (size <= MAX_FILE_SIZE) return true; + return false + } + return true + } + , + `El tamaño máximo entre toda las imagenes es de 5MB` + ).refine((files) => + (files && Array.from(files).every(file => ACCEPTED_IMAGE_TYPES.includes(file.type))) || files === undefined, + "Solo se aceptan archivos .jpg, .jpeg, .png y .webp" + ).refine((files) => + (files && Array.from(files).every(file => file.name.length <= MAX_FILENAME_LENGTH)) || files === undefined, + `El nombre de cada archivo no puede superar los ${MAX_FILENAME_LENGTH} caracteres` + ), +}) + +export const createProduct = validateProduct.extend({ urlImg: z.custom() .refine((files) => files && files.length > 0, "Se requiere al menos una imagen") .refine((files) => files && files.length <= 10, "Máximo 10 imágenes") - .refine((files) => - files && Array.from(files).every(file => file.size <= MAX_FILE_SIZE), - `El tamaño máximo de cada imagen es de 5MB` + .refine((files) => { + let size = 0; + if (files) Array.from(files).map(file => { + size += file.size; + }) + if (size <= MAX_FILE_SIZE) return true; + return false + }, + `El tamaño máximo entre toda las imagenes es de 5MB` ).refine((files) => files && Array.from(files).every(file => ACCEPTED_IMAGE_TYPES.includes(file.type)), "Solo se aceptan archivos .jpg, .jpeg, .png y .webp" @@ -55,13 +95,11 @@ export const editInventory = z.object({ files && Array.from(files).every(file => file.name.length <= MAX_FILENAME_LENGTH), `El nombre de cada archivo no puede superar los ${MAX_FILENAME_LENGTH} caracteres` ), - status: z.string().min(1, { message: "Debe de seleccionar un valor" }), - userId: z.number().optional(), }) export const ApiResponseSchema = z.object({ message: z.string(), - data: z.array(product), + data: z.array(seeProduct), meta: z.object({ page: z.number(), limit: z.number(), @@ -89,11 +127,6 @@ export const productApiResponseSchema = z.object({ }), }) -export const test = z.object({ - // message: z.string(), - data: z.array(z.string()), -}) - export const productMutate = z.object({ message: z.string(), data: seeProduct, @@ -102,4 +135,8 @@ export const productMutate = z.object({ export const getProduct = z.object({ message: z.string(), data: productDetails, +}) + +export const deleteProduct = z.object({ + message: z.string(), }) \ No newline at end of file diff --git a/apps/web/lib/auth.config.ts b/apps/web/lib/auth.config.ts index 23985bb..247df61 100644 --- a/apps/web/lib/auth.config.ts +++ b/apps/web/lib/auth.config.ts @@ -130,21 +130,21 @@ const authConfig: NextAuthConfig = { return token; // Si no ha expirado, no hacer nada y devolver el token actual } - console.log("Now Access Expire:",token.access_expire_in); + // 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..."); + // 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."); + // console.log("Refresh token ha expirado. Forzando logout."); return null; // Forzar el logout al devolver null } - console.log("token:", token.refresh_token); + // 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..."); + // console.log("Renovando token de acceso..."); try { const res = await resfreshTokenAction({ token: token.refresh_token as string }); @@ -152,10 +152,10 @@ const authConfig: NextAuthConfig = { throw new Error('Fallo en la respuesta de la API de refresco.'); } - console.log("Old Access Expire:", token.access_expire_in); - console.log("New Access Expire:", res.tokens.access_expire_in); + // console.log("Old Access Expire:", token.access_expire_in); + // console.log("New Access Expire:", res.tokens.access_expire_in); - console.log("token:", token.refresh_token); + // console.log("token:", token.refresh_token); // Actualizar el token directamente con los nuevos valores diff --git a/apps/web/lib/fetch.api.ts b/apps/web/lib/fetch.api.ts index 56681e3..e0c6583 100644 --- a/apps/web/lib/fetch.api.ts +++ b/apps/web/lib/fetch.api.ts @@ -12,7 +12,7 @@ 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..."); + // console.log("Solicitando autenticación..."); const { auth } = await import('@/lib/auth'); // Importación dinámica const session = await auth(); diff --git a/apps/web/public/uploads/inventory/1/1/1-17102590731691.jpg b/apps/web/public/uploads/inventory/1/1/1-17102590731691.jpg deleted file mode 100644 index a6d0c54..0000000 Binary files a/apps/web/public/uploads/inventory/1/1/1-17102590731691.jpg and /dev/null differ diff --git a/apps/web/public/uploads/inventory/1/1/2-MANZNA-ROJA.jpg b/apps/web/public/uploads/inventory/1/1/2-MANZNA-ROJA.jpg deleted file mode 100644 index b24c76f..0000000 Binary files a/apps/web/public/uploads/inventory/1/1/2-MANZNA-ROJA.jpg and /dev/null differ