diff --git a/src/mesa/mesa.controller.ts b/src/mesa/mesa.controller.ts index 1273673..073ce90 100644 --- a/src/mesa/mesa.controller.ts +++ b/src/mesa/mesa.controller.ts @@ -4,7 +4,7 @@ import { UpdateMesaDto } from './dto/update-mesa.dto'; @Controller('mesa') export class MesaController { - constructor(private readonly mesaService: MesaService) {} + constructor(private readonly mesaService: MesaService) { } @Get() async findAll() { @@ -24,4 +24,9 @@ export class MesaController { ) { return this.mesaService.updateActivo(id, updateMesaDto); } + + @Patch(':id/activo') + toggleActivo(@Param('id') id: number) { + return this.mesaService.toggleActivo(+id); + } } diff --git a/src/mesa/mesa.service.ts b/src/mesa/mesa.service.ts index 76537eb..651bf72 100644 --- a/src/mesa/mesa.service.ts +++ b/src/mesa/mesa.service.ts @@ -1,4 +1,4 @@ -import { Injectable, NotFoundException } from '@nestjs/common'; +import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { UpdateMesaDto } from './dto/update-mesa.dto'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; @@ -9,14 +9,14 @@ export class MesaService { constructor( @InjectRepository(Mesa) private readonly mesaRepository: Repository, - ) {} + ) { } async findAll(): Promise { return await this.mesaRepository.find(); } async findAllActivo(): Promise { - return await this.mesaRepository.find({where:{activo:true}}); + return await this.mesaRepository.find({ where: { activo: true } }); } async updateActivo(id: number, updateMesaDto: UpdateMesaDto) { @@ -28,5 +28,38 @@ export class MesaService { mesa.activo = updateMesaDto.activo; return this.mesaRepository.save(mesa); } - + + async toggleActivo(id_mesa: number) { + if (Number.isNaN(id_mesa)) { + throw new BadRequestException('ID de mesa inválido'); + } + + const mesa = await this.mesaRepository.findOne({ + where: { id_mesa }, + }); + + if (!mesa) { + throw new NotFoundException('Mesa no encontrada'); + } + + let activoActual: boolean; + + if (Buffer.isBuffer(mesa.activo)) { + activoActual = mesa.activo[0] === 1; + } else { + activoActual = Boolean(mesa.activo); + } + + const nuevoActivo = !activoActual; + + await this.mesaRepository.update(id_mesa, { + activo: nuevoActivo, + }); + + return { + message: 'Estado de mesa actualizado', + id_mesa, + activo: nuevoActivo, + }; + } }