editar, modificar, ver y crear productos listo

This commit is contained in:
2025-08-27 14:52:47 -04:00
parent f050db4359
commit 2d596b93ad
20 changed files with 242 additions and 183 deletions

View File

@@ -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);
}
}

View File

@@ -159,7 +159,7 @@ export class InventoryService {
return { data, meta };
}
async findOne(id: string): Promise<Product> {
async findOne(id: number): Promise<Product> {
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<Product> {
// 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<Product> {
async update(file: Express.Multer.File[], updateProductDto: UpdateProductDto, userId: number): Promise<Product> {
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' };
}
}